touchpad_gestures.go RawHistoryFolder
1package webkit
2
3import (
4 "log"
5 "math"
6
7 "github.com/diamondburned/gotk4/pkg/gtk/v4"
8)
9
10// Touchpad swipe velocity threshold (pixels per second)
11// Lower values make gestures more sensitive, higher values require faster swipes
12const (
13 swipeVelocityThreshold = 500.0 // Reasonable threshold for intentional swipes
14)
15
16// AttachTouchpadGestures attaches touchpad swipe gesture handling to the WebView
17// This enables two-finger swipe navigation (left/right for back/forward)
18func (w *WebView) AttachTouchpadGestures() {
19 if w.view == nil {
20 log.Printf("[touchpad-gestures] Cannot attach: WebView is nil")
21 return
22 }
23
24 // Create gesture controller for swipe detection
25 gestureSwipe := gtk.NewGestureSwipe()
26
27 // Set to capture phase to intercept before WebView processes
28 gestureSwipe.SetPropagationPhase(gtk.PhaseCapture)
29
30 // Set to require touchpad (2 fingers minimum for touchpad gestures)
31 // This prevents single-finger drags from triggering navigation
32 gestureSwipe.SetTouchOnly(false) // Allow both touch and touchpad
33
34 // Connect to swipe signal
35 gestureSwipe.ConnectSwipe(func(velocityX, velocityY float64) {
36 // Only process horizontal swipes (ignore mostly vertical swipes)
37 // Use absolute values to compare magnitudes
38 absVelocityX := math.Abs(velocityX)
39 absVelocityY := math.Abs(velocityY)
40
41 // Require horizontal velocity to be dominant
42 if absVelocityY > absVelocityX {
43 log.Printf("[touchpad-gestures] Swipe is more vertical (X:%.1f Y:%.1f), ignoring", velocityX, velocityY)
44 return
45 }
46
47 // Check if swipe velocity meets threshold
48 if absVelocityX < swipeVelocityThreshold {
49 log.Printf("[touchpad-gestures] Swipe velocity too low (%.1f < %.1f), ignoring", absVelocityX, swipeVelocityThreshold)
50 return
51 }
52
53 // Determine swipe direction and navigate
54 if velocityX > 0 {
55 // Swipe right (positive velocity) - go back
56 if w.view.CanGoBack() {
57 log.Printf("[touchpad-gestures] Swipe right detected (velocity: %.1f) - navigating backward", velocityX)
58 w.view.GoBack()
59 } else {
60 log.Printf("[touchpad-gestures] Swipe right detected but cannot go back")
61 }
62 } else {
63 // Swipe left (negative velocity) - go forward
64 if w.view.CanGoForward() {
65 log.Printf("[touchpad-gestures] Swipe left detected (velocity: %.1f) - navigating forward", velocityX)
66 w.view.GoForward()
67 } else {
68 log.Printf("[touchpad-gestures] Swipe left detected but cannot go forward")
69 }
70 }
71 })
72
73 // Attach controller to WebView
74 w.view.AddController(gestureSwipe)
75 log.Printf("[touchpad-gestures] Touchpad gesture controller attached to WebView ID %d", w.id)
76}