loader.go 10.0 KB

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