v0.4.0 6203a22

keyboard_cgo.go RawHistoryFolder

1//go:build webkit_cgo
2
3package webkit
4
5/*
6#cgo pkg-config: gtk4
7#include <gtk/gtk.h>
8#include <gdk/gdk.h>
9
10// Declarations for Go callbacks
11extern void goOnKeyPress(unsigned long id, unsigned int keyval, GdkModifierType state);
12extern void goOnButtonPress(unsigned long id, unsigned int button, GdkModifierType state);
13extern void goOnScroll(unsigned long id, double dx, double dy, GdkModifierType state);
14
15// Key controller callback -> forward to Go
16static gboolean on_key_pressed(GtkEventControllerKey* controller, guint keyval, guint keycode, GdkModifierType state, gpointer user_data) {
17    (void)controller; (void)keycode;
18    goOnKeyPress((unsigned long)user_data, keyval, state);
19    return FALSE; // do not stop other handlers
20}
21
22// Mouse click gesture -> forward side buttons to Go
23static void on_click_pressed(GtkGestureClick* gesture, gint n_press, gdouble x, gdouble y, gpointer user_data) {
24    (void)n_press; (void)x; (void)y;
25    guint button = gtk_gesture_single_get_current_button(GTK_GESTURE_SINGLE(gesture));
26    // Pass 0 for modifier state (not provided via gesture API)
27    goOnButtonPress((unsigned long)user_data, button, 0);
28}
29
30// Attach controllers to a widget (GTK4)
31static void attach_key_controller(GtkWidget* widget, unsigned long id) {
32    if (!widget) return;
33    GtkEventController* keyc = gtk_event_controller_key_new();
34    // Capture phase so we see keys even if child consumes them (e.g., WebKit)
35    gtk_event_controller_set_propagation_phase(keyc, GTK_PHASE_CAPTURE);
36    g_signal_connect_data(keyc, "key-pressed", G_CALLBACK(on_key_pressed), (gpointer)id, NULL, 0);
37    gtk_widget_add_controller(widget, keyc);
38}
39
40static void attach_mouse_gesture(GtkWidget* widget, unsigned long id) {
41    if (!widget) return;
42    GtkGesture* click = gtk_gesture_click_new();
43    g_signal_connect_data(click, "pressed", G_CALLBACK(on_click_pressed), (gpointer)id, NULL, 0);
44    gtk_widget_add_controller(widget, GTK_EVENT_CONTROLLER(click));
45}
46
47// Legacy controller to capture side buttons (8/9) reliably in GTK4
48static gboolean on_legacy_event(GtkEventController* controller, GdkEvent* event, gpointer user_data) {
49    (void)controller;
50    if (!event) return FALSE;
51    GdkEventType type = gdk_event_get_event_type(event);
52    if (type == GDK_BUTTON_PRESS) {
53        guint button = gdk_button_event_get_button(event);
54        GdkModifierType state = gdk_event_get_modifier_state(event);
55        if (button == 8 || button == 9) {
56            goOnButtonPress((unsigned long)user_data, button, state);
57            return TRUE; // consume side buttons
58        }
59        return FALSE; // let WebKit handle normal clicks
60    } else if (type == GDK_SCROLL) {
61        double dx = 0.0, dy = 0.0;
62        gdk_scroll_event_get_deltas(event, &dx, &dy);
63        GdkModifierType state = gdk_event_get_modifier_state(event);
64        goOnScroll((unsigned long)user_data, dx, dy, state);
65        return FALSE; // don't steal regular scrolling
66    }
67    return FALSE;
68}
69
70static void attach_mouse_legacy(GtkWidget* widget, unsigned long id) {
71    if (!widget) return;
72    GtkEventController* legacy = gtk_event_controller_legacy_new();
73    gtk_event_controller_set_propagation_phase(legacy, GTK_PHASE_CAPTURE);
74    g_signal_connect_data(legacy, "event", G_CALLBACK(on_legacy_event), (gpointer)id, NULL, 0);
75    gtk_widget_add_controller(widget, legacy);
76}
77*/
78import "C"
79
80import (
81	"fmt"
82	"log"
83	"sync"
84	"sync/atomic"
85	"time"
86)
87
88// Registry of accelerators per view id.
89type shortcutRegistry map[string]func()
90
91var (
92	regMu         sync.RWMutex
93	viewShortcuts = make(map[uintptr]shortcutRegistry)
94	viewIDCounter uint64
95	viewByID      = make(map[uintptr]*WebView)
96	lastKeyTime   = make(map[uintptr]map[string]time.Time)
97)
98
99// Locale hint function removed; no layout-specific remaps.
100
101// RegisterKeyboardShortcut registers a callback under an accelerator string.
102func (w *WebView) RegisterKeyboardShortcut(accel string, callback func()) error {
103	if w == nil || w.destroyed {
104		return ErrNotImplemented
105	}
106	if accel == "" || callback == nil {
107		return fmt.Errorf("invalid shortcut registration")
108	}
109	regMu.Lock()
110	if _, ok := viewShortcuts[w.id]; !ok {
111		viewShortcuts[w.id] = make(shortcutRegistry)
112	}
113	viewShortcuts[w.id][accel] = callback
114	regMu.Unlock()
115	return nil
116}
117
118//export goOnKeyPress
119func goOnKeyPress(id C.ulong, keyval C.guint, state C.GdkModifierType) {
120	// Normalize and dispatch
121	uid := uintptr(id)
122	kv := uint(keyval)
123	st := uint(state)
124	dispatchAccelerator(uid, kv, st)
125}
126
127func dispatchAccelerator(uid uintptr, keyval uint, state uint) {
128	ctrl := (state & uint(C.GDK_CONTROL_MASK)) != 0
129	alt := (state & uint(C.GDK_ALT_MASK)) != 0
130	shift := (state & uint(C.GDK_SHIFT_MASK)) != 0
131	// Map keyval to string names
132	var keyName string
133	switch keyval {
134	case uint(C.GDK_KEY_minus), uint(C.GDK_KEY_KP_Subtract), uint(C.GDK_KEY_underscore):
135		// Normalize minus; log raw detection for diagnostics
136		log.Printf("[accelerator-raw] minus key detected ctrl=%v alt=%v keyval=0x%x", ctrl, alt, keyval)
137		keyName = "-"
138	case uint(C.GDK_KEY_equal), uint(C.GDK_KEY_KP_Add):
139		keyName = "="
140	case uint(C.GDK_KEY_0), uint(C.GDK_KEY_KP_0):
141		keyName = "0"
142	case uint(C.GDK_KEY_Left):
143		keyName = "ArrowLeft"
144	case uint(C.GDK_KEY_Right):
145		keyName = "ArrowRight"
146	case uint(C.GDK_KEY_F12):
147		keyName = "F12"
148	case uint(C.GDK_KEY_c), uint(C.GDK_KEY_C):
149		keyName = "c"
150	default:
151		// If Control held, log unknown keyval for diagnostics
152		if ctrl {
153			log.Printf("[accelerator-miss] ctrl keyval=0x%x", keyval)
154		}
155		return
156	}
157
158	// Candidate accelerator strings in order
159	candidates := []string{keyName}
160	if ctrl && shift {
161		// Ctrl+Shift combinations
162		candidates = append([]string{"cmdorctrl+shift+" + keyName, "ctrl+shift+" + keyName}, candidates...)
163	} else if ctrl {
164		// Common style: modifier + '+' + keyName (e.g., cmdorctrl+=)
165		candidates = append([]string{"cmdorctrl+" + keyName, "ctrl+" + keyName}, candidates...)
166		// Also accept style without the extra '+' for punctuation keys (e.g., cmdorctrl-)
167		candidates = append([]string{"cmdorctrl" + keyName, "ctrl" + keyName}, candidates...)
168	}
169	if alt {
170		candidates = append([]string{"alt+" + keyName}, candidates...)
171	}
172
173	regMu.RLock()
174	reg := viewShortcuts[uid]
175	regMu.RUnlock()
176	if reg == nil {
177		return
178	}
179	for _, name := range candidates {
180		if cb, ok := reg[name]; ok {
181			// Debounce duplicates within 120ms for the same view+key
182			regMu.Lock()
183			if _, ok := lastKeyTime[uid]; !ok {
184				lastKeyTime[uid] = make(map[string]time.Time)
185			}
186			last := lastKeyTime[uid][name]
187			now := time.Now()
188			if now.Sub(last) < 120*time.Millisecond {
189				// Skip duplicate
190				regMu.Unlock()
191				return
192			}
193			lastKeyTime[uid][name] = now
194			regMu.Unlock()
195			log.Printf("[accelerator] %s", name)
196			cb()
197			break
198		}
199	}
200}
201
202func nextViewID() uintptr {
203	return uintptr(atomic.AddUint64(&viewIDCounter, 1))
204}
205
206func registerView(id uintptr, w *WebView) {
207	regMu.Lock()
208	viewByID[id] = w
209	regMu.Unlock()
210}
211
212func unregisterView(id uintptr) {
213	regMu.Lock()
214	delete(viewByID, id)
215	delete(viewShortcuts, id)
216	regMu.Unlock()
217}
218
219// AttachKeyboardControllers attaches GTK4 key and mouse controllers to the view widget.
220func AttachKeyboardControllers(w *WebView) {
221	if w == nil || w.native == nil || w.native.view == nil {
222		return
223	}
224	C.attach_key_controller(w.native.view, C.ulong(w.id))
225	if w.native.win != nil {
226		C.attach_key_controller(w.native.win, C.ulong(w.id))
227	}
228	C.attach_mouse_gesture(w.native.view, C.ulong(w.id))
229	// Legacy controller captures raw button presses (8/9) for back/forward reliably
230	C.attach_mouse_legacy(w.native.view, C.ulong(w.id))
231	log.Printf("[input] GTK4 key/mouse controllers attached")
232}
233
234//export goOnScroll
235func goOnScroll(id C.ulong, dx C.double, dy C.double, state C.GdkModifierType) {
236	uid := uintptr(id)
237	regMu.RLock()
238	vw := viewByID[uid]
239	regMu.RUnlock()
240	if vw == nil {
241		return
242	}
243	// Ctrl+scroll zooms
244	if (uint(state) & uint(C.GDK_CONTROL_MASK)) != 0 {
245		if float64(dy) < 0 {
246			// scroll up -> zoom in
247			nz := vw.zoom
248			if nz <= 0 {
249				nz = 1.0
250			}
251			nz *= 1.1
252			if nz < 0.25 {
253				nz = 0.25
254			}
255			if nz > 5.0 {
256				nz = 5.0
257			}
258			_ = vw.SetZoom(nz)
259		} else if float64(dy) > 0 {
260			// scroll down -> zoom out
261			nz := vw.zoom
262			if nz <= 0 {
263				nz = 1.0
264			}
265			nz /= 1.1
266			if nz < 0.25 {
267				nz = 0.25
268			}
269			if nz > 5.0 {
270				nz = 5.0
271			}
272			_ = vw.SetZoom(nz)
273		}
274	}
275}
276
277//export goOnThemeChanged
278func goOnThemeChanged(id C.ulong, preferDark C.int) {
279	uid := uintptr(id)
280	regMu.RLock()
281	vw := viewByID[uid]
282	regMu.RUnlock()
283	if vw == nil {
284		return
285	}
286	// Inject runtime theme update into the page
287	dval := "false"
288	if int(preferDark) != 0 {
289		dval = "true"
290	}
291	js := fmt.Sprintf(`(() => { try { const d=%s; const cs=d?'dark':'light'; console.log('[dumber] theme change:'+cs);
292let m=document.querySelector('meta[name="color-scheme"]');
293if(!m){ m=document.createElement('meta'); m.name='color-scheme'; document.head.appendChild(m); }
294m.setAttribute('content', d ? 'dark light' : 'light dark');
295let s=document.getElementById('__dumber_theme_style');
296if(!s){ s=document.createElement('style'); s.id='__dumber_theme_style'; document.documentElement.appendChild(s); }
297s.textContent=':root{color-scheme:' + (d?'dark':'light') + ';}';
298} catch(e) { console.warn('[dumber] theme runtime update failed', e); } })();`, dval)
299	_ = vw.InjectScript(js)
300}
301
302//export goOnUcmMessage
303func goOnUcmMessage(id C.ulong, json *C.char) {
304	uid := uintptr(id)
305	regMu.RLock()
306	vw := viewByID[uid]
307	regMu.RUnlock()
308	if vw == nil || json == nil {
309		return
310	}
311	goPayload := C.GoString(json)
312	vw.dispatchScriptMessage(goPayload)
313}
314
315//export goOnTitleChanged
316func goOnTitleChanged(id C.ulong, ctitle *C.char) {
317	uid := uintptr(id)
318	regMu.RLock()
319	vw := viewByID[uid]
320	regMu.RUnlock()
321	if vw == nil || ctitle == nil {
322		return
323	}
324	title := C.GoString(ctitle)
325	vw.dispatchTitleChanged(title)
326}
327
328//export goOnURIChanged
329func goOnURIChanged(id C.ulong, curi *C.char) {
330	uid := uintptr(id)
331	regMu.RLock()
332	vw := viewByID[uid]
333	regMu.RUnlock()
334	if vw == nil || curi == nil {
335		return
336	}
337	uri := C.GoString(curi)
338	vw.dispatchURIChanged(uri)
339}
340
341//export goOnButtonPress
342func goOnButtonPress(id C.ulong, button C.guint, state C.GdkModifierType) {
343	uid := uintptr(id)
344	btn := uint(button)
345	log.Printf("[mouse] button=%d state=0x%x", btn, uint(state))
346	regMu.RLock()
347	vw := viewByID[uid]
348	regMu.RUnlock()
349	if vw == nil {
350		return
351	}
352	switch btn {
353	case 8: // Back button on many mice
354		_ = vw.GoBack()
355	case 9: // Forward button on many mice
356		_ = vw.GoForward()
357	}
358}
359
360//export goQuitMainLoop
361func goQuitMainLoop() {
362	log.Printf("[webkit] Window close requested - quitting main loop")
363	QuitMainLoop()
364}

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