v0.10.0 0f4e9eb

browser.go RawHistoryFolder

1package browser
2
3import (
4	"database/sql"
5	"embed"
6	"fmt"
7	"log"
8	"os"
9	"os/signal"
10	"runtime"
11	"syscall"
12
13	"github.com/bnema/dumber/internal/app/api"
14	"github.com/bnema/dumber/internal/app/control"
15	"github.com/bnema/dumber/internal/app/environment"
16	"github.com/bnema/dumber/internal/app/messaging"
17	"github.com/bnema/dumber/internal/config"
18	"github.com/bnema/dumber/internal/db"
19	"github.com/bnema/dumber/internal/filtering"
20	"github.com/bnema/dumber/internal/logging"
21	"github.com/bnema/dumber/internal/migrations"
22	"github.com/bnema/dumber/internal/services"
23	"github.com/bnema/dumber/pkg/webkit"
24)
25
26// BrowserApp represents the main browser application
27type BrowserApp struct {
28	version   string
29	commit    string
30	buildDate string
31	assets    embed.FS
32
33	// Core components
34	config   *config.Config
35	database *sql.DB
36	queries  *db.Queries
37
38	// Services
39	parserService  *services.ParserService
40	browserService *services.BrowserService
41
42	// WebView and controllers
43	webView              *webkit.WebView
44	zoomController       *control.ZoomController
45	navigationController *control.NavigationController
46	clipboardController  *control.ClipboardController
47
48	// Pane workspace management
49	panes      []*BrowserPane
50	activePane *BrowserPane
51	workspace  *WorkspaceManager
52
53	// Content filtering
54	filterManager *filtering.FilterManager
55
56	// Handlers
57	schemeHandler         *api.SchemeHandler
58	messageHandler        *messaging.Handler
59	shortcutHandler       *ShortcutHandler
60	windowShortcutHandler WindowShortcutHandlerInterface
61}
62
63// Run starts the browser application
64func Run(assets embed.FS, version, commit, buildDate string) {
65	log.Printf("Starting GUI mode (webkit_cgo=%v)", webkit.IsNativeAvailable())
66
67	app := &BrowserApp{
68		version:   version,
69		commit:    commit,
70		buildDate: buildDate,
71		assets:    assets,
72	}
73
74	if err := app.Initialize(); err != nil {
75		log.Printf("Failed to initialize browser: %v", err)
76		if webkit.IsNativeAvailable() {
77			runtime.UnlockOSThread()
78		}
79		os.Exit(1)
80	}
81
82	app.Run()
83}
84
85// Initialize sets up all browser components
86func (app *BrowserApp) Initialize() error {
87	// Setup media pipeline hardening
88	environment.SetupMediaPipeline()
89
90	// Initialize configuration
91	if err := config.Init(); err != nil {
92		return err
93	}
94	app.config = config.Get()
95
96	// Apply environment configurations
97	environment.ApplyCodecConfiguration(app.config.CodecPreferences)
98
99	// Setup crash handler
100	logging.SetupCrashHandler()
101
102	// Setup output capture if configured
103	if err := app.setupOutputCapture(); err != nil {
104		log.Printf("Warning: failed to setup output capture: %v", err)
105	}
106
107	// Initialize WebKit log capture if configured
108	if app.config.Logging.CaptureCOutput {
109		if err := webkit.InitWebKitLogCapture(); err != nil {
110			log.Printf("Warning: failed to initialize WebKit log capture: %v", err)
111		} else {
112			defer webkit.StopWebKitLogCapture()
113		}
114	}
115
116	log.Printf("Config initialized")
117
118	// Detect keyboard layout
119	environment.DetectAndSetKeyboardLocale()
120
121	// Initialize database
122	database, err := db.InitDB(app.config.Database.Path)
123	if err != nil {
124		return err
125	}
126	app.database = database
127
128	// Run database migrations
129	if err := migrations.RunEmbeddedMigrations(database); err != nil {
130		return fmt.Errorf("failed to run database migrations: %w", err)
131	}
132
133	app.queries = db.New(database)
134	log.Printf("Database opened at %s", app.config.Database.Path)
135
136	// Initialize services
137	app.parserService = services.NewParserService(app.config, app.queries)
138	app.browserService = services.NewBrowserService(app.config, app.queries)
139
140	// Initialize handlers
141	app.schemeHandler = api.NewSchemeHandler(app.assets, app.parserService, app.browserService)
142	app.messageHandler = messaging.NewHandler(app.parserService, app.browserService)
143
144	return nil
145}
146
147// Run executes the main browser loop
148func (app *BrowserApp) Run() {
149	defer app.cleanup()
150	defer logging.SetupPanicRecovery()
151
152	// Register custom scheme resolver
153	webkit.SetURISchemeResolver(func(uri string) (string, []byte, bool) {
154		return app.schemeHandler.Handle(uri, app.config)
155	})
156
157	// Create and setup WebView
158	if err := app.createWebView(); err != nil {
159		log.Printf("Warning: failed to create WebView: %v", err)
160		return
161	}
162
163	// Initialize content blocking
164	if err := app.setupContentBlocking(); err != nil {
165		log.Printf("Warning: failed to setup content blocking: %v", err)
166		// Continue without content blocking
167	}
168
169	// Handle browse command if present
170	app.navigationController.HandleBrowseCommand()
171
172	// Setup signal handling
173	app.setupSignalHandling()
174
175	// Run main loop
176	app.runMainLoop()
177}
178
179// cleanup handles cleanup on shutdown
180func (app *BrowserApp) cleanup() {
181	log.Printf("Starting browser cleanup...")
182
183	// Cleanup window shortcuts first
184	if app.windowShortcutHandler != nil {
185		log.Printf("Cleaning up window shortcuts")
186		app.windowShortcutHandler.Cleanup()
187		app.windowShortcutHandler = nil
188	}
189
190	// Cleanup all panes
191	if app.panes != nil {
192		log.Printf("Cleaning up %d panes", len(app.panes))
193		for i, pane := range app.panes {
194			if pane != nil {
195				log.Printf("Cleaning up pane %d (%s)", i, pane.ID())
196				pane.Cleanup()
197			}
198		}
199		app.panes = nil
200	}
201
202	// Cleanup workspace manager
203	if app.workspace != nil {
204		log.Printf("Cleaning up workspace manager")
205		// WorkspaceManager doesn't have explicit cleanup yet, but we clear the reference
206		app.workspace = nil
207	}
208
209	// Close database last
210	if app.database != nil {
211		log.Printf("Closing database")
212		if closeErr := app.database.Close(); closeErr != nil {
213			log.Printf("Warning: failed to close database: %v", closeErr)
214		}
215	}
216
217	log.Printf("Browser cleanup completed")
218}
219
220// setupOutputCapture initializes stdout/stderr capture if configured
221func (app *BrowserApp) setupOutputCapture() error {
222	if app.config.Logging.CaptureStdout || app.config.Logging.CaptureStderr {
223		log.Printf("Warning: stdout/stderr capture is experimental and may interfere with normal operations")
224		if logger := logging.GetLogger(); logger != nil {
225			outputCapture := logging.NewOutputCapture(logger)
226			if err := outputCapture.Start(); err != nil {
227				return err
228			}
229			// Note: defer outputCapture.Stop() should be handled by the caller
230		}
231	}
232	return nil
233}
234
235// setupSignalHandling configures graceful shutdown on signals
236func (app *BrowserApp) setupSignalHandling() {
237	sigChan := make(chan os.Signal, 1)
238	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
239
240	// Handle signals in a goroutine to quit the main loop
241	go func() {
242		sig := <-sigChan
243		log.Printf("Received signal %v - shutting down gracefully", sig)
244		webkit.QuitMainLoop()
245	}()
246}
247
248// runMainLoop starts the appropriate main loop based on WebKit availability
249func (app *BrowserApp) runMainLoop() {
250	if webkit.IsNativeAvailable() {
251		log.Printf("Entering GTK main loop…")
252		webkit.RunMainLoop()
253		log.Printf("GTK main loop exited")
254	} else {
255		log.Printf("Not entering GUI loop (non-CGO build)")
256		// In non-CGO mode, just wait for signals
257		sigChan := make(chan os.Signal, 1)
258		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
259		sig := <-sigChan
260		log.Printf("Received signal %v - exiting", sig)
261	}
262}

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