detached 3f871c1

#140 feat(core): delay hover focus with focus.follow-mouse-delay

state
merged · 808463e · merge commit
branch
feat/hover-focus-delay → main
opened
bnema ·
updated

Adds focus.follow-mouse-delay (default 150ms, 0 = immediate) so hover focus only switches after the pointer dwells in a window. Brief passes, notably over stash neighbours, no longer change focus.

  • Core-owned dwell timer (ports.Clock), re-armed on target change, cancelled on button press and on config reload changing follow-mouse settings.
  • On expiry, re-validates hover guards and hit-tests the cursor again.
  • Config parsing, docs and example updated; synctest coverage for dwell, pass-through, stash neighbours, button cancel, stale hit and reload.

Checks: make check, make race, make mocks-check, staticcheck; headless e2e dwell test.

CommitSubjectAuthorDateSignatureStatus
3f871c1fix(core): revalidate pending hover focus against hit and config reloadbrice GPG Verified
a9c7cd7feat(core): delay hover focus with focus.follow-mouse-delaybrice GPG Verified

Checks 1

23 files · +388 -797
1/1
M docs/config.md +1 -0
@@ -55,6 +55,7 @@ See [examples/config](../examples/config) for every key with its default.
5555 | `animations.speed` | `normal` | `slow`, `normal`, `fast`, or a factor from `0.1` to `10` |
5656 | `navigation.edge` | `screen` | Focus past a content edge: `screen` visits only a neighbor screen; `workspace` also visits workspaces on the layout's workspace axis |
5757 | `focus.follow-move` | `off` | Follow a column moved to another workspace |
58+| `focus.follow-mouse-delay` | `150ms` | Dwell before hover focus; non-negative duration, `0` for immediate focus |
5859 | `focus.follow-mouse` | `off` | Focus the window the pointer moves into; a keyboard focus change holds until the pointer enters another window |
5960 | `focus.position-hint` | `on` | Show workspace/band dots near the output bottom for 600ms after a position change, then fade for 150ms (no fade with animations off); hidden in overview, fullscreen and session lock; never captured |
6061 | `focus.flash` | `on` | Briefly draw an inner border, inside the window border, on the window or column an action changed |
@@ -55,6 +55,7 @@ See [examples/config](../examples/config) for every key with its default.
55 | `animations.speed` | `normal` | `slow`, `normal`, `fast`, or a factor from `0.1` to `10` |55 | `animations.speed` | `normal` | `slow`, `normal`, `fast`, or a factor from `0.1` to `10` |
56 | `navigation.edge` | `screen` | Focus past a content edge: `screen` visits only a neighbor screen; `workspace` also visits workspaces on the layout's workspace axis |56 | `navigation.edge` | `screen` | Focus past a content edge: `screen` visits only a neighbor screen; `workspace` also visits workspaces on the layout's workspace axis |
57 | `focus.follow-move` | `off` | Follow a column moved to another workspace |57 | `focus.follow-move` | `off` | Follow a column moved to another workspace |
58+| `focus.follow-mouse-delay` | `150ms` | Dwell before hover focus; non-negative duration, `0` for immediate focus |
58 | `focus.follow-mouse` | `off` | Focus the window the pointer moves into; a keyboard focus change holds until the pointer enters another window |59 | `focus.follow-mouse` | `off` | Focus the window the pointer moves into; a keyboard focus change holds until the pointer enters another window |
59 | `focus.position-hint` | `on` | Show workspace/band dots near the output bottom for 600ms after a position change, then fade for 150ms (no fade with animations off); hidden in overview, fullscreen and session lock; never captured |60 | `focus.position-hint` | `on` | Show workspace/band dots near the output bottom for 600ms after a position change, then fade for 150ms (no fade with animations off); hidden in overview, fullscreen and session lock; never captured |
60 | `focus.flash` | `on` | Briefly draw an inner border, inside the window border, on the window or column an action changed |61 | `focus.flash` | `on` | Briefly draw an inner border, inside the window border, on the window or column an action changed |
M examples/config +1 -0
@@ -86,6 +86,7 @@ focus.follow-move = off
8686 # on: the window the pointer moves into gets focus; a keyboard focus change
8787 # holds until the pointer enters another window.
8888 focus.follow-mouse = off
89+focus.follow-mouse-delay = 150ms
8990 # Animations are on by default.
9091 # on: windows and the view move with springs, windows fade in and out as
9192 # they open, close or leave with the stash, the overview zooms its cards;
@@ -86,6 +86,7 @@ focus.follow-move = off
86 # on: the window the pointer moves into gets focus; a keyboard focus change86 # on: the window the pointer moves into gets focus; a keyboard focus change
87 # holds until the pointer enters another window.87 # holds until the pointer enters another window.
88 focus.follow-mouse = off88 focus.follow-mouse = off
89+focus.follow-mouse-delay = 150ms
89 # Animations are on by default.90 # Animations are on by default.
90 # on: windows and the view move with springs, windows fade in and out as91 # on: windows and the view move with springs, windows fade in and out as
91 # they open, close or leave with the stash, the overview zooms its cards;92 # they open, close or leave with the stash, the overview zooms its cards;
M internal/adapters/config/config.go +7 -0
@@ -149,6 +149,7 @@ func Defaults() domain.Config {
149149 // Animations are on unless the config turns them off.
150150 c.Animations.On = true
151151 c.Animations.Slowdown = normalSlowdown
152+ c.Focus.FollowMouseDelay = 150 * time.Millisecond
152153 c.Focus.PositionHint = true
153154 c.OSD.Enable = true
154155 c.Focus.Flash = true
@@ -915,6 +916,12 @@ func set(c *domain.Config, key, v string) error {
915916 return err
916917 }
917918 c.Focus.FollowMouse = b
919+ case "focus.follow-mouse-delay":
920+ d, err := time.ParseDuration(v)
921+ if err != nil || d < 0 {
922+ return fmt.Errorf("must be a non-negative duration, e.g. 150ms (0 for immediate)")
923+ }
924+ c.Focus.FollowMouseDelay = d
918925 case "focus.position-hint":
919926 b, err := onOff(v)
920927 if err != nil {
@@ -149,6 +149,7 @@ func Defaults() domain.Config {
149 // Animations are on unless the config turns them off.149 // Animations are on unless the config turns them off.
150 c.Animations.On = true150 c.Animations.On = true
151 c.Animations.Slowdown = normalSlowdown151 c.Animations.Slowdown = normalSlowdown
152+ c.Focus.FollowMouseDelay = 150 * time.Millisecond
152 c.Focus.PositionHint = true153 c.Focus.PositionHint = true
153 c.OSD.Enable = true154 c.OSD.Enable = true
154 c.Focus.Flash = true155 c.Focus.Flash = true
@@ -915,6 +916,12 @@ func set(c *domain.Config, key, v string) error {
915 return err916 return err
916 }917 }
917 c.Focus.FollowMouse = b918 c.Focus.FollowMouse = b
919+ case "focus.follow-mouse-delay":
920+ d, err := time.ParseDuration(v)
921+ if err != nil || d < 0 {
922+ return fmt.Errorf("must be a non-negative duration, e.g. 150ms (0 for immediate)")
923+ }
924+ c.Focus.FollowMouseDelay = d
918 case "focus.position-hint":925 case "focus.position-hint":
919 b, err := onOff(v)926 b, err := onOff(v)
920 if err != nil {927 if err != nil {
M internal/adapters/config/config_test.go +27 -0
@@ -1287,3 +1287,30 @@ func TestLogDebugNames(t *testing.T) {
12871287 }
12881288 }
12891289 }
1290+
1291+func TestFollowMouseDelay(t *testing.T) {
1292+ for _, tt := range []struct {
1293+ value string
1294+ want time.Duration
1295+ warnings int
1296+ }{
1297+ {"", 150 * time.Millisecond, 0},
1298+ {"0", 0, 0},
1299+ {"250ms", 250 * time.Millisecond, 0},
1300+ {"1s", time.Second, 0},
1301+ {"-1ms", 150 * time.Millisecond, 1},
1302+ {"150", 150 * time.Millisecond, 1},
1303+ {"invalid", 150 * time.Millisecond, 1},
1304+ } {
1305+ t.Run(tt.value, func(t *testing.T) {
1306+ text := ""
1307+ if tt.value != "" {
1308+ text = "focus.follow-mouse-delay = " + tt.value + "\n"
1309+ }
1310+ c, warnings := parseString(t, text)
1311+ if c.Focus.FollowMouseDelay != tt.want || len(warnings) != tt.warnings {
1312+ t.Fatalf("delay %s warnings %v", c.Focus.FollowMouseDelay, warnings)
1313+ }
1314+ })
1315+ }
1316+}
@@ -1287,3 +1287,30 @@ func TestLogDebugNames(t *testing.T) {
1287 }1287 }
1288 }1288 }
1289 }1289 }
1290+
1291+func TestFollowMouseDelay(t *testing.T) {
1292+ for _, tt := range []struct {
1293+ value string
1294+ want time.Duration
1295+ warnings int
1296+ }{
1297+ {"", 150 * time.Millisecond, 0},
1298+ {"0", 0, 0},
1299+ {"250ms", 250 * time.Millisecond, 0},
1300+ {"1s", time.Second, 0},
1301+ {"-1ms", 150 * time.Millisecond, 1},
1302+ {"150", 150 * time.Millisecond, 1},
1303+ {"invalid", 150 * time.Millisecond, 1},
1304+ } {
1305+ t.Run(tt.value, func(t *testing.T) {
1306+ text := ""
1307+ if tt.value != "" {
1308+ text = "focus.follow-mouse-delay = " + tt.value + "\n"
1309+ }
1310+ c, warnings := parseString(t, text)
1311+ if c.Focus.FollowMouseDelay != tt.want || len(warnings) != tt.warnings {
1312+ t.Fatalf("delay %s warnings %v", c.Focus.FollowMouseDelay, warnings)
1313+ }
1314+ })
1315+ }
1316+}
M internal/adapters/wayland/acquire_failure_test.go +2 -8
@@ -271,22 +271,16 @@ func TestFailedRootRetiresEveryChildPredecessorGraph(t *testing.T) {
271271 child.queueUpdate()
272272 later := child.queue[2]
273273 u.applyGraph()
274- if len(child.queue) != 1 || child.queue[0] != later || len(a.queue) != 0 || len(b.queue) != 0 || tl.uses != 4 || len(h.s.deferredReleases) != 2 {
274+ if len(child.queue) != 1 || child.queue[0] != later || len(a.queue) != 0 || len(b.queue) != 0 || tl.uses != 0 {
275275 t.Errorf("retirement stranded prefix graphs: uses=%d child=%d a=%d b=%d", tl.uses, len(child.queue), len(a.queue), len(b.queue))
276276 }
277277 for i, g := range graphs {
278- if !g.retired || g.refs != 1 || waits[i].cancelled.Load() {
278+ if !g.retired || g.refs != 1 || !waits[i].cancelled.Load() {
279279 t.Error("grandchild not safely retired")
280280 }
281281 g.releaseRef()
282282 }
283283 child.dropQueue()
284- // Retired graphs no longer own points; shutdown abandons the two
285- // deferred releases and cancels their waits without signalling.
286- h.s.drainDeferredReleases(true)
287- if tl.uses != 0 {
288- t.Errorf("deferred references leaked: %d", tl.uses)
289- }
290284 })
291285 if len(h.signalled()) != 0 {
292286 t.Fatal("release signalled before acquire")
@@ -271,22 +271,16 @@ func TestFailedRootRetiresEveryChildPredecessorGraph(t *testing.T) {
271 child.queueUpdate()271 child.queueUpdate()
272 later := child.queue[2]272 later := child.queue[2]
273 u.applyGraph()273 u.applyGraph()
274- if len(child.queue) != 1 || child.queue[0] != later || len(a.queue) != 0 || len(b.queue) != 0 || tl.uses != 4 || len(h.s.deferredReleases) != 2 {274+ if len(child.queue) != 1 || child.queue[0] != later || len(a.queue) != 0 || len(b.queue) != 0 || tl.uses != 0 {
275 t.Errorf("retirement stranded prefix graphs: uses=%d child=%d a=%d b=%d", tl.uses, len(child.queue), len(a.queue), len(b.queue))275 t.Errorf("retirement stranded prefix graphs: uses=%d child=%d a=%d b=%d", tl.uses, len(child.queue), len(a.queue), len(b.queue))
276 }276 }
277 for i, g := range graphs {277 for i, g := range graphs {
278- if !g.retired || g.refs != 1 || waits[i].cancelled.Load() {278+ if !g.retired || g.refs != 1 || !waits[i].cancelled.Load() {
279 t.Error("grandchild not safely retired")279 t.Error("grandchild not safely retired")
280 }280 }
281 g.releaseRef()281 g.releaseRef()
282 }282 }
283 child.dropQueue()283 child.dropQueue()
284- // Retired graphs no longer own points; shutdown abandons the two
285- // deferred releases and cancels their waits without signalling.
286- h.s.drainDeferredReleases(true)
287- if tl.uses != 0 {
288- t.Errorf("deferred references leaked: %d", tl.uses)
289- }
290 })284 })
291 if len(h.signalled()) != 0 {285 if len(h.signalled()) != 0 {
292 t.Fatal("release signalled before acquire")286 t.Fatal("release signalled before acquire")
M internal/adapters/wayland/commandring.go +1 -13
@@ -5,9 +5,9 @@ import (
55 "sync/atomic"
66 "time"
77
8- "bnema.dev/purego-libwayland/server"
98 "github.com/bnema/neferwl/internal/domain"
109 "github.com/bnema/neferwl/internal/ports"
10+ "bnema.dev/purego-libwayland/server"
1111 )
1212
1313 // commandRingSize bounds the client commands waiting for the display
@@ -127,7 +127,6 @@ func (s *Server) logCommandStats(ctx context.Context) {
127127 return
128128 case <-t.C:
129129 s.reportCommandStats()
130- s.postSurfaceStats()
131130 }
132131 }
133132 }
@@ -156,14 +155,3 @@ func (s *Server) applyQueued(q queuedCommand) {
156155 s.commandStats.observe(q.at, time.Now())
157156 s.apply(q.command())
158157 }
159-
160-// postSurfaceStats never waits for the display: command reporting must remain
161-// live during a display stall. At most one surface report can be outstanding.
162-func (s *Server) postSurfaceStats() {
163- if s.surfaceStatsPending.CompareAndSwap(false, true) {
164- s.display.Post(func() {
165- defer s.surfaceStatsPending.Store(false)
166- s.reportSurfaceStats(time.Now())
167- })
168- }
169-}
@@ -5,9 +5,9 @@ import (
5 "sync/atomic"5 "sync/atomic"
6 "time"6 "time"
7 7
8- "bnema.dev/purego-libwayland/server"
9 "github.com/bnema/neferwl/internal/domain"8 "github.com/bnema/neferwl/internal/domain"
10 "github.com/bnema/neferwl/internal/ports"9 "github.com/bnema/neferwl/internal/ports"
10+ "bnema.dev/purego-libwayland/server"
11 )11 )
12 12
13 // commandRingSize bounds the client commands waiting for the display13 // commandRingSize bounds the client commands waiting for the display
@@ -127,7 +127,6 @@ func (s *Server) logCommandStats(ctx context.Context) {
127 return127 return
128 case <-t.C:128 case <-t.C:
129 s.reportCommandStats()129 s.reportCommandStats()
130- s.postSurfaceStats()
131 }130 }
132 }131 }
133 }132 }
@@ -156,14 +155,3 @@ func (s *Server) applyQueued(q queuedCommand) {
156 s.commandStats.observe(q.at, time.Now())155 s.commandStats.observe(q.at, time.Now())
157 s.apply(q.command())156 s.apply(q.command())
158 }157 }
159-
160-// postSurfaceStats never waits for the display: command reporting must remain
161-// live during a display stall. At most one surface report can be outstanding.
162-func (s *Server) postSurfaceStats() {
163- if s.surfaceStatsPending.CompareAndSwap(false, true) {
164- s.display.Post(func() {
165- defer s.surfaceStatsPending.Store(false)
166- s.reportSurfaceStats(time.Now())
167- })
168- }
169-}
M internal/adapters/wayland/commands_test.go +0 -42
@@ -351,45 +351,3 @@ func TestReportCommandStatsDuringStall(t *testing.T) {
351351 }
352352 }
353353 }
354-
355-//testpolicy:realtime display.Do joins the real display goroutine after a deliberately blocked callback
356-func TestSurfaceStatsPostCoalescesWithoutBlockingCommands(t *testing.T) {
357- var out lockedBuffer
358- h := newAdmissionHarnessWith(t, 1, Options{}, zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland"))
359- s := h.s
360- entered, resume := make(chan struct{}), make(chan struct{})
361- s.display.Post(func() { close(entered); <-resume })
362- select {
363- case <-entered:
364- case <-waylandDeadline(time.Second):
365- t.Fatal("display did not enter callback")
366- }
367- defer func() {
368- select {
369- case <-resume:
370- default:
371- close(resume)
372- }
373- }()
374- for range 3 {
375- s.postSurfaceStats()
376- s.commandStats.observe(time.Time{}, time.Time{})
377- s.reportCommandStats()
378- }
379- if !s.surfaceStatsPending.Load() {
380- t.Fatal("surface report was not pending")
381- }
382- if n := strings.Count(out.String(), "command stats"); n != 3 {
383- t.Fatalf("command stats blocked: %d", n)
384- }
385- close(resume)
386- s.display.Do(func() {})
387- if s.surfaceStatsPending.Load() {
388- t.Fatal("pending guard not cleared")
389- }
390- s.postSurfaceStats()
391- s.display.Do(func() {})
392- if s.surfaceStatsPending.Load() {
393- t.Fatal("next interval failed to rearm")
394- }
395-}
@@ -351,45 +351,3 @@ func TestReportCommandStatsDuringStall(t *testing.T) {
351 }351 }
352 }352 }
353 }353 }
354-
355-//testpolicy:realtime display.Do joins the real display goroutine after a deliberately blocked callback
356-func TestSurfaceStatsPostCoalescesWithoutBlockingCommands(t *testing.T) {
357- var out lockedBuffer
358- h := newAdmissionHarnessWith(t, 1, Options{}, zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland"))
359- s := h.s
360- entered, resume := make(chan struct{}), make(chan struct{})
361- s.display.Post(func() { close(entered); <-resume })
362- select {
363- case <-entered:
364- case <-waylandDeadline(time.Second):
365- t.Fatal("display did not enter callback")
366- }
367- defer func() {
368- select {
369- case <-resume:
370- default:
371- close(resume)
372- }
373- }()
374- for range 3 {
375- s.postSurfaceStats()
376- s.commandStats.observe(time.Time{}, time.Time{})
377- s.reportCommandStats()
378- }
379- if !s.surfaceStatsPending.Load() {
380- t.Fatal("surface report was not pending")
381- }
382- if n := strings.Count(out.String(), "command stats"); n != 3 {
383- t.Fatalf("command stats blocked: %d", n)
384- }
385- close(resume)
386- s.display.Do(func() {})
387- if s.surfaceStatsPending.Load() {
388- t.Fatal("pending guard not cleared")
389- }
390- s.postSurfaceStats()
391- s.display.Do(func() {})
392- if s.surfaceStatsPending.Load() {
393- t.Fatal("next interval failed to rearm")
394- }
395-}
M internal/adapters/wayland/fifo.go +1 -21
@@ -212,9 +212,6 @@ func (s *Server) surfaceOf(w *wayland.Surface) *surface {
212212
213213 // update owns a captured commit until it applies or is discarded.
214214 type update struct {
215- enqueued time.Time
216- blocked headBlock
217- stalled bool
218215 // pendingCommit is the wl_surface state captured by the commit.
219216 pendingCommit
220217 vp *viewport
@@ -364,10 +361,6 @@ func (s *Server) nextRefresh(name string, now time.Time) time.Time {
364361
365362 // queueUpdate queues the pending commit until it can apply.
366363 func (s *surface) queueUpdate() {
367- s.queueUpdateAt(time.Now())
368-}
369-
370-func (s *surface) queueUpdateAt(now time.Time) {
371364 u, _ := updatePool.Get().(*update)
372365 if u == nil {
373366 u = new(update)
@@ -386,7 +379,6 @@ func (s *surface) queueUpdateAt(now time.Time) {
386379 u.sync = &u.syncStore
387380 }
388381 u.owner, u.synced = s, s.effectivelySynced()
389- u.enqueued = now
390382 if s.server.syncWait != nil && u.attached && u.buffer != nil && u.sync == nil {
391383 if b, ok := s.server.buffers[u.buffer.Resource].(*dmabufBuffer); ok {
392384 err := s.server.syncWait.watchImplicit(b.buf, &u.implicit)
@@ -418,7 +410,6 @@ func (s *surface) queueUpdateAt(now time.Time) {
418410
419411 // applyUpdate applies only the captured commit; later requests remain pending.
420412 func (s *surface) applyUpdate(u *update) {
421- s.commitsApplied++
422413 // A buffer destroyed while queued (a swapchain resize) is skipped: the
423414 // surface keeps its content, and is not unmapped behind the client.
424415 s.commitSkipped = false
@@ -572,7 +563,6 @@ func (s *Server) tickFifo(now time.Time, flipped map[string]bool) (time.Duration
572563 for len(surf.queue) > 0 && !surf.destroyed {
573564 u := surf.queue[0]
574565 if u.synced || !u.graphReady(now) {
575- surf.reportStall(now)
576566 break
577567 }
578568 s.applyingGraph = true
@@ -653,17 +643,10 @@ func (u *update) graphReady(now time.Time) bool {
653643 if gen != 0 {
654644 u.readyGeneration, u.readyResult = gen, false
655645 }
656- u.blocked = blockNone
657646 if u.prev != nil && !u.prev.graphReady(now) {
658- u.blocked = blockPrev
659- return false
660- }
661- if u.wait && s.barrier {
662- u.blocked = blockBarrier
663647 return false
664648 }
665- if s.tooEarly(u.at, now) {
666- u.blocked = blockTimestamp
649+ if u.wait && s.barrier || s.tooEarly(u.at, now) {
667650 return false
668651 }
669652 // A dead attachment is skipped by applyUpdate; waiting for its fence
@@ -677,7 +660,6 @@ func (u *update) graphReady(now time.Time) bool {
677660 }
678661 } else if !u.failed {
679662 if !s.syncReady(u.sync) {
680- u.blocked = blockAcquire
681663 return false
682664 }
683665 if u.sync != nil && u.sync.wait != nil && u.sync.wait.failed {
@@ -695,7 +677,6 @@ func (u *update) graphReady(now time.Time) bool {
695677 }
696678 }
697679 if waiting && !u.failed {
698- u.blocked = blockImplicit
699680 return false
700681 }
701682 }
@@ -705,7 +686,6 @@ func (u *update) graphReady(now time.Time) bool {
705686 }
706687 for _, dep := range u.deps {
707688 if !dep.owner.destroyed && !dep.graphReady(now) {
708- u.blocked = blockDeps
709689 return false
710690 }
711691 }
@@ -212,9 +212,6 @@ func (s *Server) surfaceOf(w *wayland.Surface) *surface {
212 212
213 // update owns a captured commit until it applies or is discarded.213 // update owns a captured commit until it applies or is discarded.
214 type update struct {214 type update struct {
215- enqueued time.Time
216- blocked headBlock
217- stalled bool
218 // pendingCommit is the wl_surface state captured by the commit.215 // pendingCommit is the wl_surface state captured by the commit.
219 pendingCommit216 pendingCommit
220 vp *viewport217 vp *viewport
@@ -364,10 +361,6 @@ func (s *Server) nextRefresh(name string, now time.Time) time.Time {
364 361
365 // queueUpdate queues the pending commit until it can apply.362 // queueUpdate queues the pending commit until it can apply.
366 func (s *surface) queueUpdate() {363 func (s *surface) queueUpdate() {
367- s.queueUpdateAt(time.Now())
368-}
369-
370-func (s *surface) queueUpdateAt(now time.Time) {
371 u, _ := updatePool.Get().(*update)364 u, _ := updatePool.Get().(*update)
372 if u == nil {365 if u == nil {
373 u = new(update)366 u = new(update)
@@ -386,7 +379,6 @@ func (s *surface) queueUpdateAt(now time.Time) {
386 u.sync = &u.syncStore379 u.sync = &u.syncStore
387 }380 }
388 u.owner, u.synced = s, s.effectivelySynced()381 u.owner, u.synced = s, s.effectivelySynced()
389- u.enqueued = now
390 if s.server.syncWait != nil && u.attached && u.buffer != nil && u.sync == nil {382 if s.server.syncWait != nil && u.attached && u.buffer != nil && u.sync == nil {
391 if b, ok := s.server.buffers[u.buffer.Resource].(*dmabufBuffer); ok {383 if b, ok := s.server.buffers[u.buffer.Resource].(*dmabufBuffer); ok {
392 err := s.server.syncWait.watchImplicit(b.buf, &u.implicit)384 err := s.server.syncWait.watchImplicit(b.buf, &u.implicit)
@@ -418,7 +410,6 @@ func (s *surface) queueUpdateAt(now time.Time) {
418 410
419 // applyUpdate applies only the captured commit; later requests remain pending.411 // applyUpdate applies only the captured commit; later requests remain pending.
420 func (s *surface) applyUpdate(u *update) {412 func (s *surface) applyUpdate(u *update) {
421- s.commitsApplied++
422 // A buffer destroyed while queued (a swapchain resize) is skipped: the413 // A buffer destroyed while queued (a swapchain resize) is skipped: the
423 // surface keeps its content, and is not unmapped behind the client.414 // surface keeps its content, and is not unmapped behind the client.
424 s.commitSkipped = false415 s.commitSkipped = false
@@ -572,7 +563,6 @@ func (s *Server) tickFifo(now time.Time, flipped map[string]bool) (time.Duration
572 for len(surf.queue) > 0 && !surf.destroyed {563 for len(surf.queue) > 0 && !surf.destroyed {
573 u := surf.queue[0]564 u := surf.queue[0]
574 if u.synced || !u.graphReady(now) {565 if u.synced || !u.graphReady(now) {
575- surf.reportStall(now)
576 break566 break
577 }567 }
578 s.applyingGraph = true568 s.applyingGraph = true
@@ -653,17 +643,10 @@ func (u *update) graphReady(now time.Time) bool {
653 if gen != 0 {643 if gen != 0 {
654 u.readyGeneration, u.readyResult = gen, false644 u.readyGeneration, u.readyResult = gen, false
655 }645 }
656- u.blocked = blockNone
657 if u.prev != nil && !u.prev.graphReady(now) {646 if u.prev != nil && !u.prev.graphReady(now) {
658- u.blocked = blockPrev
659- return false
660- }
661- if u.wait && s.barrier {
662- u.blocked = blockBarrier
663 return false647 return false
664 }648 }
665- if s.tooEarly(u.at, now) {649+ if u.wait && s.barrier || s.tooEarly(u.at, now) {
666- u.blocked = blockTimestamp
667 return false650 return false
668 }651 }
669 // A dead attachment is skipped by applyUpdate; waiting for its fence652 // A dead attachment is skipped by applyUpdate; waiting for its fence
@@ -677,7 +660,6 @@ func (u *update) graphReady(now time.Time) bool {
677 }660 }
678 } else if !u.failed {661 } else if !u.failed {
679 if !s.syncReady(u.sync) {662 if !s.syncReady(u.sync) {
680- u.blocked = blockAcquire
681 return false663 return false
682 }664 }
683 if u.sync != nil && u.sync.wait != nil && u.sync.wait.failed {665 if u.sync != nil && u.sync.wait != nil && u.sync.wait.failed {
@@ -695,7 +677,6 @@ func (u *update) graphReady(now time.Time) bool {
695 }677 }
696 }678 }
697 if waiting && !u.failed {679 if waiting && !u.failed {
698- u.blocked = blockImplicit
699 return false680 return false
700 }681 }
701 }682 }
@@ -705,7 +686,6 @@ func (u *update) graphReady(now time.Time) bool {
705 }686 }
706 for _, dep := range u.deps {687 for _, dep := range u.deps {
707 if !dep.owner.destroyed && !dep.graphReady(now) {688 if !dep.owner.destroyed && !dep.graphReady(now) {
708- u.blocked = blockDeps
709 return false689 return false
710 }690 }
711 }691 }
M internal/adapters/wayland/server.go +12 -16
@@ -153,16 +153,15 @@ type Server struct {
153153 castByCore map[uint64]*castSession
154154 castRing *postRing[domain.CastCommand]
155155 // commands carries core's client commands to the display goroutine.
156- commands *postRing[queuedCommand]
157- commandStats commandStats
158- surfaceStatsPending atomic.Bool
159- castInvFn func()
160- castInvPosted bool
161- castInvSent bool
162- castInvLast domain.CastInventory
163- nextSession uint64
164- excl *exclusion
165- ownUID uint32
156+ commands *postRing[queuedCommand]
157+ commandStats commandStats
158+ castInvFn func()
159+ castInvPosted bool
160+ castInvSent bool
161+ castInvLast domain.CastInventory
162+ nextSession uint64
163+ excl *exclusion
164+ ownUID uint32
166165 // captureAllow, peer and peers decide mayCapture (captureauth.go):
167166 // peers keeps each client's pidfd until it is destroyed.
168167 captureAllow *captureallow.Store
@@ -283,11 +282,9 @@ type Server struct {
283282 feedbacks []feedbackWait
284283 // Explicit sync (syncobj.go): the render node, imported timelines by
285284 // resource, and the acquire point waiter.
286- syncDev syncobjDevice
287- timelines map[*server.Resource]*timeline
288- syncWait *syncWaiter
289- deferredReleases []deferredRelease
290- deferredClients map[server.Client]*deferredClient
285+ syncDev syncobjDevice
286+ timelines map[*server.Resource]*timeline
287+ syncWait *syncWaiter
291288 // flips is each output's latest flip (display goroutine).
292289 flips map[string]domain.FlipInfo
293290 // inhibitors are the live inhibitor objects (inhibit.go);
@@ -631,7 +628,6 @@ func (s *Server) Run(ctx context.Context) error {
631628 // Run has destroyed the display and its withdrawn globals; no bind callback
632629 // can consult the retired set after this point.
633630 s.retiredPrivateOutputs = nil
634- s.drainDeferredReleases(true)
635631 s.syncWait.releasePending()
636632 // The display is gone: only the X connection is left to close.
637633 if s.xwm != nil {
@@ -153,16 +153,15 @@ type Server struct {
153 castByCore map[uint64]*castSession153 castByCore map[uint64]*castSession
154 castRing *postRing[domain.CastCommand]154 castRing *postRing[domain.CastCommand]
155 // commands carries core's client commands to the display goroutine.155 // commands carries core's client commands to the display goroutine.
156- commands *postRing[queuedCommand]156+ commands *postRing[queuedCommand]
157- commandStats commandStats157+ commandStats commandStats
158- surfaceStatsPending atomic.Bool158+ castInvFn func()
159- castInvFn func()159+ castInvPosted bool
160- castInvPosted bool160+ castInvSent bool
161- castInvSent bool161+ castInvLast domain.CastInventory
162- castInvLast domain.CastInventory162+ nextSession uint64
163- nextSession uint64163+ excl *exclusion
164- excl *exclusion164+ ownUID uint32
165- ownUID uint32
166 // captureAllow, peer and peers decide mayCapture (captureauth.go):165 // captureAllow, peer and peers decide mayCapture (captureauth.go):
167 // peers keeps each client's pidfd until it is destroyed.166 // peers keeps each client's pidfd until it is destroyed.
168 captureAllow *captureallow.Store167 captureAllow *captureallow.Store
@@ -283,11 +282,9 @@ type Server struct {
283 feedbacks []feedbackWait282 feedbacks []feedbackWait
284 // Explicit sync (syncobj.go): the render node, imported timelines by283 // Explicit sync (syncobj.go): the render node, imported timelines by
285 // resource, and the acquire point waiter.284 // resource, and the acquire point waiter.
286- syncDev syncobjDevice285+ syncDev syncobjDevice
287- timelines map[*server.Resource]*timeline286+ timelines map[*server.Resource]*timeline
288- syncWait *syncWaiter287+ syncWait *syncWaiter
289- deferredReleases []deferredRelease
290- deferredClients map[server.Client]*deferredClient
291 // flips is each output's latest flip (display goroutine).288 // flips is each output's latest flip (display goroutine).
292 flips map[string]domain.FlipInfo289 flips map[string]domain.FlipInfo
293 // inhibitors are the live inhibitor objects (inhibit.go);290 // inhibitors are the live inhibitor objects (inhibit.go);
@@ -631,7 +628,6 @@ func (s *Server) Run(ctx context.Context) error {
631 // Run has destroyed the display and its withdrawn globals; no bind callback628 // Run has destroyed the display and its withdrawn globals; no bind callback
632 // can consult the retired set after this point.629 // can consult the retired set after this point.
633 s.retiredPrivateOutputs = nil630 s.retiredPrivateOutputs = nil
634- s.drainDeferredReleases(true)
635 s.syncWait.releasePending()631 s.syncWait.releasePending()
636 // The display is gone: only the X connection is left to close.632 // The display is gone: only the X connection is left to close.
637 if s.xwm != nil {633 if s.xwm != nil {
M internal/adapters/wayland/session_lock_surface_test.go +0 -6
@@ -466,12 +466,6 @@ func TestLockSurfaceDestroyRetiresFencedChildDependencies(t *testing.T) {
466466 if destroy == "surface" {
467467 remaining, refs = 0, 1 // parent destruction detaches the child
468468 }
469- if destroy != "role ready" {
470- if len(s.deferredReleases) != 1 || tl.uses != 2 || wait.done {
471- t.Error("unready release was not deferred")
472- }
473- s.drainDeferredReleases(true)
474- }
475469 if len(root.queue) != 0 || len(child.queue) != remaining || !dep.retired || !parent.retired || dep.refs != refs || parent.refs != 1 || !wait.done || wait.efd >= 0 || tl.uses != 0 {
476470 t.Errorf("dependency teardown: child=%d dep refs=%d parent refs=%d uses=%d done=%v", len(child.queue), dep.refs, parent.refs, tl.uses, wait.done)
477471 }
@@ -466,12 +466,6 @@ func TestLockSurfaceDestroyRetiresFencedChildDependencies(t *testing.T) {
466 if destroy == "surface" {466 if destroy == "surface" {
467 remaining, refs = 0, 1 // parent destruction detaches the child467 remaining, refs = 0, 1 // parent destruction detaches the child
468 }468 }
469- if destroy != "role ready" {
470- if len(s.deferredReleases) != 1 || tl.uses != 2 || wait.done {
471- t.Error("unready release was not deferred")
472- }
473- s.drainDeferredReleases(true)
474- }
475 if len(root.queue) != 0 || len(child.queue) != remaining || !dep.retired || !parent.retired || dep.refs != refs || parent.refs != 1 || !wait.done || wait.efd >= 0 || tl.uses != 0 {469 if len(root.queue) != 0 || len(child.queue) != remaining || !dep.retired || !parent.retired || dep.refs != refs || parent.refs != 1 || !wait.done || wait.efd >= 0 || tl.uses != 0 {
476 t.Errorf("dependency teardown: child=%d dep refs=%d parent refs=%d uses=%d done=%v", len(child.queue), dep.refs, parent.refs, tl.uses, wait.done)470 t.Errorf("dependency teardown: child=%d dep refs=%d parent refs=%d uses=%d done=%v", len(child.queue), dep.refs, parent.refs, tl.uses, wait.done)
477 }471 }
M internal/adapters/wayland/surface.go +2 -11
@@ -42,13 +42,6 @@ type surface struct {
4242 // syncScratch holds next.sync between takeSyncPoints and queueUpdate,
4343 // which moves it into the update.
4444 syncScratch commitSync
45- syncClient *deferredClient
46- // releasePointsDropped is display-goroutine-owned diagnostic accounting.
47- // A dropped point was not signalled because its acquire was not ready.
48- releasePointsDropped uint64
49- releasePointsDeferred, statsDeferred uint64
50- commitsReceived, commitsApplied, releasePointsSignalled uint64
51- statsReceived, statsApplied, statsSignalled, statsDropped uint64
5245 // bufferScale, transform and opaque are committed state. formatOpaque is
5346 // the current buffer's own opacity (x formats).
5447 bufferScale int
@@ -406,7 +399,6 @@ func (s *surface) Frame(r *wayland.Surface, id uint32) {
406399 }
407400 }
408401 func (s *surface) Commit(*wayland.Surface) {
409- s.commitsReceived++
410402 if s.next.attached && s.next.buffer != nil {
411403 s.bufferCommitted = true
412404 }
@@ -436,9 +428,8 @@ func (s *surface) Commit(*wayland.Surface) {
436428 func (s *surface) queueAndTick() {
437429 srv := s.server
438430 srv.paceDepth++
439- now := time.Now()
440- s.queueUpdateAt(now)
441- srv.tickFifo(now, nil)
431+ s.queueUpdate()
432+ srv.tickFifo(time.Now(), nil)
442433 if n := len(s.queue); n > 0 && !s.queue[n-1].synced {
443434 // The commit waits for a barrier, a fence or a refresh: the pacer
444435 // must time it. A commit applied at once needs no tick of its own;
@@ -42,13 +42,6 @@ type surface struct {
42 // syncScratch holds next.sync between takeSyncPoints and queueUpdate,42 // syncScratch holds next.sync between takeSyncPoints and queueUpdate,
43 // which moves it into the update.43 // which moves it into the update.
44 syncScratch commitSync44 syncScratch commitSync
45- syncClient *deferredClient
46- // releasePointsDropped is display-goroutine-owned diagnostic accounting.
47- // A dropped point was not signalled because its acquire was not ready.
48- releasePointsDropped uint64
49- releasePointsDeferred, statsDeferred uint64
50- commitsReceived, commitsApplied, releasePointsSignalled uint64
51- statsReceived, statsApplied, statsSignalled, statsDropped uint64
52 // bufferScale, transform and opaque are committed state. formatOpaque is45 // bufferScale, transform and opaque are committed state. formatOpaque is
53 // the current buffer's own opacity (x formats).46 // the current buffer's own opacity (x formats).
54 bufferScale int47 bufferScale int
@@ -406,7 +399,6 @@ func (s *surface) Frame(r *wayland.Surface, id uint32) {
406 }399 }
407 }400 }
408 func (s *surface) Commit(*wayland.Surface) {401 func (s *surface) Commit(*wayland.Surface) {
409- s.commitsReceived++
410 if s.next.attached && s.next.buffer != nil {402 if s.next.attached && s.next.buffer != nil {
411 s.bufferCommitted = true403 s.bufferCommitted = true
412 }404 }
@@ -436,9 +428,8 @@ func (s *surface) Commit(*wayland.Surface) {
436 func (s *surface) queueAndTick() {428 func (s *surface) queueAndTick() {
437 srv := s.server429 srv := s.server
438 srv.paceDepth++430 srv.paceDepth++
439- now := time.Now()431+ s.queueUpdate()
440- s.queueUpdateAt(now)432+ srv.tickFifo(time.Now(), nil)
441- srv.tickFifo(now, nil)
442 if n := len(s.queue); n > 0 && !s.queue[n-1].synced {433 if n := len(s.queue); n > 0 && !s.queue[n-1].synced {
443 // The commit waits for a barrier, a fence or a refresh: the pacer434 // The commit waits for a barrier, a fence or a refresh: the pacer
444 // must time it. A commit applied at once needs no tick of its own;435 // must time it. A commit applied at once needs no tick of its own;
D internal/adapters/wayland/surfacestats.go +0 -126
@@ -1,126 +0,0 @@
1-package wayland
2-
3-import (
4- "time"
5-
6- "github.com/rs/zerolog"
7-)
8-
9-// headBlock is recorded with the cached readiness result, without formatting
10-// strings or allocating on the commit path.
11-type headBlock uint8
12-
13-const (
14- blockNone headBlock = iota
15- blockBarrier
16- blockTimestamp
17- blockAcquire
18- blockImplicit
19- blockSynced
20- blockPrev
21- blockDeps
22-)
23-
24-func (b headBlock) String() string {
25- switch b {
26- case blockBarrier:
27- return "barrier"
28- case blockTimestamp:
29- return "timestamp"
30- case blockAcquire:
31- return "acquire"
32- case blockImplicit:
33- return "implicit"
34- case blockSynced:
35- return "synced"
36- case blockPrev:
37- return "prev"
38- case blockDeps:
39- return "deps"
40- default:
41- return "none"
42- }
43-}
44-
45-func (s *surface) headState(now time.Time) (time.Duration, headBlock) {
46- if len(s.queue) == 0 {
47- return 0, blockNone
48- }
49- u := s.queue[0]
50- if u.synced {
51- return max(now.Sub(u.enqueued), 0), blockSynced
52- }
53- return max(now.Sub(u.enqueued), 0), u.blocked
54-}
55-
56-// logSurfaceState runs only on the display goroutine. Stall messages leave the
57-// interval baselines untouched so the next stats line still covers all activity.
58-func (s *surface) logSurfaceState(now time.Time, stalled bool) {
59- age, block := s.headState(now)
60- level := zerolog.InfoLevel
61- if stalled {
62- level = zerolog.WarnLevel
63- }
64- e := s.server.log.WithLevel(level)
65- e = e.Uint64("window", uint64(s.root().windowID())).
66- Bool("sub", s.sub.parent != nil).
67- Uint32("surface", s.surfaceID()).
68- Uint64("commits_received", s.commitsReceived-s.statsReceived).
69- Uint64("commits_applied", s.commitsApplied-s.statsApplied).
70- Int("queue_len", len(s.queue)).
71- Int64("head_age_ms", age.Milliseconds()).
72- Str("head_block", block.String()).
73- Uint64("release_points_signalled", s.releasePointsSignalled-s.statsSignalled).
74- Uint64("release_points_dropped", s.releasePointsDropped-s.statsDropped).
75- Uint64("release_points_deferred", s.releasePointsDeferred-s.statsDeferred)
76- if stalled {
77- if block == blockAcquire {
78- cs := s.queue[0].sync
79- if cs != nil && cs.acquire.set() {
80- e = e.Uint64("acquire_point", cs.acquire.point).Uint32("acquire_timeline", cs.acquire.tl.handle)
81- }
82- }
83- e.Msg("surface commit stalled")
84- return
85- }
86- e.Msg("surface stats")
87-}
88-
89-func (s *surface) reportStall(now time.Time) {
90- if s.root().windowID() == 0 || len(s.queue) == 0 {
91- return
92- }
93- u := s.queue[0]
94- age, block := s.headState(now)
95- // FIFO barriers intentionally wait for refresh and are not evidence of a
96- // wedged acquire. A later non-barrier block can still warn for this head.
97- if u.stalled || age <= 500*time.Millisecond || block == blockBarrier || block == blockNone {
98- return
99- }
100- u.stalled = true
101- s.logSurfaceState(now, true)
102-}
103-
104-// reportSurfaceStats is posted by the existing ten-second command stats timer.
105-// It does not evaluate readiness (which can cancel waits), apply, or wake work.
106-func (s *Server) reportSurfaceStats(now time.Time) {
107- for _, surf := range s.surfaces {
108- if surf.root().windowID() != 0 && (surf.commitsReceived != surf.statsReceived || surf.commitsApplied != surf.statsApplied ||
109- surf.releasePointsSignalled != surf.statsSignalled || surf.releasePointsDropped != surf.statsDropped ||
110- surf.releasePointsDeferred != surf.statsDeferred || len(surf.queue) != 0) {
111- surf.reportStall(now)
112- surf.logSurfaceState(now, false)
113- }
114- surf.statsDeferred = surf.releasePointsDeferred
115- surf.statsReceived, surf.statsApplied = surf.commitsReceived, surf.commitsApplied
116- surf.statsSignalled, surf.statsDropped = surf.releasePointsSignalled, surf.releasePointsDropped
117- }
118-}
119-
120-// surfaceID also supports diagnostic-only surfaces without a protocol resource.
121-func (s *surface) surfaceID() uint32 {
122- if s.wl == nil {
123- return 0
124- }
125- return s.wl.ID()
126-}
@@ -1,126 +0,0 @@
1-package wayland
2-
3-import (
4- "time"
5-
6- "github.com/rs/zerolog"
7-)
8-
9-// headBlock is recorded with the cached readiness result, without formatting
10-// strings or allocating on the commit path.
11-type headBlock uint8
12-
13-const (
14- blockNone headBlock = iota
15- blockBarrier
16- blockTimestamp
17- blockAcquire
18- blockImplicit
19- blockSynced
20- blockPrev
21- blockDeps
22-)
23-
24-func (b headBlock) String() string {
25- switch b {
26- case blockBarrier:
27- return "barrier"
28- case blockTimestamp:
29- return "timestamp"
30- case blockAcquire:
31- return "acquire"
32- case blockImplicit:
33- return "implicit"
34- case blockSynced:
35- return "synced"
36- case blockPrev:
37- return "prev"
38- case blockDeps:
39- return "deps"
40- default:
41- return "none"
42- }
43-}
44-
45-func (s *surface) headState(now time.Time) (time.Duration, headBlock) {
46- if len(s.queue) == 0 {
47- return 0, blockNone
48- }
49- u := s.queue[0]
50- if u.synced {
51- return max(now.Sub(u.enqueued), 0), blockSynced
52- }
53- return max(now.Sub(u.enqueued), 0), u.blocked
54-}
55-
56-// logSurfaceState runs only on the display goroutine. Stall messages leave the
57-// interval baselines untouched so the next stats line still covers all activity.
58-func (s *surface) logSurfaceState(now time.Time, stalled bool) {
59- age, block := s.headState(now)
60- level := zerolog.InfoLevel
61- if stalled {
62- level = zerolog.WarnLevel
63- }
64- e := s.server.log.WithLevel(level)
65- e = e.Uint64("window", uint64(s.root().windowID())).
66- Bool("sub", s.sub.parent != nil).
67- Uint32("surface", s.surfaceID()).
68- Uint64("commits_received", s.commitsReceived-s.statsReceived).
69- Uint64("commits_applied", s.commitsApplied-s.statsApplied).
70- Int("queue_len", len(s.queue)).
71- Int64("head_age_ms", age.Milliseconds()).
72- Str("head_block", block.String()).
73- Uint64("release_points_signalled", s.releasePointsSignalled-s.statsSignalled).
74- Uint64("release_points_dropped", s.releasePointsDropped-s.statsDropped).
75- Uint64("release_points_deferred", s.releasePointsDeferred-s.statsDeferred)
76- if stalled {
77- if block == blockAcquire {
78- cs := s.queue[0].sync
79- if cs != nil && cs.acquire.set() {
80- e = e.Uint64("acquire_point", cs.acquire.point).Uint32("acquire_timeline", cs.acquire.tl.handle)
81- }
82- }
83- e.Msg("surface commit stalled")
84- return
85- }
86- e.Msg("surface stats")
87-}
88-
89-func (s *surface) reportStall(now time.Time) {
90- if s.root().windowID() == 0 || len(s.queue) == 0 {
91- return
92- }
93- u := s.queue[0]
94- age, block := s.headState(now)
95- // FIFO barriers intentionally wait for refresh and are not evidence of a
96- // wedged acquire. A later non-barrier block can still warn for this head.
97- if u.stalled || age <= 500*time.Millisecond || block == blockBarrier || block == blockNone {
98- return
99- }
100- u.stalled = true
101- s.logSurfaceState(now, true)
102-}
103-
104-// reportSurfaceStats is posted by the existing ten-second command stats timer.
105-// It does not evaluate readiness (which can cancel waits), apply, or wake work.
106-func (s *Server) reportSurfaceStats(now time.Time) {
107- for _, surf := range s.surfaces {
108- if surf.root().windowID() != 0 && (surf.commitsReceived != surf.statsReceived || surf.commitsApplied != surf.statsApplied ||
109- surf.releasePointsSignalled != surf.statsSignalled || surf.releasePointsDropped != surf.statsDropped ||
110- surf.releasePointsDeferred != surf.statsDeferred || len(surf.queue) != 0) {
111- surf.reportStall(now)
112- surf.logSurfaceState(now, false)
113- }
114- surf.statsDeferred = surf.releasePointsDeferred
115- surf.statsReceived, surf.statsApplied = surf.commitsReceived, surf.commitsApplied
116- surf.statsSignalled, surf.statsDropped = surf.releasePointsSignalled, surf.releasePointsDropped
117- }
118-}
119-
120-// surfaceID also supports diagnostic-only surfaces without a protocol resource.
121-func (s *surface) surfaceID() uint32 {
122- if s.wl == nil {
123- return 0
124- }
125- return s.wl.ID()
126-}
D internal/adapters/wayland/surfacestats_test.go +0 -163
@@ -1,163 +0,0 @@
1-package wayland
2-
3-import (
4- "bytes"
5- "encoding/json"
6- "testing"
7- "testing/synctest"
8- "time"
9-
10- "bnema.dev/purego-libwayland/server"
11- "bnema.dev/zerowrap"
12-)
13-
14-func TestSurfaceAcquireStallAndStats(t *testing.T) {
15- synctest.Test(t, func(t *testing.T) {
16- var out bytes.Buffer
17- srv := &Server{log: zerowrap.New(zerowrap.Config{Level: "info", Format: "json", Output: &out}).WithField("component", "wayland"), syncWait: &syncWaiter{}, fifoSurfaces: map[*surface]struct{}{}, lastFlip: map[string]time.Time{}}
18- surf := &surface{server: srv, x11win: &window{id: 42, mapped: true}, commitsReceived: 2, commitsApplied: 1, releasePointsSignalled: 3, releasePointsDropped: 4, releasePointsDeferred: 5}
19- srv.surfaces = map[*server.Resource]*surface{nil: surf}
20- u := &update{owner: surf, enqueued: time.Now(), pendingCommit: pendingCommit{sync: &commitSync{wait: &syncWait{explicit: true}, acquire: syncPoint{tl: &timeline{handle: 7, alive: true, uses: 1}, point: 11}}}}
21- surf.queue = []*update{u}
22- srv.fifoSurfaces[surf] = struct{}{}
23- srv.tickFifo(time.Now(), nil)
24- if u.blocked != blockAcquire {
25- t.Fatalf("block = %v", u.blocked)
26- }
27- time.Sleep(501 * time.Millisecond)
28- synctest.Wait()
29- srv.tickFifo(time.Now(), nil)
30- srv.tickFifo(time.Now(), nil)
31- if n := bytes.Count(out.Bytes(), []byte("surface commit stalled")); n != 1 {
32- t.Fatalf("warnings=%d: %s", n, out.String())
33- }
34- time.Sleep(10*time.Second - 501*time.Millisecond)
35- synctest.Wait()
36- srv.reportSurfaceStats(time.Now())
37- dec := json.NewDecoder(&out)
38- var warning, stats map[string]any
39- if err := dec.Decode(&warning); err != nil {
40- t.Fatal(err)
41- }
42- if err := dec.Decode(&stats); err != nil {
43- t.Fatal(err)
44- }
45- for k, want := range map[string]any{"message": "surface stats", "component": "wayland", "window": float64(42), "head_block": "acquire", "head_age_ms": float64(10000), "queue_len": float64(1), "commits_received": float64(2), "commits_applied": float64(1), "release_points_signalled": float64(3), "release_points_dropped": float64(4), "release_points_deferred": float64(5), "sub": false, "surface": float64(0)} {
46- if stats[k] != want {
47- t.Errorf("%s=%v, want %v", k, stats[k], want)
48- }
49- }
50- if warning["acquire_point"] != float64(11) || warning["acquire_timeline"] != float64(7) || warning["release_points_deferred"] != float64(5) || warning["sub"] != false {
51- t.Fatalf("warning: %v", warning)
52- }
53- srv.reportSurfaceStats(time.Now())
54- var next map[string]any
55- if err := json.NewDecoder(&out).Decode(&next); err != nil {
56- t.Fatal(err)
57- }
58- if next["commits_received"] != float64(0) || next["release_points_dropped"] != float64(0) || next["release_points_deferred"] != float64(0) {
59- t.Fatalf("not interval counts: %v", next)
60- }
61- // Retire the warned head through the production queue teardown, then
62- // capture a new commit. Pool reuse is deliberately not assumed.
63- u.sync.release = syncPoint{tl: &timeline{alive: true, uses: 1}, point: 13}
64- surf.dropQueue()
65- surf.queueUpdateAt(time.Now())
66- fresh := surf.queue[0]
67- fresh.sync = &commitSync{release: syncPoint{tl: &timeline{alive: true, uses: 1}, point: 14}, wait: &syncWait{explicit: true}, acquire: syncPoint{tl: &timeline{handle: 7, alive: true, uses: 1}, point: 12}}
68- if !fresh.enqueued.Equal(time.Now()) {
69- t.Fatal("new head age not reset")
70- }
71- out.Reset()
72- srv.tickFifo(time.Now(), nil)
73- time.Sleep(501 * time.Millisecond)
74- synctest.Wait()
75- srv.tickFifo(time.Now(), nil)
76- srv.tickFifo(time.Now(), nil)
77- var rearmed map[string]any
78- if err := json.Unmarshal(out.Bytes(), &rearmed); err != nil {
79- t.Fatal(err)
80- }
81- if rearmed["message"] != "surface commit stalled" || rearmed["head_age_ms"] != float64(501) {
82- t.Fatalf("fresh head warning: %v", rearmed)
83- }
84- surf.dropQueue()
85- srv.drainDeferredReleases(true)
86- srv.reportSurfaceStats(time.Now()) // consume release/drop activity
87- out.Reset()
88- srv.reportSurfaceStats(time.Now())
89- if out.Len() != 0 {
90- t.Fatalf("idle surface logged: %s", out.String())
91- }
92- })
93-}
94-
95-func TestSurfaceBarrierWaitDoesNotWarn(t *testing.T) {
96- synctest.Test(t, func(t *testing.T) {
97- var out bytes.Buffer
98- srv := &Server{log: zerowrap.New(zerowrap.Config{Output: &out}).WithField("component", "wayland")}
99- surf := &surface{server: srv, x11win: &window{id: 42, mapped: true}, barrier: true}
100- u := &update{owner: surf, enqueued: time.Now(), pendingCommit: pendingCommit{wait: true}}
101- surf.queue = []*update{u}
102- if u.graphReady(time.Now()) || u.blocked != blockBarrier {
103- t.Fatal("expected barrier wait")
104- }
105- time.Sleep(20 * time.Millisecond)
106- synctest.Wait()
107- surf.reportStall(time.Now())
108- // Even an intentionally suspended FIFO barrier is not a stall warning.
109- time.Sleep(time.Second)
110- synctest.Wait()
111- surf.reportStall(time.Now())
112- if out.Len() != 0 {
113- t.Fatalf("barrier warned: %s", out.String())
114- }
115- })
116-}
117-
118-func TestSurfaceReleaseSignalCount(t *testing.T) {
119- dev := newMocksyncobjDevice(t)
120- dev.EXPECT().signal(uint32(7), uint64(11)).Return(nil).Once()
121- srv := &Server{}
122- surf := &surface{server: srv}
123- srv.releaseSync(syncHold{owner: surf, release: syncPoint{tl: &timeline{dev: dev, handle: 7, alive: true, uses: 1}, point: 11}})
124- if surf.releasePointsSignalled != 1 {
125- t.Fatal("successful signal not counted")
126- }
127-}
128-
129-func TestSubsurfaceStatsAndStallAttribution(t *testing.T) {
130- synctest.Test(t, func(t *testing.T) {
131- var out bytes.Buffer
132- srv := &Server{log: zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")}
133- root := &surface{server: srv, x11win: &window{id: 42, mapped: true}}
134- child := &surface{server: srv, commitsReceived: 1, releasePointsDeferred: 2}
135- child.sub.parent = root
136- child.queue = []*update{{enqueued: time.Now(), blocked: blockAcquire}}
137- srv.surfaces = map[*server.Resource]*surface{nil: child}
138- time.Sleep(time.Second)
139- synctest.Wait()
140- srv.reportSurfaceStats(time.Now())
141- dec := json.NewDecoder(&out)
142- for _, message := range []string{"surface commit stalled", "surface stats"} {
143- var event map[string]any
144- if err := dec.Decode(&event); err != nil {
145- t.Fatal(err)
146- }
147- if event["message"] != message || event["window"] != float64(42) || event["sub"] != true || event["release_points_deferred"] != float64(2) {
148- t.Fatalf("attribution: %v", event)
149- }
150- }
151- child.queue = nil
152- out.Reset()
153- child.releasePointsDeferred++
154- srv.reportSurfaceStats(time.Now())
155- var event map[string]any
156- if err := json.Unmarshal(out.Bytes(), &event); err != nil {
157- t.Fatal(err)
158- }
159- if event["release_points_deferred"] != float64(1) {
160- t.Fatalf("deferred-only interval: %v", event)
161- }
162- })
163-}
@@ -1,163 +0,0 @@
1-package wayland
2-
3-import (
4- "bytes"
5- "encoding/json"
6- "testing"
7- "testing/synctest"
8- "time"
9-
10- "bnema.dev/purego-libwayland/server"
11- "bnema.dev/zerowrap"
12-)
13-
14-func TestSurfaceAcquireStallAndStats(t *testing.T) {
15- synctest.Test(t, func(t *testing.T) {
16- var out bytes.Buffer
17- srv := &Server{log: zerowrap.New(zerowrap.Config{Level: "info", Format: "json", Output: &out}).WithField("component", "wayland"), syncWait: &syncWaiter{}, fifoSurfaces: map[*surface]struct{}{}, lastFlip: map[string]time.Time{}}
18- surf := &surface{server: srv, x11win: &window{id: 42, mapped: true}, commitsReceived: 2, commitsApplied: 1, releasePointsSignalled: 3, releasePointsDropped: 4, releasePointsDeferred: 5}
19- srv.surfaces = map[*server.Resource]*surface{nil: surf}
20- u := &update{owner: surf, enqueued: time.Now(), pendingCommit: pendingCommit{sync: &commitSync{wait: &syncWait{explicit: true}, acquire: syncPoint{tl: &timeline{handle: 7, alive: true, uses: 1}, point: 11}}}}
21- surf.queue = []*update{u}
22- srv.fifoSurfaces[surf] = struct{}{}
23- srv.tickFifo(time.Now(), nil)
24- if u.blocked != blockAcquire {
25- t.Fatalf("block = %v", u.blocked)
26- }
27- time.Sleep(501 * time.Millisecond)
28- synctest.Wait()
29- srv.tickFifo(time.Now(), nil)
30- srv.tickFifo(time.Now(), nil)
31- if n := bytes.Count(out.Bytes(), []byte("surface commit stalled")); n != 1 {
32- t.Fatalf("warnings=%d: %s", n, out.String())
33- }
34- time.Sleep(10*time.Second - 501*time.Millisecond)
35- synctest.Wait()
36- srv.reportSurfaceStats(time.Now())
37- dec := json.NewDecoder(&out)
38- var warning, stats map[string]any
39- if err := dec.Decode(&warning); err != nil {
40- t.Fatal(err)
41- }
42- if err := dec.Decode(&stats); err != nil {
43- t.Fatal(err)
44- }
45- for k, want := range map[string]any{"message": "surface stats", "component": "wayland", "window": float64(42), "head_block": "acquire", "head_age_ms": float64(10000), "queue_len": float64(1), "commits_received": float64(2), "commits_applied": float64(1), "release_points_signalled": float64(3), "release_points_dropped": float64(4), "release_points_deferred": float64(5), "sub": false, "surface": float64(0)} {
46- if stats[k] != want {
47- t.Errorf("%s=%v, want %v", k, stats[k], want)
48- }
49- }
50- if warning["acquire_point"] != float64(11) || warning["acquire_timeline"] != float64(7) || warning["release_points_deferred"] != float64(5) || warning["sub"] != false {
51- t.Fatalf("warning: %v", warning)
52- }
53- srv.reportSurfaceStats(time.Now())
54- var next map[string]any
55- if err := json.NewDecoder(&out).Decode(&next); err != nil {
56- t.Fatal(err)
57- }
58- if next["commits_received"] != float64(0) || next["release_points_dropped"] != float64(0) || next["release_points_deferred"] != float64(0) {
59- t.Fatalf("not interval counts: %v", next)
60- }
61- // Retire the warned head through the production queue teardown, then
62- // capture a new commit. Pool reuse is deliberately not assumed.
63- u.sync.release = syncPoint{tl: &timeline{alive: true, uses: 1}, point: 13}
64- surf.dropQueue()
65- surf.queueUpdateAt(time.Now())
66- fresh := surf.queue[0]
67- fresh.sync = &commitSync{release: syncPoint{tl: &timeline{alive: true, uses: 1}, point: 14}, wait: &syncWait{explicit: true}, acquire: syncPoint{tl: &timeline{handle: 7, alive: true, uses: 1}, point: 12}}
68- if !fresh.enqueued.Equal(time.Now()) {
69- t.Fatal("new head age not reset")
70- }
71- out.Reset()
72- srv.tickFifo(time.Now(), nil)
73- time.Sleep(501 * time.Millisecond)
74- synctest.Wait()
75- srv.tickFifo(time.Now(), nil)
76- srv.tickFifo(time.Now(), nil)
77- var rearmed map[string]any
78- if err := json.Unmarshal(out.Bytes(), &rearmed); err != nil {
79- t.Fatal(err)
80- }
81- if rearmed["message"] != "surface commit stalled" || rearmed["head_age_ms"] != float64(501) {
82- t.Fatalf("fresh head warning: %v", rearmed)
83- }
84- surf.dropQueue()
85- srv.drainDeferredReleases(true)
86- srv.reportSurfaceStats(time.Now()) // consume release/drop activity
87- out.Reset()
88- srv.reportSurfaceStats(time.Now())
89- if out.Len() != 0 {
90- t.Fatalf("idle surface logged: %s", out.String())
91- }
92- })
93-}
94-
95-func TestSurfaceBarrierWaitDoesNotWarn(t *testing.T) {
96- synctest.Test(t, func(t *testing.T) {
97- var out bytes.Buffer
98- srv := &Server{log: zerowrap.New(zerowrap.Config{Output: &out}).WithField("component", "wayland")}
99- surf := &surface{server: srv, x11win: &window{id: 42, mapped: true}, barrier: true}
100- u := &update{owner: surf, enqueued: time.Now(), pendingCommit: pendingCommit{wait: true}}
101- surf.queue = []*update{u}
102- if u.graphReady(time.Now()) || u.blocked != blockBarrier {
103- t.Fatal("expected barrier wait")
104- }
105- time.Sleep(20 * time.Millisecond)
106- synctest.Wait()
107- surf.reportStall(time.Now())
108- // Even an intentionally suspended FIFO barrier is not a stall warning.
109- time.Sleep(time.Second)
110- synctest.Wait()
111- surf.reportStall(time.Now())
112- if out.Len() != 0 {
113- t.Fatalf("barrier warned: %s", out.String())
114- }
115- })
116-}
117-
118-func TestSurfaceReleaseSignalCount(t *testing.T) {
119- dev := newMocksyncobjDevice(t)
120- dev.EXPECT().signal(uint32(7), uint64(11)).Return(nil).Once()
121- srv := &Server{}
122- surf := &surface{server: srv}
123- srv.releaseSync(syncHold{owner: surf, release: syncPoint{tl: &timeline{dev: dev, handle: 7, alive: true, uses: 1}, point: 11}})
124- if surf.releasePointsSignalled != 1 {
125- t.Fatal("successful signal not counted")
126- }
127-}
128-
129-func TestSubsurfaceStatsAndStallAttribution(t *testing.T) {
130- synctest.Test(t, func(t *testing.T) {
131- var out bytes.Buffer
132- srv := &Server{log: zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")}
133- root := &surface{server: srv, x11win: &window{id: 42, mapped: true}}
134- child := &surface{server: srv, commitsReceived: 1, releasePointsDeferred: 2}
135- child.sub.parent = root
136- child.queue = []*update{{enqueued: time.Now(), blocked: blockAcquire}}
137- srv.surfaces = map[*server.Resource]*surface{nil: child}
138- time.Sleep(time.Second)
139- synctest.Wait()
140- srv.reportSurfaceStats(time.Now())
141- dec := json.NewDecoder(&out)
142- for _, message := range []string{"surface commit stalled", "surface stats"} {
143- var event map[string]any
144- if err := dec.Decode(&event); err != nil {
145- t.Fatal(err)
146- }
147- if event["message"] != message || event["window"] != float64(42) || event["sub"] != true || event["release_points_deferred"] != float64(2) {
148- t.Fatalf("attribution: %v", event)
149- }
150- }
151- child.queue = nil
152- out.Reset()
153- child.releasePointsDeferred++
154- srv.reportSurfaceStats(time.Now())
155- var event map[string]any
156- if err := json.Unmarshal(out.Bytes(), &event); err != nil {
157- t.Fatal(err)
158- }
159- if event["release_points_deferred"] != float64(1) {
160- t.Fatalf("deferred-only interval: %v", event)
161- }
162- })
163-}
D internal/adapters/wayland/syncdrop_test.go +0 -213
@@ -1,213 +0,0 @@
1-package wayland
2-
3-import (
4- "bytes"
5- "encoding/json"
6- "fmt"
7- "strings"
8- "testing"
9- "time"
10-
11- "bnema.dev/zerowrap"
12-)
13-
14-func TestDropSyncDeferredLifecycle(t *testing.T) {
15- for _, outcome := range []string{"ready", "failed", "acquire_destroyed", "release_destroyed", "shutdown", "client_gone", "already_ready", "already_ready_destroyed"} {
16- t.Run(outcome, func(t *testing.T) {
17- var out bytes.Buffer
18- dev := newMocksyncobjDevice(t)
19- srv := &Server{syncWait: &syncWaiter{}, log: zerowrap.New(zerowrap.Config{Level: "debug", Format: "json", Output: &out}).WithField("component", "wayland")}
20- surf := &surface{server: srv}
21- surf.sub.parent = &surface{server: srv, x11win: &window{id: 42, mapped: true}}
22- acquire := &timeline{dev: dev, handle: 7, alive: true, uses: 1}
23- release := &timeline{dev: dev, handle: 8, alive: true, uses: 1}
24- w := &syncWait{explicit: true, efd: -1, done: (outcome == "already_ready" || outcome == "already_ready_destroyed")}
25- cs := commitSync{acquire: syncPoint{tl: acquire, point: 11}, release: syncPoint{tl: release, point: 12}, wait: w}
26- signals := outcome == "ready" || outcome == "acquire_destroyed" || outcome == "release_destroyed" || outcome == "already_ready" || outcome == "already_ready_destroyed"
27- if signals {
28- dev.EXPECT().signal(uint32(8), uint64(12)).Return(nil).Once()
29- }
30- if outcome == "already_ready_destroyed" {
31- acquire.alive = false
32- release.alive = false
33- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
34- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
35- }
36- surf.dropSync(&cs)
37- if outcome != "already_ready" && outcome != "already_ready_destroyed" {
38- if surf.releasePointsDeferred != 1 {
39- t.Fatal("deferred counter not incremented")
40- }
41- var event map[string]any
42- if err := json.NewDecoder(bytes.NewReader(out.Bytes())).Decode(&event); err != nil {
43- t.Fatal(err)
44- }
45- if event["level"] != "debug" || event["window"] != float64(42) || event["sub"] != true {
46- t.Fatalf("deferred attribution: %v", event)
47- }
48- if len(srv.deferredReleases) != 1 || w.done || acquire.uses != 1 || release.uses != 1 || surf.releasePointsDropped != 0 {
49- t.Fatalf("ownership not retained: deferred=%d done=%v uses=%d/%d dropped=%d", len(srv.deferredReleases), w.done, acquire.uses, release.uses, surf.releasePointsDropped)
50- }
51- // Retiring/reusing the original update must not change deferred points.
52- cs = commitSync{}
53- srv.drainDeferredReleases(false)
54- if len(srv.deferredReleases) != 1 {
55- t.Fatal("unready acquire was drained")
56- }
57- switch outcome {
58- case "ready":
59- w.done = true
60- case "failed":
61- w.done, w.failed = true, true
62- case "client_gone":
63- surf.syncClient.gone = true
64- case "acquire_destroyed":
65- acquire.alive = false
66- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
67- case "release_destroyed":
68- release.alive = false
69- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
70- }
71- if outcome == "acquire_destroyed" || outcome == "release_destroyed" {
72- srv.drainDeferredReleases(false)
73- if len(srv.deferredReleases) != 1 {
74- t.Fatal("protocol timeline destruction cancelled committed point")
75- }
76- w.done = true
77- }
78- srv.drainDeferredReleases(outcome == "shutdown")
79- }
80- srv.drainDeferredReleases(false)
81- if len(srv.deferredReleases) != 0 || acquire.uses != 0 || release.uses != 0 || !w.done {
82- t.Fatalf("ownership leaked: deferred=%d uses=%d/%d done=%v", len(srv.deferredReleases), acquire.uses, release.uses, w.done)
83- }
84- if signals {
85- if surf.releasePointsSignalled != 1 || surf.releasePointsDropped != 0 {
86- t.Fatal("signal accounting")
87- }
88- if bytes.Contains(out.Bytes(), []byte("surface release point dropped without signal")) {
89- t.Fatalf("successful release warned: %s", out.String())
90- }
91- } else {
92- if surf.releasePointsSignalled != 0 || surf.releasePointsDropped != 1 {
93- t.Fatal("abandon accounting")
94- }
95- if n := bytes.Count(out.Bytes(), []byte("surface release point dropped without signal")); n != 1 {
96- t.Fatalf("warnings=%d: %s", n, out.String())
97- }
98- }
99- if !signals {
100- want := "client_gone"
101- if outcome == "failed" {
102- want = "wait_failed"
103- }
104- if outcome == "shutdown" {
105- want = "shutdown"
106- }
107- dec := json.NewDecoder(bytes.NewReader(out.Bytes()))
108- var deferred, warning map[string]any
109- if err := dec.Decode(&deferred); err != nil {
110- t.Fatal(err)
111- }
112- if err := dec.Decode(&warning); err != nil {
113- t.Fatal(err)
114- }
115- if warning["reason"] != want || warning["window"] != float64(42) || warning["sub"] != true {
116- t.Fatalf("abandon diagnostic: %v", warning)
117- }
118- }
119- if (outcome == "already_ready" || outcome == "already_ready_destroyed") && surf.releasePointsDeferred != 0 {
120- t.Fatal("ready release counted as deferred")
121- }
122- // Destroy remaining live timelines after the references have retired.
123- if acquire.alive {
124- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
125- acquire.alive = false
126- srv.dropTimeline(acquire)
127- }
128- if release.alive {
129- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
130- release.alive = false
131- srv.dropTimeline(release)
132- }
133- if acquire.handle != 0 || release.handle != 0 {
134- t.Fatal("timeline handles leaked")
135- }
136- })
137- }
138-}
139-
140-func TestDropSyncMissingWaitWarns(t *testing.T) {
141- var out bytes.Buffer
142- srv := &Server{log: zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")}
143- surf := &surface{server: srv}
144- tl := &timeline{alive: true, uses: 2}
145- surf.dropSync(&commitSync{acquire: syncPoint{tl: tl, point: 11}, release: syncPoint{tl: tl, point: 12}})
146- surf.dropSync(nil)
147- var event map[string]any
148- if err := json.Unmarshal(out.Bytes(), &event); err != nil {
149- t.Fatal(err)
150- }
151- if event["reason"] != "no_wait" || event["sub"] != false {
152- t.Fatalf("missing wait diagnostic: %v", event)
153- }
154- if tl.uses != 0 || surf.releasePointsDropped != 1 || !bytes.Contains(out.Bytes(), []byte("surface release point dropped without signal")) {
155- t.Fatal("missing wait must be abandoned and warned")
156- }
157-}
158-
159-//testpolicy:realtime client disconnect is delivered by the real Wayland display loop
160-func TestDeferredReleaseClientTeardownAndBudget(t *testing.T) {
161- for _, budget := range []bool{false, true} {
162- t.Run(fmt.Sprint(budget), func(t *testing.T) {
163- h := newSyncHarness(t)
164- var out lockedBuffer
165- var client *deferredClient
166- gone := make(chan struct{})
167- h.s.display.Do(func() {
168- h.s.log = zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")
169- var surf *surface
170- for _, s := range h.s.surfaces {
171- if s.wl.ID() == h.surf {
172- surf = s
173- }
174- }
175- client = surf.syncClient
176- client.client.OnDestroy(func() { close(gone) })
177- n := 1
178- if budget {
179- n = maxDeferredReleasesPerClient + 1
180- }
181- tl := &timeline{dev: h.dev, handle: 7, alive: true, uses: 2 * n}
182- for range n {
183- surf.dropSync(&commitSync{acquire: syncPoint{tl: tl, point: 11}, release: syncPoint{tl: tl, point: 12}, wait: &syncWait{explicit: true, efd: -1}})
184- }
185- if budget && (client.count != 0 || tl.uses != 0 || len(h.s.deferredReleases) != 0) {
186- t.Error("budget cleanup leaked")
187- }
188- })
189- if budget {
190- if err := h.c.Roundtrip(); err == nil {
191- t.Fatal("budget did not post a protocol error")
192- }
193- }
194- _ = h.c.Close()
195- select {
196- case <-gone:
197- case <-waylandDeadline(2 * time.Second):
198- t.Fatal("client teardown not observed")
199- }
200- h.s.display.Do(func() {
201- if client.count != 0 || len(h.s.deferredReleases) != 0 {
202- t.Error("client releases leaked")
203- }
204- if _, ok := h.s.deferredClients[client.client]; ok {
205- t.Error("client state retained")
206- }
207- })
208- if !strings.Contains(out.String(), `"reason":"client_gone"`) {
209- t.Fatalf("missing client_gone: %s", out.String())
210- }
211- })
212- }
213-}
@@ -1,213 +0,0 @@
1-package wayland
2-
3-import (
4- "bytes"
5- "encoding/json"
6- "fmt"
7- "strings"
8- "testing"
9- "time"
10-
11- "bnema.dev/zerowrap"
12-)
13-
14-func TestDropSyncDeferredLifecycle(t *testing.T) {
15- for _, outcome := range []string{"ready", "failed", "acquire_destroyed", "release_destroyed", "shutdown", "client_gone", "already_ready", "already_ready_destroyed"} {
16- t.Run(outcome, func(t *testing.T) {
17- var out bytes.Buffer
18- dev := newMocksyncobjDevice(t)
19- srv := &Server{syncWait: &syncWaiter{}, log: zerowrap.New(zerowrap.Config{Level: "debug", Format: "json", Output: &out}).WithField("component", "wayland")}
20- surf := &surface{server: srv}
21- surf.sub.parent = &surface{server: srv, x11win: &window{id: 42, mapped: true}}
22- acquire := &timeline{dev: dev, handle: 7, alive: true, uses: 1}
23- release := &timeline{dev: dev, handle: 8, alive: true, uses: 1}
24- w := &syncWait{explicit: true, efd: -1, done: (outcome == "already_ready" || outcome == "already_ready_destroyed")}
25- cs := commitSync{acquire: syncPoint{tl: acquire, point: 11}, release: syncPoint{tl: release, point: 12}, wait: w}
26- signals := outcome == "ready" || outcome == "acquire_destroyed" || outcome == "release_destroyed" || outcome == "already_ready" || outcome == "already_ready_destroyed"
27- if signals {
28- dev.EXPECT().signal(uint32(8), uint64(12)).Return(nil).Once()
29- }
30- if outcome == "already_ready_destroyed" {
31- acquire.alive = false
32- release.alive = false
33- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
34- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
35- }
36- surf.dropSync(&cs)
37- if outcome != "already_ready" && outcome != "already_ready_destroyed" {
38- if surf.releasePointsDeferred != 1 {
39- t.Fatal("deferred counter not incremented")
40- }
41- var event map[string]any
42- if err := json.NewDecoder(bytes.NewReader(out.Bytes())).Decode(&event); err != nil {
43- t.Fatal(err)
44- }
45- if event["level"] != "debug" || event["window"] != float64(42) || event["sub"] != true {
46- t.Fatalf("deferred attribution: %v", event)
47- }
48- if len(srv.deferredReleases) != 1 || w.done || acquire.uses != 1 || release.uses != 1 || surf.releasePointsDropped != 0 {
49- t.Fatalf("ownership not retained: deferred=%d done=%v uses=%d/%d dropped=%d", len(srv.deferredReleases), w.done, acquire.uses, release.uses, surf.releasePointsDropped)
50- }
51- // Retiring/reusing the original update must not change deferred points.
52- cs = commitSync{}
53- srv.drainDeferredReleases(false)
54- if len(srv.deferredReleases) != 1 {
55- t.Fatal("unready acquire was drained")
56- }
57- switch outcome {
58- case "ready":
59- w.done = true
60- case "failed":
61- w.done, w.failed = true, true
62- case "client_gone":
63- surf.syncClient.gone = true
64- case "acquire_destroyed":
65- acquire.alive = false
66- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
67- case "release_destroyed":
68- release.alive = false
69- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
70- }
71- if outcome == "acquire_destroyed" || outcome == "release_destroyed" {
72- srv.drainDeferredReleases(false)
73- if len(srv.deferredReleases) != 1 {
74- t.Fatal("protocol timeline destruction cancelled committed point")
75- }
76- w.done = true
77- }
78- srv.drainDeferredReleases(outcome == "shutdown")
79- }
80- srv.drainDeferredReleases(false)
81- if len(srv.deferredReleases) != 0 || acquire.uses != 0 || release.uses != 0 || !w.done {
82- t.Fatalf("ownership leaked: deferred=%d uses=%d/%d done=%v", len(srv.deferredReleases), acquire.uses, release.uses, w.done)
83- }
84- if signals {
85- if surf.releasePointsSignalled != 1 || surf.releasePointsDropped != 0 {
86- t.Fatal("signal accounting")
87- }
88- if bytes.Contains(out.Bytes(), []byte("surface release point dropped without signal")) {
89- t.Fatalf("successful release warned: %s", out.String())
90- }
91- } else {
92- if surf.releasePointsSignalled != 0 || surf.releasePointsDropped != 1 {
93- t.Fatal("abandon accounting")
94- }
95- if n := bytes.Count(out.Bytes(), []byte("surface release point dropped without signal")); n != 1 {
96- t.Fatalf("warnings=%d: %s", n, out.String())
97- }
98- }
99- if !signals {
100- want := "client_gone"
101- if outcome == "failed" {
102- want = "wait_failed"
103- }
104- if outcome == "shutdown" {
105- want = "shutdown"
106- }
107- dec := json.NewDecoder(bytes.NewReader(out.Bytes()))
108- var deferred, warning map[string]any
109- if err := dec.Decode(&deferred); err != nil {
110- t.Fatal(err)
111- }
112- if err := dec.Decode(&warning); err != nil {
113- t.Fatal(err)
114- }
115- if warning["reason"] != want || warning["window"] != float64(42) || warning["sub"] != true {
116- t.Fatalf("abandon diagnostic: %v", warning)
117- }
118- }
119- if (outcome == "already_ready" || outcome == "already_ready_destroyed") && surf.releasePointsDeferred != 0 {
120- t.Fatal("ready release counted as deferred")
121- }
122- // Destroy remaining live timelines after the references have retired.
123- if acquire.alive {
124- dev.EXPECT().destroy(uint32(7)).Return(nil).Once()
125- acquire.alive = false
126- srv.dropTimeline(acquire)
127- }
128- if release.alive {
129- dev.EXPECT().destroy(uint32(8)).Return(nil).Once()
130- release.alive = false
131- srv.dropTimeline(release)
132- }
133- if acquire.handle != 0 || release.handle != 0 {
134- t.Fatal("timeline handles leaked")
135- }
136- })
137- }
138-}
139-
140-func TestDropSyncMissingWaitWarns(t *testing.T) {
141- var out bytes.Buffer
142- srv := &Server{log: zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")}
143- surf := &surface{server: srv}
144- tl := &timeline{alive: true, uses: 2}
145- surf.dropSync(&commitSync{acquire: syncPoint{tl: tl, point: 11}, release: syncPoint{tl: tl, point: 12}})
146- surf.dropSync(nil)
147- var event map[string]any
148- if err := json.Unmarshal(out.Bytes(), &event); err != nil {
149- t.Fatal(err)
150- }
151- if event["reason"] != "no_wait" || event["sub"] != false {
152- t.Fatalf("missing wait diagnostic: %v", event)
153- }
154- if tl.uses != 0 || surf.releasePointsDropped != 1 || !bytes.Contains(out.Bytes(), []byte("surface release point dropped without signal")) {
155- t.Fatal("missing wait must be abandoned and warned")
156- }
157-}
158-
159-//testpolicy:realtime client disconnect is delivered by the real Wayland display loop
160-func TestDeferredReleaseClientTeardownAndBudget(t *testing.T) {
161- for _, budget := range []bool{false, true} {
162- t.Run(fmt.Sprint(budget), func(t *testing.T) {
163- h := newSyncHarness(t)
164- var out lockedBuffer
165- var client *deferredClient
166- gone := make(chan struct{})
167- h.s.display.Do(func() {
168- h.s.log = zerowrap.New(zerowrap.Config{Format: "json", Output: &out}).WithField("component", "wayland")
169- var surf *surface
170- for _, s := range h.s.surfaces {
171- if s.wl.ID() == h.surf {
172- surf = s
173- }
174- }
175- client = surf.syncClient
176- client.client.OnDestroy(func() { close(gone) })
177- n := 1
178- if budget {
179- n = maxDeferredReleasesPerClient + 1
180- }
181- tl := &timeline{dev: h.dev, handle: 7, alive: true, uses: 2 * n}
182- for range n {
183- surf.dropSync(&commitSync{acquire: syncPoint{tl: tl, point: 11}, release: syncPoint{tl: tl, point: 12}, wait: &syncWait{explicit: true, efd: -1}})
184- }
185- if budget && (client.count != 0 || tl.uses != 0 || len(h.s.deferredReleases) != 0) {
186- t.Error("budget cleanup leaked")
187- }
188- })
189- if budget {
190- if err := h.c.Roundtrip(); err == nil {
191- t.Fatal("budget did not post a protocol error")
192- }
193- }
194- _ = h.c.Close()
195- select {
196- case <-gone:
197- case <-waylandDeadline(2 * time.Second):
198- t.Fatal("client teardown not observed")
199- }
200- h.s.display.Do(func() {
201- if client.count != 0 || len(h.s.deferredReleases) != 0 {
202- t.Error("client releases leaked")
203- }
204- if _, ok := h.s.deferredClients[client.client]; ok {
205- t.Error("client state retained")
206- }
207- })
208- if !strings.Contains(out.String(), `"reason":"client_gone"`) {
209- t.Fatalf("missing client_gone: %s", out.String())
210- }
211- })
212- }
213-}
M internal/adapters/wayland/syncobj.go +6 -134
@@ -79,7 +79,6 @@ func (m syncManager) GetSurface(r *linuxdrmsyncobj.WpLinuxDrmSyncobjManagerV1, i
7979 }
8080 st.resource = res
8181 state.sync = st
82- state.syncClient = m.server.deferredClientFor(r.Client())
8382 m.server.log.Debug().Uint32("surface", state.wl.ID()).
8483 Uint64("window", uint64(state.root().windowID())).Msg("explicit sync surface created")
8584 res.OnDestroy = func() {
@@ -609,7 +608,6 @@ func (sw *syncWaiter) discard() {
609608 // syncHold is a buffer's explicit-sync state while it is on screen: the
610609 // acquire fence handed to readers and the release point to signal.
611610 type syncHold struct {
612- owner *surface
613611 acquire *os.File
614612 release syncPoint
615613 }
@@ -623,8 +621,6 @@ func (s *Server) releaseSync(h syncHold) {
623621 if h.release.set() {
624622 if err := h.release.tl.dev.signal(h.release.tl.handle, h.release.point); err != nil {
625623 s.log.Warn().Err(err).Msg("release point")
626- } else if h.owner != nil {
627- h.owner.releasePointsSignalled++
628624 }
629625 h.release.tl.uses--
630626 s.dropTimeline(h.release.tl)
@@ -671,57 +667,9 @@ func (s *surface) syncReady(cs *commitSync) bool {
671667 return cs == nil || cs.wait == nil || s.server.syncWait.fired(cs.wait)
672668 }
673669
674-// Bound retained waits for each client without advancing unsubmitted work.
675-const maxDeferredReleasesPerClient = 64
676-
677-type deferredClient struct {
678- client server.Client
679- count int
680- gone bool
681-}
682-
683-func (s *Server) deferredClientFor(c server.Client) *deferredClient {
684- if s.deferredClients == nil {
685- s.deferredClients = make(map[server.Client]*deferredClient)
686- }
687- if state := s.deferredClients[c]; state != nil {
688- return state
689- }
690- state := &deferredClient{client: c}
691- s.deferredClients[c] = state
692- c.OnDestroy(func() {
693- state.gone = true
694- s.abandonDeferredClient(state)
695- delete(s.deferredClients, c)
696- })
697- return state
698-}
699-
700-func (s *Server) abandonDeferredClient(client *deferredClient) {
701- kept := s.deferredReleases[:0]
702- for _, d := range s.deferredReleases {
703- if d.client == client {
704- d.owner.finishDroppedSync(&d.sync, false)
705- client.count--
706- } else {
707- kept = append(kept, d)
708- }
709- }
710- clear(s.deferredReleases[len(kept):])
711- s.deferredReleases = kept
712-}
713-
714-// deferredRelease owns points and a wait independently of the retired update.
715-// Only the display goroutine creates and drains these records.
716-type deferredRelease struct {
717- client *deferredClient
718- owner *surface
719- sync commitSync
720-}
721-
722-// dropSync retires an unused attachment. An unready acquire must retain its
723-// release point until the acquire has a fence; advancing a shared timeline
724-// sooner could pass work the client has not submitted yet.
670+// dropSync forgets a commit that will never apply. Its release point is
671+// signalled only once the acquire point has a fence: signalling earlier
672+// could move a shared timeline past a point the client has not submitted.
725673 func (s *surface) dropSync(cs *commitSync) {
726674 if cs == nil {
727675 return
@@ -730,95 +678,20 @@ func (s *surface) dropSync(cs *commitSync) {
730678 logging.CloseFile(s.server.log, cs.fence, "acquire fence")
731679 cs.fence = nil
732680 }
733- if s.syncClient == nil {
734- c := server.Client{}
735- if s.wl != nil {
736- c = s.wl.Client()
737- }
738- s.syncClient = s.server.deferredClientFor(c)
739- }
740- if cs.wait != nil && !s.syncClient.gone &&
741- !s.server.syncWait.fired(cs.wait) && !cs.wait.failed {
742- if s.syncClient.count >= maxDeferredReleasesPerClient {
743- s.syncClient.client.PostImplementationError("too many deferred explicit-sync releases")
744- s.syncClient.gone = true
745- s.server.abandonDeferredClient(s.syncClient)
746- s.finishDroppedSync(cs, false)
747- return
748- }
749- s.syncClient.count++
750- s.server.deferredReleases = append(s.server.deferredReleases, deferredRelease{client: s.syncClient, owner: s, sync: *cs})
751- s.releasePointsDeferred++
752- s.server.log.Debug().Uint64("window", uint64(s.root().windowID())).
753- Bool("sub", s.sub.parent != nil).
754- Uint32("surface", s.surfaceID()).
755- Uint64("release_point", cs.release.point).Uint32("release_timeline", cs.release.tl.handle).
756- Msg("surface release point deferred")
757- return
758- }
759- s.finishDroppedSync(cs, false)
760-}
761-
762-// finishDroppedSync consumes both references exactly once. Protocol object
763-// destruction does not unset committed points or invalidate retained handles.
764-func (s *surface) finishDroppedSync(cs *commitSync, shutdown bool) {
765- reason := ""
766- switch {
767- case shutdown:
768- reason = "shutdown"
769- case s.syncClient != nil && s.syncClient.gone:
770- reason = "client_gone"
771- case cs.wait == nil:
772- reason = "no_wait"
773- case cs.wait.failed:
774- reason = "wait_failed"
775- }
776- acquireHandle := cs.acquire.tl.handle
777- ready := !shutdown && (s.syncClient == nil || !s.syncClient.gone) &&
778- cs.wait != nil && s.server.syncWait.fired(cs.wait) && !cs.wait.failed
681+ ready := cs.wait != nil && s.server.syncWait.fired(cs.wait) && !cs.wait.failed
779682 if cs.wait != nil {
780683 s.server.syncWait.cancel(cs.wait)
781684 }
782685 cs.acquire.tl.uses--
783686 s.server.dropTimeline(cs.acquire.tl)
784687 if ready {
785- s.server.releaseSync(syncHold{owner: s, release: cs.release})
688+ s.server.releaseSync(syncHold{release: cs.release})
786689 return
787690 }
788- s.releasePointsDropped++
789- s.server.log.Warn().
790- Uint64("window", uint64(s.root().windowID())).
791- Bool("sub", s.sub.parent != nil).
792- Uint32("surface", s.surfaceID()).
793- Str("reason", reason).
794- Uint64("release_point", cs.release.point).
795- Uint32("release_timeline", cs.release.tl.handle).
796- Uint64("acquire_point", cs.acquire.point).
797- Uint32("acquire_timeline", acquireHandle).
798- Uint64("release_points_dropped", s.releasePointsDropped).
799- Msg("surface release point dropped without signal")
800691 cs.release.tl.uses--
801692 s.server.dropTimeline(cs.release.tl)
802693 }
803694
804-// drainDeferredReleases runs on acquire notification.
805-// Shutdown abandons remaining waits before the waiter's registrations close.
806-func (s *Server) drainDeferredReleases(shutdown bool) {
807- kept := s.deferredReleases[:0]
808- for _, d := range s.deferredReleases {
809- cs := &d.sync
810- dead := shutdown || d.client.gone
811- if dead || cs.wait.failed || s.syncWait.fired(cs.wait) {
812- d.owner.finishDroppedSync(cs, shutdown)
813- d.client.count--
814- } else {
815- kept = append(kept, d)
816- }
817- }
818- clear(s.deferredReleases[len(kept):])
819- s.deferredReleases = kept
820-}
821-
822695 // prepareSync exports only after observed readiness, before any current state
823696 // changes. Export failure must not fall back to native implicit synchronization.
824697 func (s *surface) prepareSync(cs *commitSync) bool {
@@ -850,13 +723,12 @@ func (s *surface) applySync(cs *commitSync) {
850723 cs.fence = nil
851724 cs.acquire.tl.uses--
852725 s.server.dropTimeline(cs.acquire.tl)
853- s.hold = syncHold{owner: s, acquire: f, release: cs.release}
726+ s.hold = syncHold{acquire: f, release: cs.release}
854727 }
855728
856729 // acquireSignalled applies what a fired acquire point unblocked: like a
857730 // commit, it ticks inline instead of posting a tick to the display loop.
858731 func (s *Server) acquireSignalled() {
859- s.drainDeferredReleases(false)
860732 s.paceDepth++
861733 s.wakePacer()
862734 s.paceDepth--
@@ -79,7 +79,6 @@ func (m syncManager) GetSurface(r *linuxdrmsyncobj.WpLinuxDrmSyncobjManagerV1, i
79 }79 }
80 st.resource = res80 st.resource = res
81 state.sync = st81 state.sync = st
82- state.syncClient = m.server.deferredClientFor(r.Client())
83 m.server.log.Debug().Uint32("surface", state.wl.ID()).82 m.server.log.Debug().Uint32("surface", state.wl.ID()).
84 Uint64("window", uint64(state.root().windowID())).Msg("explicit sync surface created")83 Uint64("window", uint64(state.root().windowID())).Msg("explicit sync surface created")
85 res.OnDestroy = func() {84 res.OnDestroy = func() {
@@ -609,7 +608,6 @@ func (sw *syncWaiter) discard() {
609 // syncHold is a buffer's explicit-sync state while it is on screen: the608 // syncHold is a buffer's explicit-sync state while it is on screen: the
610 // acquire fence handed to readers and the release point to signal.609 // acquire fence handed to readers and the release point to signal.
611 type syncHold struct {610 type syncHold struct {
612- owner *surface
613 acquire *os.File611 acquire *os.File
614 release syncPoint612 release syncPoint
615 }613 }
@@ -623,8 +621,6 @@ func (s *Server) releaseSync(h syncHold) {
623 if h.release.set() {621 if h.release.set() {
624 if err := h.release.tl.dev.signal(h.release.tl.handle, h.release.point); err != nil {622 if err := h.release.tl.dev.signal(h.release.tl.handle, h.release.point); err != nil {
625 s.log.Warn().Err(err).Msg("release point")623 s.log.Warn().Err(err).Msg("release point")
626- } else if h.owner != nil {
627- h.owner.releasePointsSignalled++
628 }624 }
629 h.release.tl.uses--625 h.release.tl.uses--
630 s.dropTimeline(h.release.tl)626 s.dropTimeline(h.release.tl)
@@ -671,57 +667,9 @@ func (s *surface) syncReady(cs *commitSync) bool {
671 return cs == nil || cs.wait == nil || s.server.syncWait.fired(cs.wait)667 return cs == nil || cs.wait == nil || s.server.syncWait.fired(cs.wait)
672 }668 }
673 669
674-// Bound retained waits for each client without advancing unsubmitted work.670+// dropSync forgets a commit that will never apply. Its release point is
675-const maxDeferredReleasesPerClient = 64671+// signalled only once the acquire point has a fence: signalling earlier
676-672+// could move a shared timeline past a point the client has not submitted.
677-type deferredClient struct {
678- client server.Client
679- count int
680- gone bool
681-}
682-
683-func (s *Server) deferredClientFor(c server.Client) *deferredClient {
684- if s.deferredClients == nil {
685- s.deferredClients = make(map[server.Client]*deferredClient)
686- }
687- if state := s.deferredClients[c]; state != nil {
688- return state
689- }
690- state := &deferredClient{client: c}
691- s.deferredClients[c] = state
692- c.OnDestroy(func() {
693- state.gone = true
694- s.abandonDeferredClient(state)
695- delete(s.deferredClients, c)
696- })
697- return state
698-}
699-
700-func (s *Server) abandonDeferredClient(client *deferredClient) {
701- kept := s.deferredReleases[:0]
702- for _, d := range s.deferredReleases {
703- if d.client == client {
704- d.owner.finishDroppedSync(&d.sync, false)
705- client.count--
706- } else {
707- kept = append(kept, d)
708- }
709- }
710- clear(s.deferredReleases[len(kept):])
711- s.deferredReleases = kept
712-}
713-
714-// deferredRelease owns points and a wait independently of the retired update.
715-// Only the display goroutine creates and drains these records.
716-type deferredRelease struct {
717- client *deferredClient
718- owner *surface
719- sync commitSync
720-}
721-
722-// dropSync retires an unused attachment. An unready acquire must retain its
723-// release point until the acquire has a fence; advancing a shared timeline
724-// sooner could pass work the client has not submitted yet.
725 func (s *surface) dropSync(cs *commitSync) {673 func (s *surface) dropSync(cs *commitSync) {
726 if cs == nil {674 if cs == nil {
727 return675 return
@@ -730,95 +678,20 @@ func (s *surface) dropSync(cs *commitSync) {
730 logging.CloseFile(s.server.log, cs.fence, "acquire fence")678 logging.CloseFile(s.server.log, cs.fence, "acquire fence")
731 cs.fence = nil679 cs.fence = nil
732 }680 }
733- if s.syncClient == nil {681+ ready := cs.wait != nil && s.server.syncWait.fired(cs.wait) && !cs.wait.failed
734- c := server.Client{}
735- if s.wl != nil {
736- c = s.wl.Client()
737- }
738- s.syncClient = s.server.deferredClientFor(c)
739- }
740- if cs.wait != nil && !s.syncClient.gone &&
741- !s.server.syncWait.fired(cs.wait) && !cs.wait.failed {
742- if s.syncClient.count >= maxDeferredReleasesPerClient {
743- s.syncClient.client.PostImplementationError("too many deferred explicit-sync releases")
744- s.syncClient.gone = true
745- s.server.abandonDeferredClient(s.syncClient)
746- s.finishDroppedSync(cs, false)
747- return
748- }
749- s.syncClient.count++
750- s.server.deferredReleases = append(s.server.deferredReleases, deferredRelease{client: s.syncClient, owner: s, sync: *cs})
751- s.releasePointsDeferred++
752- s.server.log.Debug().Uint64("window", uint64(s.root().windowID())).
753- Bool("sub", s.sub.parent != nil).
754- Uint32("surface", s.surfaceID()).
755- Uint64("release_point", cs.release.point).Uint32("release_timeline", cs.release.tl.handle).
756- Msg("surface release point deferred")
757- return
758- }
759- s.finishDroppedSync(cs, false)
760-}
761-
762-// finishDroppedSync consumes both references exactly once. Protocol object
763-// destruction does not unset committed points or invalidate retained handles.
764-func (s *surface) finishDroppedSync(cs *commitSync, shutdown bool) {
765- reason := ""
766- switch {
767- case shutdown:
768- reason = "shutdown"
769- case s.syncClient != nil && s.syncClient.gone:
770- reason = "client_gone"
771- case cs.wait == nil:
772- reason = "no_wait"
773- case cs.wait.failed:
774- reason = "wait_failed"
775- }
776- acquireHandle := cs.acquire.tl.handle
777- ready := !shutdown && (s.syncClient == nil || !s.syncClient.gone) &&
778- cs.wait != nil && s.server.syncWait.fired(cs.wait) && !cs.wait.failed
779 if cs.wait != nil {682 if cs.wait != nil {
780 s.server.syncWait.cancel(cs.wait)683 s.server.syncWait.cancel(cs.wait)
781 }684 }
782 cs.acquire.tl.uses--685 cs.acquire.tl.uses--
783 s.server.dropTimeline(cs.acquire.tl)686 s.server.dropTimeline(cs.acquire.tl)
784 if ready {687 if ready {
785- s.server.releaseSync(syncHold{owner: s, release: cs.release})688+ s.server.releaseSync(syncHold{release: cs.release})
786 return689 return
787 }690 }
788- s.releasePointsDropped++
789- s.server.log.Warn().
790- Uint64("window", uint64(s.root().windowID())).
791- Bool("sub", s.sub.parent != nil).
792- Uint32("surface", s.surfaceID()).
793- Str("reason", reason).
794- Uint64("release_point", cs.release.point).
795- Uint32("release_timeline", cs.release.tl.handle).
796- Uint64("acquire_point", cs.acquire.point).
797- Uint32("acquire_timeline", acquireHandle).
798- Uint64("release_points_dropped", s.releasePointsDropped).
799- Msg("surface release point dropped without signal")
800 cs.release.tl.uses--691 cs.release.tl.uses--
801 s.server.dropTimeline(cs.release.tl)692 s.server.dropTimeline(cs.release.tl)
802 }693 }
803 694
804-// drainDeferredReleases runs on acquire notification.
805-// Shutdown abandons remaining waits before the waiter's registrations close.
806-func (s *Server) drainDeferredReleases(shutdown bool) {
807- kept := s.deferredReleases[:0]
808- for _, d := range s.deferredReleases {
809- cs := &d.sync
810- dead := shutdown || d.client.gone
811- if dead || cs.wait.failed || s.syncWait.fired(cs.wait) {
812- d.owner.finishDroppedSync(cs, shutdown)
813- d.client.count--
814- } else {
815- kept = append(kept, d)
816- }
817- }
818- clear(s.deferredReleases[len(kept):])
819- s.deferredReleases = kept
820-}
821-
822 // prepareSync exports only after observed readiness, before any current state695 // prepareSync exports only after observed readiness, before any current state
823 // changes. Export failure must not fall back to native implicit synchronization.696 // changes. Export failure must not fall back to native implicit synchronization.
824 func (s *surface) prepareSync(cs *commitSync) bool {697 func (s *surface) prepareSync(cs *commitSync) bool {
@@ -850,13 +723,12 @@ func (s *surface) applySync(cs *commitSync) {
850 cs.fence = nil723 cs.fence = nil
851 cs.acquire.tl.uses--724 cs.acquire.tl.uses--
852 s.server.dropTimeline(cs.acquire.tl)725 s.server.dropTimeline(cs.acquire.tl)
853- s.hold = syncHold{owner: s, acquire: f, release: cs.release}726+ s.hold = syncHold{acquire: f, release: cs.release}
854 }727 }
855 728
856 // acquireSignalled applies what a fired acquire point unblocked: like a729 // acquireSignalled applies what a fired acquire point unblocked: like a
857 // commit, it ticks inline instead of posting a tick to the display loop.730 // commit, it ticks inline instead of posting a tick to the display loop.
858 func (s *Server) acquireSignalled() {731 func (s *Server) acquireSignalled() {
859- s.drainDeferredReleases(false)
860 s.paceDepth++732 s.paceDepth++
861 s.wakePacer()733 s.wakePacer()
862 s.paceDepth--734 s.paceDepth--
M internal/adapters/wayland/syncobj_test.go +9 -30
@@ -516,9 +516,7 @@ func TestSyncobjInvalidTimeline(t *testing.T) {
516516 }
517517
518518 // A synchronized subsurface dropped before its acquire is ready must
519-// defer its release point without sending wl_buffer.release.
520-//
521-//testpolicy:realtime real display eventfd callback signals the deferred release
519+// retire its release point without sending wl_buffer.release.
522520 func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
523521 h := newSyncHarness(t)
524522 h.releases = map[uint32]*syncReleaseProxy{}
@@ -544,20 +542,12 @@ func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
544542 if err := c.Roundtrip(); err != nil {
545543 t.Fatal(err)
546544 }
547- if got := h.signalled(); len(got) != 0 {
548- t.Fatalf("release before acquire: %v", got)
549- }
550- h.fire(21)
551- select {
552- case <-h.signalReady:
553- case <-waylandDeadline(2 * time.Second):
554- t.Fatal("deferred release not signalled")
555- }
545+ h.fire(21) // dropping before acquire means the later signal must not release
556546 if err := c.Roundtrip(); err != nil {
557547 t.Fatal(err)
558548 }
559- if got := h.signalled(); len(got) != 1 || got[0] != 22 {
560- t.Fatalf("deferred release point: %v", got)
549+ if got := h.signalled(); len(got) != 0 {
550+ t.Fatalf("premature release point: %v", got)
561551 }
562552 select {
563553 case <-h.releases[b].released:
@@ -568,8 +558,7 @@ func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
568558
569559 // A commit dropped before its acquire point has a fence signals nothing
570560 // (the client has not submitted that point) and sends no wl_buffer.release;
571-// protocol timeline destruction retains it until the acquire arrives.
572-//
561+// the waiter closes its eventfd and no acquire file is left open.
573562 func TestSyncobjDroppedCommit(t *testing.T) {
574563 h := newSyncHarness(t)
575564 h.releases = map[uint32]*syncReleaseProxy{}
@@ -580,8 +569,8 @@ func TestSyncobjDroppedCommit(t *testing.T) {
580569 if err := h.c.Roundtrip(); err != nil {
581570 t.Fatal(err)
582571 }
583- // Timeline object destruction must not unset committed points.
584- requestProtocol(t, h.c, h.timeline, linuxdrmsyncobj.WpLinuxDrmSyncobjTimelineV1RequestDestroy)
572+ // Explicit acquire registrations are removed synchronously by destruction;
573+ // the roundtrip above joins that display-owner work.
585574 if err := h.c.Roundtrip(); err != nil {
586575 t.Fatal(err)
587576 }
@@ -593,18 +582,8 @@ func TestSyncobjDroppedCommit(t *testing.T) {
593582 t.Fatal("wl_buffer.release sent under explicit sync")
594583 default:
595584 }
596- h.fire(1)
597- h.s.display.Do(func() {
598- if len(h.s.deferredReleases) > 0 {
599- h.s.syncWait.onAcquire(h.s.deferredReleases[0].sync.wait)
600- }
601- })
602- if got := h.signalled(); len(got) != 1 || got[0] != 2 {
603- t.Fatalf("retained release: %v", got)
604- }
605- // The harness keeps its own duplicate of the eventfd, and the waiter caches
606- // its drained registration for reuse.
607- if after := openFDs(t); after > before+3 {
585+ // The harness keeps its own duplicate of the eventfd.
586+ if after := openFDs(t); after > before+1 {
608587 t.Fatalf("eventfds and sync files %d -> %d", before, after)
609588 }
610589 }
@@ -516,9 +516,7 @@ func TestSyncobjInvalidTimeline(t *testing.T) {
516 }516 }
517 517
518 // A synchronized subsurface dropped before its acquire is ready must518 // A synchronized subsurface dropped before its acquire is ready must
519-// defer its release point without sending wl_buffer.release.519+// retire its release point without sending wl_buffer.release.
520-//
521-//testpolicy:realtime real display eventfd callback signals the deferred release
522 func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {520 func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
523 h := newSyncHarness(t)521 h := newSyncHarness(t)
524 h.releases = map[uint32]*syncReleaseProxy{}522 h.releases = map[uint32]*syncReleaseProxy{}
@@ -544,20 +542,12 @@ func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
544 if err := c.Roundtrip(); err != nil {542 if err := c.Roundtrip(); err != nil {
545 t.Fatal(err)543 t.Fatal(err)
546 }544 }
547- if got := h.signalled(); len(got) != 0 {545+ h.fire(21) // dropping before acquire means the later signal must not release
548- t.Fatalf("release before acquire: %v", got)
549- }
550- h.fire(21)
551- select {
552- case <-h.signalReady:
553- case <-waylandDeadline(2 * time.Second):
554- t.Fatal("deferred release not signalled")
555- }
556 if err := c.Roundtrip(); err != nil {546 if err := c.Roundtrip(); err != nil {
557 t.Fatal(err)547 t.Fatal(err)
558 }548 }
559- if got := h.signalled(); len(got) != 1 || got[0] != 22 {549+ if got := h.signalled(); len(got) != 0 {
560- t.Fatalf("deferred release point: %v", got)550+ t.Fatalf("premature release point: %v", got)
561 }551 }
562 select {552 select {
563 case <-h.releases[b].released:553 case <-h.releases[b].released:
@@ -568,8 +558,7 @@ func TestSyncobjDroppedSubsurfaceCommit(t *testing.T) {
568 558
569 // A commit dropped before its acquire point has a fence signals nothing559 // A commit dropped before its acquire point has a fence signals nothing
570 // (the client has not submitted that point) and sends no wl_buffer.release;560 // (the client has not submitted that point) and sends no wl_buffer.release;
571-// protocol timeline destruction retains it until the acquire arrives.561+// the waiter closes its eventfd and no acquire file is left open.
572-//
573 func TestSyncobjDroppedCommit(t *testing.T) {562 func TestSyncobjDroppedCommit(t *testing.T) {
574 h := newSyncHarness(t)563 h := newSyncHarness(t)
575 h.releases = map[uint32]*syncReleaseProxy{}564 h.releases = map[uint32]*syncReleaseProxy{}
@@ -580,8 +569,8 @@ func TestSyncobjDroppedCommit(t *testing.T) {
580 if err := h.c.Roundtrip(); err != nil {569 if err := h.c.Roundtrip(); err != nil {
581 t.Fatal(err)570 t.Fatal(err)
582 }571 }
583- // Timeline object destruction must not unset committed points.572+ // Explicit acquire registrations are removed synchronously by destruction;
584- requestProtocol(t, h.c, h.timeline, linuxdrmsyncobj.WpLinuxDrmSyncobjTimelineV1RequestDestroy)573+ // the roundtrip above joins that display-owner work.
585 if err := h.c.Roundtrip(); err != nil {574 if err := h.c.Roundtrip(); err != nil {
586 t.Fatal(err)575 t.Fatal(err)
587 }576 }
@@ -593,18 +582,8 @@ func TestSyncobjDroppedCommit(t *testing.T) {
593 t.Fatal("wl_buffer.release sent under explicit sync")582 t.Fatal("wl_buffer.release sent under explicit sync")
594 default:583 default:
595 }584 }
596- h.fire(1)585+ // The harness keeps its own duplicate of the eventfd.
597- h.s.display.Do(func() {586+ if after := openFDs(t); after > before+1 {
598- if len(h.s.deferredReleases) > 0 {
599- h.s.syncWait.onAcquire(h.s.deferredReleases[0].sync.wait)
600- }
601- })
602- if got := h.signalled(); len(got) != 1 || got[0] != 2 {
603- t.Fatalf("retained release: %v", got)
604- }
605- // The harness keeps its own duplicate of the eventfd, and the waiter caches
606- // its drained registration for reuse.
607- if after := openFDs(t); after > before+3 {
608 t.Fatalf("eventfds and sync files %d -> %d", before, after)587 t.Fatalf("eventfds and sync files %d -> %d", before, after)
609 }588 }
610 }589 }
M internal/core/core.go +12 -0
@@ -137,6 +137,7 @@ type Core struct {
137137 pressed map[string]bool
138138 configures configures
139139 pointer WindowID
140+ hover pendingHover
140141 hoverLocked bool // a non-pointer focus change holds hover focus
141142 hoverLock WindowID // hover target the hold ignores: the window under the cursor, retargeted when layout changes what lies there
142143 focusByPointer bool // set while focusPointer publishes, so syncFocus does not arm the hold
@@ -410,6 +411,9 @@ func (c *Core) apply(cfg domain.Config) error {
410411 if c.cfg.Keyboard.CmdKey != cfg.Keyboard.CmdKey {
411412 c.osdCancel()
412413 }
414+ if c.cfg.Focus.FollowMouse != cfg.Focus.FollowMouse || c.cfg.Focus.FollowMouseDelay != cfg.Focus.FollowMouseDelay {
415+ c.cancelHover()
416+ }
413417 c.cfg = cfg
414418 c.inputBindings = false
415419 for _, output := range cfg.Outputs {
@@ -851,6 +855,7 @@ func (c *Core) rehit(ctx context.Context) error {
851855 }
852856 id, x, y := c.hit(c.cursorX, c.cursorY)
853857 if id != c.pointer {
858+ c.cancelHover()
854859 if c.hoverLocked {
855860 c.hoverLock = id
856861 }
@@ -1026,6 +1031,7 @@ func (c *Core) syncFocus(ctx context.Context, focus WindowID) error {
10261031 return nil
10271032 }
10281033 if !c.focusByPointer {
1034+ c.cancelHover()
10291035 c.hoverLocked, c.hoverLock = true, c.pointer
10301036 }
10311037 if err := c.command(ctx, ports.FocusWindow{ID: focus}); err != nil {
@@ -1190,6 +1196,7 @@ func (c *Core) Run(ctx context.Context) error {
11901196 defer c.stopCaptureTimer()
11911197 defer c.stopFlashTimer()
11921198 defer c.stopPositionHintTimer()
1199+ defer c.cancelHover()
11931200 defer c.cancelSwitcher()
11941201 defer c.stopRepeat()
11951202 // Startup commands run once per session. Full launcher queues retain a
@@ -1287,6 +1294,11 @@ func (c *Core) Run(ctx context.Context) error {
12871294 return nil
12881295 }
12891296 continue
1297+ case <-c.hover.timerC:
1298+ if c.securityCheckpoint(ctx) != nil || c.hoverTick(ctx) != nil {
1299+ return nil
1300+ }
1301+ continue
12901302 case <-c.positionHintTimer.timerC:
12911303 c.positionHintTimer.timerC = nil
12921304 if c.securityCheckpoint(ctx) != nil || c.publish(ctx) != nil {
@@ -137,6 +137,7 @@ type Core struct {
137 pressed map[string]bool137 pressed map[string]bool
138 configures configures138 configures configures
139 pointer WindowID139 pointer WindowID
140+ hover pendingHover
140 hoverLocked bool // a non-pointer focus change holds hover focus141 hoverLocked bool // a non-pointer focus change holds hover focus
141 hoverLock WindowID // hover target the hold ignores: the window under the cursor, retargeted when layout changes what lies there142 hoverLock WindowID // hover target the hold ignores: the window under the cursor, retargeted when layout changes what lies there
142 focusByPointer bool // set while focusPointer publishes, so syncFocus does not arm the hold143 focusByPointer bool // set while focusPointer publishes, so syncFocus does not arm the hold
@@ -410,6 +411,9 @@ func (c *Core) apply(cfg domain.Config) error {
410 if c.cfg.Keyboard.CmdKey != cfg.Keyboard.CmdKey {411 if c.cfg.Keyboard.CmdKey != cfg.Keyboard.CmdKey {
411 c.osdCancel()412 c.osdCancel()
412 }413 }
414+ if c.cfg.Focus.FollowMouse != cfg.Focus.FollowMouse || c.cfg.Focus.FollowMouseDelay != cfg.Focus.FollowMouseDelay {
415+ c.cancelHover()
416+ }
413 c.cfg = cfg417 c.cfg = cfg
414 c.inputBindings = false418 c.inputBindings = false
415 for _, output := range cfg.Outputs {419 for _, output := range cfg.Outputs {
@@ -851,6 +855,7 @@ func (c *Core) rehit(ctx context.Context) error {
851 }855 }
852 id, x, y := c.hit(c.cursorX, c.cursorY)856 id, x, y := c.hit(c.cursorX, c.cursorY)
853 if id != c.pointer {857 if id != c.pointer {
858+ c.cancelHover()
854 if c.hoverLocked {859 if c.hoverLocked {
855 c.hoverLock = id860 c.hoverLock = id
856 }861 }
@@ -1026,6 +1031,7 @@ func (c *Core) syncFocus(ctx context.Context, focus WindowID) error {
1026 return nil1031 return nil
1027 }1032 }
1028 if !c.focusByPointer {1033 if !c.focusByPointer {
1034+ c.cancelHover()
1029 c.hoverLocked, c.hoverLock = true, c.pointer1035 c.hoverLocked, c.hoverLock = true, c.pointer
1030 }1036 }
1031 if err := c.command(ctx, ports.FocusWindow{ID: focus}); err != nil {1037 if err := c.command(ctx, ports.FocusWindow{ID: focus}); err != nil {
@@ -1190,6 +1196,7 @@ func (c *Core) Run(ctx context.Context) error {
1190 defer c.stopCaptureTimer()1196 defer c.stopCaptureTimer()
1191 defer c.stopFlashTimer()1197 defer c.stopFlashTimer()
1192 defer c.stopPositionHintTimer()1198 defer c.stopPositionHintTimer()
1199+ defer c.cancelHover()
1193 defer c.cancelSwitcher()1200 defer c.cancelSwitcher()
1194 defer c.stopRepeat()1201 defer c.stopRepeat()
1195 // Startup commands run once per session. Full launcher queues retain a1202 // Startup commands run once per session. Full launcher queues retain a
@@ -1287,6 +1294,11 @@ func (c *Core) Run(ctx context.Context) error {
1287 return nil1294 return nil
1288 }1295 }
1289 continue1296 continue
1297+ case <-c.hover.timerC:
1298+ if c.securityCheckpoint(ctx) != nil || c.hoverTick(ctx) != nil {
1299+ return nil
1300+ }
1301+ continue
1290 case <-c.positionHintTimer.timerC:1302 case <-c.positionHintTimer.timerC:
1291 c.positionHintTimer.timerC = nil1303 c.positionHintTimer.timerC = nil
1292 if c.securityCheckpoint(ctx) != nil || c.publish(ctx) != nil {1304 if c.securityCheckpoint(ctx) != nil || c.publish(ctx) != nil {
M internal/core/flash_test.go +1 -0
@@ -428,6 +428,7 @@ func TestFlashHoverFocus(t *testing.T) {
428428 synctest.Test(t, func(t *testing.T) {
429429 c, _ := flashCore(t)
430430 c.cfg.Focus.FollowMouse = true
431+ c.cfg.Focus.FollowMouseDelay = 0
431432 ctx := context.Background()
432433 indicatorScene(t, c)
433434 focused, _ := c.cur().mon.Focused()
@@ -428,6 +428,7 @@ func TestFlashHoverFocus(t *testing.T) {
428 synctest.Test(t, func(t *testing.T) {428 synctest.Test(t, func(t *testing.T) {
429 c, _ := flashCore(t)429 c, _ := flashCore(t)
430 c.cfg.Focus.FollowMouse = true430 c.cfg.Focus.FollowMouse = true
431+ c.cfg.Focus.FollowMouseDelay = 0
431 ctx := context.Background()432 ctx := context.Background()
432 indicatorScene(t, c)433 indicatorScene(t, c)
433 focused, _ := c.cur().mon.Focused()434 focused, _ := c.cur().mon.Focused()
M internal/core/focusmouse.go +69 -6
@@ -1,12 +1,15 @@
11 package core
22
3-import "github.com/bnema/neferwl/internal/domain"
3+import (
4+ "context"
5+ "time"
46
5-// hoverEntry reports whether the pointer moving from (px, py) into id is a
6-// real entry that focus.follow-mouse turns into focus. A window that slid
7-// under a still cursor (layout change) is not: the previous point hit-tests
8-// to it in the current layout. Called only when the hit window changed.
9-func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
7+ "github.com/bnema/neferwl/internal/domain"
8+ "github.com/bnema/neferwl/internal/ports"
9+)
10+
11+// hoverEligible checks guards shared by entry and delayed focus.
12+func (c *Core) hoverEligible(id WindowID) bool {
1013 if !c.cfg.Focus.FollowMouse || id == 0 || c.synthetic || c.grab != 0 || len(c.buttons) != 0 ||
1114 c.constraint.Mode != domain.ConstraintNone || c.constrained.Mode != domain.ConstraintNone ||
1215 c.hint.phase != hintIdle || c.switching() || c.swipe != nil || c.gesture.on {
@@ -19,6 +22,17 @@ func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
1922 if f, _ := c.cur().mon.Focused(); c.keyboardFocus() != f {
2023 return false // a layer, grab or menu holds the keyboard
2124 }
25+ return true
26+}
27+
28+// hoverEntry reports whether the pointer moving from (px, py) into id is a
29+// real entry that focus.follow-mouse turns into focus. A window that slid
30+// under a still cursor (layout change) is not: the previous point hit-tests
31+// to it in the current layout. Called only when the hit window changed.
32+func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
33+ if !c.hoverEligible(id) {
34+ return false
35+ }
2236 if prev, _, _ := c.hit(px, py); prev == id {
2337 if c.hoverLocked {
2438 c.hoverLock = id
@@ -31,3 +45,52 @@ func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
3145 c.hoverLocked, c.hoverLock = false, 0
3246 return true
3347 }
48+
49+// pendingHover is owned by the core event loop; a nil channel disables it.
50+type pendingHover struct {
51+ target WindowID
52+ timer ports.Timer
53+ timerC <-chan time.Time
54+}
55+
56+func (c *Core) cancelHover() {
57+ if c.hover.timer != nil {
58+ c.hover.timer.Stop()
59+ }
60+ c.hover = pendingHover{}
61+}
62+
63+func (c *Core) startHover(ctx context.Context, id WindowID) error {
64+ c.cancelHover()
65+ if c.cfg.Focus.FollowMouseDelay == 0 {
66+ return c.applyHover(ctx, id)
67+ }
68+ timer := c.opts.Clock.NewTimer(c.cfg.Focus.FollowMouseDelay)
69+ c.hover = pendingHover{target: id, timer: timer, timerC: timer.C()}
70+ return nil
71+}
72+
73+func (c *Core) hoverTick(ctx context.Context) error {
74+ id := c.hover.target
75+ c.cancelHover()
76+ if c.pointer != id || !c.hoverEligible(id) || c.hoverLocked {
77+ return nil
78+ }
79+ // Surface input regions and overlays can change without re-hitting the
80+ // cached pointer target. Dwell only counts while the target still wins.
81+ if hit, _, _ := c.hit(c.cursorX, c.cursorY); hit != id {
82+ return nil
83+ }
84+ return c.applyHover(ctx, id)
85+}
86+
87+func (c *Core) applyHover(ctx context.Context, id WindowID) error {
88+ sent := c.keyboard.sent
89+ if err := c.focusPointer(ctx, id, true); err != nil {
90+ return err
91+ }
92+ if c.keyboard.sent != sent {
93+ return c.rehit(ctx)
94+ }
95+ return nil
96+}
@@ -1,12 +1,15 @@
1 package core1 package core
2 2
3-import "github.com/bnema/neferwl/internal/domain"3+import (
4+ "context"
5+ "time"
4 6
5-// hoverEntry reports whether the pointer moving from (px, py) into id is a7+ "github.com/bnema/neferwl/internal/domain"
6-// real entry that focus.follow-mouse turns into focus. A window that slid8+ "github.com/bnema/neferwl/internal/ports"
7-// under a still cursor (layout change) is not: the previous point hit-tests9+)
8-// to it in the current layout. Called only when the hit window changed.10+
9-func (c *Core) hoverEntry(id WindowID, px, py float64) bool {11+// hoverEligible checks guards shared by entry and delayed focus.
12+func (c *Core) hoverEligible(id WindowID) bool {
10 if !c.cfg.Focus.FollowMouse || id == 0 || c.synthetic || c.grab != 0 || len(c.buttons) != 0 ||13 if !c.cfg.Focus.FollowMouse || id == 0 || c.synthetic || c.grab != 0 || len(c.buttons) != 0 ||
11 c.constraint.Mode != domain.ConstraintNone || c.constrained.Mode != domain.ConstraintNone ||14 c.constraint.Mode != domain.ConstraintNone || c.constrained.Mode != domain.ConstraintNone ||
12 c.hint.phase != hintIdle || c.switching() || c.swipe != nil || c.gesture.on {15 c.hint.phase != hintIdle || c.switching() || c.swipe != nil || c.gesture.on {
@@ -19,6 +22,17 @@ func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
19 if f, _ := c.cur().mon.Focused(); c.keyboardFocus() != f {22 if f, _ := c.cur().mon.Focused(); c.keyboardFocus() != f {
20 return false // a layer, grab or menu holds the keyboard23 return false // a layer, grab or menu holds the keyboard
21 }24 }
25+ return true
26+}
27+
28+// hoverEntry reports whether the pointer moving from (px, py) into id is a
29+// real entry that focus.follow-mouse turns into focus. A window that slid
30+// under a still cursor (layout change) is not: the previous point hit-tests
31+// to it in the current layout. Called only when the hit window changed.
32+func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
33+ if !c.hoverEligible(id) {
34+ return false
35+ }
22 if prev, _, _ := c.hit(px, py); prev == id {36 if prev, _, _ := c.hit(px, py); prev == id {
23 if c.hoverLocked {37 if c.hoverLocked {
24 c.hoverLock = id38 c.hoverLock = id
@@ -31,3 +45,52 @@ func (c *Core) hoverEntry(id WindowID, px, py float64) bool {
31 c.hoverLocked, c.hoverLock = false, 045 c.hoverLocked, c.hoverLock = false, 0
32 return true46 return true
33 }47 }
48+
49+// pendingHover is owned by the core event loop; a nil channel disables it.
50+type pendingHover struct {
51+ target WindowID
52+ timer ports.Timer
53+ timerC <-chan time.Time
54+}
55+
56+func (c *Core) cancelHover() {
57+ if c.hover.timer != nil {
58+ c.hover.timer.Stop()
59+ }
60+ c.hover = pendingHover{}
61+}
62+
63+func (c *Core) startHover(ctx context.Context, id WindowID) error {
64+ c.cancelHover()
65+ if c.cfg.Focus.FollowMouseDelay == 0 {
66+ return c.applyHover(ctx, id)
67+ }
68+ timer := c.opts.Clock.NewTimer(c.cfg.Focus.FollowMouseDelay)
69+ c.hover = pendingHover{target: id, timer: timer, timerC: timer.C()}
70+ return nil
71+}
72+
73+func (c *Core) hoverTick(ctx context.Context) error {
74+ id := c.hover.target
75+ c.cancelHover()
76+ if c.pointer != id || !c.hoverEligible(id) || c.hoverLocked {
77+ return nil
78+ }
79+ // Surface input regions and overlays can change without re-hitting the
80+ // cached pointer target. Dwell only counts while the target still wins.
81+ if hit, _, _ := c.hit(c.cursorX, c.cursorY); hit != id {
82+ return nil
83+ }
84+ return c.applyHover(ctx, id)
85+}
86+
87+func (c *Core) applyHover(ctx context.Context, id WindowID) error {
88+ sent := c.keyboard.sent
89+ if err := c.focusPointer(ctx, id, true); err != nil {
90+ return err
91+ }
92+ if c.keyboard.sent != sent {
93+ return c.rehit(ctx)
94+ }
95+ return nil
96+}
M internal/core/focusmouse_alloc_test.go +1 -0
@@ -25,6 +25,7 @@ func TestHoverAllocations(t *testing.T) {
2525 }
2626 off := testing.AllocsPerRun(100, motion)
2727 c.cfg.Focus.FollowMouse = true
28+ c.cfg.Focus.FollowMouseDelay = 0
2829 on := testing.AllocsPerRun(100, motion)
2930 t.Logf("in-window motion: off=%g on=%g", off, on)
3031 if on != off {
@@ -25,6 +25,7 @@ func TestHoverAllocations(t *testing.T) {
25 }25 }
26 off := testing.AllocsPerRun(100, motion)26 off := testing.AllocsPerRun(100, motion)
27 c.cfg.Focus.FollowMouse = true27 c.cfg.Focus.FollowMouse = true
28+ c.cfg.Focus.FollowMouseDelay = 0
28 on := testing.AllocsPerRun(100, motion)29 on := testing.AllocsPerRun(100, motion)
29 t.Logf("in-window motion: off=%g on=%g", off, on)30 t.Logf("in-window motion: off=%g on=%g", off, on)
30 if on != off {31 if on != off {
M internal/core/focusmouse_test.go +229 -0
@@ -47,6 +47,7 @@ func TestHoverFocusMotion(t *testing.T) {
4747 }
4848 c.cfg.Animations.On = false
4949 c.cfg.Focus.FollowMouse = on
50+ c.cfg.Focus.FollowMouseDelay = 0
5051 indicatorScene(t, c)
5152 x, y := hoverPoint(t, c, 3)
5253 if err := c.pointerMotion(context.Background(), ports.PointerMotion{X: x, Y: y}); err != nil {
@@ -94,6 +95,7 @@ func TestHoverEntryGuardsAndHold(t *testing.T) {
9495 c, _ := flashCore(t)
9596 c.cfg.Animations.On = false
9697 c.cfg.Focus.FollowMouse = true
98+ c.cfg.Focus.FollowMouseDelay = 0
9799 indicatorScene(t, c)
98100 x, y := hoverPoint(t, c, 3)
99101 for _, guard := range []string{"button", "grab", "synthetic", "overview"} {
@@ -148,6 +150,7 @@ func TestHoverKeyboardHoldMotion(t *testing.T) {
148150 }
149151 c.cfg.Animations.On = false
150152 c.cfg.Focus.FollowMouse = true
153+ c.cfg.Focus.FollowMouseDelay = 0
151154 indicatorScene(t, c)
152155 x, y := hoverPoint(t, c, 3)
153156 ctx := context.Background()
@@ -182,6 +185,7 @@ func TestHoverOtherOutput(t *testing.T) {
182185 c, clock := flashCore(t)
183186 c.cfg.Animations.On = false
184187 c.cfg.Focus.FollowMouse = true
188+ c.cfg.Focus.FollowMouseDelay = 0
185189 c.addScreen(domain.OutputInfo{Name: "B", Width: 300, Height: 200})
186190 b := c.screens[1]
187191 c.windows.mapped(ports.WindowMapped{ID: 4}, clock.now)
@@ -219,6 +223,7 @@ func hoverEventCore(t *testing.T, n int) (*Core, *indicatorClock, chan ports.Cli
219223 cmds := make(chan ports.ClientCommand, 256)
220224 c, clock := indicatorCoreWith(t, cmds)
221225 c.cfg.Focus.FollowMouse = true
226+ c.cfg.Focus.FollowMouseDelay = 0
222227 c.cfg.Layout.Overflow = "scroll"
223228 c.settings(c.cur().mon)
224229 for id := WindowID(1); id <= WindowID(n); id++ {
@@ -448,6 +453,7 @@ func TestHoverShownStash(t *testing.T) {
448453 synctest.Test(t, func(t *testing.T) {
449454 c, _, _, cmds := stashRig(t, false)
450455 c.cfg.Focus.FollowMouse = true
456+ c.cfg.Focus.FollowMouseDelay = 0
451457 indicatorScene(t, c)
452458 w := c.cur().mon.Current()
453459 if !w.StashShown() {
@@ -492,3 +498,226 @@ func TestHoverShownStash(t *testing.T) {
492498 }
493499 })
494500 }
501+
502+func TestHoverDwell(t *testing.T) {
503+ for _, mode := range []string{"dwell", "pass through", "button", "keyboard", "overview", "disabled"} {
504+ t.Run(mode, func(t *testing.T) {
505+ synctest.Test(t, func(t *testing.T) {
506+ c, _, cmds := hoverEventCore(t, 3)
507+ x, y := hoverPoint(t, c, 3)
508+ hoverMove(t, c, x, y)
509+ drainHoverFocus(cmds)
510+ c.opts.Clock = testClock(t)
511+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
512+ x, y = hoverPoint(t, c, 2)
513+ hoverMove(t, c, x, y)
514+ if c.hover.target != 2 {
515+ t.Fatal("hover not armed")
516+ }
517+ time.Sleep(149 * time.Millisecond)
518+ select {
519+ case <-c.hover.timerC:
520+ t.Fatal("early timer")
521+ default:
522+ }
523+ hoverWantFocus(t, c, 3)
524+ hoverNoFocusCommand(t, cmds)
525+ switch mode {
526+ case "pass through":
527+ x, y = hoverPoint(t, c, 3)
528+ hoverMove(t, c, x, y)
529+ time.Sleep(time.Millisecond)
530+ select {
531+ case <-c.hover.timerC:
532+ t.Fatal("new target inherited old deadline")
533+ default:
534+ }
535+ hoverNoFocusCommand(t, cmds)
536+ time.Sleep(149 * time.Millisecond)
537+ case "button":
538+ if err := c.pointerButton(context.Background(), ports.PointerButton{Button: btnLeft, Pressed: true}); err != nil {
539+ t.Fatal(err)
540+ }
541+ if c.hover.timerC != nil {
542+ t.Fatal("button did not cancel")
543+ }
544+ drainHoverFocus(cmds) // Click itself may focus; the hover must not do so later.
545+ time.Sleep(time.Millisecond)
546+ hoverNoFocusCommand(t, cmds)
547+ return
548+ case "keyboard":
549+ if err := c.syncFocus(context.Background(), 1); err != nil {
550+ t.Fatal(err)
551+ }
552+ if c.hover.timerC != nil {
553+ t.Fatal("keyboard did not cancel")
554+ }
555+ return
556+ case "overview":
557+ hoverBind(t, c, ActionToggleOverview)
558+ time.Sleep(time.Millisecond)
559+ case "disabled":
560+ c.cfg.Focus.FollowMouse = false
561+ time.Sleep(time.Millisecond)
562+ default:
563+ time.Sleep(time.Millisecond)
564+ }
565+ <-c.hover.timerC
566+ if err := c.hoverTick(context.Background()); err != nil {
567+ t.Fatal(err)
568+ }
569+ want := WindowID(2)
570+ if mode == "pass through" {
571+ want = 3
572+ }
573+ if mode == "overview" || mode == "disabled" {
574+ hoverNoFocusCommand(t, cmds)
575+ return
576+ }
577+ hoverWantFocus(t, c, want)
578+ ids := drainHoverFocus(cmds)
579+ if mode == "pass through" && len(ids) == 0 {
580+ return // Returning to the focused window sends no redundant focus.
581+ }
582+ if len(ids) != 1 || ids[0] != want {
583+ t.Fatalf("focus commands %v want %d", ids, want)
584+ }
585+ })
586+ })
587+ }
588+}
589+
590+func TestHoverStashBriefDwell(t *testing.T) {
591+ synctest.Test(t, func(t *testing.T) {
592+ c, _, _, cmds := stashRig(t, false)
593+ c.cfg.Focus.FollowMouse = true
594+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
595+ c.opts.Clock = testClock(t)
596+ indicatorScene(t, c)
597+ point := func(id WindowID) (float64, float64) {
598+ for y := 5; y < 200; y += 5 {
599+ for x := 5; x < 300; x += 5 {
600+ if hit, _, _ := c.hit(float64(x), float64(y)); hit == id {
601+ return float64(x), float64(y)
602+ }
603+ }
604+ }
605+ t.Fatalf("no exposed pixels for %d", id)
606+ return 0, 0
607+ }
608+ x, y := point(2)
609+ hoverMove(t, c, x, y)
610+ drainHoverFocus(cmds)
611+ x, y = point(3)
612+ hoverMove(t, c, x, y)
613+ if c.hover.target != 3 {
614+ t.Fatal("neighbour hover not armed")
615+ }
616+ time.Sleep(50 * time.Millisecond)
617+ hoverWantFocus(t, c, 2)
618+ hoverNoFocusCommand(t, cmds)
619+ x, y = point(2)
620+ hoverMove(t, c, x, y)
621+ time.Sleep(150 * time.Millisecond)
622+ if c.hover.timerC != nil {
623+ <-c.hover.timerC
624+ if err := c.hoverTick(context.Background()); err != nil {
625+ t.Fatal(err)
626+ }
627+ }
628+ hoverWantFocus(t, c, 2)
629+ hoverNoFocusCommand(t, cmds)
630+ if !c.cur().mon.Current().StashShown() {
631+ t.Fatal("hover hid stash")
632+ }
633+ })
634+}
635+
636+func TestHoverDwellInputRegionChanged(t *testing.T) {
637+ synctest.Test(t, func(t *testing.T) {
638+ c, _, cmds := hoverEventCore(t, 3)
639+ x, y := hoverPoint(t, c, 3)
640+ hoverMove(t, c, x, y)
641+ drainHoverFocus(cmds)
642+ c.opts.Clock = testClock(t)
643+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
644+ x, y = hoverPoint(t, c, 2)
645+ hoverMove(t, c, x, y)
646+ if c.hover.target != 2 {
647+ t.Fatal("hover not armed")
648+ }
649+ c.clientEvent(context.Background(), ports.InputRegionChanged{ID: 2})
650+ if c.pointer != 2 {
651+ t.Fatal("test requires stale cached pointer")
652+ }
653+ if hit, _, _ := c.hit(c.cursorX, c.cursorY); hit == 2 {
654+ t.Fatal("input region still hits target")
655+ }
656+ time.Sleep(150 * time.Millisecond)
657+ <-c.hover.timerC
658+ if err := c.hoverTick(context.Background()); err != nil {
659+ t.Fatal(err)
660+ }
661+ hoverWantFocus(t, c, 3)
662+ hoverNoFocusCommand(t, cmds)
663+ })
664+}
665+
666+func TestHoverDwellConfigReload(t *testing.T) {
667+ for _, mode := range []string{"delay", "disable-enable", "unchanged", "invalid"} {
668+ t.Run(mode, func(t *testing.T) {
669+ synctest.Test(t, func(t *testing.T) {
670+ c, _, cmds := hoverEventCore(t, 3)
671+ x, y := hoverPoint(t, c, 3)
672+ hoverMove(t, c, x, y)
673+ drainHoverFocus(cmds)
674+ c.opts.Clock = testClock(t)
675+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
676+ x, y = hoverPoint(t, c, 2)
677+ hoverMove(t, c, x, y)
678+ if c.hover.target != 2 {
679+ t.Fatal("hover not armed")
680+ }
681+ time.Sleep(50 * time.Millisecond)
682+ cfg := c.cfg
683+ switch mode {
684+ case "delay":
685+ cfg.Focus.FollowMouseDelay = 300 * time.Millisecond
686+ case "disable-enable":
687+ cfg.Focus.FollowMouse = false
688+ case "invalid":
689+ cfg.Focus.FollowMouseDelay = 300 * time.Millisecond
690+ cfg.Layout.MaxColumns = 0
691+ }
692+ err := c.apply(cfg)
693+ if mode == "invalid" {
694+ if err == nil {
695+ t.Fatal("invalid reload succeeded")
696+ }
697+ } else if err != nil {
698+ t.Fatal(err)
699+ }
700+ if mode == "disable-enable" {
701+ cfg.Focus.FollowMouse = true
702+ if err := c.apply(cfg); err != nil {
703+ t.Fatal(err)
704+ }
705+ }
706+ time.Sleep(100 * time.Millisecond)
707+ if mode == "delay" || mode == "disable-enable" {
708+ if c.hover.timerC != nil || c.hover.target != 0 {
709+ t.Fatal("reload retained pending hover")
710+ }
711+ hoverWantFocus(t, c, 3)
712+ hoverNoFocusCommand(t, cmds)
713+ return
714+ }
715+ <-c.hover.timerC
716+ if err := c.hoverTick(context.Background()); err != nil {
717+ t.Fatal(err)
718+ }
719+ hoverWantFocus(t, c, 2)
720+ })
721+ })
722+ }
723+}
@@ -47,6 +47,7 @@ func TestHoverFocusMotion(t *testing.T) {
47 }47 }
48 c.cfg.Animations.On = false48 c.cfg.Animations.On = false
49 c.cfg.Focus.FollowMouse = on49 c.cfg.Focus.FollowMouse = on
50+ c.cfg.Focus.FollowMouseDelay = 0
50 indicatorScene(t, c)51 indicatorScene(t, c)
51 x, y := hoverPoint(t, c, 3)52 x, y := hoverPoint(t, c, 3)
52 if err := c.pointerMotion(context.Background(), ports.PointerMotion{X: x, Y: y}); err != nil {53 if err := c.pointerMotion(context.Background(), ports.PointerMotion{X: x, Y: y}); err != nil {
@@ -94,6 +95,7 @@ func TestHoverEntryGuardsAndHold(t *testing.T) {
94 c, _ := flashCore(t)95 c, _ := flashCore(t)
95 c.cfg.Animations.On = false96 c.cfg.Animations.On = false
96 c.cfg.Focus.FollowMouse = true97 c.cfg.Focus.FollowMouse = true
98+ c.cfg.Focus.FollowMouseDelay = 0
97 indicatorScene(t, c)99 indicatorScene(t, c)
98 x, y := hoverPoint(t, c, 3)100 x, y := hoverPoint(t, c, 3)
99 for _, guard := range []string{"button", "grab", "synthetic", "overview"} {101 for _, guard := range []string{"button", "grab", "synthetic", "overview"} {
@@ -148,6 +150,7 @@ func TestHoverKeyboardHoldMotion(t *testing.T) {
148 }150 }
149 c.cfg.Animations.On = false151 c.cfg.Animations.On = false
150 c.cfg.Focus.FollowMouse = true152 c.cfg.Focus.FollowMouse = true
153+ c.cfg.Focus.FollowMouseDelay = 0
151 indicatorScene(t, c)154 indicatorScene(t, c)
152 x, y := hoverPoint(t, c, 3)155 x, y := hoverPoint(t, c, 3)
153 ctx := context.Background()156 ctx := context.Background()
@@ -182,6 +185,7 @@ func TestHoverOtherOutput(t *testing.T) {
182 c, clock := flashCore(t)185 c, clock := flashCore(t)
183 c.cfg.Animations.On = false186 c.cfg.Animations.On = false
184 c.cfg.Focus.FollowMouse = true187 c.cfg.Focus.FollowMouse = true
188+ c.cfg.Focus.FollowMouseDelay = 0
185 c.addScreen(domain.OutputInfo{Name: "B", Width: 300, Height: 200})189 c.addScreen(domain.OutputInfo{Name: "B", Width: 300, Height: 200})
186 b := c.screens[1]190 b := c.screens[1]
187 c.windows.mapped(ports.WindowMapped{ID: 4}, clock.now)191 c.windows.mapped(ports.WindowMapped{ID: 4}, clock.now)
@@ -219,6 +223,7 @@ func hoverEventCore(t *testing.T, n int) (*Core, *indicatorClock, chan ports.Cli
219 cmds := make(chan ports.ClientCommand, 256)223 cmds := make(chan ports.ClientCommand, 256)
220 c, clock := indicatorCoreWith(t, cmds)224 c, clock := indicatorCoreWith(t, cmds)
221 c.cfg.Focus.FollowMouse = true225 c.cfg.Focus.FollowMouse = true
226+ c.cfg.Focus.FollowMouseDelay = 0
222 c.cfg.Layout.Overflow = "scroll"227 c.cfg.Layout.Overflow = "scroll"
223 c.settings(c.cur().mon)228 c.settings(c.cur().mon)
224 for id := WindowID(1); id <= WindowID(n); id++ {229 for id := WindowID(1); id <= WindowID(n); id++ {
@@ -448,6 +453,7 @@ func TestHoverShownStash(t *testing.T) {
448 synctest.Test(t, func(t *testing.T) {453 synctest.Test(t, func(t *testing.T) {
449 c, _, _, cmds := stashRig(t, false)454 c, _, _, cmds := stashRig(t, false)
450 c.cfg.Focus.FollowMouse = true455 c.cfg.Focus.FollowMouse = true
456+ c.cfg.Focus.FollowMouseDelay = 0
451 indicatorScene(t, c)457 indicatorScene(t, c)
452 w := c.cur().mon.Current()458 w := c.cur().mon.Current()
453 if !w.StashShown() {459 if !w.StashShown() {
@@ -492,3 +498,226 @@ func TestHoverShownStash(t *testing.T) {
492 }498 }
493 })499 })
494 }500 }
501+
502+func TestHoverDwell(t *testing.T) {
503+ for _, mode := range []string{"dwell", "pass through", "button", "keyboard", "overview", "disabled"} {
504+ t.Run(mode, func(t *testing.T) {
505+ synctest.Test(t, func(t *testing.T) {
506+ c, _, cmds := hoverEventCore(t, 3)
507+ x, y := hoverPoint(t, c, 3)
508+ hoverMove(t, c, x, y)
509+ drainHoverFocus(cmds)
510+ c.opts.Clock = testClock(t)
511+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
512+ x, y = hoverPoint(t, c, 2)
513+ hoverMove(t, c, x, y)
514+ if c.hover.target != 2 {
515+ t.Fatal("hover not armed")
516+ }
517+ time.Sleep(149 * time.Millisecond)
518+ select {
519+ case <-c.hover.timerC:
520+ t.Fatal("early timer")
521+ default:
522+ }
523+ hoverWantFocus(t, c, 3)
524+ hoverNoFocusCommand(t, cmds)
525+ switch mode {
526+ case "pass through":
527+ x, y = hoverPoint(t, c, 3)
528+ hoverMove(t, c, x, y)
529+ time.Sleep(time.Millisecond)
530+ select {
531+ case <-c.hover.timerC:
532+ t.Fatal("new target inherited old deadline")
533+ default:
534+ }
535+ hoverNoFocusCommand(t, cmds)
536+ time.Sleep(149 * time.Millisecond)
537+ case "button":
538+ if err := c.pointerButton(context.Background(), ports.PointerButton{Button: btnLeft, Pressed: true}); err != nil {
539+ t.Fatal(err)
540+ }
541+ if c.hover.timerC != nil {
542+ t.Fatal("button did not cancel")
543+ }
544+ drainHoverFocus(cmds) // Click itself may focus; the hover must not do so later.
545+ time.Sleep(time.Millisecond)
546+ hoverNoFocusCommand(t, cmds)
547+ return
548+ case "keyboard":
549+ if err := c.syncFocus(context.Background(), 1); err != nil {
550+ t.Fatal(err)
551+ }
552+ if c.hover.timerC != nil {
553+ t.Fatal("keyboard did not cancel")
554+ }
555+ return
556+ case "overview":
557+ hoverBind(t, c, ActionToggleOverview)
558+ time.Sleep(time.Millisecond)
559+ case "disabled":
560+ c.cfg.Focus.FollowMouse = false
561+ time.Sleep(time.Millisecond)
562+ default:
563+ time.Sleep(time.Millisecond)
564+ }
565+ <-c.hover.timerC
566+ if err := c.hoverTick(context.Background()); err != nil {
567+ t.Fatal(err)
568+ }
569+ want := WindowID(2)
570+ if mode == "pass through" {
571+ want = 3
572+ }
573+ if mode == "overview" || mode == "disabled" {
574+ hoverNoFocusCommand(t, cmds)
575+ return
576+ }
577+ hoverWantFocus(t, c, want)
578+ ids := drainHoverFocus(cmds)
579+ if mode == "pass through" && len(ids) == 0 {
580+ return // Returning to the focused window sends no redundant focus.
581+ }
582+ if len(ids) != 1 || ids[0] != want {
583+ t.Fatalf("focus commands %v want %d", ids, want)
584+ }
585+ })
586+ })
587+ }
588+}
589+
590+func TestHoverStashBriefDwell(t *testing.T) {
591+ synctest.Test(t, func(t *testing.T) {
592+ c, _, _, cmds := stashRig(t, false)
593+ c.cfg.Focus.FollowMouse = true
594+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
595+ c.opts.Clock = testClock(t)
596+ indicatorScene(t, c)
597+ point := func(id WindowID) (float64, float64) {
598+ for y := 5; y < 200; y += 5 {
599+ for x := 5; x < 300; x += 5 {
600+ if hit, _, _ := c.hit(float64(x), float64(y)); hit == id {
601+ return float64(x), float64(y)
602+ }
603+ }
604+ }
605+ t.Fatalf("no exposed pixels for %d", id)
606+ return 0, 0
607+ }
608+ x, y := point(2)
609+ hoverMove(t, c, x, y)
610+ drainHoverFocus(cmds)
611+ x, y = point(3)
612+ hoverMove(t, c, x, y)
613+ if c.hover.target != 3 {
614+ t.Fatal("neighbour hover not armed")
615+ }
616+ time.Sleep(50 * time.Millisecond)
617+ hoverWantFocus(t, c, 2)
618+ hoverNoFocusCommand(t, cmds)
619+ x, y = point(2)
620+ hoverMove(t, c, x, y)
621+ time.Sleep(150 * time.Millisecond)
622+ if c.hover.timerC != nil {
623+ <-c.hover.timerC
624+ if err := c.hoverTick(context.Background()); err != nil {
625+ t.Fatal(err)
626+ }
627+ }
628+ hoverWantFocus(t, c, 2)
629+ hoverNoFocusCommand(t, cmds)
630+ if !c.cur().mon.Current().StashShown() {
631+ t.Fatal("hover hid stash")
632+ }
633+ })
634+}
635+
636+func TestHoverDwellInputRegionChanged(t *testing.T) {
637+ synctest.Test(t, func(t *testing.T) {
638+ c, _, cmds := hoverEventCore(t, 3)
639+ x, y := hoverPoint(t, c, 3)
640+ hoverMove(t, c, x, y)
641+ drainHoverFocus(cmds)
642+ c.opts.Clock = testClock(t)
643+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
644+ x, y = hoverPoint(t, c, 2)
645+ hoverMove(t, c, x, y)
646+ if c.hover.target != 2 {
647+ t.Fatal("hover not armed")
648+ }
649+ c.clientEvent(context.Background(), ports.InputRegionChanged{ID: 2})
650+ if c.pointer != 2 {
651+ t.Fatal("test requires stale cached pointer")
652+ }
653+ if hit, _, _ := c.hit(c.cursorX, c.cursorY); hit == 2 {
654+ t.Fatal("input region still hits target")
655+ }
656+ time.Sleep(150 * time.Millisecond)
657+ <-c.hover.timerC
658+ if err := c.hoverTick(context.Background()); err != nil {
659+ t.Fatal(err)
660+ }
661+ hoverWantFocus(t, c, 3)
662+ hoverNoFocusCommand(t, cmds)
663+ })
664+}
665+
666+func TestHoverDwellConfigReload(t *testing.T) {
667+ for _, mode := range []string{"delay", "disable-enable", "unchanged", "invalid"} {
668+ t.Run(mode, func(t *testing.T) {
669+ synctest.Test(t, func(t *testing.T) {
670+ c, _, cmds := hoverEventCore(t, 3)
671+ x, y := hoverPoint(t, c, 3)
672+ hoverMove(t, c, x, y)
673+ drainHoverFocus(cmds)
674+ c.opts.Clock = testClock(t)
675+ c.cfg.Focus.FollowMouseDelay = 150 * time.Millisecond
676+ x, y = hoverPoint(t, c, 2)
677+ hoverMove(t, c, x, y)
678+ if c.hover.target != 2 {
679+ t.Fatal("hover not armed")
680+ }
681+ time.Sleep(50 * time.Millisecond)
682+ cfg := c.cfg
683+ switch mode {
684+ case "delay":
685+ cfg.Focus.FollowMouseDelay = 300 * time.Millisecond
686+ case "disable-enable":
687+ cfg.Focus.FollowMouse = false
688+ case "invalid":
689+ cfg.Focus.FollowMouseDelay = 300 * time.Millisecond
690+ cfg.Layout.MaxColumns = 0
691+ }
692+ err := c.apply(cfg)
693+ if mode == "invalid" {
694+ if err == nil {
695+ t.Fatal("invalid reload succeeded")
696+ }
697+ } else if err != nil {
698+ t.Fatal(err)
699+ }
700+ if mode == "disable-enable" {
701+ cfg.Focus.FollowMouse = true
702+ if err := c.apply(cfg); err != nil {
703+ t.Fatal(err)
704+ }
705+ }
706+ time.Sleep(100 * time.Millisecond)
707+ if mode == "delay" || mode == "disable-enable" {
708+ if c.hover.timerC != nil || c.hover.target != 0 {
709+ t.Fatal("reload retained pending hover")
710+ }
711+ hoverWantFocus(t, c, 3)
712+ hoverNoFocusCommand(t, cmds)
713+ return
714+ }
715+ <-c.hover.timerC
716+ if err := c.hoverTick(context.Background()); err != nil {
717+ t.Fatal(err)
718+ }
719+ hoverWantFocus(t, c, 2)
720+ })
721+ })
722+ }
723+}
M internal/core/input.go +5 -7
@@ -145,6 +145,7 @@ func (c *Core) pointerMotion(ctx context.Context, v ports.PointerMotion) error {
145145 // Most layout changes re-hit-test only on motion; stash visibility
146146 // changes also re-hit after publishing to update pointer modality.
147147 if id != c.pointer {
148+ c.cancelHover()
148149 entered = c.hoverEntry(id, px, py)
149150 c.pointer = id
150151 if err := c.pointerFocus(ctx, ports.PointerFocus{ID: id, X: x, Y: y}); err != nil {
@@ -158,13 +159,7 @@ func (c *Core) pointerMotion(ctx context.Context, v ports.PointerMotion) error {
158159 }
159160 }
160161 if entered {
161- sent := c.keyboard.sent
162- if err := c.focusPointer(ctx, id, true); err != nil {
163- return err
164- }
165- if c.keyboard.sent != sent {
166- return c.rehit(ctx)
167- }
162+ return c.startHover(ctx, id)
168163 }
169164 return nil
170165 }
@@ -199,6 +194,9 @@ func (c *Core) focusClick(s *screen, w *Workspace, id WindowID, flash bool) {
199194 }
200195
201196 func (c *Core) pointerButton(ctx context.Context, v ports.PointerButton) error {
197+ if v.Pressed {
198+ c.cancelHover()
199+ }
202200 // Buttons a drag took stay in c.buttons until released, so the
203201 // security gate admits their release; no client sees it.
204202 if !v.Pressed && c.swallow[v.Button] {
@@ -145,6 +145,7 @@ func (c *Core) pointerMotion(ctx context.Context, v ports.PointerMotion) error {
145 // Most layout changes re-hit-test only on motion; stash visibility145 // Most layout changes re-hit-test only on motion; stash visibility
146 // changes also re-hit after publishing to update pointer modality.146 // changes also re-hit after publishing to update pointer modality.
147 if id != c.pointer {147 if id != c.pointer {
148+ c.cancelHover()
148 entered = c.hoverEntry(id, px, py)149 entered = c.hoverEntry(id, px, py)
149 c.pointer = id150 c.pointer = id
150 if err := c.pointerFocus(ctx, ports.PointerFocus{ID: id, X: x, Y: y}); err != nil {151 if err := c.pointerFocus(ctx, ports.PointerFocus{ID: id, X: x, Y: y}); err != nil {
@@ -158,13 +159,7 @@ func (c *Core) pointerMotion(ctx context.Context, v ports.PointerMotion) error {
158 }159 }
159 }160 }
160 if entered {161 if entered {
161- sent := c.keyboard.sent162+ return c.startHover(ctx, id)
162- if err := c.focusPointer(ctx, id, true); err != nil {
163- return err
164- }
165- if c.keyboard.sent != sent {
166- return c.rehit(ctx)
167- }
168 }163 }
169 return nil164 return nil
170 }165 }
@@ -199,6 +194,9 @@ func (c *Core) focusClick(s *screen, w *Workspace, id WindowID, flash bool) {
199 }194 }
200 195
201 func (c *Core) pointerButton(ctx context.Context, v ports.PointerButton) error {196 func (c *Core) pointerButton(ctx context.Context, v ports.PointerButton) error {
197+ if v.Pressed {
198+ c.cancelHover()
199+ }
202 // Buttons a drag took stay in c.buttons until released, so the200 // Buttons a drag took stay in c.buttons until released, so the
203 // security gate admits their release; no client sees it.201 // security gate admits their release; no client sees it.
204 if !v.Pressed && c.swallow[v.Button] {202 if !v.Pressed && c.swallow[v.Button] {
M internal/domain/config.go +2 -1
@@ -172,7 +172,8 @@ type Config struct {
172172 FollowMove bool
173173 // FollowMouse focuses the window the pointer moves into; keyboard
174174 // focus changes hold until the pointer enters another window.
175- FollowMouse bool
175+ FollowMouse bool
176+ FollowMouseDelay time.Duration
176177 // Flash briefly draws an inner border on the entity an action changed
177178 // (window or column). FlashWidth is in logical pixels (1 to 8),
178179 // FlashOpacity the starting opacity (0.1 to 1), FlashDuration the fade
@@ -172,7 +172,8 @@ type Config struct {
172 FollowMove bool172 FollowMove bool
173 // FollowMouse focuses the window the pointer moves into; keyboard173 // FollowMouse focuses the window the pointer moves into; keyboard
174 // focus changes hold until the pointer enters another window.174 // focus changes hold until the pointer enters another window.
175- FollowMouse bool175+ FollowMouse bool
176+ FollowMouseDelay time.Duration
176 // Flash briefly draws an inner border on the entity an action changed177 // Flash briefly draws an inner border on the entity an action changed
177 // (window or column). FlashWidth is in logical pixels (1 to 8),178 // (window or column). FlashWidth is in logical pixels (1 to 8),
178 // FlashOpacity the starting opacity (0.1 to 1), FlashDuration the fade179 // FlashOpacity the starting opacity (0.1 to 1), FlashDuration the fade

Comments00 unresolved

    no comments yet.

    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. On pages with a side panel: into the 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; in a file, click a line number to select it, shift-click for a range
    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
    l
    merge request: the list of files (j k move, enter opens, esc back)
    M
    merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
    R
    merge request: mark the head read
    esc
    close a dialog, leave a field

    Branches 33

    Tags 15

    ↑↓ moveenter openesc close