loader.go 10 KB

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