v0.1 bf7c821

main.go RawHistoryFolder

1package main
2
3import (
4    "context"
5    "embed"
6    "encoding/json"
7    "fmt"
8    "mime"
9    "log"
10    "os"
11    "runtime"
12    neturl "net/url"
13    "path/filepath"
14    "strings"
15    "strconv"
16    
17
18    "github.com/bnema/dumber/internal/cli"
19    "github.com/bnema/dumber/internal/config"
20    "github.com/bnema/dumber/internal/db"
21    "github.com/bnema/dumber/services"
22    "github.com/bnema/dumber/pkg/webkit"
23)
24
25// Build information set via ldflags
26var (
27	version   = "dev"
28	commit    = "none"
29	buildDate = "unknown"
30)
31
32func main() {
33	// Check if we should run the CLI mode
34	if shouldRunCLI() {
35		runCLI()
36		return
37	}
38
39    // Otherwise run the GUI browser
40    runBrowser()
41}
42
43// shouldRunCLI determines if we should run in CLI mode based on arguments
44func shouldRunCLI() bool {
45	// No args = GUI landing page mode
46	if len(os.Args) <= 1 {
47		return false
48	}
49
50	// Check for GUI-specific flags
51	for _, arg := range os.Args[1:] {
52		if arg == "--gui" || arg == "-g" {
53			return false // Explicit GUI mode
54		}
55	}
56
57	// Check for browse command - this should open GUI in direct navigation mode
58	if len(os.Args) >= 2 && os.Args[1] == "browse" {
59		return false // Browse command uses GUI mode but navigates directly
60	}
61
62	// Any other arguments mean CLI mode
63	return true
64}
65
66// runCLI executes the CLI functionality using the existing CLI package
67func runCLI() {
68	// Initialize configuration system
69	if err := config.Init(); err != nil {
70		fmt.Fprintf(os.Stderr, "Error initializing configuration: %v\n", err)
71		os.Exit(1)
72	}
73
74	// Start configuration watching for live reload
75	if err := config.Watch(); err != nil {
76		// Don't exit on watch error, just warn
77		fmt.Fprintf(os.Stderr, "Warning: failed to start config watching: %v\n", err)
78	}
79
80	rootCmd := cli.NewRootCmd(version, commit, buildDate)
81
82	// Handle dmenu flag at the root level for direct integration
83	if len(os.Args) > 1 && os.Args[1] == "--dmenu" {
84		// Create a temporary CLI instance to handle dmenu mode
85		cliInstance, err := cli.NewCLI()
86		if err != nil {
87			fmt.Fprintf(os.Stderr, "Error initializing CLI: %v\n", err)
88			os.Exit(1)
89		}
90		defer func() {
91			if closeErr := cliInstance.Close(); closeErr != nil {
92				fmt.Fprintf(os.Stderr, "Warning: failed to close database: %v\n", closeErr)
93			}
94		}()
95
96		// Generate dmenu options
97		dmenuCmd := cli.NewDmenuCmd()
98		if err := dmenuCmd.RunE(dmenuCmd, []string{}); err != nil {
99			fmt.Fprintf(os.Stderr, "Error in dmenu mode: %v\n", err)
100			os.Exit(1)
101		}
102		return
103	}
104
105	// Execute the root command
106	if err := rootCmd.Execute(); err != nil {
107		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
108		os.Exit(1)
109    }
110}
111
112//go:embed frontend/dist
113var assets embed.FS
114
115// runBrowser launches a minimal native WebKit window and integrates services.
116func runBrowser() {
117    log.Printf("Starting GUI mode (webkit_cgo=%v)", webkit.IsNativeAvailable())
118    // GTK requires all UI calls to run on the main OS thread
119    if webkit.IsNativeAvailable() {
120        runtime.LockOSThread()
121        defer runtime.UnlockOSThread()
122    }
123
124    if err := config.Init(); err != nil {
125        log.Fatalf("Failed to initialize config: %v", err)
126    }
127    cfg := config.Get()
128    log.Printf("Config initialized")
129
130    // Initialize database
131    database, err := db.InitDB(cfg.Database.Path)
132    if err != nil {
133        log.Fatalf("Failed to initialize database: %v", err)
134    }
135    defer database.Close()
136    queries := db.New(database)
137    log.Printf("Database opened at %s", cfg.Database.Path)
138
139    // Initialize services
140    parserService := services.NewParserService(cfg, queries)
141    browserService := services.NewBrowserService(cfg, queries)
142    // JS controls injection is disabled; using native shortcuts via GTK.
143
144    // Track current URL for zoom persistence
145    var currentURL string
146
147    // Register custom scheme resolver for dumb://
148    webkit.SetURISchemeResolver(func(uri string) (string, []byte, bool) {
149        log.Printf("[scheme] request: %s", uri)
150        // Known forms:
151        // - dumb://homepage or dumb:homepage → index.html
152        // - dumb://app/index.html, dumb://app/<path> → serve from frontend/dist/<path>
153        // - dumb://<anything> without path → index.html
154        u, err := neturl.Parse(uri)
155        if err != nil || u.Scheme != "dumb" {
156            return "", nil, false
157        }
158        // API routes
159        if u.Host == "api" || strings.HasPrefix(u.Opaque, "api") || strings.HasPrefix(u.Path, "/api") {
160            // Normalize path for opaque or hierarchical forms
161            path := u.Path
162            if path == "" && u.Opaque != "" {
163                // e.g., dumb:api/config or dumb:api/history/recent
164                parts := strings.SplitN(u.Opaque, ":", 2)
165                if len(parts) == 2 {
166                    path = "/" + parts[1]
167                }
168            }
169            if strings.HasPrefix(path, "/api/") { path = strings.TrimPrefix(path, "/api") }
170            if path == "/api" { path = "/" }
171            switch {
172            case strings.HasPrefix(path, "/config"):
173                log.Printf("[api] GET /config")
174                // Build config info
175                cfgPath, _ := config.GetConfigFile()
176                info := struct {
177                    ConfigPath     string                                    `json:"config_path"`
178                    DatabasePath   string                                    `json:"database_path"`
179                    SearchShortcuts map[string]config.SearchShortcut          `json:"search_shortcuts"`
180                    Appearance     config.AppearanceConfig                    `json:"appearance"`
181                }{
182                    ConfigPath: cfgPath,
183                    DatabasePath: cfg.Database.Path,
184                    SearchShortcuts: cfg.SearchShortcuts,
185                    Appearance: cfg.Appearance,
186                }
187                b, _ := json.Marshal(info)
188                return "application/json; charset=utf-8", b, true
189            case strings.HasPrefix(path, "/history/recent"):
190                log.Printf("[api] GET /history/recent%s", u.RawQuery)
191                // Parse limit
192                q := u.Query()
193                limit := 50
194                if l := q.Get("limit"); l != "" {
195                    if n, err := strconv.Atoi(l); err == nil && n > 0 {
196                        limit = n
197                    }
198                }
199                ctx := context.Background()
200                entries, err := browserService.GetRecentHistory(ctx, limit)
201                if err != nil {
202                    return "application/json; charset=utf-8", []byte("[]"), true
203                }
204                b, _ := json.Marshal(entries)
205                return "application/json; charset=utf-8", b, true
206            case strings.HasPrefix(path, "/history/search"):
207                log.Printf("[api] GET /history/search%s", u.RawQuery)
208                q := u.Query()
209                query := q.Get("q")
210                limit := 50
211                if l := q.Get("limit"); l != "" {
212                    if n, err := strconv.Atoi(l); err == nil && n > 0 {
213                        limit = n
214                    }
215                }
216                ctx := context.Background()
217                entries, err := browserService.SearchHistory(ctx, query, limit)
218                if err != nil {
219                    return "application/json; charset=utf-8", []byte("[]"), true
220                }
221                b, _ := json.Marshal(entries)
222                return "application/json; charset=utf-8", b, true
223            case strings.HasPrefix(path, "/history/stats"):
224                log.Printf("[api] GET /history/stats")
225                ctx := context.Background()
226                stats, err := browserService.GetHistoryStats(ctx)
227                if err != nil { return "application/json; charset=utf-8", []byte("{}"), true }
228                b, _ := json.Marshal(stats)
229                return "application/json; charset=utf-8", b, true
230            default:
231                return "application/json; charset=utf-8", []byte("{}"), true
232            }
233        }
234        // Resolve target path inside embed FS
235        var rel string
236        if u.Opaque == "homepage" || (u.Host == "homepage" && (u.Path == "" || u.Path == "/")) || (u.Host == "" && (u.Path == "" || u.Path == "/")) {
237            rel = "index.html"
238        } else {
239            host := u.Host
240            p := strings.TrimPrefix(u.Path, "/")
241            if host == "app" && p == "" {
242                rel = "index.html"
243            } else if host == "app" {
244                rel = p
245            } else if host == "homepage" && p != "" {
246                // dumb://homepage/<asset>
247                rel = p
248            } else if p != "" {
249                rel = p
250            } else {
251                rel = "index.html"
252            }
253        }
254        log.Printf("[scheme] asset: rel=%s (host=%s path=%s)", rel, u.Host, u.Path)
255        data, rerr := assets.ReadFile(filepath.ToSlash(filepath.Join("frontend", "dist", rel)))
256        if rerr != nil {
257            log.Printf("[scheme] not found: %s", rel)
258            return "", nil, false
259        }
260        // Determine mime type
261        mt := mime.TypeByExtension(strings.ToLower(filepath.Ext(rel)))
262        if mt == "" {
263            // Fallbacks
264            switch strings.ToLower(filepath.Ext(rel)) {
265            case ".js": mt = "application/javascript"
266            case ".css": mt = "text/css"
267            case ".svg": mt = "image/svg+xml"
268            case ".ico": mt = "image/x-icon"
269            default: mt = "text/html; charset=utf-8"
270            }
271        }
272        return mt, data, true
273    })
274
275    // Create WebKit view
276    log.Printf("Creating WebView (native backend expected: %v)", webkit.IsNativeAvailable())
277    dataDir, _ := config.GetDataDir()
278    stateDir, _ := config.GetStateDir()
279    webkitData := filepath.Join(dataDir, "webkit")
280    webkitCache := filepath.Join(stateDir, "webkit-cache")
281    _ = os.MkdirAll(webkitData, 0o755)
282    _ = os.MkdirAll(webkitCache, 0o755)
283    view, err := webkit.NewWebView(&webkit.Config{
284        InitialURL:        "dumb://homepage",
285        ZoomDefault:       1.0,
286        EnableDeveloperExtras: true,
287        DataDir:           webkitData,
288        CacheDir:          webkitCache,
289        DefaultSansFont:      cfg.Appearance.SansFont,
290        DefaultSerifFont:     cfg.Appearance.SerifFont,
291        DefaultMonospaceFont: cfg.Appearance.MonospaceFont,
292        DefaultFontSize:      cfg.Appearance.DefaultFontSize,
293    })
294    if err != nil {
295        log.Printf("Warning: failed to create WebView: %v", err)
296    } else {
297        browserService.AttachWebView(view)
298        // Use native window as title updater
299        if win := view.Window(); win != nil {
300            browserService.SetWindowTitleUpdater(win)
301        }
302        // Persist page titles to DB when they change
303        view.RegisterTitleChangedHandler(func(title string) {
304            ctx := context.Background()
305            url := view.GetCurrentURL()
306            if url != "" && title != "" {
307                if err := browserService.UpdatePageTitle(ctx, url, title); err != nil {
308                    log.Printf("Warning: failed to update page title: %v", err)
309                }
310            }
311        })
312        // Track current URL changes and apply saved zoom
313        view.RegisterURIChangedHandler(func(u string) {
314            currentURL = u
315            if u == "" { return }
316            ctx := context.Background()
317            if z, err := browserService.GetZoomLevel(ctx, u); err == nil {
318                _ = view.SetZoom(z)
319            }
320        })
321        // Bridge UCM messages: navigate + history queries
322        view.RegisterScriptMessageHandler(func(payload string) {
323            type msg struct {
324                Type   string `json:"type"`
325                URL    string `json:"url"`
326                Q      string `json:"q"`
327                Limit  int    `json:"limit"`
328                // Wails fetch bridge
329                ID     string          `json:"id"`
330                Payload json.RawMessage `json:"payload"`
331            }
332            var m msg
333            if err := json.Unmarshal([]byte(payload), &m); err != nil { return }
334            switch m.Type {
335            case "navigate":
336                ctx := context.Background()
337                res, err := parserService.ParseInput(ctx, m.URL)
338                if err == nil {
339                    currentURL = res.URL
340                    browserService.Navigate(ctx, currentURL)
341                    _ = view.LoadURL(currentURL)
342                    if z, zerr := browserService.GetZoomLevel(ctx, currentURL); zerr == nil { _ = view.SetZoom(z) }
343                }
344            case "query":
345                ctx := context.Background()
346                lim := m.Limit
347                if lim <= 0 || lim > 25 { lim = 10 }
348                entries, err := browserService.SearchHistory(ctx, m.Q, lim)
349                if err != nil { return }
350                // Map to lightweight items
351                type item struct { URL string `json:"url"`; Favicon string `json:"favicon"` }
352                buildFavicon := func(raw string) string {
353                    u, err := parserService.ParseInput(ctx, raw)
354                    if err != nil || u.URL == "" { return "" }
355                    parsed, perr := neturl.Parse(u.URL)
356                    if perr != nil || parsed.Host == "" { return "" }
357                    scheme := parsed.Scheme
358                    if scheme == "" { scheme = "https" }
359                    return scheme + "://" + parsed.Host + "/favicon.ico"
360                }
361                items := make([]item, 0, len(entries))
362                for _, e := range entries { items = append(items, item{URL: e.URL, Favicon: buildFavicon(e.URL)}) }
363                b, _ := json.Marshal(items)
364                // Update suggestions in page
365                _ = view.InjectScript("window.__dumber_setSuggestions && window.__dumber_setSuggestions(" + string(b) + ")")
366            case "wails":
367                // Handle Wails runtime fetch bridge calls for homepage
368                // Payload contains { methodID, methodName?, args }
369                var p struct {
370                    MethodID uint32           `json:"methodID"`
371                    MethodName string         `json:"methodName"`
372                    Args     json.RawMessage  `json:"args"`
373                }
374                if err := json.Unmarshal(m.Payload, &p); err != nil { return }
375                // Only implement the IDs we need
376                switch p.MethodID {
377                case 3708519028: // BrowserService.GetRecentHistory(limit)
378                    var args []interface{}
379                    _ = json.Unmarshal(p.Args, &args)
380                    limit := 50
381                    if len(args) > 0 {
382                        if f, ok := args[0].(float64); ok { limit = int(f) }
383                    }
384                    ctx := context.Background()
385                    entries, err := browserService.GetRecentHistory(ctx, limit)
386                    if err != nil { return }
387                    resp, _ := json.Marshal(entries)
388                    _ = view.InjectScript("window.__dumber_wails_resolve('" + m.ID + "', " + string(resp) + ")")
389                case 4078533762: // BrowserService.GetSearchShortcuts()
390                    ctx := context.Background()
391                    shortcuts, err := browserService.GetSearchShortcuts(ctx)
392                    if err != nil { return }
393                    resp, _ := json.Marshal(shortcuts)
394                    _ = view.InjectScript("window.__dumber_wails_resolve('" + m.ID + "', " + string(resp) + ")")
395                default:
396                    // Return empty JSON to avoid breaking UI
397                    _ = view.InjectScript("window.__dumber_wails_resolve('" + m.ID + "', '{}')")
398                }
399            case "theme":
400                if m.URL != "" { log.Printf("[theme] page reported color-scheme: %s", m.URL) }
401            }
402        })
403        log.Printf("Showing WebView window…")
404        if err := view.Show(); err != nil {
405            log.Printf("Warning: failed to show WebView: %v", err)
406        } else {
407            if !webkit.IsNativeAvailable() {
408                log.Printf("Notice: running without webkit_cgo tag — no native window will be displayed.")
409            }
410        }
411    }
412
413    // Parse browse argument if present
414    if len(os.Args) >= 3 && os.Args[1] == "browse" {
415        log.Printf("Browse command detected: %s", os.Args[2])
416        ctx := context.Background()
417        result, err := parserService.ParseInput(ctx, os.Args[2])
418        if err == nil {
419            currentURL = result.URL
420            log.Printf("Parsed input → URL: %s", currentURL)
421            browserService.Navigate(ctx, currentURL)
422            if view != nil {
423                log.Printf("Loading URL in WebView: %s", currentURL)
424                if err := view.LoadURL(currentURL); err != nil {
425                    log.Printf("Warning: failed to load URL: %v", err)
426                }
427                if z, zerr := browserService.GetZoomLevel(ctx, currentURL); zerr == nil {
428                    log.Printf("Applying stored zoom: %.2f", z)
429                    if err := view.SetZoom(z); err != nil {
430                        log.Printf("Warning: failed to set zoom: %v", err)
431                    }
432                }
433                // No JS injection; native accelerators handle zoom/devtools.
434            }
435        }
436    }
437
438    // Register basic keyboard shortcuts on the native view to preserve behavior
439    if view != nil {
440        ctx := context.Background()
441        // DevTools
442        _ = view.RegisterKeyboardShortcut("F12", func() { log.Printf("Shortcut: F12 (devtools)"); _ = view.ShowDevTools() })
443        // Omnibox (Ctrl+L): rely on injected script listener
444        _ = view.RegisterKeyboardShortcut("cmdorctrl+l", func() {
445            log.Printf("Shortcut: Omnibox toggle")
446            _ = view.InjectScript("window.__dumber_toggle && window.__dumber_toggle()")
447        })
448        // Zoom In
449        _ = view.RegisterKeyboardShortcut("cmdorctrl+=", func() {
450            log.Printf("Shortcut: Zoom In")
451            if currentURL == "" { return }
452            if z, err := browserService.ZoomIn(ctx, currentURL); err == nil { _ = view.SetZoom(z) }
453        })
454        _ = view.RegisterKeyboardShortcut("cmdorctrl+plus", func() {
455            log.Printf("Shortcut: Zoom In")
456            if currentURL == "" { return }
457            if z, err := browserService.ZoomIn(ctx, currentURL); err == nil { _ = view.SetZoom(z) }
458        })
459        // Zoom Out
460        _ = view.RegisterKeyboardShortcut("cmdorctrl+-", func() {
461            log.Printf("Shortcut: Zoom Out")
462            if currentURL == "" { return }
463            if z, err := browserService.ZoomOut(ctx, currentURL); err == nil { _ = view.SetZoom(z) }
464        })
465        // Zoom Reset
466        _ = view.RegisterKeyboardShortcut("cmdorctrl+0", func() {
467            log.Printf("Shortcut: Zoom Reset")
468            if currentURL == "" { return }
469            if z, err := browserService.ResetZoom(ctx, currentURL); err == nil { _ = view.SetZoom(z) }
470        })
471    }
472
473    // Enter GTK main loop only when native backend is available.
474    if webkit.IsNativeAvailable() {
475        log.Printf("Entering GTK main loop…")
476        webkit.RunMainLoop()
477        log.Printf("GTK main loop exited")
478    } else {
479        log.Printf("Not entering GUI loop (non-CGO build)")
480    }
481}

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