v0.14.0 76d1892

webview.go RawHistoryFolder

1package browser
2
3import (
4	"context"
5	"encoding/json"
6	"fmt"
7	"log"
8	"os"
9	"path/filepath"
10	"time"
11
12	"github.com/bnema/dumber/internal/app/constants"
13	"github.com/bnema/dumber/internal/app/control"
14	"github.com/bnema/dumber/internal/app/messaging"
15	"github.com/bnema/dumber/internal/config"
16	"github.com/bnema/dumber/internal/filtering"
17	"github.com/bnema/dumber/internal/services"
18	"github.com/bnema/dumber/pkg/webkit"
19)
20
21// Note: Memory management and color palettes are now handled at the application level
22// The gotk4 webkit.Config only contains basic WebKit settings
23
24func (app *BrowserApp) buildWebkitConfig() (*webkit.Config, error) {
25	// Ensure data directories exist for WebKit
26	dataDir, err := config.GetDataDir()
27	if err != nil {
28		return nil, err
29	}
30	stateDir, err := config.GetStateDir()
31	if err != nil {
32		return nil, err
33	}
34
35	webkitData := filepath.Join(dataDir, "webkit")
36	webkitCache := filepath.Join(stateDir, "webkit-cache")
37	if err := os.MkdirAll(webkitData, constants.DirPerm); err != nil {
38		return nil, err
39	}
40	if err := os.MkdirAll(webkitCache, constants.DirPerm); err != nil {
41		return nil, err
42	}
43
44	// Build WebKit configuration with data directories for persistence
45	cfg := &webkit.Config{
46		UserAgent:             buildUserAgent(app.config),
47		EnableJavaScript:      true,
48		EnableWebGL:           true,
49		EnableMediaStream:     true,
50		HardwareAcceleration:  true,
51		DefaultFontSize:       app.config.Appearance.DefaultFontSize,
52		MinimumFontSize:       8,
53		EnablePageCache:       true, // Instant back/forward navigation (bfcache)
54		EnableSmoothScrolling: true, // Smooth scrolling animations
55		DataDir:               webkitData,
56		CacheDir:              webkitCache,
57		AppearanceConfigJSON:  app.buildAppearanceConfigJSON(),
58		CreateWindow:          true, // Default to creating a window for standalone WebViews
59	}
60
61	return cfg, nil
62}
63
64// buildUserAgent constructs the user agent string from config
65func buildUserAgent(cfg *config.Config) string {
66	if cfg.CodecPreferences.CustomUserAgent != "" {
67		return cfg.CodecPreferences.CustomUserAgent
68	}
69	// Use default WebKit user agent
70	return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
71}
72
73// buildAppearanceConfigJSON builds the palette configuration as JSON
74// The GUI expects window.__dumber_palette with just the palette data
75func (app *BrowserApp) buildAppearanceConfigJSON() string {
76	if app.config == nil {
77		return ""
78	}
79
80	// Build palette config in the format main-world.ts expects
81	// It looks for window.__dumber_palette = { "light": {...}, "dark": {...} }
82	paletteConfig := map[string]interface{}{
83		"light": map[string]string{
84			"background":      app.config.Appearance.LightPalette.Background,
85			"surface":         app.config.Appearance.LightPalette.Surface,
86			"surface_variant": app.config.Appearance.LightPalette.SurfaceVariant,
87			"text":            app.config.Appearance.LightPalette.Text,
88			"muted":           app.config.Appearance.LightPalette.Muted,
89			"accent":          app.config.Appearance.LightPalette.Accent,
90			"border":          app.config.Appearance.LightPalette.Border,
91		},
92		"dark": map[string]string{
93			"background":      app.config.Appearance.DarkPalette.Background,
94			"surface":         app.config.Appearance.DarkPalette.Surface,
95			"surface_variant": app.config.Appearance.DarkPalette.SurfaceVariant,
96			"text":            app.config.Appearance.DarkPalette.Text,
97			"muted":           app.config.Appearance.DarkPalette.Muted,
98			"accent":          app.config.Appearance.DarkPalette.Accent,
99			"border":          app.config.Appearance.DarkPalette.Border,
100		},
101	}
102
103	payload, err := json.Marshal(paletteConfig)
104	if err != nil {
105		log.Printf("[webview] Failed to marshal palette config: %v", err)
106		return ""
107	}
108
109	return string(payload)
110}
111
112func (app *BrowserApp) buildPane(view *webkit.WebView) (*BrowserPane, error) {
113	pane := &BrowserPane{
114		webView: view,
115	}
116
117	pane.clipboardController = control.NewClipboardController(view)
118	pane.zoomController = control.NewZoomController(app.browserService, view)
119	pane.navigationController = control.NewNavigationController(
120		app.parserService,
121		app.browserService,
122		view,
123		pane.zoomController,
124	)
125	pane.messageHandler = messaging.NewHandler(app.parserService, app.browserService)
126	pane.messageHandler.SetWebView(view)
127	pane.messageHandler.SetNavigationController(pane.navigationController)
128	pane.shortcutHandler = NewShortcutHandler(view, pane.clipboardController, app.config, app)
129
130	pane.zoomController.RegisterHandlers()
131	pane.shortcutHandler.RegisterShortcuts()
132
133	// Register navigation handler for workspace focus events if workspace exists
134	if app.workspace != nil {
135		app.workspace.RegisterNavigationHandler(view)
136	}
137
138	return pane, nil
139}
140
141func (app *BrowserApp) createPaneForView(view *webkit.WebView) (*BrowserPane, error) {
142	pane, err := app.buildPane(view)
143	if err != nil {
144		return nil, err
145	}
146
147	// Generate unique pane ID
148	pane.SetID(fmt.Sprintf("pane-%d-%p", time.Now().Unix(), view))
149	pane.initializeGUITracking()
150
151	// GUI manager will be loaded on-demand when needed
152	log.Printf("[webview] Created pane for webview: %d", view.ID())
153
154	app.attachPaneHandlers(pane)
155	return pane, nil
156}
157
158func (app *BrowserApp) attachPaneHandlers(pane *BrowserPane) {
159	if pane == nil || pane.webView == nil {
160		return
161	}
162
163	pane.webView.RegisterTitleChangedHandler(func(title string) {
164		if title == "" {
165			return
166		}
167		url := pane.webView.GetCurrentURL()
168		if url == "" {
169			return
170		}
171
172		// Update database with new title
173		go func(url, title string) {
174			ctx := context.Background()
175			if err := app.browserService.UpdatePageTitle(ctx, url, title); err != nil {
176				log.Printf("Warning: failed to update page title: %v", err)
177			}
178		}(url, title)
179
180		// Update stacked pane title bar if this pane is in a stack
181		if app.workspace != nil {
182			app.workspace.UpdateTitleBar(pane.webView, title)
183		}
184	})
185
186	pane.webView.RegisterScriptMessageHandler(func(payload string) {
187		if app.workspace != nil && shouldFocusForScriptMessage(payload) {
188			app.workspace.focusByView(pane.webView)
189		}
190		pane.messageHandler.Handle(payload)
191	})
192
193	if pane.messageHandler != nil && pane.navigationController != nil {
194		pane.messageHandler.SetNavigationController(pane.navigationController)
195	}
196
197	// Setup WebKit-native popup lifecycle using create/ready-to-show/close signals
198	if app.workspace != nil {
199		node := app.workspace.GetNodeForWebView(pane.webView)
200		if node != nil {
201			app.workspace.setupPopupHandling(pane.webView, node)
202			log.Printf("[webview] Setup native popup handling for WebView ID: %d", pane.webView.ID())
203		}
204	}
205}
206
207// shouldFocusForScriptMessage filters script messages and only allows focus handoff
208// for explicit user-driven actions (navigation, history commands, popup lifecycle).
209// Background bootstrap messages (palette sync, workspace bridge chatter, etc.) are
210// ignored so they don't steal focus from the user's active pane.
211func shouldFocusForScriptMessage(payload string) bool {
212	var msg messaging.Message
213	if err := json.Unmarshal([]byte(payload), &msg); err != nil {
214		return true // keep legacy behaviour if parsing fails
215	}
216
217	switch msg.Type {
218	case "navigate", "query", "wails", "history_recent", "history_stats", "history_search", "history_delete", "close-popup":
219		return true
220	default:
221		return false
222	}
223}
224
225// createWebView creates and configures the WebView
226func (app *BrowserApp) createWebView() error {
227	log.Printf("Creating WebView (native backend expected: %v)", webkit.IsNativeAvailable())
228
229	cfg, err := app.buildWebkitConfig()
230	if err != nil {
231		return err
232	}
233
234	// Note: Window creation is now handled automatically by webkit.NewWebView
235	view, err := webkit.NewWebView(cfg)
236
237	if err != nil {
238		return err
239	}
240
241	pane, err := app.createPaneForView(view)
242	if err != nil {
243		return err
244	}
245
246	app.webView = view
247	app.zoomController = pane.zoomController
248	app.navigationController = pane.navigationController
249	app.clipboardController = pane.clipboardController
250	app.messageHandler = pane.messageHandler
251	app.shortcutHandler = pane.shortcutHandler
252
253	// Initialize tab manager (which manages workspaces)
254	window := view.Window()
255	if window != nil && app.tabManager == nil {
256		app.tabManager = NewTabManager(app, window)
257
258		// Determine initial URL
259		initialURL := "about:blank"
260
261		// Initialize tab system (creates root container with tab bar and first tab)
262		if err := app.tabManager.Initialize(initialURL); err != nil {
263			log.Printf("ERROR: failed to initialize tab manager: %v", err)
264			return err
265		}
266
267		// Set tab manager's root container as window content
268		rootContainer := app.tabManager.GetRootContainer()
269		if rootContainer != nil {
270			window.SetChild(rootContainer)
271			log.Printf("[tabs] Tab system initialized and set as window content")
272		} else {
273			log.Printf("ERROR: tab manager root container is nil")
274			return fmt.Errorf("failed to get tab manager root container")
275		}
276	}
277
278	// Initialize window-level global shortcuts AFTER tab manager is set up
279	if window != nil {
280		app.windowShortcutHandler = NewWindowShortcutHandler(window, app)
281		if app.windowShortcutHandler != nil {
282			log.Printf("Window-level global shortcuts initialized")
283		} else {
284			log.Printf("Warning: failed to initialize window-level shortcuts")
285		}
286	}
287
288	app.setupWebViewIntegration()
289
290	// Initialize FaviconService after WebView is created
291	if err := app.initializeFaviconService(); err != nil {
292		log.Printf("Warning: failed to initialize favicon service: %v", err)
293		// Continue without favicon service - not critical
294	}
295
296	// Apply initial zoom and show window
297	app.zoomController.ApplyInitialZoom()
298
299	log.Printf("Showing WebView window…")
300	if err := view.Show(); err != nil {
301		log.Printf("Warning: failed to show WebView: %v", err)
302	} else if !webkit.IsNativeAvailable() {
303		log.Printf("Notice: running without webkit_cgo tag — no native window will be displayed.")
304	}
305
306	return nil
307}
308
309// setupWebViewIntegration connects the WebView to browser services
310func (app *BrowserApp) setupWebViewIntegration() {
311	app.browserService.AttachWebView(app.webView)
312
313	// GUI bundle is loaded via WebKit user scripts in SetupUserContentManager
314	// Appearance config is also injected at document-start via UserContentManager
315
316	// Use native window as title updater
317	if win := app.webView.Window(); win != nil {
318		app.browserService.SetWindowTitleUpdater(win)
319	}
320}
321
322// initializeFaviconService creates and initializes the FaviconService
323func (app *BrowserApp) initializeFaviconService() error {
324	// Get the FaviconDatabase from the WebView
325	faviconDB := app.webView.GetFaviconDatabase()
326	if faviconDB == nil {
327		return fmt.Errorf("favicon database not available")
328	}
329
330	// Get the WebKit data directory
331	dataDir, err := config.GetDataDir()
332	if err != nil {
333		return fmt.Errorf("failed to get data directory: %w", err)
334	}
335	webkitData := filepath.Join(dataDir, "webkit")
336
337	// Create FaviconService
338	faviconService, err := services.NewFaviconService(faviconDB, app.queries, webkitData)
339	if err != nil {
340		return fmt.Errorf("failed to create favicon service: %w", err)
341	}
342
343	app.faviconService = faviconService
344	log.Printf("[favicon] FaviconService initialized successfully")
345	return nil
346}
347
348// setupContentBlocking initializes the content blocking system with proper timing
349func (app *BrowserApp) setupContentBlocking() error {
350	log.Printf("Initializing content blocking system...")
351
352	// Enable WebKit debug logging if requested
353	webkit.SetupWebKitDebugLogging()
354
355	defer func() {
356		if r := recover(); r != nil {
357			log.Printf("Content blocking setup panic recovered: %v", r)
358		}
359	}()
360
361	// Setup filter system
362	filterManager, err := filtering.SetupFilterSystem()
363	if err != nil {
364		log.Printf("Warning: Failed to setup filter system: %v", err)
365		return nil // Don't fail browser startup, continue without filters
366	}
367
368	// Store reference to filter manager
369	app.filterManager = filterManager
370
371	// Set up callback to apply network filters when they become ready
372	// This callback will be called from the async filter loading process
373	filterManager.SetFiltersReadyCallback(func() {
374		log.Printf("[filtering] Filters ready, applying to WebView...")
375
376		// Get the WebKit JSON rules from filter manager
377		filterJSON, err := filterManager.GetNetworkFilters()
378		if err != nil {
379			log.Printf("[filtering] Failed to get network filters: %v", err)
380			return
381		}
382
383		if len(filterJSON) == 0 {
384			log.Printf("[filtering] No network filters to apply")
385			return
386		}
387
388		log.Printf("[filtering] Got %d bytes of WebKit JSON rules", len(filterJSON))
389
390		// Apply filters to the WebView
391		// This must be done on the main thread since it touches GTK/WebKit
392		if app.webView != nil {
393			app.webView.RunOnMainThread(func() {
394				if err := app.webView.InitializeContentBlocking(filterJSON); err != nil {
395					log.Printf("[filtering] Failed to apply content filters: %v", err)
396				} else {
397					log.Printf("[filtering] ✅ Content blocking enabled successfully")
398				}
399			})
400		}
401	})
402
403	// Start async filter loading
404	// This allows filters to compile in the background while the browser starts
405	go func() {
406		if err := filtering.InitializeFiltersAsync(filterManager); err != nil {
407			log.Printf("Warning: failed to initialize filters asynchronously: %v", err)
408		}
409	}()
410
411	log.Printf("Content blocking system initialization started")
412	return nil
413}

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