Profpatsch/users/Profpatsch/alacritty-change-color-scheme/alacritty-change-color-scheme.go
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/godbus/dbus/v5"
)

const (
	serviceName   = "org.freedesktop.portal.Desktop"
	objectPath    = "/org/freedesktop/portal/desktop"
	interfaceName = "org.freedesktop.portal.Settings"
)

type ColorScheme string

const (
	PreferDark  ColorScheme = "prefer-dark"
	PreferLight ColorScheme = "prefer-light"
)

// getColorScheme reads the current color scheme from GNOME D-Bus
func getColorScheme(conn *dbus.Conn) (ColorScheme, error) {
	obj := conn.Object(serviceName, objectPath)

	// ReadOne returns a variant
	call := obj.Call(interfaceName+".ReadOne", 0, "org.gnome.desktop.interface", "color-scheme")
	if call.Err != nil {
		return "", fmt.Errorf("failed to call ReadOne: %w", call.Err)
	}

	// The response is a single variant
	if len(call.Body) != 1 {
		return "", fmt.Errorf("unexpected response length: %d", len(call.Body))
	}

	variant, ok := call.Body[0].(dbus.Variant)
	if !ok {
		return "", fmt.Errorf("expected variant, got %T", call.Body[0])
	}

	// Extract the string from the variant
	value, ok := variant.Value().(string)
	if !ok {
		return "", fmt.Errorf("unexpected value type: %T", variant.Value())
	}

	cs := ColorScheme(value)
	if cs != PreferDark && cs != PreferLight {
		return "", fmt.Errorf("invalid color scheme value: %s", value)
	}

	return cs, nil
}

// writeAlacrittyColorConfig writes the Alacritty config file with the appropriate theme
func writeAlacrittyColorConfig(cs ColorScheme, darkTheme, lightTheme, programName string) error {
	theme := darkTheme
	if cs == PreferLight {
		theme = lightTheme
	}

	configHome := os.Getenv("XDG_CONFIG_HOME")
	if configHome == "" {
		homeDir, err := os.UserHomeDir()
		if err != nil {
			return fmt.Errorf("failed to get home directory: %w", err)
		}
		configHome = filepath.Join(homeDir, ".config")
	}

	configPath := filepath.Join(configHome, "alacritty", "alacritty-colors-autogen.toml")
	content := fmt.Sprintf("# !! THIS FILE IS GENERATED BY %s\ngeneral.import = [\"%s\"]", programName, theme)

	log.Printf("Writing color scheme %s with theme %s\n", cs, theme)

	if err := os.WriteFile(configPath, []byte(content), 0644); err != nil {
		return fmt.Errorf("failed to write config file: %w", err)
	}

	return nil
}

// listenForColorSchemeChange subscribes to D-Bus signals for color scheme changes
func listenForColorSchemeChange(conn *dbus.Conn, darkTheme, lightTheme, programName string) error {
	if err := conn.AddMatchSignal(dbus.WithMatchInterface(interfaceName), dbus.WithMatchMember("SettingChanged")); err != nil {
		return fmt.Errorf("failed to add match rule: %w", err)
	}

	// Create signal channel
	signals := make(chan *dbus.Signal, 10)
	conn.Signal(signals)

	log.Println("Listening for color scheme changes...")

	var previousColorScheme ColorScheme

	// Process signals
	for sig := range signals {
		if sig.Name != interfaceName+".SettingChanged" {
			continue
		}

		if len(sig.Body) < 3 {
			log.Printf("Unexpected signal body length: %d\n", len(sig.Body))
			continue
		}

		interfaceName, ok := sig.Body[0].(string)
		if !ok || interfaceName != "org.gnome.desktop.interface" {
			continue
		}

		key, ok := sig.Body[1].(string)
		if !ok || key != "color-scheme" {
			continue
		}

		// Body[2] is a variant
		variant, ok := sig.Body[2].(dbus.Variant)
		if !ok {
			log.Printf("Failed to extract variant from signal, got %T\n", sig.Body[2])
			continue
		}

		// Extract the string value directly from the variant
		newValue, ok := variant.Value().(string)
		if !ok {
			log.Printf("Unexpected variant value type: %T, value: %v\n", variant.Value(), variant.Value())
			continue
		}

		newColorScheme := ColorScheme(newValue)

		// Only change if different from previous
		if previousColorScheme == newColorScheme {
			log.Printf("Color scheme already set to %s\n", newColorScheme)
			continue
		}

		previousColorScheme = newColorScheme
		log.Printf("Color scheme changed to %s\n", newColorScheme)

		if err := writeAlacrittyColorConfig(newColorScheme, darkTheme, lightTheme, programName); err != nil {
			log.Printf("Error writing config: %v\n", err)
		}
	}

	return nil
}

// getThemeDirectory returns the theme cache directory, creating it if necessary
func getThemeDirectory() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("failed to get home directory: %w", err)
	}

	cacheDir := filepath.Join(homeDir, ".cache", "alacritty-change-color-scheme", "themes")

	// Create cache directory if it doesn't exist
	if err := os.MkdirAll(cacheDir, 0755); err != nil {
		return "", fmt.Errorf("failed to create cache directory: %w", err)
	}

	return cacheDir, nil
}

// downloadTheme downloads a specific theme file from GitHub
func downloadTheme(themeName, targetPath string) error {
	repos := []struct {
		owner string
		repo  string
		rev   string
	}{
		{"alacritty", "alacritty-theme", "95a7d695605863ede5b7430eb80d9e80f5f504bc"},
		{"anhsirk0", "alacritty-themes", "5a2c194a682ec75d46553f9a9d6c43fbf39c689d"},
	}

	client := &http.Client{}
	fileName := themeName + ".toml"

	// Try each repository
	for _, repo := range repos {
		rawURL := fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/themes/%s",
			repo.owner, repo.repo, repo.rev, fileName)

		log.Printf("Attempting to download %s from %s/%s...\n", fileName, repo.owner, repo.repo)

		resp, err := client.Get(rawURL)
		if err != nil {
			log.Printf("Failed to fetch from %s/%s: %v\n", repo.owner, repo.repo, err)
			continue
		}
		defer resp.Body.Close()

		if resp.StatusCode == 200 {
			out, err := os.Create(targetPath)
			if err != nil {
				return fmt.Errorf("failed to create file: %w", err)
			}
			defer out.Close()

			if _, err := io.Copy(out, resp.Body); err != nil {
				return fmt.Errorf("failed to write file: %w", err)
			}

			log.Printf("Successfully downloaded %s\n", fileName)
			return nil
		}

		if resp.StatusCode == 404 {
			log.Printf("Theme not found in %s/%s\n", repo.owner, repo.repo)
			continue
		}

		return fmt.Errorf("unexpected status %d from %s/%s", resp.StatusCode, repo.owner, repo.repo)
	}

	return fmt.Errorf("theme %s not found in any repository", themeName)
}

// patchDayfoxTheme patches the dayfox theme to fix white color contrast issues
func patchDayfoxTheme(path string) error {
	content, err := os.ReadFile(path)
	if err != nil {
		return fmt.Errorf("failed to read theme file: %w", err)
	}

	text := string(content)

	// Check if already patched
	if strings.Contains(text, "# PATCHED") {
		log.Printf("Theme already patched, skipping\n")
		return nil
	}

	// Apply patches - replace white colors with foreground colors
	// because many applications use white where foreground should be used
	replacements := map[string]string{
		`white = "#f2e9e1"`: `white = "#908a85"`, // normal white
		`white = "#f4ece6"`: `white = "#9f9791"`, // bright white
		`white = "#cec6bf"`: `white = "#85827f"`, // dim white
	}

	for old, new := range replacements {
		text = strings.ReplaceAll(text, old, new)
	}

	// Add patched marker
	text = "# PATCHED\n" + text

	if err := os.WriteFile(path, []byte(text), 0644); err != nil {
		return fmt.Errorf("failed to write patched theme: %w", err)
	}

	log.Printf("Successfully patched dayfox theme\n")
	return nil
}

// getThemePath resolves and validates a theme file path, downloading if necessary
func getThemePath(themeDir, themeName string) (string, error) {
	path := filepath.Join(themeDir, themeName+".toml")

	// Check if file exists
	if _, err := os.Stat(path); os.IsNotExist(err) {
		log.Printf("Theme %s not found locally, downloading...\n", themeName)
		if err := downloadTheme(themeName, path); err != nil {
			return "", fmt.Errorf("failed to download theme: %w", err)
		}
	}

	// Always patch dayfox (idempotent with marker check)
	if themeName == "dayfox" {
		if err := patchDayfoxTheme(path); err != nil {
			return "", fmt.Errorf("failed to patch dayfox theme: %w", err)
		}
	}

	absPath, err := filepath.EvalSymlinks(path)
	if err != nil {
		return "", fmt.Errorf("failed to resolve theme path %s: %w", path, err)
	}

	return absPath, nil
}

func main() {
	programName := os.Args[0]

	// Fixed theme names
	darkThemeName := "alacritty_0_12"
	lightThemeName := "dayfox"

	// Get theme directory
	themeDir, err := getThemeDirectory()
	if err != nil {
		log.Fatalf("Failed to get theme directory: %v\n", err)
	}

	// Resolve theme paths
	darkTheme, err := getThemePath(themeDir, darkThemeName)
	if err != nil {
		log.Fatalf("Error resolving dark theme: %v\n", err)
	}

	lightTheme, err := getThemePath(themeDir, lightThemeName)
	if err != nil {
		log.Fatalf("Error resolving light theme: %v\n", err)
	}

	log.Printf("Dark theme: %s\n", darkTheme)
	log.Printf("Light theme: %s\n", lightTheme)

	// Connect to D-Bus session bus
	conn, err := dbus.SessionBus()
	if err != nil {
		log.Fatalf("Failed to connect to session bus: %v\n", err)
	}
	defer conn.Close()

	// Get current color scheme
	currentColorScheme, err := getColorScheme(conn)
	if err != nil {
		log.Fatalf("Failed to get current color scheme: %v\n", err)
	}

	log.Printf("Current color scheme: %s\n", currentColorScheme)

	// Write initial config
	if err := writeAlacrittyColorConfig(currentColorScheme, darkTheme, lightTheme, programName); err != nil {
		log.Fatalf("Failed to write initial config: %v\n", err)
	}

	// Listen for changes (blocks)
	if err := listenForColorSchemeChange(conn, darkTheme, lightTheme, programName); err != nil {
		log.Fatalf("Failed to listen for color scheme changes: %v\n", err)
	}
}