1package input
2
3// Manual Testing: Dead Key / Compose Support
4//
5// To verify native dead key support works correctly:
6//
7// 1. Set keyboard layout to "US International with dead keys"
8// 2. Open dumber, navigate to a page with a text input (e.g. Google search)
9// 3. Click into the text input field
10// 4. Type: ' then e -- should produce e with acute accent
11// 5. Type: " then u -- should produce u with diaeresis
12// 6. Type: ` then a -- should produce a with grave accent
13// 7. Type: ~ then n -- should produce n with tilde
14// 8. Verify Ctrl+L still opens omnibox
15// 9. Verify Alt+1-9 still switches tabs
16// 10. Verify modal modes (Ctrl+T for tab mode) still work
17// 11. In omnibox, verify long-press accent picker still works (hold 'e' for 400ms)
18// 12. Verify Escape closes omnibox / exits modal modes
19// 13. Verify session manager overlay captures all keyboard input
20
21import (
22 "context"
23 "sync"
24 "time"
25
26 "github.com/bnema/dumber/internal/domain/entity"
27 "github.com/bnema/dumber/internal/logging"
28 "github.com/bnema/puregotk/v4/gdk"
29 "github.com/bnema/puregotk/v4/glib"
30 "github.com/bnema/puregotk/v4/gtk"
31 "github.com/rs/zerolog"
32)
33
34// ActionHandler is called when a keyboard action is triggered.
35// It receives the context and the action to perform.
36// Return an error if the action fails.
37type ActionHandler func(ctx context.Context, action Action) error
38
39// VimScrollPhase identifies held-scroll lifecycle events. It is internal input
40// state, not a configurable action or shortcut.
41type VimScrollPhase uint8
42
43const (
44 VimScrollContinuous VimScrollPhase = iota
45 VimScrollStop
46)
47
48// VimScrollLifecycleHandler receives autonomous held-scroll ticks and the
49// matching stop event without changing the normal configurable action API.
50type VimScrollLifecycleHandler func(ctx context.Context, action Action, phase VimScrollPhase) error
51
52// PageFocusNavigationHandler handles native-like focus traversal inside the
53// focused page. It returns true when the event was handled by the page.
54type PageFocusNavigationHandler func(ctx context.Context, backward bool) bool
55
56const (
57 vimScrollHoldDelay = 250 * time.Millisecond
58 vimScrollCadence = 16 * time.Millisecond
59)
60
61// AccentHandler handles long-press accent detection.
62// Called for character keys that may have accent variants.
63type AccentHandler interface {
64 // OnKeyPressed is called when a key is pressed.
65 // Returns true if the accent handler is handling this key (picker visible or will show).
66 OnKeyPressed(ctx context.Context, char rune, shiftHeld bool) bool
67 // OnKeyReleased is called when a key is released.
68 OnKeyReleased(ctx context.Context, char rune)
69 // IsPickerVisible returns true if the accent picker is currently visible.
70 IsPickerVisible() bool
71 // Cancel cancels any pending long-press detection.
72 Cancel(ctx context.Context)
73}
74
75// KeyboardHandler processes keyboard events and dispatches actions.
76// It manages modal input modes and routes key events to the appropriate handlers.
77type KeyboardHandler struct {
78 shortcuts *ShortcutSet
79 modal *ModalState
80 workspace *entity.WorkspaceConfig
81 session *entity.SessionConfig
82
83 // Action handler callbacks.
84 onAction ActionHandler
85 onVimScrollLifecycle VimScrollLifecycleHandler
86 onPageFocusNavigation PageFocusNavigationHandler
87 // Optional routing callback that determines how a key should be handled.
88 // Returns RouteHandleShortcuts (default), RoutePassToWidget (let focused
89 // widget handle it), or RouteAccentDetection (long-press accent for GTK entries).
90 routeKey func(KeyContext) KeyRoute
91 // Optional accent handler for dead keys support
92 accentHandler AccentHandler
93 // Optional escape hook for app-level overlays
94 onEscape func(ctx context.Context) bool
95 // Optional hook that blocks Vim mode activation and lets the original key
96 // event pass through to the focused widget/page instead.
97 vimModeActivationPassthrough func() bool
98
99 // GTK controller (nil until attached)
100 controller *gtk.EventControllerKey
101 window *gtk.ApplicationWindow
102
103 // Callback retention: must stay reachable by Go GC.
104 keyPressedCb func(gtk.EventControllerKey, uint, uint, gdk.ModifierType) bool
105 keyReleasedCb func(gtk.EventControllerKey, uint, uint, gdk.ModifierType)
106 keyPressedHandlerID uint
107 keyReleasedHandlerID uint
108
109 activePressedActions map[Action]uint
110 ctx context.Context
111 mu sync.RWMutex
112
113 vimScrollRepeatAction Action
114 vimScrollRepeatKeyval uint
115 vimScrollRepeatTimer uint
116 vimScrollRepeatGeneration uint64
117 vimScrollRepeatPressedAt time.Time
118 vimScrollRepeatCb glib.SourceFunc
119 vimScrollRepeatAdd func(intervalMS uint, cb *glib.SourceFunc) uint
120 vimScrollRepeatRemove func(id uint) bool
121 vimScrollNow func() time.Time
122
123 seq vimModeSequenceState
124}
125
126// NewKeyboardHandler creates a new keyboard handler.
127func NewKeyboardHandler(ctx context.Context, workspace *entity.WorkspaceConfig, session *entity.SessionConfig) *KeyboardHandler {
128 log := logging.FromContext(ctx)
129
130 log.Debug().Msg("creating keyboard handler")
131
132 shortcuts := NewShortcutSet(ctx, workspace, session)
133 seqTimeout := time.Duration(0)
134 if workspace != nil {
135 seqTimeout = time.Duration(workspace.VimMode.SequenceTimeoutMilliseconds) * time.Millisecond
136 }
137 h := &KeyboardHandler{
138 shortcuts: shortcuts,
139 modal: NewModalState(ctx),
140 workspace: workspace,
141 session: session,
142 activePressedActions: make(map[Action]uint),
143 ctx: ctx,
144 vimScrollRepeatAdd: func(intervalMS uint, cb *glib.SourceFunc) uint {
145 return glib.TimeoutAdd(intervalMS, cb, 0)
146 },
147 vimScrollRepeatRemove: glib.SourceRemove,
148 vimScrollNow: time.Now,
149 seq: newVimModeSequenceState(shortcuts.VimModeSequences(), seqTimeout),
150 }
151 h.SetOnModeChange(nil)
152
153 return h
154}
155
156// SetOnAction sets the callback for when actions are triggered.
157func (h *KeyboardHandler) SetOnAction(fn ActionHandler) {
158 h.mu.Lock()
159 defer h.mu.Unlock()
160 h.onAction = fn
161}
162
163// SetOnVimScrollLifecycle sets the callback for autonomous held-scroll ticks
164// and stop notification. Tap actions continue through SetOnAction.
165func (h *KeyboardHandler) SetOnVimScrollLifecycle(fn VimScrollLifecycleHandler) {
166 h.mu.Lock()
167 defer h.mu.Unlock()
168 h.onVimScrollLifecycle = fn
169}
170
171// SetOnPageFocusNavigation sets the optional callback for keeping page focus
172// traversal inside the active WebView.
173func (h *KeyboardHandler) SetOnPageFocusNavigation(fn PageFocusNavigationHandler) {
174 h.mu.Lock()
175 defer h.mu.Unlock()
176 h.onPageFocusNavigation = fn
177}
178
179// SetVimModeActivationPassthrough sets the callback that can block Vim mode
180// activation and let the original key event propagate instead.
181func (h *KeyboardHandler) SetVimModeActivationPassthrough(fn func() bool) {
182 h.mu.Lock()
183 defer h.mu.Unlock()
184 h.vimModeActivationPassthrough = fn
185}
186
187// ReloadShortcuts rebuilds the shortcut set from new config values.
188// This enables hot-reloading of keybindings without restarting.
189func (h *KeyboardHandler) ReloadShortcuts(ctx context.Context, workspace *entity.WorkspaceConfig, session *entity.SessionConfig) {
190 h.stopVimScrollRepeat()
191 h.mu.Lock()
192
193 log := logging.FromContext(ctx)
194 log.Debug().Msg("reloading shortcuts from config")
195
196 h.shortcuts = NewShortcutSet(ctx, workspace, session)
197 h.workspace = workspace
198 h.session = session
199 seqTimeout := time.Duration(0)
200 if workspace != nil {
201 seqTimeout = time.Duration(workspace.VimMode.SequenceTimeoutMilliseconds) * time.Millisecond
202 }
203 h.mu.Unlock()
204
205 h.InvalidateSequenceMatcher()
206 h.SetSequenceTimeout(seqTimeout)
207}
208
209// SetOnModeChange sets the callback for mode changes (for UI updates).
210func (h *KeyboardHandler) SetOnModeChange(fn func(from, to Mode)) {
211 h.modal.SetOnModeChange(func(from, to Mode) {
212 // Switch controller phase: capture during modal, bubble for normal.
213 // This ensures plain modal keys (s, h, etc.) reach the handler
214 // before WebView, while normal typing still goes through WebKit IM.
215 if to == ModeNormal {
216 h.setControllerPhase(gtk.PhaseBubbleValue)
217 } else if from == ModeNormal {
218 h.setControllerPhase(gtk.PhaseCaptureValue)
219 }
220 if to != ModeVim {
221 h.stopVimScrollRepeat()
222 // Silent reset under ModalState lock: no pending callback (avoids Mode() re-entry).
223 h.resetPendingSequence(false)
224 }
225 // Forward to app-level callback
226 if fn != nil {
227 fn(from, to)
228 }
229 })
230}
231
232// setControllerPhase changes the propagation phase of the key controller.
233// Capture phase during modal modes so plain keys reach the handler before WebView.
234// Bubble phase in normal mode for WebKit IM/dead-key support.
235//
236// This is called synchronously from onModeChange so the phase switch takes
237// effect before the next key event. The caller must ensure GTK thread safety;
238// modal timeouts dispatch to the GTK main thread via glib.IdleAdd before
239// calling ExitMode, so the onModeChange callback always runs on the GTK thread.
240func (h *KeyboardHandler) setControllerPhase(phase gtk.PropagationPhase) {
241 if h.controller == nil {
242 return
243 }
244 h.controller.SetPropagationPhase(phase)
245}
246
247// SetRouteKey sets the callback that determines how each key event should be routed.
248// The callback receives key context and returns a KeyRoute indicating whether the
249// key should be handled by the shortcut system, passed to the focused widget
250// (for IM/compose support), or routed through accent detection.
251//
252// If not set, all keys are routed through the shortcut system (RouteHandleShortcuts).
253func (h *KeyboardHandler) SetRouteKey(fn func(KeyContext) KeyRoute) {
254 h.mu.Lock()
255 defer h.mu.Unlock()
256 h.routeKey = fn
257}
258
259// SetAccentHandler sets the handler for long-press accent detection.
260func (h *KeyboardHandler) SetAccentHandler(handler AccentHandler) {
261 h.mu.Lock()
262 defer h.mu.Unlock()
263 h.accentHandler = handler
264}
265
266// SetOnEscape sets an optional callback invoked for plain Escape in normal mode.
267// Return true to consume the key and stop further handling.
268func (h *KeyboardHandler) SetOnEscape(fn func(ctx context.Context) bool) {
269 h.mu.Lock()
270 defer h.mu.Unlock()
271 h.onEscape = fn
272}
273
274// Mode returns the current input mode.
275func (h *KeyboardHandler) Mode() Mode {
276 return h.modal.Mode()
277}
278
279// AttachTo attaches the keyboard handler to a GTK window.
280// The handler runs in the bubble phase so that WebKit's IM pipeline (including
281// dead-key / compose sequences) processes key events first. App-level shortcuts
282// are still intercepted because WebKit only consumes events it recognizes as
283// text input; unhandled events bubble up to this controller.
284func (h *KeyboardHandler) AttachTo(window *gtk.ApplicationWindow) {
285 log := logging.FromContext(h.ctx)
286
287 if window == nil {
288 log.Error().Msg("cannot attach keyboard handler to nil window")
289 return
290 }
291
292 h.controller = gtk.NewEventControllerKey()
293 if h.controller == nil {
294 log.Error().Msg("failed to create event controller key")
295 return
296 }
297
298 // Bubble phase: let WebKit IM handle key events first (dead keys, compose
299 // sequences, input methods). Events not consumed by WebKit bubble up here
300 // so app shortcuts still work.
301 h.controller.SetPropagationPhase(gtk.PhaseBubbleValue)
302
303 // Wire GTK main thread schedulers for modal and sequence ambiguity timeouts.
304 // Timer goroutines must dispatch back to the GTK thread because callbacks
305 // may touch GTK widgets / EventController phase.
306 h.installGTKMainThreadSchedulers()
307
308 // Connect key pressed handler (retain callback to prevent GC).
309 // The callback receives: keyval (translated key), keycode (hardware key position), state (modifiers)
310 h.keyPressedCb = func(_ gtk.EventControllerKey, keyval uint, keycode uint, state gdk.ModifierType) bool {
311 return h.handleKeyPress(keyval, keycode, state)
312 }
313 h.keyPressedHandlerID = h.controller.ConnectKeyPressed(&h.keyPressedCb)
314
315 // Connect key released handler for accent detection.
316 h.keyReleasedCb = func(_ gtk.EventControllerKey, keyval uint, _ uint, _ gdk.ModifierType) {
317 h.handleKeyRelease(keyval)
318 }
319 h.keyReleasedHandlerID = h.controller.ConnectKeyReleased(&h.keyReleasedCb)
320
321 // Add controller to window
322 h.window = window
323 window.AddController(&h.controller.EventController)
324
325 log.Debug().Msg("keyboard handler attached to window")
326}
327
328// installGTKMainThreadSchedulers routes modal and sequence timer callbacks
329// through glib.IdleAdd so they run on the GTK main thread.
330func (h *KeyboardHandler) installGTKMainThreadSchedulers() {
331 if h == nil {
332 return
333 }
334 schedule := func(fn func()) {
335 cb := glib.SourceFunc(func(_ uintptr) bool {
336 fn()
337 return false
338 })
339 glib.IdleAdd(&cb, 0)
340 }
341 h.modal.SetMainThreadScheduler(schedule)
342 h.SetSequenceMainThreadScheduler(schedule)
343 logging.FromContext(h.ctx).Debug().Msg("gtk main-thread schedulers installed for modal and vim-mode sequences")
344}
345
346// Detach removes the keyboard handler from a live GTK window and releases its
347// retained GTK signal callbacks.
348func (h *KeyboardHandler) Detach() {
349 h.detach(true)
350}
351
352// DetachForDestroy releases retained GTK signal callbacks during window
353// teardown without mutating the window's controller list while GTK is
354// destroying it.
355func (h *KeyboardHandler) DetachForDestroy() {
356 h.detach(false)
357}
358
359func (h *KeyboardHandler) detach(removeController bool) {
360 h.stopVimScrollRepeat()
361 // Sequence teardown uses seq.mu only; keep it outside h.mu to preserve
362 // the existing h.mu → (never seq) / seq.mu standalone lock order.
363 h.teardownSequenceState()
364 h.mu.Lock()
365 if h.controller != nil && h.keyPressedHandlerID != 0 {
366 h.controller.DisconnectSignal(h.keyPressedHandlerID)
367 }
368 if h.controller != nil && h.keyReleasedHandlerID != 0 {
369 h.controller.DisconnectSignal(h.keyReleasedHandlerID)
370 }
371 if removeController && h.window != nil && h.controller != nil {
372 h.window.RemoveController(&h.controller.EventController)
373 }
374 h.controller = nil
375 h.window = nil
376 h.keyPressedCb = nil
377 h.keyReleasedCb = nil
378 h.keyPressedHandlerID = 0
379 h.keyReleasedHandlerID = 0
380 h.activePressedActions = nil
381 h.mu.Unlock()
382}
383
384// handleKeyPress processes a key press event.
385// Returns true if the event was handled and should not propagate further.
386func (h *KeyboardHandler) handleKeyPress(keyval, keycode uint, state gdk.ModifierType) bool {
387 log := logging.FromContext(h.ctx)
388
389 h.mu.RLock()
390 routeKey := h.routeKey
391 accentHandler := h.accentHandler
392 onEscape := h.onEscape
393 h.mu.RUnlock()
394
395 // Accent picker takes absolute priority when visible -- it has its own key controller
396 if accentHandler != nil && accentHandler.IsPickerVisible() {
397 return false
398 }
399
400 modifiers := Modifier(state) & modifierMask
401 mode := h.modal.Mode()
402
403 // Escape in normal mode: check app-level escape hook first
404 if mode == ModeNormal && keyval == uint(gdk.KEY_Escape) && modifiers == 0 {
405 if onEscape != nil && onEscape(h.ctx) {
406 return true
407 }
408 }
409
410 if h.handleGuaranteedModalExit(mode, keyval, modifiers) {
411 return true
412 }
413
414 // Page focus traversal must stay out of shortcut lookup. The callback keeps
415 // traversal inside CEF when the active page control needs it; otherwise the
416 // event passes through to the native widget.
417 if shouldPassthroughNativePageFocusNavigation(mode, keyval, modifiers) {
418 return h.handlePageFocusNavigation(keyval, modifiers)
419 }
420
421 // Determine routing for this key event
422 route := RouteHandleShortcuts // default: process through shortcut system
423 if routeKey != nil && mode == ModeNormal {
424 route = routeKey(KeyContext{
425 Keyval: keyval,
426 Keycode: keycode,
427 Modifiers: modifiers,
428 })
429 }
430
431 switch route {
432 case RoutePassToWidget:
433 // Let the focused widget handle this key directly (WebView IM, etc.)
434 // No accent detection here -- WebView has its own JS-based accent detection.
435 log.Trace().Uint("keyval", keyval).Msg("routing key to focused widget")
436 return false
437
438 case RouteAccentDetection:
439 // Try long-press accent detection for GTK Entry widgets (omnibox, find bar).
440 // If the accent handler doesn't consume the key, pass it to the widget.
441 if h.tryAccentDetection(accentHandler, keyval, modifiers) {
442 return true
443 }
444 log.Trace().Uint("keyval", keyval).Msg("accent detection declined, routing to widget")
445 return false
446
447 case RouteHandleShortcuts:
448 // Fall through to shortcut processing below
449 }
450
451 // Vim-mode multi-key sequences run before legacy single-chord lookup.
452 if h.feedVimModeSequence(keyval, state) {
453 return true
454 }
455
456 // --- Shortcut processing path ---
457
458 // Normalize uppercase letters for consistent binding lookup
459 keyval = normalizeKeyval(keyval)
460
461 binding := KeyBinding{Keyval: keyval, Modifiers: modifiers}
462 action, found := h.lookupAction(log, binding, mode, modifiers, keycode)
463 return h.handleShortcutLookupResult(log, action, found, mode, keyval, modifiers)
464}
465
466// handleGuaranteedModalExit preserves Escape and Enter as modal fallbacks even
467// when the current configuration omits explicit cancel or confirm bindings.
468func (h *KeyboardHandler) handleGuaranteedModalExit(mode Mode, keyval uint, modifiers Modifier) bool {
469 if mode == ModeNormal || modifiers != 0 {
470 return false
471 }
472
473 switch keyval {
474 case uint(gdk.KEY_Escape):
475 if mode == ModeVim {
476 h.stopVimScrollRepeat()
477 }
478 h.modal.ExitMode(h.ctx)
479 return true
480 case uint(gdk.KEY_Return), uint(gdk.KEY_KP_Enter):
481 if mode == ModeVim {
482 h.confirmVimMode()
483 } else {
484 h.modal.ExitMode(h.ctx)
485 }
486 return true
487 default:
488 return false
489 }
490}
491
492func (h *KeyboardHandler) handleShortcutLookupResult(
493 log *zerolog.Logger,
494 action Action,
495 found bool,
496 mode Mode,
497 keyval uint,
498 modifiers Modifier,
499) bool {
500 if !found {
501 if shouldPassthroughNativeVimModeNavigation(mode, keyval, modifiers) {
502 log.Trace().Uint("keyval", keyval).Msg("routing native page navigation key to focused widget in vim mode")
503 return false
504 }
505 return mode != ModeNormal // Consume unrecognized keys in modal mode
506 }
507 if h.shouldPassthroughVimModeActivation(action, mode) {
508 return false
509 }
510 if mode == ModeVim && isVimScrollAction(action) {
511 return h.handleVimScrollAction(log, action, mode, keyval)
512 }
513 if h.suppressHeldAction(action, keyval) {
514 log.Trace().
515 Str("action", string(action)).
516 Msg("held keyboard action repeat suppressed")
517 return true
518 }
519 return h.dispatchAction(action, mode)
520}
521
522func (h *KeyboardHandler) handleVimScrollAction(log *zerolog.Logger, action Action, mode Mode, keyval uint) bool {
523 h.mu.RLock()
524 sameHeldKey := h.vimScrollRepeatAction == action &&
525 h.vimScrollRepeatKeyval == keyval && h.vimScrollRepeatTimer != 0
526 h.mu.RUnlock()
527 if sameHeldKey {
528 log.Trace().Str("action", string(action)).Msg("vim scroll OS repeat suppressed")
529 return true
530 }
531
532 h.stopVimScrollRepeat()
533 if !h.dispatchAction(action, mode) {
534 return false
535 }
536 h.startVimScrollRepeat(action, keyval)
537 return true
538}
539
540func (h *KeyboardHandler) startVimScrollRepeat(action Action, keyval uint) {
541 h.mu.Lock()
542 if h.vimScrollRepeatTimer != 0 || h.vimScrollRepeatAdd == nil {
543 h.mu.Unlock()
544 return
545 }
546 h.vimScrollRepeatGeneration++
547 generation := h.vimScrollRepeatGeneration
548 h.vimScrollRepeatAction = action
549 h.vimScrollRepeatKeyval = keyval
550 h.vimScrollRepeatPressedAt = h.vimScrollNow()
551 cb := glib.SourceFunc(func(_ uintptr) bool {
552 return h.vimScrollRepeatTick(action, keyval, generation)
553 })
554 h.vimScrollRepeatCb = cb
555 add := h.vimScrollRepeatAdd
556 id := add(uint(vimScrollCadence/time.Millisecond), &h.vimScrollRepeatCb)
557 if id == 0 {
558 h.clearVimScrollRepeatLocked()
559 h.mu.Unlock()
560 return
561 }
562 h.vimScrollRepeatTimer = id
563 h.mu.Unlock()
564}
565
566func (h *KeyboardHandler) vimScrollRepeatTick(action Action, keyval uint, generation uint64) bool {
567 h.mu.RLock()
568 active := h.vimScrollRepeatAction == action && h.vimScrollRepeatKeyval == keyval &&
569 h.vimScrollRepeatTimer != 0 && h.vimScrollRepeatGeneration == generation
570 pressedAt := h.vimScrollRepeatPressedAt
571 now := h.vimScrollNow
572 h.mu.RUnlock()
573 if !active || h.modal.Mode() != ModeVim {
574 return false
575 }
576 if now().Sub(pressedAt) < vimScrollHoldDelay {
577 return true
578 }
579 // Continuous dispatch bypasses dispatchAction, so refresh Vim Mode timeout here.
580 h.modal.ResetTimeout(h.ctx)
581 h.dispatchVimScrollLifecycle(action, VimScrollContinuous)
582 return true
583}
584
585func (h *KeyboardHandler) stopVimScrollRepeat() {
586 h.mu.Lock()
587 action := h.vimScrollRepeatAction
588 timerID := h.vimScrollRepeatTimer
589 remove := h.vimScrollRepeatRemove
590 h.clearVimScrollRepeatLocked()
591 h.mu.Unlock()
592 if timerID != 0 && remove != nil {
593 remove(timerID)
594 }
595 if action != "" {
596 h.dispatchVimScrollLifecycle(action, VimScrollStop)
597 }
598}
599
600func (h *KeyboardHandler) clearVimScrollRepeatLocked() {
601 h.vimScrollRepeatGeneration++
602 h.vimScrollRepeatAction = ""
603 h.vimScrollRepeatKeyval = 0
604 h.vimScrollRepeatTimer = 0
605 h.vimScrollRepeatPressedAt = time.Time{}
606 h.vimScrollRepeatCb = nil
607}
608
609func (h *KeyboardHandler) dispatchVimScrollLifecycle(action Action, phase VimScrollPhase) {
610 h.mu.RLock()
611 handler := h.onVimScrollLifecycle
612 h.mu.RUnlock()
613 if handler == nil {
614 if phase == VimScrollContinuous {
615 h.dispatchAction(action, ModeVim)
616 }
617 return
618 }
619 if err := handler(h.ctx, action, phase); err != nil {
620 logging.FromContext(h.ctx).Error().Err(err).Str("action", string(action)).Msg("vim scroll lifecycle handler error")
621 }
622}
623
624// tryAccentDetection starts long-press detection for accent-eligible keys.
625// It is used only for the RouteAccentDetection route (GTK Entry widgets such as
626// the omnibox and find bar). RoutePassToWidget does not call tryAccentDetection;
627// WebView long-press accent behavior is handled entirely by the injected JS bridge
628// (accentDetectionScript) and the Go-side accent key detection script, not here.
629// Returns true if the key should be suppressed (i.e. RouteAccentDetection consumed it).
630func (h *KeyboardHandler) tryAccentDetection(accentHandler AccentHandler, keyval uint, modifiers Modifier) bool {
631 if accentHandler == nil {
632 return false
633 }
634 // Only consider keys without Ctrl/Alt modifiers (Shift is OK for uppercase)
635 if modifiers != 0 && modifiers != ModShift {
636 return false
637 }
638 if char := KeyvalToRune(keyval); char != 0 {
639 return accentHandler.OnKeyPressed(h.ctx, char, modifiers == ModShift)
640 }
641 return false
642}
643
644// normalizeKeyval converts uppercase A-Z to lowercase for consistent binding lookup.
645func normalizeKeyval(keyval uint) uint {
646 if keyval >= uint('A') && keyval <= uint('Z') {
647 return keyval + (uint('a') - uint('A'))
648 }
649 return keyval
650}
651
652func (h *KeyboardHandler) handlePageFocusNavigation(keyval uint, modifiers Modifier) bool {
653 h.mu.RLock()
654 handler := h.onPageFocusNavigation
655 h.mu.RUnlock()
656 if handler == nil {
657 return false
658 }
659 backward := keyval == uint(gdk.KEY_ISO_Left_Tab) || modifiers == ModShift
660 return handler(h.ctx, backward)
661}
662
663func shouldPassthroughNativePageFocusNavigation(mode Mode, keyval uint, modifiers Modifier) bool {
664 if mode != ModeNormal && mode != ModeVim {
665 return false
666 }
667 switch keyval {
668 case uint(gdk.KEY_Tab), uint(gdk.KEY_ISO_Left_Tab):
669 return modifiers == ModNone || modifiers == ModShift
670 default:
671 return false
672 }
673}
674
675func shouldPassthroughNativeVimModeNavigation(mode Mode, keyval uint, modifiers Modifier) bool {
676 if mode != ModeVim {
677 return false
678 }
679 switch keyval {
680 case uint(gdk.KEY_Left), uint(gdk.KEY_Right), uint(gdk.KEY_Up), uint(gdk.KEY_Down):
681 return modifiers == ModNone
682 case uint(gdk.KEY_Tab), uint(gdk.KEY_ISO_Left_Tab):
683 return modifiers == ModNone || modifiers == ModShift
684 default:
685 return false
686 }
687}
688
689func (h *KeyboardHandler) confirmVimMode() {
690 h.stopVimScrollRepeat()
691 h.seq.mu.Lock()
692 onAction := h.seq.onAction
693 h.seq.mu.Unlock()
694 if onAction != nil {
695 onAction("confirm", 0)
696 }
697 h.modal.ExitMode(h.ctx)
698}
699
700// dispatchAction dispatches the action and handles mode-related logic.
701func (h *KeyboardHandler) dispatchAction(action Action, mode Mode) bool {
702 if h.handleModeAction(action) {
703 return true
704 }
705
706 h.mu.RLock()
707 handler := h.onAction
708 h.mu.RUnlock()
709
710 if handler != nil {
711 if err := handler(h.ctx, action); err != nil {
712 log := logging.FromContext(h.ctx)
713 log.Error().Err(err).Str("action", string(action)).Msg("action handler error")
714 }
715 }
716
717 if mode == ModeResize && isResizeAction(action) {
718 h.modal.ResetTimeout(h.ctx)
719 }
720 if mode == ModeVim && isVimScrollAction(action) {
721 h.modal.ResetTimeout(h.ctx)
722 }
723
724 if mode != ModeNormal && ShouldAutoExitMode(action) {
725 h.modal.ExitMode(h.ctx)
726 }
727
728 return true // Consumed the key
729}
730
731func (h *KeyboardHandler) suppressHeldAction(action Action, keyval uint) bool {
732 if h == nil || !isRepeatedKeyboardActionSuppressed(action) {
733 return false
734 }
735
736 h.mu.Lock()
737 defer h.mu.Unlock()
738 if h.activePressedActions == nil {
739 return true
740 }
741 if pressedKeyval, ok := h.activePressedActions[action]; ok && pressedKeyval == keyval {
742 return true
743 }
744 h.activePressedActions[action] = keyval
745 return false
746}
747
748func isRepeatedKeyboardActionSuppressed(action Action) bool {
749 if isRepeatedGlobalShortcutSuppressed(action) {
750 return true
751 }
752 switch action {
753 case ActionEnterTabMode,
754 ActionEnterPaneMode,
755 ActionEnterSessionMode,
756 ActionEnterResizeMode,
757 ActionEnterVimMode,
758 ActionNewTab,
759 ActionRenameTab,
760 ActionSplitRight,
761 ActionSplitLeft,
762 ActionSplitUp,
763 ActionSplitDown,
764 ActionStackPane,
765 ActionMovePaneToTab,
766 ActionMovePaneToNextTab:
767 return true
768 default:
769 return false
770 }
771}
772
773func (h *KeyboardHandler) lookupAction(
774 log *zerolog.Logger,
775 binding KeyBinding,
776 mode Mode,
777 modifiers Modifier,
778 keycode uint,
779) (Action, bool) {
780 action, found := h.shortcuts.Lookup(binding, mode)
781
782 // Fallback: check hardware keycode for Alt+number shortcuts on non-QWERTY layouts.
783 if !found && mode == ModeNormal && modifiers == ModAlt {
784 if keycodeAction, ok := KeycodeToTabAction[keycode]; ok {
785 action = keycodeAction
786 found = true
787 if log != nil {
788 log.Debug().
789 Uint("keycode", keycode).
790 Str("action", string(action)).
791 Msg("tab switch via hardware keycode fallback (non-QWERTY layout)")
792 }
793 }
794 }
795
796 if !found && mode == ModeNormal && (modifiers == ModAlt || modifiers == (ModAlt|ModShift)) {
797 if bracketActions, ok := KeycodeToBracketAction[keycode]; ok {
798 if modifiers == (ModAlt | ModShift) {
799 action = bracketActions.WithShift
800 } else {
801 action = bracketActions.NoShift
802 }
803 found = action != ""
804 if found && log != nil {
805 log.Debug().
806 Uint("keycode", keycode).
807 Str("action", string(action)).
808 Msg("consume/expel via hardware keycode fallback (non-QWERTY layout)")
809 }
810 }
811 }
812
813 return action, found
814}
815
816func isResizeAction(action Action) bool {
817 switch action {
818 case ActionResizeIncreaseLeft,
819 ActionResizeIncreaseRight,
820 ActionResizeIncreaseUp,
821 ActionResizeIncreaseDown,
822 ActionResizeDecreaseLeft,
823 ActionResizeDecreaseRight,
824 ActionResizeDecreaseUp,
825 ActionResizeDecreaseDown,
826 ActionResizeIncrease,
827 ActionResizeDecrease:
828 return true
829 default:
830 return false
831 }
832}
833
834func isVimScrollAction(action Action) bool {
835 switch action {
836 case ActionVimScrollLeft,
837 ActionVimScrollDown,
838 ActionVimScrollUp,
839 ActionVimScrollRight,
840 ActionVimScrollDownFast,
841 ActionVimScrollUpFast:
842 return true
843 default:
844 return false
845 }
846}
847
848func (h *KeyboardHandler) handleVimModeAction(action Action, workspace *entity.WorkspaceConfig) bool {
849 switch action {
850 case ActionEnterVimMode:
851 if h.modal.Mode() == ModeVim {
852 h.stopVimScrollRepeat()
853 h.modal.ExitMode(h.ctx)
854 return true
855 }
856 var timeoutMS int
857 if workspace != nil {
858 timeoutMS = workspace.VimMode.TimeoutMilliseconds
859 }
860 h.modal.EnterVimMode(h.ctx, time.Duration(timeoutMS)*time.Millisecond)
861 return true
862 case ActionVimConfirm:
863 if h.modal.Mode() == ModeVim {
864 h.confirmVimMode()
865 }
866 return true
867 default:
868 return false
869 }
870}
871
872func (h *KeyboardHandler) handleModeAction(action Action) bool {
873 h.mu.RLock()
874 workspace := h.workspace
875 session := h.session
876 h.mu.RUnlock()
877
878 if h.handleVimModeAction(action, workspace) {
879 return true
880 }
881
882 switch action {
883 case ActionEnterTabMode:
884 var ms int
885 if workspace != nil {
886 ms = workspace.TabMode.TimeoutMilliseconds
887 }
888 h.modal.EnterTabMode(h.ctx, time.Duration(ms)*time.Millisecond)
889 return true
890 case ActionEnterPaneMode:
891 var ms int
892 if workspace != nil {
893 ms = workspace.PaneMode.TimeoutMilliseconds
894 }
895 h.modal.EnterPaneMode(h.ctx, time.Duration(ms)*time.Millisecond)
896 return true
897 case ActionEnterSessionMode:
898 var ms int
899 if session != nil {
900 ms = session.SessionMode.TimeoutMilliseconds
901 }
902 h.modal.EnterSessionMode(h.ctx, time.Duration(ms)*time.Millisecond)
903 return true
904 case ActionEnterResizeMode:
905 if h.modal.Mode() == ModeResize {
906 h.modal.ExitMode(h.ctx)
907 return true
908 }
909 var ms int
910 if workspace != nil {
911 ms = workspace.ResizeMode.TimeoutMilliseconds
912 }
913 h.modal.EnterResizeMode(h.ctx, time.Duration(ms)*time.Millisecond)
914 return true
915 case ActionExitMode:
916 if h.modal.Mode() == ModeVim {
917 h.stopVimScrollRepeat()
918 }
919 h.modal.ExitMode(h.ctx)
920 return true
921 default:
922 return false
923 }
924}
925
926// EnterTabMode programmatically enters tab mode.
927// Useful for testing or programmatic mode changes.
928func (h *KeyboardHandler) EnterTabMode() {
929 h.mu.RLock()
930 workspace := h.workspace
931 h.mu.RUnlock()
932 var ms int
933 if workspace != nil {
934 ms = workspace.TabMode.TimeoutMilliseconds
935 }
936 h.modal.EnterTabMode(h.ctx, time.Duration(ms)*time.Millisecond)
937}
938
939// EnterPaneMode programmatically enters pane mode.
940// Useful for testing or programmatic mode changes.
941func (h *KeyboardHandler) EnterPaneMode() {
942 h.mu.RLock()
943 workspace := h.workspace
944 h.mu.RUnlock()
945 var ms int
946 if workspace != nil {
947 ms = workspace.PaneMode.TimeoutMilliseconds
948 }
949 h.modal.EnterPaneMode(h.ctx, time.Duration(ms)*time.Millisecond)
950}
951
952// EnterSessionMode programmatically enters session mode.
953// Useful for testing or programmatic mode changes.
954func (h *KeyboardHandler) EnterSessionMode() {
955 h.mu.RLock()
956 session := h.session
957 h.mu.RUnlock()
958 var ms int
959 if session != nil {
960 ms = session.SessionMode.TimeoutMilliseconds
961 }
962 h.modal.EnterSessionMode(h.ctx, time.Duration(ms)*time.Millisecond)
963}
964
965// EnterVimMode programmatically enters Vim-style scrolling mode.
966// Useful for testing or programmatic mode changes.
967func (h *KeyboardHandler) EnterVimMode() {
968 h.mu.RLock()
969 workspace := h.workspace
970 h.mu.RUnlock()
971 var ms int
972 if workspace != nil {
973 ms = workspace.VimMode.TimeoutMilliseconds
974 }
975 h.modal.EnterVimMode(h.ctx, time.Duration(ms)*time.Millisecond)
976}
977
978// ExitMode programmatically exits modal mode.
979// Useful for testing or programmatic mode changes.
980func (h *KeyboardHandler) ExitMode() {
981 h.modal.ExitMode(h.ctx)
982}
983
984func (h *KeyboardHandler) shouldPassthroughVimModeActivation(action Action, mode Mode) bool {
985 if action != ActionEnterVimMode || mode != ModeNormal {
986 return false
987 }
988 h.mu.RLock()
989 passthrough := h.vimModeActivationPassthrough
990 h.mu.RUnlock()
991 return passthrough != nil && passthrough()
992}
993
994// DispatchAction processes an action externally triggered (e.g., by a global
995// shortcut). Mode-enter actions update modal state; other actions are forwarded
996// to the registered action handler. It returns whether the action was consumed.
997func (h *KeyboardHandler) DispatchAction(action Action) bool {
998 mode := h.modal.Mode()
999 if h.shouldPassthroughVimModeActivation(action, mode) {
1000 return false
1001 }
1002 h.dispatchAction(action, mode)
1003 return true
1004}
1005
1006// handleKeyRelease processes a key release event for accent detection.
1007func (h *KeyboardHandler) handleKeyRelease(keyval uint) {
1008 keyval = normalizeKeyval(keyval)
1009 h.mu.Lock()
1010 accentHandler := h.accentHandler
1011 if len(h.activePressedActions) > 0 {
1012 for action, pressedKeyval := range h.activePressedActions {
1013 if pressedKeyval == keyval {
1014 delete(h.activePressedActions, action)
1015 }
1016 }
1017 }
1018 stopVimScroll := h.vimScrollRepeatKeyval == keyval
1019 h.mu.Unlock()
1020 if stopVimScroll {
1021 h.stopVimScrollRepeat()
1022 }
1023
1024 if accentHandler == nil {
1025 return
1026 }
1027
1028 // Convert keyval to rune for the accent handler
1029 if char := KeyvalToRune(keyval); char != 0 {
1030 accentHandler.OnKeyReleased(h.ctx, char)
1031 }
1032}
1033
1034// KeyvalToRune converts a GTK keyval to a lowercase rune.
1035// Returns 0 if the keyval is not a printable character with potential accents.
1036func KeyvalToRune(keyval uint) rune {
1037 // Handle lowercase a-z
1038 if keyval >= uint('a') && keyval <= uint('z') {
1039 return rune(keyval)
1040 }
1041 // Handle uppercase A-Z (convert to lowercase for accent lookup)
1042 if keyval >= uint('A') && keyval <= uint('Z') {
1043 return rune(keyval + ('a' - 'A'))
1044 }
1045 return 0
1046}
1047
1048// KeyRoute determines how a key event should be routed.
1049type KeyRoute int
1050
1051const (
1052 // RouteHandleShortcuts means the key should be processed by the shortcut system.
1053 // This is the default route -- app-level shortcuts, modal mode keys, etc.
1054 RouteHandleShortcuts KeyRoute = iota
1055
1056 // RoutePassToWidget means the key should propagate to the focused widget.
1057 // Used when overlays (session manager, tab picker) are visible, or when a
1058 // WebView should receive text input for native IM/compose/dead-key processing.
1059 // Long-press accent detection still runs first for accessibility: users with
1060 // motor disabilities may not be able to execute rapid compose sequences.
1061 RoutePassToWidget
1062
1063 // RouteAccentDetection means the key should go through long-press accent
1064 // detection, then pass to the focused widget. Used for GTK Entry widgets
1065 // (omnibox, find bar) and as a universal accessibility fallback.
1066 RouteAccentDetection
1067)
1068
1069// KeyContext provides key event information for routing decisions.
1070type KeyContext struct {
1071 Keyval uint // Translated key value
1072 Keycode uint // Hardware keycode
1073 Modifiers Modifier // Active modifiers (masked)
1074}
1075
1076// IsShortcutModified returns true if the modifiers indicate a shortcut combination
1077// (Ctrl or Alt pressed), as opposed to plain text input (no modifier or Shift-only).
1078// Dead keys and compose sequences only use no-modifier or Shift, so this correctly
1079// identifies keys that should be intercepted vs passed through to the IM pipeline.
1080func IsShortcutModified(modifiers Modifier) bool {
1081 return modifiers&(ModCtrl|ModAlt) != 0
1082}
1083
1084// IsTextInputKey returns true if the keyval represents a text input key
1085// (printable character or dead key) as opposed to a function/navigation key.
1086// This is used to determine whether a key should be passed through to the
1087// WebKit IM pipeline for compose/dead-key processing.
1088func IsTextInputKey(keyval uint) bool {
1089 // Dead keys used by compose sequences (US International, etc.)
1090 // GDK dead key range: KEY_dead_grave (0xfe50) to KEY_dead_greek (0xfe8c)
1091 if keyval >= 0xfe50 && keyval <= 0xfe8c {
1092 return true
1093 }
1094
1095 // Printable ASCII range (space through tilde)
1096 if keyval >= 0x020 && keyval <= 0x07e {
1097 return true
1098 }
1099 // Latin-1 supplement (non-breaking space through ÿ)
1100 if keyval >= 0x0a0 && keyval <= 0x0ff {
1101 return true
1102 }
1103 // Extended Latin and other Unicode characters mapped in GDK keyval space
1104 if keyval >= 0x100 && keyval <= 0x20ff {
1105 return true
1106 }
1107
1108 return false
1109}