loader.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package theme
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "fmt"
  6. "image/color"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/charmbracelet/lipgloss/v2"
  11. "github.com/charmbracelet/lipgloss/v2/compat"
  12. )
  13. //go:embed themes/*.json
  14. var themesFS embed.FS
  15. type JSONTheme struct {
  16. Defs map[string]any `json:"defs,omitempty"`
  17. Theme map[string]any `json:"theme"`
  18. }
  19. type LoadedTheme struct {
  20. BaseTheme
  21. name string
  22. }
  23. type colorRef struct {
  24. value any
  25. resolved bool
  26. }
  27. func LoadThemesFromJSON() error {
  28. entries, err := themesFS.ReadDir("themes")
  29. if err != nil {
  30. return fmt.Errorf("failed to read themes directory: %w", err)
  31. }
  32. for _, entry := range entries {
  33. if !strings.HasSuffix(entry.Name(), ".json") {
  34. continue
  35. }
  36. themeName := strings.TrimSuffix(entry.Name(), ".json")
  37. data, err := themesFS.ReadFile(filepath.Join("themes", entry.Name()))
  38. if err != nil {
  39. return fmt.Errorf("failed to read theme file %s: %w", entry.Name(), err)
  40. }
  41. theme, err := parseJSONTheme(themeName, data)
  42. if err != nil {
  43. return fmt.Errorf("failed to parse theme %s: %w", themeName, err)
  44. }
  45. RegisterTheme(themeName, theme)
  46. }
  47. return nil
  48. }
  49. // LoadThemesFromDirectories loads themes from user directories in the correct override order.
  50. // The hierarchy is (from lowest to highest priority):
  51. // 1. Built-in themes (embedded)
  52. // 2. USER_CONFIG/opencode/themes/*.json
  53. // 3. PROJECT_ROOT/.opencode/themes/*.json
  54. // 4. CWD/.opencode/themes/*.json
  55. func LoadThemesFromDirectories(userConfig, projectRoot, cwd string) error {
  56. if err := LoadThemesFromJSON(); err != nil {
  57. return fmt.Errorf("failed to load built-in themes: %w", err)
  58. }
  59. dirs := []string{
  60. filepath.Join(userConfig, "themes"),
  61. filepath.Join(projectRoot, ".opencode", "themes"),
  62. }
  63. if cwd != projectRoot {
  64. dirs = append(dirs, filepath.Join(cwd, ".opencode", "themes"))
  65. }
  66. for _, dir := range dirs {
  67. if err := loadThemesFromDirectory(dir); err != nil {
  68. fmt.Printf("Warning: Failed to load themes from %s: %v\n", dir, err)
  69. }
  70. }
  71. return nil
  72. }
  73. func loadThemesFromDirectory(dir string) error {
  74. if _, err := os.Stat(dir); os.IsNotExist(err) {
  75. return nil // Directory doesn't exist, which is fine
  76. }
  77. entries, err := os.ReadDir(dir)
  78. if err != nil {
  79. return fmt.Errorf("failed to read directory: %w", err)
  80. }
  81. for _, entry := range entries {
  82. if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
  83. continue
  84. }
  85. themeName := strings.TrimSuffix(entry.Name(), ".json")
  86. filePath := filepath.Join(dir, entry.Name())
  87. data, err := os.ReadFile(filePath)
  88. if err != nil {
  89. fmt.Printf("Warning: Failed to read theme file %s: %v\n", filePath, err)
  90. continue
  91. }
  92. theme, err := parseJSONTheme(themeName, data)
  93. if err != nil {
  94. fmt.Printf("Warning: Failed to parse theme %s: %v\n", filePath, err)
  95. continue
  96. }
  97. RegisterTheme(themeName, theme)
  98. }
  99. return nil
  100. }
  101. func parseJSONTheme(name string, data []byte) (Theme, error) {
  102. var jsonTheme JSONTheme
  103. if err := json.Unmarshal(data, &jsonTheme); err != nil {
  104. return nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
  105. }
  106. theme := &LoadedTheme{
  107. name: name,
  108. }
  109. colorMap := make(map[string]*colorRef)
  110. for key, value := range jsonTheme.Defs {
  111. colorMap[key] = &colorRef{value: value, resolved: false}
  112. }
  113. for key, value := range jsonTheme.Theme {
  114. colorMap[key] = &colorRef{value: value, resolved: false}
  115. }
  116. resolver := &colorResolver{
  117. colors: colorMap,
  118. visited: make(map[string]bool),
  119. }
  120. for key, value := range jsonTheme.Theme {
  121. resolved, err := resolver.resolveColor(key, value)
  122. if err != nil {
  123. return nil, fmt.Errorf("failed to resolve color %s: %w", key, err)
  124. }
  125. adaptiveColor, err := parseResolvedColor(resolved)
  126. if err != nil {
  127. return nil, fmt.Errorf("failed to parse color %s: %w", key, err)
  128. }
  129. if err := setThemeColor(theme, key, adaptiveColor); err != nil {
  130. return nil, fmt.Errorf("failed to set color %s: %w", key, err)
  131. }
  132. }
  133. return theme, nil
  134. }
  135. type colorResolver struct {
  136. colors map[string]*colorRef
  137. visited map[string]bool
  138. }
  139. func (r *colorResolver) resolveColor(key string, value any) (any, error) {
  140. if r.visited[key] {
  141. return nil, fmt.Errorf("circular reference detected for color %s", key)
  142. }
  143. r.visited[key] = true
  144. defer func() { r.visited[key] = false }()
  145. switch v := value.(type) {
  146. case string:
  147. if strings.HasPrefix(v, "#") {
  148. return v, nil
  149. }
  150. return r.resolveReference(v)
  151. case float64:
  152. return v, nil
  153. case map[string]any:
  154. resolved := make(map[string]any)
  155. if dark, ok := v["dark"]; ok {
  156. resolvedDark, err := r.resolveColorValue(dark)
  157. if err != nil {
  158. return nil, fmt.Errorf("failed to resolve dark variant: %w", err)
  159. }
  160. resolved["dark"] = resolvedDark
  161. }
  162. if light, ok := v["light"]; ok {
  163. resolvedLight, err := r.resolveColorValue(light)
  164. if err != nil {
  165. return nil, fmt.Errorf("failed to resolve light variant: %w", err)
  166. }
  167. resolved["light"] = resolvedLight
  168. }
  169. return resolved, nil
  170. default:
  171. return nil, fmt.Errorf("invalid color value type: %T", value)
  172. }
  173. }
  174. func (r *colorResolver) resolveColorValue(value any) (any, error) {
  175. switch v := value.(type) {
  176. case string:
  177. if strings.HasPrefix(v, "#") {
  178. return v, nil
  179. }
  180. return r.resolveReference(v)
  181. case float64:
  182. return v, nil
  183. default:
  184. return nil, fmt.Errorf("invalid color value type: %T", value)
  185. }
  186. }
  187. func (r *colorResolver) resolveReference(ref string) (any, error) {
  188. colorRef, exists := r.colors[ref]
  189. if !exists {
  190. return nil, fmt.Errorf("color reference '%s' not found", ref)
  191. }
  192. if colorRef.resolved {
  193. return colorRef.value, nil
  194. }
  195. resolved, err := r.resolveColor(ref, colorRef.value)
  196. if err != nil {
  197. return nil, err
  198. }
  199. colorRef.value = resolved
  200. colorRef.resolved = true
  201. return resolved, nil
  202. }
  203. func parseResolvedColor(value any) (compat.AdaptiveColor, error) {
  204. switch v := value.(type) {
  205. case string:
  206. return compat.AdaptiveColor{
  207. Dark: lipgloss.Color(v),
  208. Light: lipgloss.Color(v),
  209. }, nil
  210. case float64:
  211. colorStr := fmt.Sprintf("%d", int(v))
  212. return compat.AdaptiveColor{
  213. Dark: lipgloss.Color(colorStr),
  214. Light: lipgloss.Color(colorStr),
  215. }, nil
  216. case map[string]any:
  217. dark, darkOk := v["dark"]
  218. light, lightOk := v["light"]
  219. if !darkOk || !lightOk {
  220. return compat.AdaptiveColor{}, fmt.Errorf("color object must have both 'dark' and 'light' keys")
  221. }
  222. darkColor, err := parseColorValue(dark)
  223. if err != nil {
  224. return compat.AdaptiveColor{}, fmt.Errorf("failed to parse dark color: %w", err)
  225. }
  226. lightColor, err := parseColorValue(light)
  227. if err != nil {
  228. return compat.AdaptiveColor{}, fmt.Errorf("failed to parse light color: %w", err)
  229. }
  230. return compat.AdaptiveColor{
  231. Dark: darkColor,
  232. Light: lightColor,
  233. }, nil
  234. default:
  235. return compat.AdaptiveColor{}, fmt.Errorf("invalid resolved color type: %T", value)
  236. }
  237. }
  238. func parseColorValue(value any) (color.Color, error) {
  239. switch v := value.(type) {
  240. case string:
  241. return lipgloss.Color(v), nil
  242. case float64:
  243. return lipgloss.Color(fmt.Sprintf("%d", int(v))), nil
  244. default:
  245. return nil, fmt.Errorf("invalid color value type: %T", value)
  246. }
  247. }
  248. func setThemeColor(theme *LoadedTheme, key string, color compat.AdaptiveColor) error {
  249. switch key {
  250. case "primary":
  251. theme.PrimaryColor = color
  252. case "secondary":
  253. theme.SecondaryColor = color
  254. case "accent":
  255. theme.AccentColor = color
  256. case "error":
  257. theme.ErrorColor = color
  258. case "warning":
  259. theme.WarningColor = color
  260. case "success":
  261. theme.SuccessColor = color
  262. case "info":
  263. theme.InfoColor = color
  264. case "text":
  265. theme.TextColor = color
  266. case "textMuted":
  267. theme.TextMutedColor = color
  268. case "background":
  269. theme.BackgroundColor = color
  270. case "backgroundPanel":
  271. theme.BackgroundPanelColor = color
  272. case "backgroundElement":
  273. theme.BackgroundElementColor = color
  274. case "border":
  275. theme.BorderColor = color
  276. case "borderActive":
  277. theme.BorderActiveColor = color
  278. case "borderSubtle":
  279. theme.BorderSubtleColor = color
  280. case "diffAdded":
  281. theme.DiffAddedColor = color
  282. case "diffRemoved":
  283. theme.DiffRemovedColor = color
  284. case "diffContext":
  285. theme.DiffContextColor = color
  286. case "diffHunkHeader":
  287. theme.DiffHunkHeaderColor = color
  288. case "diffHighlightAdded":
  289. theme.DiffHighlightAddedColor = color
  290. case "diffHighlightRemoved":
  291. theme.DiffHighlightRemovedColor = color
  292. case "diffAddedBg":
  293. theme.DiffAddedBgColor = color
  294. case "diffRemovedBg":
  295. theme.DiffRemovedBgColor = color
  296. case "diffContextBg":
  297. theme.DiffContextBgColor = color
  298. case "diffLineNumber":
  299. theme.DiffLineNumberColor = color
  300. case "diffAddedLineNumberBg":
  301. theme.DiffAddedLineNumberBgColor = color
  302. case "diffRemovedLineNumberBg":
  303. theme.DiffRemovedLineNumberBgColor = color
  304. case "markdownText":
  305. theme.MarkdownTextColor = color
  306. case "markdownHeading":
  307. theme.MarkdownHeadingColor = color
  308. case "markdownLink":
  309. theme.MarkdownLinkColor = color
  310. case "markdownLinkText":
  311. theme.MarkdownLinkTextColor = color
  312. case "markdownCode":
  313. theme.MarkdownCodeColor = color
  314. case "markdownBlockQuote":
  315. theme.MarkdownBlockQuoteColor = color
  316. case "markdownEmph":
  317. theme.MarkdownEmphColor = color
  318. case "markdownStrong":
  319. theme.MarkdownStrongColor = color
  320. case "markdownHorizontalRule":
  321. theme.MarkdownHorizontalRuleColor = color
  322. case "markdownListItem":
  323. theme.MarkdownListItemColor = color
  324. case "markdownListEnumeration":
  325. theme.MarkdownListEnumerationColor = color
  326. case "markdownImage":
  327. theme.MarkdownImageColor = color
  328. case "markdownImageText":
  329. theme.MarkdownImageTextColor = color
  330. case "markdownCodeBlock":
  331. theme.MarkdownCodeBlockColor = color
  332. case "syntaxComment":
  333. theme.SyntaxCommentColor = color
  334. case "syntaxKeyword":
  335. theme.SyntaxKeywordColor = color
  336. case "syntaxFunction":
  337. theme.SyntaxFunctionColor = color
  338. case "syntaxVariable":
  339. theme.SyntaxVariableColor = color
  340. case "syntaxString":
  341. theme.SyntaxStringColor = color
  342. case "syntaxNumber":
  343. theme.SyntaxNumberColor = color
  344. case "syntaxType":
  345. theme.SyntaxTypeColor = color
  346. case "syntaxOperator":
  347. theme.SyntaxOperatorColor = color
  348. case "syntaxPunctuation":
  349. theme.SyntaxPunctuationColor = color
  350. default:
  351. // Ignore unknown keys for forward compatibility
  352. return nil
  353. }
  354. return nil
  355. }