gioui.org@v0.6.1-0.20240506124620-7a9ce51988ce/gesture/gesture_test.go (about) 1 // SPDX-License-Identifier: Unlicense OR MIT 2 3 package gesture 4 5 import ( 6 "image" 7 "testing" 8 "time" 9 10 "gioui.org/f32" 11 "gioui.org/io/event" 12 "gioui.org/io/input" 13 "gioui.org/io/pointer" 14 "gioui.org/op" 15 "gioui.org/op/clip" 16 ) 17 18 func TestHover(t *testing.T) { 19 ops := new(op.Ops) 20 var h Hover 21 rect := image.Rect(20, 20, 40, 40) 22 stack := clip.Rect(rect).Push(ops) 23 h.Add(ops) 24 stack.Pop() 25 r := new(input.Router) 26 h.Update(r.Source()) 27 r.Frame(ops) 28 29 r.Queue( 30 pointer.Event{Kind: pointer.Move, Position: f32.Pt(30, 30)}, 31 ) 32 if !h.Update(r.Source()) { 33 t.Fatal("expected hovered") 34 } 35 36 r.Queue( 37 pointer.Event{Kind: pointer.Move, Position: f32.Pt(50, 50)}, 38 ) 39 if h.Update(r.Source()) { 40 t.Fatal("expected not hovered") 41 } 42 } 43 44 func TestMouseClicks(t *testing.T) { 45 for _, tc := range []struct { 46 label string 47 events []event.Event 48 clicks []int // number of combined clicks per click (single, double...) 49 }{ 50 { 51 label: "single click", 52 events: mouseClickEvents(200 * time.Millisecond), 53 clicks: []int{1}, 54 }, 55 { 56 label: "double click", 57 events: mouseClickEvents( 58 100*time.Millisecond, 59 100*time.Millisecond+doubleClickDuration-1), 60 clicks: []int{1, 2}, 61 }, 62 { 63 label: "two single clicks", 64 events: mouseClickEvents( 65 100*time.Millisecond, 66 100*time.Millisecond+doubleClickDuration+1), 67 clicks: []int{1, 1}, 68 }, 69 } { 70 t.Run(tc.label, func(t *testing.T) { 71 var click Click 72 var ops op.Ops 73 click.Add(&ops) 74 75 var r input.Router 76 click.Update(r.Source()) 77 r.Frame(&ops) 78 r.Queue(tc.events...) 79 80 var clicks []ClickEvent 81 for { 82 ev, ok := click.Update(r.Source()) 83 if !ok { 84 break 85 } 86 if ev.Kind == KindClick { 87 clicks = append(clicks, ev) 88 } 89 } 90 if got, want := len(clicks), len(tc.clicks); got != want { 91 t.Fatalf("got %d mouse clicks, expected %d", got, want) 92 } 93 94 for i, click := range clicks { 95 if got, want := click.NumClicks, tc.clicks[i]; got != want { 96 t.Errorf("got %d combined mouse clicks, expected %d", got, want) 97 } 98 } 99 }) 100 } 101 } 102 103 func mouseClickEvents(times ...time.Duration) []event.Event { 104 press := pointer.Event{ 105 Kind: pointer.Press, 106 Source: pointer.Mouse, 107 Buttons: pointer.ButtonPrimary, 108 } 109 events := make([]event.Event, 0, 2*len(times)) 110 for _, t := range times { 111 press := press 112 press.Time = t 113 release := press 114 release.Kind = pointer.Release 115 events = append(events, press, release) 116 } 117 return events 118 }