1package core
2
3import (
4 "math"
5 "slices"
6 "time"
7
8 "github.com/bnema/neferwl/internal/ports"
9)
10
11// A three-finger swipe follows the fingers: sideways it scrolls the columns,
12// up or down it slides between workspaces. Each swipe moves one step at
13// most (snapswipe.go): the next column edge or the next workspace. When
14// the fingers lift, a quick swipe goes on to that step, a slow one settles
15// on the closest, and a spring takes the view there (motion.go). Sideways
16// over the shown stash the swipe slides the stash the same way, one window
17// at most. Where the view cannot slide (fixed overflow, a float, a
18// fullscreen window), the swipe runs one focus action instead.
19// In the overview, three fingers use distance-based selection during movement.
20
21const (
22 // swipeDecide is the touchpad distance before the swipe picks its axis
23 // (GNOME Shell's threshold).
24 swipeDecide = 16.0
25 // viewSwipeMovement is the touchpad distance that scrolls the columns by
26 // one usable width.
27 viewSwipeMovement = 1200.0
28 // workspaceSwipeMovement is the touchpad distance that slides one
29 // workspace.
30 workspaceSwipeMovement = 300.0
31 // stashSwipeMovement is the touchpad distance that slides the stash by
32 // one window.
33 stashSwipeMovement = 300.0
34)
35
36type swipeMode uint8
37
38const (
39 swipeUndecided swipeMode = iota
40 swipeColumns
41 swipeWorkspaces
42 swipeDiscrete
43 // swipeNavigation navigates overview cards during a three-finger gesture.
44 swipeNavigation
45 // swipeOverview is a vertical four-finger swipe: up opens the
46 // overview, down closes it on the selection (niri's gesture). With
47 // the overview closed, down shows or hides the stash, and up hides
48 // it when it is shown, else opens the overview.
49 swipeOverview
50 // swipeStash is a sideways swipe over the shown stash: its view
51 // follows the fingers, with a stop on each window, and lands on a
52 // neighbor of the selection at most.
53 swipeStash
54 // swipeDropped ignores the rest of a swipe whose workspace changed.
55 swipeDropped
56)
57
58// swipeGesture is the swipe in progress, on the screen focused when it began.
59type swipeGesture struct {
60 screen *screen
61 fingers int
62 mode swipeMode
63 horizontal bool
64 cx, cy float64
65 // snap follows the movement along the chosen axis, natural scroll
66 // applied: positive scrolls right or down. Its view is absolute: the
67 // columns' x in pixels or the monitor's fractional workspace index,
68 // so a focus change during the swipe does not move the fingers' view.
69 // A discrete or overview swipe counts steps of -1, 0 or 1.
70 snap snapSwipe
71 // ws is the workspace whose columns scroll, or the active one when a
72 // workspace slide began.
73 ws *Workspace
74 // points are ws's column snap points when a column swipe began: the
75 // swipe ends if the layout no longer has them.
76 points []float64
77 // list is the numbered workspaces when a workspace slide began: the
78 // slide indexes it, so it ends if the list changes.
79 list []*Workspace
80 // ids and home are the stash windows and the selection when a stash
81 // swipe began: it ends if either changes.
82 ids []WindowID
83 home int
84 // opens is the monitor's overviewOpens when the swipe picked its
85 // mode: a slide the overview opened over is dropped, even once the
86 // overview closed again.
87 opens int
88}
89
90// listChanged reports whether the numbered workspaces or the active one
91// changed since a workspace slide began, or the overview opened over it.
92func (g *swipeGesture) listChanged(m *Monitor) bool {
93 return m.overviewOpens != g.opens || m.shown != nil || m.Workspaces[m.Active] != g.ws || g.horizontal != (g.ws.policy().workspace == horizontalAxis) || !slices.Equal(m.Workspaces, g.list)
94}
95
96// columnsChanged reports whether a column swipe lost its workspace: it is
97// no longer shown or slidable, its snap points moved (an output resize, a
98// panel, a window mapped or resized, other gaps), or the overview opened
99// over it.
100func (g *swipeGesture) columnsChanged(m *Monitor) bool {
101 if m.overviewOpens != g.opens || m.Current() != g.ws || !g.ws.slidable() || g.horizontal != (g.ws.policy().content == horizontalAxis) {
102 return true
103 }
104 if g.ws.policy().wraps {
105 n, spacing := g.ws.cascadeBands()
106 if len(g.points) != n {
107 return true
108 }
109 for i, p := range g.points {
110 if p != float64(i*spacing) {
111 return true
112 }
113 }
114 return false
115 }
116 return !slices.Equal(g.ws.snapPoints(), g.points)
117}
118
119// stashChanged reports whether a stash swipe lost its stash: it is no
120// longer shown or focused, its windows or selection changed, or the
121// overview opened over it.
122func (g *swipeGesture) stashChanged(m *Monitor) bool {
123 w := g.ws
124 return m.overviewOpens != g.opens || m.Current() != w || !w.stashFocused() || w.floatFocus || !w.stashShown() || w.stashAt != g.home ||
125 !slices.EqualFunc(w.Stash, g.ids, func(f Float, id WindowID) bool { return f.ID == id })
126}
127
128// swipeSign turns finger movement into view movement: natural scroll moves
129// the content with the fingers.
130func (c *Core) swipeSign() float64 {
131 if c.cfg.Touchpad.NaturalScroll {
132 return -1
133 }
134 return 1
135}
136
137// swipeBegin starts a swipe. Input streams one swipe at a time; one still
138// running (its end was lost) ends cancelled first: its slide settles back.
139func (c *Core) swipeBegin(b ports.SwipeBegin) bool {
140 changed := false
141 if c.switching() {
142 c.cancelSwitcher()
143 changed = true
144 }
145 if c.swipe != nil {
146 c.swipeEnd(ports.SwipeEnd{Cancelled: true, Time: b.Time})
147 changed = true
148 }
149 c.swipe = &swipeGesture{screen: c.cur(), fingers: b.Fingers}
150 if b.Fingers == 3 && c.cur().mon.ov.open && !c.overviewKeyboardTaken() {
151 c.scrollStop(ports.PointerAxis{Horizontal: ports.ScrollAxis{Stop: true}})
152 c.swipe.mode = swipeNavigation
153 }
154 return changed
155}
156
157// swipeUpdate moves the swipe; it reports whether the scene changed.
158func (c *Core) swipeUpdate(u ports.SwipeUpdate) bool {
159 g := c.swipe
160 if g == nil {
161 return false
162 }
163 if !c.hasScreen(g.screen) {
164 // Its screen went: let go of what it moved, or that stays shifted.
165 c.dropSwipe()
166 c.swipe = nil
167 return false
168 }
169 if g.mode == swipeNavigation {
170 m := g.screen.mon
171 if !m.ov.open || c.cur() != g.screen || c.overviewKeyboardTaken() {
172 g.mode = swipeDropped
173 return false
174 }
175 now := c.now()
176 shots := c.snapshot(now)
177 changed := m.overviewScroll(ports.PointerAxis{Source: ports.AxisFinger,
178 Horizontal: ports.ScrollAxis{Set: true, Value: u.DX * c.swipeSign()},
179 Vertical: ports.ScrollAxis{Set: true, Value: u.DY * c.swipeSign()}})
180 if changed {
181 c.keyboard.takeBack()
182 c.transition(shots, now)
183 }
184 return changed
185 }
186 if g.mode == swipeUndecided {
187 g.cx += u.DX
188 g.cy += u.DY
189 if g.cx*g.cx+g.cy*g.cy < swipeDecide*swipeDecide {
190 return false
191 }
192 c.decide(g)
193 }
194 d := u.DY
195 if g.horizontal {
196 d = u.DX
197 }
198 if g.mode == swipeOverview {
199 // Like niri, the overview gesture ignores natural scroll: the
200 // fingers going up open it.
201 g.snap.push(d, u.Time)
202 return false
203 }
204 g.snap.push(d*c.swipeSign(), u.Time)
205 m := g.screen.mon
206 switch g.mode {
207 case swipeColumns:
208 if g.columnsChanged(m) {
209 g.ws.view.stop()
210 g.mode = swipeDropped
211 return true
212 }
213 g.ws.view.off = g.snap.pos() - float64(g.ws.View)
214 return true
215 case swipeWorkspaces:
216 if g.listChanged(m) {
217 m.stopSwitch()
218 g.mode = swipeDropped
219 return true
220 }
221 m.switchView.off = g.snap.pos() - float64(m.Active)
222 return true
223 case swipeStash:
224 if g.stashChanged(m) {
225 g.ws.stashView.stop()
226 g.mode = swipeDropped
227 return true
228 }
229 g.ws.stashView.off = g.snap.pos() - float64(g.ws.stashAt)
230 return true
231 }
232 return false
233}
234
235// decide picks the swipe's axis and what it moves. A running slide stops
236// where it is: the fingers take it from there.
237func (c *Core) decide(g *swipeGesture) {
238 g.horizontal = math.Abs(g.cx) > math.Abs(g.cy)
239 m := g.screen.mon
240 g.opens = m.overviewOpens
241 w := m.Current()
242 switch {
243 case g.fingers == 4 && !g.horizontal:
244 g.mode, g.snap = swipeOverview, newStepSwipe()
245 case g.fingers == 4:
246 // Four fingers sideways do nothing.
247 g.mode = swipeDropped
248 case m.ov.open:
249 // Overview navigation is chosen at begin, never on release.
250 g.mode = swipeDropped
251 case !c.animOn():
252 // With animations off nothing slides: the swipe runs a
253 // focus action when the fingers lift.
254 g.mode, g.snap = swipeDiscrete, newStepSwipe()
255 case g.horizontal && w.stashFocused() && !w.floatFocus && w.stashShown():
256 g.mode, g.ws, g.home = swipeStash, w, w.stashAt
257 g.ids = make([]WindowID, 0, len(w.Stash))
258 for _, f := range w.Stash {
259 g.ids = append(g.ids, f.ID)
260 }
261 w.stashView.motion = motion{}
262 g.snap = newSnapSwipe(float64(w.stashAt)+w.stashView.off, float64(w.stashAt), 1/stashSwipeMovement, indexPoints(len(w.Stash)), workspaceBand)
263 case g.horizontal == (w.policy().content == horizontalAxis) && w.slidable():
264 g.mode, g.ws, g.points = swipeColumns, w, w.snapPoints()
265 w.view.motion = motion{}
266 g.snap = newSnapSwipe(float64(w.View)+w.view.off, float64(w.View), w.swipeScale(), g.points, workspaceBand.scaled(float64(w.policy().content.span(w.Usable))))
267 case g.horizontal == (w.policy().workspace == horizontalAxis) && m.shown == nil:
268 // A landing slide measured in an older list lands at once first.
269 if m.switchList != nil && !slices.Equal(m.switchList, m.Workspaces) {
270 m.stopSwitch()
271 }
272 g.mode, g.ws = swipeWorkspaces, m.Workspaces[m.Active]
273 axis := w.policy().workspace
274 if m.switchView.busy() && m.switchAxis != axis {
275 m.stopSwitch()
276 }
277 m.switchAxis = axis
278 g.list = slices.Clone(m.Workspaces)
279 m.switchView.motion, m.switchList = motion{}, nil
280 g.snap = newSnapSwipe(float64(m.Active)+m.switchView.off, float64(m.Active), 1/workspaceSwipeMovement, indexPoints(len(m.Workspaces)), workspaceBand)
281 default:
282 g.mode, g.snap = swipeDiscrete, newStepSwipe()
283 }
284}
285
286// swipeEnd lands the swipe. shown reports that another workspace came on
287// screen.
288func (c *Core) swipeEnd(e ports.SwipeEnd) (shown bool) {
289 g := c.swipe
290 if g != nil && !c.hasScreen(g.screen) {
291 c.dropSwipe()
292 }
293 c.swipe = nil
294 if g == nil || !c.hasScreen(g.screen) {
295 return false
296 }
297 now := c.now()
298 m := g.screen.mon
299 switch g.mode {
300 case swipeNavigation:
301 c.scrollStop(ports.PointerAxis{Horizontal: ports.ScrollAxis{Stop: true}})
302 return false
303 case swipeColumns:
304 w := g.ws
305 if g.columnsChanged(m) {
306 w.view.stop()
307 return false
308 }
309 shown := float64(w.View) + w.view.off
310 target, velocity := g.snap.end(e.Cancelled, e.Time)
311 if !e.Cancelled {
312 view := int(math.Round(target))
313 focus := w.snapFocus(view, target >= shown)
314 if focus != w.Focus && w.policy().maximizeHides() {
315 w.unmaximize()
316 }
317 w.Focus = focus
318 w.View = view
319 // A column wider than the view aligns as focus moves align it.
320 w.scroll()
321 c.focusScreen = c.screenIndex(g.screen.name())
322 c.keyboard.takeBack()
323 }
324 w.view.off = shown - float64(w.View)
325 if c.animOn() {
326 w.view.motion = c.spring(viewSpring(w.view.off, velocity), now)
327 } else {
328 w.view.stop()
329 }
330 case swipeWorkspaces:
331 if g.listChanged(m) {
332 m.stopSwitch()
333 return false
334 }
335 cur := float64(m.Active) + m.switchView.off
336 target, velocity := g.snap.end(e.Cancelled, e.Time)
337 idx := m.Active
338 if !e.Cancelled {
339 idx = int(math.Round(target))
340 }
341 // Focus may drop the empty workspace left behind and renumber the
342 // list: the slide keeps measuring in the list it began on.
343 off := cur - float64(idx)
344 if idx != m.Active {
345 m.Focus(idx)
346 shown = true
347 }
348 if !e.Cancelled {
349 c.focusScreen = c.screenIndex(g.screen.name())
350 c.keyboard.takeBack()
351 }
352 m.switchView.off, m.switchList = off, g.list
353 if c.animOn() {
354 m.switchView.motion = c.spring(m.switchSpring(off, velocity), now)
355 } else {
356 m.stopSwitch()
357 }
358 case swipeStash:
359 w := g.ws
360 if g.stashChanged(m) {
361 w.stashView.stop()
362 return false
363 }
364 drawn := float64(w.stashAt) + w.stashView.off
365 target, velocity := g.snap.end(e.Cancelled, e.Time)
366 dir := 0
367 if !e.Cancelled {
368 dir = int(math.Round(target)) - w.stashAt
369 }
370 if c.cur() == g.screen && dir != 0 {
371 // The landing is the focus action's: the selection, the focus
372 // and the veils move as a bind moves them.
373 a := ActionFocusColumnRight
374 if dir < 0 {
375 a = ActionFocusColumnLeft
376 }
377 c.keyboard.takeBack()
378 c.applyAction(a)
379 }
380 w.stashView.off = drawn - float64(w.stashAt)
381 if c.animOn() {
382 w.stashView.motion = c.spring(w.stashSpring(w.stashView.off, velocity), now)
383 } else {
384 w.stashView.stop()
385 }
386 // The stash never brings another workspace on screen.
387 return false
388 case swipeOverview:
389 step := g.snap.step(e.Cancelled, e.Time)
390 if step == 0 {
391 return false
392 }
393 if !m.ov.open && (step > 0 || m.Current().stashShown()) {
394 return c.swipeStash(g, now)
395 }
396 if (step < 0) == m.ov.open {
397 return false
398 }
399 before := m.Current()
400 shots := c.snapshot(now)
401 m.ToggleOverview()
402 c.focusScreen = c.screenIndex(g.screen.name())
403 c.keyboard.takeBack()
404 c.transition(shots, now)
405 return m.Current() != before
406 case swipeDiscrete:
407 step := g.snap.step(e.Cancelled, e.Time)
408 if step == 0 {
409 return false
410 }
411 w := g.screen.mon.Current()
412 p := w.policy()
413 workspace := g.horizontal == (p.workspace == horizontalAxis)
414 a := ActionFocusColumnRight
415 if step < 0 {
416 a = ActionFocusColumnLeft
417 }
418 if workspace {
419 a = ActionFocusWorkspaceNext
420 if step < 0 {
421 a = ActionFocusWorkspacePrev
422 }
423 } else if p.wraps {
424 // A content swipe cannot escape the last band to another workspace.
425 if w.onFloat() || w.fullscreen != 0 || w.laneNeighbor(step) < 0 {
426 return false
427 }
428 }
429 // Focus actions act on the focused screen: the swipe's, unless the
430 // pointer took the focus to another output meanwhile.
431 if c.cur() != g.screen {
432 return false
433 }
434 if c.cur().mon.ov.open {
435 return false
436 }
437 before := c.cur().mon.Current()
438 shots := c.snapshot(now)
439 c.keyboard.takeBack()
440 if p.wraps && !workspace {
441 w.focusBand(step)
442 } else {
443 c.applyAction(a)
444 }
445 c.transition(shots, now)
446 return c.cur().mon.Current() != before
447 }
448 return shown
449}
450
451// swipeStash runs toggle-stash-visible for a four-finger swipe down, or up
452// while the stash is shown, with the overview closed, on the swipe's screen
453// unless the pointer took the focus to another output meanwhile. It reports
454// whether the stash showed or hid: an empty stash stays as it is.
455func (c *Core) swipeStash(g *swipeGesture, now time.Time) bool {
456 if c.cur() != g.screen {
457 return false
458 }
459 w := g.screen.mon.Current()
460 hidden, over := w.stashHidden, w.stashOver
461 shots := c.snapshot(now)
462 c.keyboard.takeBack()
463 c.applyAction(ActionToggleStashVisible)
464 c.transition(shots, now)
465 return w.stashHidden != hidden || w.stashOver != over
466}
467
468// swipedWorkspace is the workspace on the swipe's screen, or nil without
469// a swipe.
470func (c *Core) swipedWorkspace() *Workspace {
471 if c.swipe == nil {
472 return nil
473 }
474 return c.swipe.screen.mon.Current()
475}
476
477// dropSwipe lets go of the swipe in progress: a bind changed the workspace
478// on its screen. Its slide stops where the bind left the view; the rest of
479// the swipe is ignored, even if a later bind shows its workspace again.
480func (c *Core) dropSwipe() {
481 g := c.swipe
482 if g == nil {
483 return
484 }
485 switch g.mode {
486 case swipeColumns:
487 g.ws.view.stop()
488 case swipeWorkspaces:
489 g.screen.mon.stopSwitch()
490 case swipeStash:
491 g.ws.stashView.stop()
492 }
493 g.mode = swipeDropped
494}
495
496func (c *Core) hasScreen(s *screen) bool {
497 for _, v := range c.screens {
498 if v == s {
499 return true
500 }
501 }
502 return false
503}
504
505// animOn reports whether transitions run (animations = on).
506func (c *Core) animOn() bool { return c.cfg.Animations.On }
507
508// spring starts s at now, stretched by animations.speed (Slowdown). Every motion
509// core creates goes through it, except a retarget, which keeps the slowdown
510// of the motion it replaces.
511func (c *Core) spring(s spring, now time.Time) motion {
512 return newMotion(s, now, c.cfg.Animations.Slowdown)
513}
514
515// stopAnimations settles every running spring where it is going and stops
516// the frame timer: a session lock or a switch to animations = off. A swipe
517// in progress keeps its fingers' view: only running springs stop. Per-window
518// rect motions stop too.
519func (c *Core) stopAnimations() {
520 for _, sc := range c.screens {
521 sc.stopAnimations()
522 }
523 c.stopFrame()
524}
525
526// stopAnimations settles the screen's running springs where they are going.
527func (s *screen) stopAnimations() {
528 if s.mon.switchView.motion.on {
529 s.mon.stopSwitch()
530 }
531 for w := range s.mon.all() {
532 if w.view.motion.on {
533 w.view.stop()
534 }
535 if w.stashView.motion.on {
536 w.stashView.stop()
537 }
538 }
539 s.stopRects()
540}
541
542// animate moves the running springs to now; settled ones stop. A non-nil only
543// limits it to that screen (its own page flip); nil moves every screen.
544func (c *Core) animate(now time.Time, only *screen) {
545 for _, sc := range c.screens {
546 if only != nil && sc != only {
547 continue
548 }
549 m := sc.mon
550 if m.switchView.motion.on {
551 m.switchView.step(now)
552 if !m.switchView.motion.on {
553 m.switchList = nil
554 }
555 }
556 for w := range m.all() {
557 w.view.step(now)
558 w.stashView.step(now)
559 }
560 for id, rm := range sc.rects {
561 rm.advance(now)
562 if rm.on() {
563 sc.rects[id] = rm
564 } else {
565 delete(sc.rects, id)
566 }
567 }
568 }
569}
570
571// sliding reports whether a spring runs on the named output.
572func (c *Core) sliding(output string) bool {
573 i := c.screenIndex(output)
574 return i >= 0 && (c.screens[i].springing() || c.pulsing(c.screens[i]))
575}
576
577// animating reports whether a spring or the focus pulse runs on any output.
578func (c *Core) animating() bool {
579 if c.pulse.id != 0 {
580 return true
581 }
582 for _, sc := range c.screens {
583 if sc.springing() {
584 return true
585 }
586 }
587 return false
588}
589
590func (m *Monitor) springing() bool {
591 if m.switchView.motion.on {
592 return true
593 }
594 for w := range m.all() {
595 if w.view.motion.on || w.stashView.motion.on {
596 return true
597 }
598 }
599 return false
600}
601
602// frameFallback is how long core waits for a page flip before it moves a
603// running slide on its own (an output that stopped flipping).
604func (c *Core) frameFallback() time.Duration {
605 refresh := 60000
606 for _, sc := range c.screens {
607 if r := sc.info.RefreshMilli; r > 0 && (sc.springing() || c.pulsing(sc)) {
608 refresh = min(refresh, r)
609 }
610 }
611 return 2 * time.Second * 1000 / time.Duration(refresh)
612}
613
614// armFrame starts the fallback timer of a running slide. The timer is made
615// on the first arm and reset afterwards (Go 1.23 timers deliver nothing
616// stale after a Stop or Reset), so a frame costs no allocation.
617func (c *Core) armFrame() {
618 d := c.frameFallback()
619 if c.frameTimer == nil {
620 c.frameTimer = newPortTimer(c.opts.Clock, d)
621 } else {
622 c.frameTimer.Stop()
623 c.frameTimer.Reset(d)
624 }
625 c.frameC = c.frameTimer.C()
626}
627
628func (c *Core) stopFrame() {
629 if c.frameC != nil {
630 c.frameTimer.Stop()
631 }
632 c.frameC = nil
633}