v0.14.0 76d1892

config.go RawHistoryFolder

1// Package config provides configuration management for dumber with Viper integration.
2package config
3
4import (
5	"errors"
6	"fmt"
7	"os"
8	"path/filepath"
9	"strings"
10	"sync"
11
12	"github.com/bnema/dumber/internal/logging"
13	"github.com/bnema/dumber/pkg/gpu"
14	"github.com/fsnotify/fsnotify"
15	"github.com/spf13/viper"
16)
17
18// File permission constants
19const (
20	dirPerm  = 0755 // Standard directory permissions (rwxr-xr-x)
21	filePerm = 0644 // Standard file permissions (rw-r--r--)
22)
23
24// Config represents the complete configuration for dumber.
25type Config struct {
26	Database          DatabaseConfig            `mapstructure:"database" yaml:"database"`
27	History           HistoryConfig             `mapstructure:"history" yaml:"history"`
28	SearchShortcuts   map[string]SearchShortcut `mapstructure:"search_shortcuts" yaml:"search_shortcuts"`
29	// DefaultSearchEngine is the URL template for the default search engine (must contain %s placeholder)
30	DefaultSearchEngine string `mapstructure:"default_search_engine" yaml:"default_search_engine"`
31	Dmenu               DmenuConfig `mapstructure:"dmenu" yaml:"dmenu"`
32	Logging           LoggingConfig             `mapstructure:"logging" yaml:"logging"`
33	Appearance        AppearanceConfig          `mapstructure:"appearance" yaml:"appearance"`
34	VideoAcceleration VideoAccelerationConfig   `mapstructure:"video_acceleration" yaml:"video_acceleration"`
35	CodecPreferences  CodecConfig               `mapstructure:"codec_preferences" yaml:"codec_preferences"`
36	Debug             DebugConfig               `mapstructure:"debug" yaml:"debug"`
37	// RenderingMode controls GPU/CPU rendering selection for WebKit
38	RenderingMode RenderingMode `mapstructure:"rendering_mode" yaml:"rendering_mode"`
39	// UseDomZoom toggles DOM-based zoom instead of native WebKit zoom.
40	UseDomZoom bool `mapstructure:"use_dom_zoom" yaml:"use_dom_zoom"`
41	// DefaultZoom sets the default zoom level for pages without saved zoom settings (1.0 = 100%, 1.2 = 120%)
42	DefaultZoom float64 `mapstructure:"default_zoom" yaml:"default_zoom"`
43	// Workspace defines workspace, pane, and tab handling behaviour.
44	Workspace WorkspaceConfig `mapstructure:"workspace" yaml:"workspace"`
45	// ContentFilteringWhitelist domains skip ad blocking (e.g. Twitch breaks with bot detection)
46	ContentFilteringWhitelist []string `mapstructure:"content_filtering_whitelist" yaml:"content_filtering_whitelist"`
47}
48
49// RenderingMode selects GPU vs CPU rendering.
50type RenderingMode string
51
52const (
53	RenderingModeAuto RenderingMode = "auto"
54	RenderingModeGPU  RenderingMode = "gpu"
55	RenderingModeCPU  RenderingMode = "cpu"
56)
57
58// DatabaseConfig holds database-related configuration.
59type DatabaseConfig struct {
60	Path string `mapstructure:"path" yaml:"path"`
61}
62
63// HistoryConfig holds history-related configuration.
64type HistoryConfig struct {
65	MaxEntries          int `mapstructure:"max_entries" yaml:"max_entries"`
66	RetentionPeriodDays int `mapstructure:"retention_period_days" yaml:"retention_period_days"`
67	CleanupIntervalDays int `mapstructure:"cleanup_interval_days" yaml:"cleanup_interval_days"`
68}
69
70// SearchShortcut represents a search shortcut configuration.
71type SearchShortcut struct {
72	URL         string `mapstructure:"url" toml:"url" yaml:"url" json:"url"`
73	Description string `mapstructure:"description" toml:"description" yaml:"description" json:"description"`
74}
75
76// DmenuConfig holds dmenu/rofi integration configuration.
77type DmenuConfig struct {
78	MaxHistoryItems  int    `mapstructure:"max_history_items" yaml:"max_history_items"`
79	ShowVisitCount   bool   `mapstructure:"show_visit_count" yaml:"show_visit_count"`
80	ShowLastVisited  bool   `mapstructure:"show_last_visited" yaml:"show_last_visited"`
81	HistoryPrefix    string `mapstructure:"history_prefix" yaml:"history_prefix"`
82	ShortcutPrefix   string `mapstructure:"shortcut_prefix" yaml:"shortcut_prefix"`
83	URLPrefix        string `mapstructure:"url_prefix" yaml:"url_prefix"`
84	DateFormat       string `mapstructure:"date_format" yaml:"date_format"`
85	SortByVisitCount bool   `mapstructure:"sort_by_visit_count" yaml:"sort_by_visit_count"`
86}
87
88// LoggingConfig holds logging configuration.
89type LoggingConfig struct {
90	Level      string `mapstructure:"level" yaml:"level"`
91	Format     string `mapstructure:"format" yaml:"format"`
92	Filename   string `mapstructure:"filename" yaml:"filename"`
93	MaxSize    int    `mapstructure:"max_size" yaml:"max_size"`
94	MaxBackups int    `mapstructure:"max_backups" yaml:"max_backups"`
95	MaxAge     int    `mapstructure:"max_age" yaml:"max_age"`
96	Compress   bool   `mapstructure:"compress" yaml:"compress"`
97
98	// File output configuration
99	LogDir        string `mapstructure:"log_dir" yaml:"log_dir"`
100	EnableFileLog bool   `mapstructure:"enable_file_log" yaml:"enable_file_log"`
101
102	// Capture settings
103	CaptureStdout  bool `mapstructure:"capture_stdout" yaml:"capture_stdout" json:"capture_stdout"`
104	CaptureStderr  bool `mapstructure:"capture_stderr" yaml:"capture_stderr" json:"capture_stderr"`
105	CaptureCOutput bool `mapstructure:"capture_c_output" yaml:"capture_c_output" json:"capture_c_output"`
106	CaptureConsole bool `mapstructure:"capture_console" yaml:"capture_console" json:"capture_console"`
107
108	// Debug output
109	DebugFile     string `mapstructure:"debug_file" yaml:"debug_file"`
110	VerboseWebKit bool   `mapstructure:"verbose_webkit" yaml:"verbose_webkit"`
111}
112
113// AppearanceConfig holds UI/rendering preferences.
114type AppearanceConfig struct {
115	// Default fonts for pages that do not specify fonts.
116	SansFont      string `mapstructure:"sans_font" yaml:"sans_font"`
117	SerifFont     string `mapstructure:"serif_font" yaml:"serif_font"`
118	MonospaceFont string `mapstructure:"monospace_font" yaml:"monospace_font"`
119	// Default font size in CSS pixels (approx).
120	DefaultFontSize int          `mapstructure:"default_font_size" yaml:"default_font_size"`
121	LightPalette    ColorPalette `mapstructure:"light_palette" yaml:"light_palette"`
122	DarkPalette     ColorPalette `mapstructure:"dark_palette" yaml:"dark_palette"`
123	// ColorScheme controls the initial theme preference: "prefer-dark", "prefer-light", or "default" (follows system)
124	ColorScheme string `mapstructure:"color_scheme" yaml:"color_scheme"`
125}
126
127// ColorPalette contains semantic color tokens for light/dark themes.
128type ColorPalette struct {
129	Background     string `mapstructure:"background" yaml:"background" json:"background"`
130	Surface        string `mapstructure:"surface" yaml:"surface" json:"surface"`
131	SurfaceVariant string `mapstructure:"surface_variant" yaml:"surface_variant" json:"surface_variant"`
132	Text           string `mapstructure:"text" yaml:"text" json:"text"`
133	Muted          string `mapstructure:"muted" yaml:"muted" json:"muted"`
134	Accent         string `mapstructure:"accent" yaml:"accent" json:"accent"`
135	Border         string `mapstructure:"border" yaml:"border" json:"border"`
136}
137
138// VideoAccelerationConfig holds video hardware acceleration preferences.
139type VideoAccelerationConfig struct {
140	EnableVAAPI      bool   `mapstructure:"enable_vaapi" yaml:"enable_vaapi"`
141	AutoDetectGPU    bool   `mapstructure:"auto_detect_gpu" yaml:"auto_detect_gpu"`
142	VAAPIDriverName  string `mapstructure:"vaapi_driver_name" yaml:"vaapi_driver_name"`
143	EnableAllDrivers bool   `mapstructure:"enable_all_drivers" yaml:"enable_all_drivers"`
144	LegacyVAAPI      bool   `mapstructure:"legacy_vaapi" yaml:"legacy_vaapi"`
145}
146
147// CodecConfig holds video codec preferences and handling
148type CodecConfig struct {
149	// Codec preference order (e.g., "av1,h264,vp8")
150	PreferredCodecs string `mapstructure:"preferred_codecs" yaml:"preferred_codecs"`
151
152	// Force specific codec for platforms
153	ForceAV1 bool `mapstructure:"force_av1" yaml:"force_av1"`
154
155	// Block problematic codecs
156	BlockVP9 bool `mapstructure:"block_vp9" yaml:"block_vp9"`
157	BlockVP8 bool `mapstructure:"block_vp8" yaml:"block_vp8"`
158
159	// Hardware acceleration per codec
160	AV1HardwareOnly    bool `mapstructure:"av1_hardware_only" yaml:"av1_hardware_only"`
161	DisableVP9Hardware bool `mapstructure:"disable_vp9_hardware" yaml:"disable_vp9_hardware"`
162
163	// Buffer configuration for smooth playback
164	VideoBufferSizeMB  int `mapstructure:"video_buffer_size_mb" yaml:"video_buffer_size_mb"`
165	QueueBufferTimeSec int `mapstructure:"queue_buffer_time_sec" yaml:"queue_buffer_time_sec"`
166
167	// Custom User-Agent for codec negotiation
168	CustomUserAgent string `mapstructure:"custom_user_agent" yaml:"custom_user_agent"`
169
170	// Maximum resolution for AV1 codec (720p, 1080p, 1440p, 4k, unlimited)
171	AV1MaxResolution string `mapstructure:"av1_max_resolution" yaml:"av1_max_resolution"`
172
173	// Site-specific codec control settings
174	DisableTwitchCodecControl bool `mapstructure:"disable_twitch_codec_control" yaml:"disable_twitch_codec_control"`
175}
176
177// DebugConfig holds debug and troubleshooting options
178type DebugConfig struct {
179	// Enable WebKit internal debug logging
180	EnableWebKitDebug bool `mapstructure:"enable_webkit_debug" yaml:"enable_webkit_debug"`
181
182	// WebKit debug categories (comma-separated)
183	// Common values: "Network:preconnectTo", "ContentFilters", "Loading", "JavaScript"
184	WebKitDebugCategories string `mapstructure:"webkit_debug_categories" yaml:"webkit_debug_categories"`
185
186	// Enable content filtering debug logs
187	EnableFilteringDebug bool `mapstructure:"enable_filtering_debug" yaml:"enable_filtering_debug"`
188
189	// Enable detailed WebView state logging
190	EnableWebViewDebug bool `mapstructure:"enable_webview_debug" yaml:"enable_webview_debug"`
191
192	// Log WebKit crashes and errors to file
193	LogWebKitCrashes bool `mapstructure:"log_webkit_crashes" yaml:"log_webkit_crashes"`
194
195	// Enable script injection debug logs
196	EnableScriptDebug bool `mapstructure:"enable_script_debug" yaml:"enable_script_debug"`
197
198	// Enable general debug mode (equivalent to DUMBER_DEBUG env var)
199	EnableGeneralDebug bool `mapstructure:"enable_general_debug" yaml:"enable_general_debug"`
200
201	// Enable workspace navigation and focus debug logs
202	EnableWorkspaceDebug bool `mapstructure:"enable_workspace_debug" yaml:"enable_workspace_debug"`
203
204	// Enable focus state machine debug logs
205	EnableFocusDebug bool `mapstructure:"enable_focus_debug" yaml:"enable_focus_debug"`
206
207	// Enable CSS reconciler debug logs
208	EnableCSSDebug bool `mapstructure:"enable_css_debug" yaml:"enable_css_debug"`
209
210	// Enable focus metrics tracking
211	EnableFocusMetrics bool `mapstructure:"enable_focus_metrics" yaml:"enable_focus_metrics"`
212
213	// Enable detailed pane close instrumentation and tree snapshots
214	EnablePaneCloseDebug bool `mapstructure:"enable_pane_close_debug" yaml:"enable_pane_close_debug"`
215}
216
217// WorkspaceConfig captures layout, pane, and tab behaviour preferences.
218type WorkspaceConfig struct {
219	// PaneMode defines modal pane behaviour and bindings.
220	PaneMode PaneModeConfig `mapstructure:"pane_mode" yaml:"pane_mode" json:"pane_mode"`
221	// TabMode defines modal tab behaviour and bindings (Alt+T).
222	TabMode TabModeConfig `mapstructure:"tab_mode" yaml:"tab_mode" json:"tab_mode"`
223	// Tabs holds classic browser tab shortcuts.
224	Tabs TabKeyConfig `mapstructure:"tabs" yaml:"tabs" json:"tabs"`
225	// TabBarPosition determines tab bar placement: "top" or "bottom".
226	TabBarPosition string `mapstructure:"tab_bar_position" yaml:"tab_bar_position" json:"tab_bar_position"`
227	// Popups configures default popup placement rules.
228	Popups PopupBehaviorConfig `mapstructure:"popups" yaml:"popups" json:"popups"`
229	// Styling configures workspace visual appearance.
230	Styling WorkspaceStylingConfig `mapstructure:"styling" yaml:"styling" json:"styling"`
231}
232
233// PaneModeConfig defines modal behaviour for pane management.
234type PaneModeConfig struct {
235	ActivationShortcut  string              `mapstructure:"activation_shortcut" yaml:"activation_shortcut" json:"activation_shortcut"`
236	TimeoutMilliseconds int                 `mapstructure:"timeout_ms" yaml:"timeout_ms" json:"timeout_ms"`
237	Actions             map[string][]string `mapstructure:"actions" yaml:"actions" json:"actions"`
238}
239
240// GetKeyBindings returns an inverted map for O(1) key→action lookup.
241// This is built from the action→keys structure in the config.
242func (p *PaneModeConfig) GetKeyBindings() map[string]string {
243	keyToAction := make(map[string]string)
244	for action, keys := range p.Actions {
245		for _, key := range keys {
246			keyToAction[key] = action
247		}
248	}
249	return keyToAction
250}
251
252// TabModeConfig defines modal behaviour for tab management (Zellij-style).
253type TabModeConfig struct {
254	ActivationShortcut  string              `mapstructure:"activation_shortcut" yaml:"activation_shortcut" json:"activation_shortcut"`
255	TimeoutMilliseconds int                 `mapstructure:"timeout_ms" yaml:"timeout_ms" json:"timeout_ms"`
256	Actions             map[string][]string `mapstructure:"actions" yaml:"actions" json:"actions"`
257}
258
259// GetKeyBindings returns an inverted map for O(1) key→action lookup.
260// This is built from the action→keys structure in the config.
261func (t *TabModeConfig) GetKeyBindings() map[string]string {
262	keyToAction := make(map[string]string)
263	for action, keys := range t.Actions {
264		for _, key := range keys {
265			keyToAction[key] = action
266		}
267	}
268	return keyToAction
269}
270
271// TabKeyConfig defines Zellij-inspired tab shortcuts.
272type TabKeyConfig struct {
273	NewTab      string `mapstructure:"new_tab" yaml:"new_tab" json:"new_tab"`
274	CloseTab    string `mapstructure:"close_tab" yaml:"close_tab" json:"close_tab"`
275	NextTab     string `mapstructure:"next_tab" yaml:"next_tab" json:"next_tab"`
276	PreviousTab string `mapstructure:"previous_tab" yaml:"previous_tab" json:"previous_tab"`
277}
278
279// PopupBehavior defines how popup windows should be opened
280type PopupBehavior string
281
282const (
283	// PopupBehaviorSplit opens popups in a split pane (default)
284	PopupBehaviorSplit PopupBehavior = "split"
285	// PopupBehaviorStacked opens popups in a stacked pane
286	PopupBehaviorStacked PopupBehavior = "stacked"
287	// PopupBehaviorTabbed opens popups as a new tab
288	PopupBehaviorTabbed PopupBehavior = "tabbed"
289	// PopupBehaviorWindowed opens popups in a new workspace window
290	PopupBehaviorWindowed PopupBehavior = "windowed"
291)
292
293// PopupBehaviorConfig defines handling for popup windows.
294type PopupBehaviorConfig struct {
295	// Behavior determines how popups are opened (split/stacked/tabbed/windowed)
296	Behavior PopupBehavior `mapstructure:"behavior" yaml:"behavior" json:"behavior"`
297
298	// Placement specifies direction for split behavior ("right", "left", "top", "bottom")
299	// Only used when Behavior is "split"
300	Placement string `mapstructure:"placement" yaml:"placement" json:"placement"`
301
302	// OpenInNewPane controls whether popups are opened in workspace or blocked
303	OpenInNewPane bool `mapstructure:"open_in_new_pane" yaml:"open_in_new_pane" json:"open_in_new_pane"`
304
305	// FollowPaneContext determines if popup placement follows parent pane context
306	FollowPaneContext bool `mapstructure:"follow_pane_context" yaml:"follow_pane_context" json:"follow_pane_context"`
307
308	// BlankTargetBehavior determines how target="_blank" links are opened
309	// Accepted values: "split", "stacked" (default), "tabbed"
310	// This is separate from Behavior which controls JavaScript popups
311	BlankTargetBehavior string `mapstructure:"blank_target_behavior" yaml:"blank_target_behavior" json:"blank_target_behavior"`
312
313	// EnableSmartDetection uses WebKitWindowProperties to detect popup vs tab intents
314	EnableSmartDetection bool `mapstructure:"enable_smart_detection" yaml:"enable_smart_detection" json:"enable_smart_detection"`
315
316	// OAuthAutoClose enables auto-closing OAuth popups after successful auth redirects
317	OAuthAutoClose bool `mapstructure:"oauth_auto_close" yaml:"oauth_auto_close" json:"oauth_auto_close"`
318}
319
320// WorkspaceStylingConfig defines visual styling for workspace panes.
321type WorkspaceStylingConfig struct {
322	// BorderWidth in pixels for active pane borders
323	BorderWidth int `mapstructure:"border_width" yaml:"border_width" json:"border_width"`
324	// BorderColor for focused panes (CSS color value or theme variable)
325	BorderColor string `mapstructure:"border_color" yaml:"border_color" json:"border_color"`
326	// InactiveBorderWidth in pixels for inactive pane borders (0 = hidden)
327	InactiveBorderWidth int `mapstructure:"inactive_border_width" yaml:"inactive_border_width" json:"inactive_border_width"`
328	// InactiveBorderColor for unfocused panes (CSS color value or theme variable)
329	InactiveBorderColor string `mapstructure:"inactive_border_color" yaml:"inactive_border_color" json:"inactive_border_color"`
330	// ShowStackedTitleBorder enables the separator line below stacked pane titles
331	ShowStackedTitleBorder bool `mapstructure:"show_stacked_title_border" yaml:"show_stacked_title_border" json:"show_stacked_title_border"`
332	// PaneModeBorderColor for the pane mode indicator border (CSS color value or theme variable)
333	// Defaults to "#4A90E2" (blue) if not set
334	PaneModeBorderColor string `mapstructure:"pane_mode_border_color" yaml:"pane_mode_border_color" json:"pane_mode_border_color"`
335	// TabModeBorderColor for the tab mode indicator border (CSS color value or theme variable)
336	// Defaults to "#FFA500" (orange) if not set - MUST be different from PaneModeBorderColor
337	TabModeBorderColor string `mapstructure:"tab_mode_border_color" yaml:"tab_mode_border_color" json:"tab_mode_border_color"`
338	// TransitionDuration in milliseconds for border animations
339	TransitionDuration int `mapstructure:"transition_duration" yaml:"transition_duration" json:"transition_duration"`
340	// BorderRadius in pixels for pane border corners
341	BorderRadius int `mapstructure:"border_radius" yaml:"border_radius" json:"border_radius"`
342	// UIScale is a multiplier for UI elements like title bars (1.0 = 100%, 1.2 = 120%)
343	UIScale float64 `mapstructure:"ui_scale" yaml:"ui_scale" json:"ui_scale"`
344}
345
346// Manager handles configuration loading, watching, and reloading.
347type Manager struct {
348	config    *Config
349	viper     *viper.Viper
350	mu        sync.RWMutex
351	callbacks []func(*Config)
352	watching  bool
353}
354
355// NewManager creates a new configuration manager.
356func NewManager() (*Manager, error) {
357	v := viper.New()
358
359	// Configure Viper - supports yaml, json, toml automatically
360	v.SetConfigName("config") // Will find config.yaml, config.json, config.toml, etc.
361
362	// Add config paths
363	configDir, err := GetConfigDir()
364	if err != nil {
365		return nil, fmt.Errorf("failed to determine config directory: %w\nCheck XDG_CONFIG_HOME environment variable or HOME directory", err)
366	}
367	v.AddConfigPath(configDir)
368	v.AddConfigPath(".") // Current directory for development
369
370	// Set up environment variable support
371	v.SetEnvPrefix("DUMB_BROWSER")
372	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
373	v.AutomaticEnv()
374
375	// Note: Most environment variables are handled automatically via AutomaticEnv()
376	// with the DUMB_BROWSER_ prefix (e.g., DUMB_BROWSER_DATABASE_PATH).
377	// The explicit bindings below are only for special cases with different naming patterns.
378
379	// Explicit bindings for DUMBER_* prefix (different from DUMB_BROWSER_)
380	if err := v.BindEnv("rendering_mode", "DUMBER_RENDERING_MODE"); err != nil {
381		return nil, fmt.Errorf("failed to bind DUMBER_RENDERING_MODE: %w", err)
382	}
383	if err := v.BindEnv("use_dom_zoom", "DUMBER_USE_DOM_ZOOM"); err != nil {
384		return nil, fmt.Errorf("failed to bind DUMBER_USE_DOM_ZOOM: %w", err)
385	}
386	if err := v.BindEnv("default_zoom", "DUMBER_DEFAULT_ZOOM"); err != nil {
387		return nil, fmt.Errorf("failed to bind DUMBER_DEFAULT_ZOOM: %w", err)
388	}
389
390	// Video acceleration environment variable bindings
391	// These use system-standard env vars (LIBVA_*, GST_*, WEBKIT_*) and DUMBER_* prefix
392	videoAccelEnvBindings := map[string]string{
393		"video_acceleration.enable_vaapi":       "DUMBER_VIDEO_ACCELERATION_ENABLE",
394		"video_acceleration.auto_detect_gpu":    "DUMBER_VIDEO_AUTO_DETECT",
395		"video_acceleration.vaapi_driver_name":  "LIBVA_DRIVER_NAME",
396		"video_acceleration.enable_all_drivers": "GST_VAAPI_ALL_DRIVERS",
397		"video_acceleration.legacy_vaapi":       "WEBKIT_GST_ENABLE_LEGACY_VAAPI",
398	}
399
400	for key, env := range videoAccelEnvBindings {
401		if err := v.BindEnv(key, env); err != nil {
402			return nil, fmt.Errorf("failed to bind environment variable %s: %w", env, err)
403		}
404	}
405
406	// Codec preferences environment variable bindings
407	// These use DUMBER_* prefix for shorter, more convenient env var names
408	codecEnvBindings := map[string]string{
409		"codec_preferences.preferred_codecs":             "DUMBER_PREFERRED_CODECS",
410		"codec_preferences.force_av1":                    "DUMBER_FORCE_AV1",
411		"codec_preferences.block_vp9":                    "DUMBER_BLOCK_VP9",
412		"codec_preferences.block_vp8":                    "DUMBER_BLOCK_VP8",
413		"codec_preferences.av1_hardware_only":            "DUMBER_AV1_HW_ONLY",
414		"codec_preferences.disable_vp9_hardware":         "DUMBER_DISABLE_VP9_HW",
415		"codec_preferences.video_buffer_size_mb":         "DUMBER_VIDEO_BUFFER_MB",
416		"codec_preferences.queue_buffer_time_sec":        "DUMBER_QUEUE_BUFFER_SEC",
417		"codec_preferences.custom_user_agent":            "DUMBER_CUSTOM_UA",
418		"codec_preferences.av1_max_resolution":           "DUMBER_AV1_MAX_RES",
419		"codec_preferences.disable_twitch_codec_control": "DUMBER_DISABLE_TWITCH_CODEC",
420	}
421
422	for key, env := range codecEnvBindings {
423		if err := v.BindEnv(key, env); err != nil {
424			return nil, fmt.Errorf("failed to bind environment variable %s: %w", env, err)
425		}
426	}
427
428	return &Manager{
429		viper:     v,
430		callbacks: make([]func(*Config), 0),
431	}, nil
432}
433
434// Load loads the configuration from file and environment variables.
435func (m *Manager) Load() error {
436	m.mu.Lock()
437	defer m.mu.Unlock()
438
439	// Ensure directories exist
440	if err := EnsureDirectories(); err != nil {
441		return fmt.Errorf("failed to ensure directories: %w", err)
442	}
443
444	// Set defaults
445	m.setDefaults()
446
447	// Read config file if it exists
448	if err := m.viper.ReadInConfig(); err != nil {
449		var configFileNotFoundError viper.ConfigFileNotFoundError
450		if errors.As(err, &configFileNotFoundError) {
451			// Config file not found, create default one
452			if err := m.createDefaultConfig(); err != nil {
453				configDir, _ := GetConfigDir()
454				return fmt.Errorf("failed to create default config at %s: %w\nTry creating the directory manually or check permissions", configDir, err)
455			}
456			// Re-read the newly created config file
457			if err := m.viper.ReadInConfig(); err != nil {
458				return fmt.Errorf("failed to read newly created config file: %w\nThe config file was created but couldn't be read. Please check the file format", err)
459			}
460		} else {
461			configFile := m.viper.ConfigFileUsed()
462			if configFile == "" {
463				configDir, _ := GetConfigDir()
464				configFile = filepath.Join(configDir, "config.*")
465			}
466			return fmt.Errorf("failed to read config file at %s: %w\nCheck the file format (must be valid TOML, JSON, or YAML) and permissions", configFile, err)
467		}
468	}
469
470	// Unmarshal into config struct
471	config := &Config{}
472	if err := m.viper.Unmarshal(config); err != nil {
473		configFile := m.viper.ConfigFileUsed()
474		return fmt.Errorf("failed to parse config file at %s: %w\nCheck for syntax errors, invalid values, or type mismatches", configFile, err)
475	}
476
477	// Set database path if not specified
478	if config.Database.Path == "" {
479		dbPath, err := GetDatabaseFile()
480		if err != nil {
481			return fmt.Errorf("failed to get database path: %w", err)
482		}
483		config.Database.Path = dbPath
484	}
485
486	// Normalize/validate rendering mode
487	switch strings.ToLower(string(config.RenderingMode)) {
488	case "", string(RenderingModeAuto):
489		config.RenderingMode = RenderingModeAuto
490	case string(RenderingModeGPU):
491		config.RenderingMode = RenderingModeGPU
492	case string(RenderingModeCPU):
493		config.RenderingMode = RenderingModeCPU
494	default:
495		config.RenderingMode = RenderingModeAuto
496	}
497
498	// Auto-detect GPU if enabled and driver name is not set
499	if config.VideoAcceleration.AutoDetectGPU && config.VideoAcceleration.VAAPIDriverName == "" {
500		gpuInfo := gpu.DetectGPU()
501		if gpuInfo.SupportsVAAPI() {
502			config.VideoAcceleration.VAAPIDriverName = gpuInfo.GetVAAPIDriverName()
503		}
504	}
505
506	// Validate and configure codec preferences
507	config = m.validateAndConfigureCodecPreferences(config)
508
509	// Validate ColorScheme setting
510	m.validateColorScheme(config)
511
512	// Validate all config values
513	if err := validateConfig(config); err != nil {
514		return fmt.Errorf("configuration validation failed: %w", err)
515	}
516
517	m.config = config
518	return nil
519}
520
521// Get returns the current configuration (thread-safe).
522func (m *Manager) Get() *Config {
523	m.mu.RLock()
524	defer m.mu.RUnlock()
525
526	// Return a copy to prevent external modification
527	configCopy := *m.config
528	return &configCopy
529}
530
531// Watch starts watching the config file for changes and reloads automatically.
532func (m *Manager) Watch() error {
533	m.mu.Lock()
534	defer m.mu.Unlock()
535
536	if m.watching {
537		return nil // Already watching
538	}
539
540	m.viper.WatchConfig()
541	m.viper.OnConfigChange(func(_ fsnotify.Event) {
542		// Reload config
543		if err := m.reload(); err != nil {
544			fmt.Fprintf(os.Stderr, "Warning: failed to reload config: %v\n", err)
545			return
546		}
547
548		// Notify callbacks
549		m.mu.RLock()
550		config := m.config
551		callbacks := make([]func(*Config), len(m.callbacks))
552		copy(callbacks, m.callbacks)
553		m.mu.RUnlock()
554
555		for _, callback := range callbacks {
556			callback(config)
557		}
558	})
559
560	m.watching = true
561	return nil
562}
563
564// OnConfigChange registers a callback function to be called when config changes.
565func (m *Manager) OnConfigChange(callback func(*Config)) {
566	m.mu.Lock()
567	defer m.mu.Unlock()
568
569	m.callbacks = append(m.callbacks, callback)
570}
571
572// reload reloads the configuration (internal method, must be called with lock).
573func (m *Manager) reload() error {
574	if err := m.viper.ReadInConfig(); err != nil {
575		return err
576	}
577
578	config := &Config{}
579	if err := m.viper.Unmarshal(config); err != nil {
580		return err
581	}
582
583	// Set database path if not specified
584	if config.Database.Path == "" {
585		dbPath, err := GetDatabaseFile()
586		if err != nil {
587			return fmt.Errorf("failed to get database path: %w", err)
588		}
589		config.Database.Path = dbPath
590	}
591
592	// Normalize/validate rendering mode
593	switch strings.ToLower(string(config.RenderingMode)) {
594	case "", string(RenderingModeAuto):
595		config.RenderingMode = RenderingModeAuto
596	case string(RenderingModeGPU):
597		config.RenderingMode = RenderingModeGPU
598	case string(RenderingModeCPU):
599		config.RenderingMode = RenderingModeCPU
600	default:
601		config.RenderingMode = RenderingModeAuto
602	}
603
604	// Auto-detect GPU if enabled and driver name is not set
605	if config.VideoAcceleration.AutoDetectGPU && config.VideoAcceleration.VAAPIDriverName == "" {
606		gpuInfo := gpu.DetectGPU()
607		if gpuInfo.SupportsVAAPI() {
608			config.VideoAcceleration.VAAPIDriverName = gpuInfo.GetVAAPIDriverName()
609		}
610	}
611
612	// Validate and configure codec preferences
613	config = m.validateAndConfigureCodecPreferences(config)
614
615	// Validate ColorScheme setting
616	m.validateColorScheme(config)
617
618	// Validate all config values
619	if err := validateConfig(config); err != nil {
620		return fmt.Errorf("configuration validation failed: %w", err)
621	}
622
623	m.config = config
624	return nil
625}
626
627// setDefaults sets default configuration values in Viper.
628func (m *Manager) setDefaults() {
629	defaults := DefaultConfig()
630
631	// Note: Database.Path is set dynamically in Load(), no defaults needed
632
633	// Note: Browser config removed - we build our own browser
634
635	// History defaults
636	m.viper.SetDefault("history.max_entries", defaults.History.MaxEntries)
637	m.viper.SetDefault("history.retention_period_days", defaults.History.RetentionPeriodDays)
638	m.viper.SetDefault("history.cleanup_interval_days", defaults.History.CleanupIntervalDays)
639
640	// Search shortcuts defaults
641	m.viper.SetDefault("search_shortcuts", defaults.SearchShortcuts)
642	m.viper.SetDefault("default_search_engine", defaults.DefaultSearchEngine)
643
644	// Dmenu defaults
645	m.viper.SetDefault("dmenu.max_history_items", defaults.Dmenu.MaxHistoryItems)
646	m.viper.SetDefault("dmenu.show_visit_count", defaults.Dmenu.ShowVisitCount)
647	m.viper.SetDefault("dmenu.show_last_visited", defaults.Dmenu.ShowLastVisited)
648	m.viper.SetDefault("dmenu.history_prefix", defaults.Dmenu.HistoryPrefix)
649	m.viper.SetDefault("dmenu.shortcut_prefix", defaults.Dmenu.ShortcutPrefix)
650	m.viper.SetDefault("dmenu.url_prefix", defaults.Dmenu.URLPrefix)
651	m.viper.SetDefault("dmenu.date_format", defaults.Dmenu.DateFormat)
652	m.viper.SetDefault("dmenu.sort_by_visit_count", defaults.Dmenu.SortByVisitCount)
653
654	// Logging defaults
655	m.viper.SetDefault("logging.level", defaults.Logging.Level)
656	m.viper.SetDefault("logging.format", defaults.Logging.Format)
657	m.viper.SetDefault("logging.filename", defaults.Logging.Filename)
658	m.viper.SetDefault("logging.max_size", defaults.Logging.MaxSize)
659	m.viper.SetDefault("logging.max_backups", defaults.Logging.MaxBackups)
660	m.viper.SetDefault("logging.max_age", defaults.Logging.MaxAge)
661	m.viper.SetDefault("logging.compress", defaults.Logging.Compress)
662	m.viper.SetDefault("logging.log_dir", defaults.Logging.LogDir)
663	m.viper.SetDefault("logging.enable_file_log", defaults.Logging.EnableFileLog)
664	m.viper.SetDefault("logging.capture_stdout", defaults.Logging.CaptureStdout)
665	m.viper.SetDefault("logging.capture_stderr", defaults.Logging.CaptureStderr)
666	m.viper.SetDefault("logging.capture_c_output", defaults.Logging.CaptureCOutput)
667	m.viper.SetDefault("logging.debug_file", defaults.Logging.DebugFile)
668	m.viper.SetDefault("logging.verbose_webkit", defaults.Logging.VerboseWebKit)
669
670	// Debug defaults
671	m.viper.SetDefault("debug.enable_webkit_debug", defaults.Debug.EnableWebKitDebug)
672	m.viper.SetDefault("debug.webkit_debug_categories", defaults.Debug.WebKitDebugCategories)
673	m.viper.SetDefault("debug.enable_filtering_debug", defaults.Debug.EnableFilteringDebug)
674	m.viper.SetDefault("debug.enable_webview_debug", defaults.Debug.EnableWebViewDebug)
675	m.viper.SetDefault("debug.log_webkit_crashes", defaults.Debug.LogWebKitCrashes)
676	m.viper.SetDefault("debug.enable_script_debug", defaults.Debug.EnableScriptDebug)
677	m.viper.SetDefault("debug.enable_general_debug", defaults.Debug.EnableGeneralDebug)
678	m.viper.SetDefault("debug.enable_workspace_debug", defaults.Debug.EnableWorkspaceDebug)
679	m.viper.SetDefault("debug.enable_focus_debug", defaults.Debug.EnableFocusDebug)
680	m.viper.SetDefault("debug.enable_css_debug", defaults.Debug.EnableCSSDebug)
681	m.viper.SetDefault("debug.enable_focus_metrics", defaults.Debug.EnableFocusMetrics)
682	m.viper.SetDefault("debug.enable_pane_close_debug", defaults.Debug.EnablePaneCloseDebug)
683
684	// Appearance defaults
685	m.viper.SetDefault("appearance.sans_font", defaults.Appearance.SansFont)
686	m.viper.SetDefault("appearance.serif_font", defaults.Appearance.SerifFont)
687	m.viper.SetDefault("appearance.monospace_font", defaults.Appearance.MonospaceFont)
688	m.viper.SetDefault("appearance.default_font_size", defaults.Appearance.DefaultFontSize)
689	m.viper.SetDefault("appearance.light_palette", defaults.Appearance.LightPalette)
690	m.viper.SetDefault("appearance.dark_palette", defaults.Appearance.DarkPalette)
691	m.viper.SetDefault("appearance.color_scheme", defaults.Appearance.ColorScheme)
692
693	// Video acceleration defaults
694	m.viper.SetDefault("video_acceleration.enable_vaapi", defaults.VideoAcceleration.EnableVAAPI)
695	m.viper.SetDefault("video_acceleration.auto_detect_gpu", defaults.VideoAcceleration.AutoDetectGPU)
696	m.viper.SetDefault("video_acceleration.vaapi_driver_name", defaults.VideoAcceleration.VAAPIDriverName)
697	m.viper.SetDefault("video_acceleration.enable_all_drivers", defaults.VideoAcceleration.EnableAllDrivers)
698	m.viper.SetDefault("video_acceleration.legacy_vaapi", defaults.VideoAcceleration.LegacyVAAPI)
699
700	// Codec preferences defaults
701	m.viper.SetDefault("codec_preferences.preferred_codecs", defaults.CodecPreferences.PreferredCodecs)
702	m.viper.SetDefault("codec_preferences.force_av1", defaults.CodecPreferences.ForceAV1)
703	m.viper.SetDefault("codec_preferences.block_vp9", defaults.CodecPreferences.BlockVP9)
704	m.viper.SetDefault("codec_preferences.block_vp8", defaults.CodecPreferences.BlockVP8)
705	m.viper.SetDefault("codec_preferences.av1_hardware_only", defaults.CodecPreferences.AV1HardwareOnly)
706	m.viper.SetDefault("codec_preferences.disable_vp9_hardware", defaults.CodecPreferences.DisableVP9Hardware)
707	m.viper.SetDefault("codec_preferences.video_buffer_size_mb", defaults.CodecPreferences.VideoBufferSizeMB)
708	m.viper.SetDefault("codec_preferences.queue_buffer_time_sec", defaults.CodecPreferences.QueueBufferTimeSec)
709	m.viper.SetDefault("codec_preferences.custom_user_agent", defaults.CodecPreferences.CustomUserAgent)
710	m.viper.SetDefault("codec_preferences.av1_max_resolution", defaults.CodecPreferences.AV1MaxResolution)
711	m.viper.SetDefault("codec_preferences.disable_twitch_codec_control", defaults.CodecPreferences.DisableTwitchCodecControl)
712
713	// Rendering defaults
714	m.viper.SetDefault("rendering_mode", string(RenderingModeGPU))
715	m.viper.SetDefault("use_dom_zoom", defaults.UseDomZoom)
716	m.viper.SetDefault("default_zoom", defaults.DefaultZoom)
717
718	// Workspace defaults
719	m.viper.SetDefault("workspace.pane_mode.activation_shortcut", defaults.Workspace.PaneMode.ActivationShortcut)
720	m.viper.SetDefault("workspace.pane_mode.timeout_ms", defaults.Workspace.PaneMode.TimeoutMilliseconds)
721	m.viper.SetDefault("workspace.pane_mode.actions", defaults.Workspace.PaneMode.Actions)
722	m.viper.SetDefault("workspace.tab_mode.activation_shortcut", defaults.Workspace.TabMode.ActivationShortcut)
723	m.viper.SetDefault("workspace.tab_mode.timeout_ms", defaults.Workspace.TabMode.TimeoutMilliseconds)
724	m.viper.SetDefault("workspace.tab_mode.actions", defaults.Workspace.TabMode.Actions)
725	m.viper.SetDefault("workspace.tabs.new_tab", defaults.Workspace.Tabs.NewTab)
726	m.viper.SetDefault("workspace.tabs.close_tab", defaults.Workspace.Tabs.CloseTab)
727	m.viper.SetDefault("workspace.tabs.next_tab", defaults.Workspace.Tabs.NextTab)
728	m.viper.SetDefault("workspace.tabs.previous_tab", defaults.Workspace.Tabs.PreviousTab)
729	m.viper.SetDefault("workspace.tab_bar_position", defaults.Workspace.TabBarPosition)
730	m.viper.SetDefault("workspace.popups.behavior", string(defaults.Workspace.Popups.Behavior))
731	m.viper.SetDefault("workspace.popups.placement", defaults.Workspace.Popups.Placement)
732	m.viper.SetDefault("workspace.popups.open_in_new_pane", defaults.Workspace.Popups.OpenInNewPane)
733	m.viper.SetDefault("workspace.popups.follow_pane_context", defaults.Workspace.Popups.FollowPaneContext)
734	// New popup behaviour defaults
735	m.viper.SetDefault("workspace.popups.blank_target_behavior", defaults.Workspace.Popups.BlankTargetBehavior)
736	m.viper.SetDefault("workspace.popups.enable_smart_detection", defaults.Workspace.Popups.EnableSmartDetection)
737	m.viper.SetDefault("workspace.popups.oauth_auto_close", defaults.Workspace.Popups.OAuthAutoClose)
738	m.viper.SetDefault("workspace.styling.border_width", defaults.Workspace.Styling.BorderWidth)
739	m.viper.SetDefault("workspace.styling.border_color", defaults.Workspace.Styling.BorderColor)
740	m.viper.SetDefault("workspace.styling.inactive_border_width", defaults.Workspace.Styling.InactiveBorderWidth)
741	m.viper.SetDefault("workspace.styling.inactive_border_color", defaults.Workspace.Styling.InactiveBorderColor)
742	m.viper.SetDefault("workspace.styling.show_stacked_title_border", defaults.Workspace.Styling.ShowStackedTitleBorder)
743	m.viper.SetDefault("workspace.styling.pane_mode_border_color", defaults.Workspace.Styling.PaneModeBorderColor)
744	m.viper.SetDefault("workspace.styling.transition_duration", defaults.Workspace.Styling.TransitionDuration)
745	m.viper.SetDefault("workspace.styling.border_radius", defaults.Workspace.Styling.BorderRadius)
746	m.viper.SetDefault("workspace.styling.ui_scale", defaults.Workspace.Styling.UIScale)
747}
748
749// createDefaultConfig creates a default configuration file.
750func (m *Manager) createDefaultConfig() error {
751	configFile, err := GetConfigFile()
752	if err != nil {
753		return err
754	}
755
756	// Create config directory if it doesn't exist
757	if err := os.MkdirAll(filepath.Dir(configFile), dirPerm); err != nil {
758		return err
759	}
760
761	// Use Viper's SafeWriteConfigAs to avoid duplicate keys
762	if err := m.viper.SafeWriteConfigAs(configFile); err != nil {
763		return fmt.Errorf("failed to write config file: %w", err)
764	}
765
766	fmt.Printf("Created default configuration file: %s (TOML format)\n", configFile)
767
768	// Generate JSON schema file only for JSON configs (used for IDE autocompletion)
769	if filepath.Ext(configFile) == ".json" {
770		if err := GenerateSchemaFile(); err != nil {
771			// Log error but don't fail config creation
772			fmt.Fprintf(os.Stderr, "Warning: failed to generate config schema: %v\n", err)
773		}
774	}
775
776	return nil
777}
778
779// GetConfigFile returns the path to the configuration file being used.
780func (m *Manager) GetConfigFile() string {
781	return m.viper.ConfigFileUsed()
782}
783
784// New returns a new default configuration instance.
785// This is a convenience function for getting default config without the full manager.
786func New() *Config {
787	return DefaultConfig()
788}
789
790// Global configuration manager instance
791var globalManager *Manager
792var globalManagerOnce sync.Once
793
794// Init initializes the global configuration manager.
795func Init() error {
796	var err error
797	globalManagerOnce.Do(func() {
798		globalManager, err = NewManager()
799		if err != nil {
800			return
801		}
802		err = globalManager.Load()
803	})
804	return err
805}
806
807// Get returns the global configuration.
808func Get() *Config {
809	if globalManager == nil {
810		// Return defaults if not initialized
811		return DefaultConfig()
812	}
813	return globalManager.Get()
814}
815
816// Watch starts watching the global configuration for changes.
817func Watch() error {
818	if globalManager == nil {
819		return fmt.Errorf("configuration not initialized")
820	}
821	return globalManager.Watch()
822}
823
824// OnConfigChange registers a callback for global configuration changes.
825func OnConfigChange(callback func(*Config)) {
826	if globalManager == nil {
827		return
828	}
829	globalManager.OnConfigChange(callback)
830}
831
832// validateAndConfigureCodecPreferences validates and auto-configures codec preferences based on GPU capabilities
833func (m *Manager) validateAndConfigureCodecPreferences(config *Config) *Config {
834	// Validate codec preferences
835	if config.CodecPreferences.PreferredCodecs == "" {
836		config.CodecPreferences.PreferredCodecs = "av1,h264,vp8"
837		fmt.Printf("Config: Set default codec preferences: %s\n", config.CodecPreferences.PreferredCodecs)
838	}
839
840	// Auto-configure based on GPU capabilities
841	if config.VideoAcceleration.AutoDetectGPU {
842		gpuInfo := gpu.DetectGPU()
843
844		// Check AV1 hardware support
845		if config.CodecPreferences.AV1HardwareOnly && !gpuInfo.SupportsAV1Hardware() {
846			// Disable AV1 hardware-only if GPU doesn't support it
847			config.CodecPreferences.AV1HardwareOnly = false
848			fmt.Printf("Config: GPU doesn't support AV1 hardware, enabling software fallback\n")
849		}
850
851		// Get detailed AV1 capabilities
852		av1Caps := gpuInfo.GetAV1HardwareCapabilities()
853		if av1Caps["decode"] {
854			logging.Info("GPU supports AV1 hardware decode")
855
856			// If GPU supports AV1, prefer it over VP9
857			if !config.CodecPreferences.ForceAV1 &&
858				!strings.HasPrefix(config.CodecPreferences.PreferredCodecs, "av1") {
859				config.CodecPreferences.PreferredCodecs = "av1," + config.CodecPreferences.PreferredCodecs
860				fmt.Printf("Config: Auto-enabled AV1 preference due to hardware support\n")
861			}
862		} else {
863			// If no AV1 support, ensure VP9 hardware is disabled to prevent issues
864			if !config.CodecPreferences.DisableVP9Hardware {
865				config.CodecPreferences.DisableVP9Hardware = true
866				fmt.Printf("Config: Auto-disabled VP9 hardware acceleration (no AV1 fallback)\n")
867			}
868		}
869
870		// Log GPU-specific codec capabilities
871		logging.Info(fmt.Sprintf("%s GPU codec capabilities - AV1: decode=%t, encode=%t, 10bit=%t",
872			gpuInfo.Vendor, av1Caps["decode"], av1Caps["encode"], av1Caps["10bit"]))
873	}
874
875	return config
876}
877
878// validateColorScheme validates and normalizes the ColorScheme setting
879func (m *Manager) validateColorScheme(config *Config) {
880	switch config.Appearance.ColorScheme {
881	case "prefer-dark", "prefer-light", ThemeDefault, "":
882		// Valid values - no changes needed
883		// Empty string is treated the same as "default"
884		if config.Appearance.ColorScheme == "" {
885			config.Appearance.ColorScheme = ThemeDefault
886			logging.Info("Config: ColorScheme not set, defaulting to '" + ThemeDefault + "' (follows system)")
887		}
888	default:
889		// Invalid value - warn and reset to default
890		logging.Info(fmt.Sprintf("Config: Invalid color_scheme value '%s', valid values are: 'prefer-dark', 'prefer-light', '"+ThemeDefault+"'. Resetting to '"+ThemeDefault+"'",
891			config.Appearance.ColorScheme))
892		config.Appearance.ColorScheme = ThemeDefault
893	}
894}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 8

Tags 42

↑↓ moveenter openesc close