lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! One finger as the pointer. A touch screen is reported as touches only, with no mouse events, so the tree turns
//! the first finger into the pointer and scroll input it already takes ([`Tree::finger`]): a shell gives it every
//! touch winit reports, the desktop's emulation of a phone its mouse as fingers, and MCP its gestures. The timings and
//! distances are UIKit's, so a list here answers a finger as a `UIScrollView` does.
//!
//! Where nothing under the finger scrolls, and on a control that is dragged (a slider, a scrollbar), the finger
//! is the pointer with its button down: it presses when it lands, moves the pointer and releases when it lifts.
//! One that went further than [`TAP_SLOP`] from where it landed is no tap, as on the platform: its release clicks
//! nothing, and ends what holds the press (a slider, a selection, a drag) as any release does. So is one that
//! travels after its long press.
//!
//! Over content that scrolls, a finger that lands may be about to scroll or to tap, so nothing is pressed yet,
//! and nothing is hovered: a finger has no hover.
//!
//! - Rested for [`PRESS_DELAY`], it presses, so what it is on shows its pressed state.
//! - Lifted within [`TAP_SLOP`], it taps where it landed: the click comes at once, and what was tapped shows its
//!   pressed state for [`TAP_HIGHLIGHT`] even when the tap was quicker than the delay.
//! - Moved past the slop, it scrolls, and a press already sent ends without a click. The content starts from where it
//!   is: the travel that told the scroll from a tap is not caught up with. The scroll goes on after the finger lifts,
//!   slowing down, until it stops or reaches an end of the content.
//! - Rested for [`LONG_PRESS`], it is a long press (`on_long_press`) and stays the pointer whatever it does next: text
//!   selection and `on_drag_*` sessions over a list start this way.
//!
//! A finger that lands while content is still moving, with momentum or springing back from past an end, catches
//! it: the content stops, nothing is pressed, and any move scrolls on from there with no slop.
//!
//! A finger that lands while another scrolls joins the scroll: the content follows the middle of the fingers,
//! and goes on with those that stay when one lifts. Before a scroll starts, further fingers are ignored.
//!
//! The pointer leaves the window once the gesture ends. Positions and deltas are physical pixels, as the tree's pointer
//! input takes them.

use std::{collections::VecDeque, time::Duration};

use super::{ElementHandle, TouchMomentum, TouchRoute, Tree, hit_test_tree};
use crate::{
  app::events::{ScrollPhase, TouchPhase},
  time::Instant,
};

/// How far apart two taps may land and still be a double tap, in logical pixels.
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
pub(crate) const DOUBLE_TAP_DISTANCE: f32 = 40.0;
/// How long after a tap the next one is still a double tap; UIKit's.
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
pub(crate) const DOUBLE_TAP_INTERVAL: Duration = Duration::from_millis(350);
/// How far a finger may travel and still tap, in logical pixels.
const TAP_SLOP: f64 = 10.0;
/// How long a finger rests over content that scrolls before it presses; a scroll view's delay of content
/// touches.
pub(super) const PRESS_DELAY: Duration = Duration::from_millis(150);
/// How long what a tap landed on goes on showing as pressed, so that a quick tap shows.
pub(super) const TAP_HIGHLIGHT: Duration = Duration::from_millis(80);
/// How long a finger rests over content that scrolls before it no longer scrolls it.
pub(super) const LONG_PRESS: Duration = Duration::from_millis(500);
/// The time between two steps of content springing back from past an end.
pub(crate) const SPRING_STEP: Duration = Duration::from_millis(4);
/// The time between two steps of momentum. Shorter than any display's frame, so every frame has a step.
const FLING_STEP: Duration = Duration::from_millis(4);

/// What the tree is given for a touch, in order.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum TouchAction {
  /// The pointer moves to the point; nothing is pressed, or the press is held.
  Move { x: f64, y: f64 },
  /// The left button goes down at the point.
  Press { x: f64, y: f64 },
  /// The left button comes up at the point, and the pointer leaves. It clicks where `tap`: a finger that
  /// travelled past the slop is no tap, and its release ends what holds the press (a slider, a drag) and clicks
  /// nothing.
  Release { x: f64, y: f64, tap: bool },
  /// A press and its release at the point at once: a tap, whose click is not held back.
  Tap { x: f64, y: f64 },
  /// The finger rested at the point: `on_long_press`. The shell tells back whether a handler took it; see
  /// [`TouchPointer::long_press_taken`].
  LongPress { x: f64, y: f64 },
  /// The held press ends without a click, and the pointer leaves.
  CancelPress { x: f64, y: f64 },
  /// Content a finger caught and held still is let go: past an end, it springs back.
  Settle,
  /// A scroll gesture starts at the point with this first travel: the tree picks what the gesture scrolls.
  ScrollTarget { x: f64, y: f64, dx: f64, dy: f64 },
  /// A scroll of what the gesture started on, sent at the point the finger started from.
  Scroll {
    x: f64,
    y: f64,
    dx: f64,
    dy: f64,
    phase: ScrollPhase,
  },
}

#[derive(Debug)]
enum State {
  Idle,
  /// The finger is down over content that scrolls, and has neither moved past the slop nor rested for
  /// [`LONG_PRESS`].
  Pending {
    id: u64,
    start: (f64, f64),
    started_at: Instant,
    /// The touch caught content that was moving: it scrolls if it moves at all, and presses nothing.
    caught: bool,
    /// The press was sent, after [`PRESS_DELAY`].
    pressed: bool,
  },
  /// The press was sent and the finger is the pointer until it lifts.
  Dragging {
    id: u64,
    /// Where the finger is.
    at: (f64, f64),
    /// When the finger becomes a long press if it stays near where it landed, and where that is.
    rest: Option<(Instant, (f64, f64))>,
    /// A handler took the long press: the finger clicks nothing when it lifts.
    taken: bool,
    /// Where the finger landed, and whether it has gone further from there than the slop since: then it is no
    /// tap, and clicks nothing when it lifts.
    landed: (f64, f64),
    travelled: bool,
  },
  Scrolling {
    /// The fingers on the content and where each one is: the one that started the scroll, and those that
    /// joined it since.
    fingers: Vec<(u64, (f64, f64))>,
    /// Where the finger started: the point every scroll of the gesture is sent at, so one target takes it all.
    anchor: (f64, f64),
    /// The middle of the fingers, which the content follows.
    last: (f64, f64),
    samples: VecDeque<(Instant, (f64, f64))>,
  },
}

#[derive(Debug)]
struct Fling {
  anchor: (f64, f64),
  /// Physical pixels per second.
  velocity: (f64, f64),
  stop_speed: f64,
  last_step: Instant,
}

#[derive(Debug)]
pub(super) struct TouchPointer {
  state: State,
  /// The fingers that landed while another was pressing, each with where it landed: one that lifts there taps
  /// what it is on, beside the finger that is the pointer.
  beside: Vec<(u64, (f64, f64))>,
  fling: Option<Fling>,
  /// How a scroll goes on after the finger lifts; the app's, from the tree.
  momentum: TouchMomentum,
}

impl Default for TouchPointer {
  fn default() -> Self {
    Self {
      state: State::Idle,
      beside: Vec::new(),
      fling: None,
      momentum: TouchMomentum::default(),
    }
  }
}

impl TouchPointer {
  /// Takes the app's momentum; a scroll that is under way keeps going by it.
  pub(super) fn set_momentum(&mut self, momentum: TouchMomentum) {
    self.momentum = momentum;
  }

  /// Whether another finger than `id` is the pointer, with its press sent.
  fn pressed_by_another(&self, id: u64) -> bool {
    match &self.state {
      State::Dragging { id: held, .. }
      | State::Pending {
        id: held,
        pressed: true,
        ..
      } => *held != id,
      _ => false,
    }
  }

  /// A finger's event, where the finger is one beside the pointer: it landed while another was pressing, and is
  /// none of the pointer's. `None` for a finger that is not. `Some(true)` as it lifts where it landed: a tap of
  /// its own.
  pub(super) fn beside(&mut self, id: u64, phase: TouchPhase, position: (f64, f64), scale: f64) -> Option<bool> {
    if phase == TouchPhase::Start {
      if !self.pressed_by_another(id) {
        return None;
      }
      self.beside.push((id, position));
      return Some(false);
    }
    let at = self.beside.iter().position(|(held, _)| *held == id)?;
    let start = self.beside[at].1;
    let near = (position.0 - start.0).hypot(position.1 - start.1) <= TAP_SLOP * scale;
    match phase {
      // One that travels is no tap: it is nothing from then on.
      TouchPhase::Move if near => Some(false),
      TouchPhase::End => {
        self.beside.remove(at);
        Some(near)
      }
      _ => {
        self.beside[at].1 = (f64::INFINITY, f64::INFINITY);
        if phase == TouchPhase::Cancel {
          self.beside.remove(at);
        }
        Some(false)
      }
    }
  }

  /// Takes one touch event. `scale` is the window's scale factor; `springing` tells that the finger landed while
  /// content was springing back from past an end, which the shell has stopped; `scrolls` tells whether a finger
  /// that moves from a point scrolls what is under it.
  pub(super) fn touch(
    &mut self,
    id: u64,
    phase: TouchPhase,
    position: (f64, f64),
    now: Instant,
    scale: f64,
    springing: bool,
    scrolls: impl FnOnce((f64, f64)) -> bool,
  ) -> Vec<TouchAction> {
    match phase {
      TouchPhase::Start => self.started(id, position, now, springing, scrolls),
      TouchPhase::Move => self.moved(id, position, now, scale),
      TouchPhase::End => self.ended(id, position, now, scale),
      TouchPhase::Cancel => self.cancelled(id, position),
    }
  }

  fn started(
    &mut self,
    id: u64,
    position: (f64, f64),
    now: Instant,
    springing: bool,
    scrolls: impl FnOnce((f64, f64)) -> bool,
  ) -> Vec<TouchAction> {
    if let State::Scrolling {
      fingers, last, samples, ..
    } = &mut self.state
    {
      // Another finger joins the scroll, and may carry it on when the first one lifts. The content follows the
      // middle of the fingers, and does not jump to where that now is.
      fingers.push((id, position));
      *last = middle(fingers);
      samples.clear();
      return Vec::new();
    }
    if !matches!(self.state, State::Idle) {
      return Vec::new();
    }
    let mut actions = Vec::new();
    let fling = self.fling.take();
    if fling.is_some() || springing {
      self.state = State::Pending {
        id,
        start: position,
        started_at: now,
        caught: true,
        pressed: false,
      };
      actions.extend(fling.map(|fling| scroll(fling.anchor, (0.0, 0.0), ScrollPhase::End)));
      return actions;
    }
    if !scrolls(position) {
      self.state = State::Dragging {
        id,
        at: position,
        rest: Some((now + LONG_PRESS, position)),
        taken: false,
        landed: position,
        travelled: false,
      };
      actions.push(TouchAction::Press {
        x: position.0,
        y: position.1,
      });
      return actions;
    }
    self.state = State::Pending {
      id,
      start: position,
      started_at: now,
      caught: false,
      pressed: false,
    };
    actions
  }

  fn moved(&mut self, id: u64, position: (f64, f64), now: Instant, scale: f64) -> Vec<TouchAction> {
    match &mut self.state {
      State::Pending {
        id: held,
        start,
        caught,
        pressed,
        ..
      } if *held == id => {
        let (start, pressed) = (*start, *pressed);
        // Content the finger caught goes on with its first move.
        let slop = if *caught { 0.0 } else { TAP_SLOP * scale };
        if distance(start, position) <= slop {
          return Vec::new();
        }
        self.state = State::Scrolling {
          fingers: vec![(id, position)],
          anchor: start,
          last: position,
          samples: VecDeque::from([(now, position)]),
        };
        let mut actions = Vec::new();
        if pressed {
          actions.push(TouchAction::CancelPress { x: start.0, y: start.1 });
        }
        // The travel so far says which way the gesture goes, and scrolls nothing.
        actions.push(TouchAction::ScrollTarget {
          x: start.0,
          y: start.1,
          dx: position.0 - start.0,
          dy: position.1 - start.1,
        });
        actions.push(scroll(start, (0.0, 0.0), ScrollPhase::Start));
        actions
      }
      State::Dragging {
        id: held,
        at,
        rest,
        landed,
        travelled,
        ..
      } if *held == id => {
        *at = position;
        // A finger that travels is not resting.
        if rest.is_some_and(|(_, start)| distance(start, position) > TAP_SLOP * scale) {
          *rest = None;
        }
        *travelled |= distance(*landed, position) > TAP_SLOP * scale;
        vec![TouchAction::Move {
          x: position.0,
          y: position.1,
        }]
      }
      State::Scrolling {
        fingers,
        anchor,
        last,
        samples,
      } => {
        let Some(finger) = fingers.iter_mut().find(|(held, _)| *held == id) else {
          return Vec::new();
        };
        finger.1 = position;
        let position = middle(fingers);
        let delta = (position.0 - last.0, position.1 - last.1);
        *last = position;
        samples.push_back((now, position));
        while samples
          .front()
          .is_some_and(|(at, _)| now.saturating_duration_since(*at) > self.momentum.velocity_window)
        {
          samples.pop_front();
        }
        vec![scroll(*anchor, delta, ScrollPhase::Scroll)]
      }
      _ => Vec::new(),
    }
  }

  fn ended(&mut self, id: u64, position: (f64, f64), now: Instant, scale: f64) -> Vec<TouchAction> {
    if self.one_of_several_lifted(id) {
      return Vec::new();
    }
    if self.held_id() != Some(id) {
      return Vec::new();
    }
    match std::mem::replace(&mut self.state, State::Idle) {
      State::Pending { caught: true, .. } => vec![TouchAction::Settle],
      State::Pending {
        start, pressed: true, ..
      } => vec![TouchAction::Release {
        x: start.0,
        y: start.1,
        tap: true,
      }],
      State::Pending { start, .. } => vec![TouchAction::Tap { x: start.0, y: start.1 }],
      State::Dragging { taken: true, .. } => vec![TouchAction::CancelPress {
        x: position.0,
        y: position.1,
      }],
      State::Dragging { landed, travelled, .. } => vec![TouchAction::Release {
        x: position.0,
        y: position.1,
        tap: !travelled && distance(landed, position) <= TAP_SLOP * scale,
      }],
      State::Scrolling {
        anchor, last, samples, ..
      } => {
        let mut actions = vec![scroll(
          anchor,
          (position.0 - last.0, position.1 - last.1),
          ScrollPhase::End,
        )];
        if let Some(velocity) = lift_velocity(&samples, position, now, scale, &self.momentum) {
          // Momentum is a scroll gesture of its own, as a trackpad reports it.
          actions.push(scroll(anchor, (0.0, 0.0), ScrollPhase::Start));
          self.fling = Some(Fling {
            anchor,
            velocity,
            stop_speed: f64::from(self.momentum.stop_speed) * scale,
            last_step: now,
          });
        }
        actions
      }
      State::Idle => Vec::new(),
    }
  }

  fn cancelled(&mut self, id: u64, position: (f64, f64)) -> Vec<TouchAction> {
    if self.one_of_several_lifted(id) {
      return Vec::new();
    }
    if self.held_id() != Some(id) {
      return Vec::new();
    }
    match std::mem::replace(&mut self.state, State::Idle) {
      State::Pending { caught: true, .. } => vec![TouchAction::Settle],
      State::Pending { pressed: false, .. } | State::Idle => Vec::new(),
      State::Pending { .. } | State::Dragging { .. } => vec![TouchAction::CancelPress {
        x: position.0,
        y: position.1,
      }],
      State::Scrolling { anchor, .. } => vec![scroll(anchor, (0.0, 0.0), ScrollPhase::End)],
    }
  }

  /// Runs what time brings: the press and the long press of a finger that rested, and the next step of
  /// momentum.
  pub(super) fn tick(&mut self, now: Instant) -> Vec<TouchAction> {
    if let State::Dragging { rest, .. } = &mut self.state
      && let Some((due, start)) = *rest
      && now >= due
    {
      *rest = None;
      return vec![TouchAction::LongPress { x: start.0, y: start.1 }];
    }
    if let State::Pending {
      id,
      start,
      started_at,
      caught: false,
      pressed,
    } = &mut self.state
    {
      let rested = now.saturating_duration_since(*started_at);
      let press = (!*pressed && rested >= PRESS_DELAY).then_some(TouchAction::Press { x: start.0, y: start.1 });
      *pressed |= press.is_some();
      let mut actions: Vec<TouchAction> = press.into_iter().collect();
      if rested >= LONG_PRESS {
        actions.push(TouchAction::LongPress { x: start.0, y: start.1 });
        self.state = State::Dragging {
          id: *id,
          at: *start,
          rest: None,
          taken: false,
          landed: *start,
          travelled: false,
        };
      }
      return actions;
    }

    let Some(fling) = self.fling.as_mut() else {
      return Vec::new();
    };
    let elapsed = now.saturating_duration_since(fling.last_step);
    if elapsed < FLING_STEP {
      return Vec::new();
    }
    fling.last_step = now;
    let seconds = elapsed.as_secs_f64();
    let kept = f64::from(self.momentum.deceleration_rate).powf(seconds * 1000.0);
    let (vx, vy) = fling.velocity;
    let next = (vx * kept, vy * kept);
    // The mean of the speeds before and after the step, over its time.
    let delta = ((vx + next.0) * 0.5 * seconds, (vy + next.1) * 0.5 * seconds);
    fling.velocity = next;
    let anchor = fling.anchor;
    let mut actions = vec![scroll(anchor, delta, ScrollPhase::Scroll)];
    if next.0.hypot(next.1) < fling.stop_speed {
      self.fling = None;
      actions.push(scroll(anchor, (0.0, 0.0), ScrollPhase::End));
    }
    actions
  }

  /// When [`tick`](Self::tick) next has something to do, for the loop to wake at.
  pub(super) fn next_deadline(&self) -> Option<Instant> {
    let rest = match self.state {
      State::Pending {
        started_at,
        caught: false,
        pressed,
        ..
      } => Some(started_at + if pressed { LONG_PRESS } else { PRESS_DELAY }),
      State::Dragging { rest, .. } => rest.map(|(due, _)| due),
      _ => None,
    };
    let fling = self.fling.as_ref().map(|fling| fling.last_step + FLING_STEP);
    rest.into_iter().chain(fling).min()
  }

  /// The fingers became a gesture's: whatever the pointer was doing ends, without a click and without momentum,
  /// and the fingers are no longer followed.
  pub(super) fn abandon(&mut self) -> Vec<TouchAction> {
    self.fling = None;
    match std::mem::replace(&mut self.state, State::Idle) {
      State::Idle
      | State::Pending {
        pressed: false,
        caught: false,
        ..
      } => Vec::new(),
      State::Pending { caught: true, .. } => vec![TouchAction::Settle],
      State::Pending { start, .. } => vec![TouchAction::CancelPress { x: start.0, y: start.1 }],
      State::Dragging { at, .. } => vec![TouchAction::CancelPress { x: at.0, y: at.1 }],
      State::Scrolling { anchor, .. } => vec![scroll(anchor, (0.0, 0.0), ScrollPhase::End)],
    }
  }

  /// Whether the finger caught content that was moving and holds it still.
  pub(super) fn holds_caught(&self) -> bool {
    matches!(self.state, State::Pending { caught: true, .. })
  }

  /// A handler took the long press the shell was just given: the finger clicks nothing when it lifts.
  pub(super) fn long_press_taken(&mut self) {
    if let State::Dragging { taken, .. } = &mut self.state {
      *taken = true;
    }
  }

  /// Ends momentum whose last step moved nothing: the content reached its end. Gives the scroll's last event
  /// and the velocity it ended at, in physical pixels per second, which carries the content past that end.
  pub(super) fn end_fling(&mut self) -> Option<(TouchAction, (f64, f64))> {
    let fling = self.fling.take()?;
    Some((scroll(fling.anchor, (0.0, 0.0), ScrollPhase::End), fling.velocity))
  }

  /// Whether the finger is one of several scrolling the content. It leaves the scroll, which goes on with
  /// the others from where the content is.
  fn one_of_several_lifted(&mut self, id: u64) -> bool {
    let State::Scrolling {
      fingers, last, samples, ..
    } = &mut self.state
    else {
      return false;
    };
    if fingers.len() < 2 {
      return false;
    }
    let Some(index) = fingers.iter().position(|(held, _)| *held == id) else {
      return false;
    };
    fingers.remove(index);
    *last = middle(fingers);
    samples.clear();
    true
  }

  fn held_id(&self) -> Option<u64> {
    match &self.state {
      State::Idle => None,
      State::Pending { id, .. } | State::Dragging { id, .. } => Some(*id),
      State::Scrolling { fingers, .. } => fingers.first().map(|(id, _)| *id),
    }
  }
}

fn scroll(anchor: (f64, f64), delta: (f64, f64), phase: ScrollPhase) -> TouchAction {
  TouchAction::Scroll {
    x: anchor.0,
    y: anchor.1,
    dx: delta.0,
    dy: delta.1,
    phase,
  }
}

/// Whether the actions end a scroll: of a finger, or of its momentum.
pub(super) fn ends_scroll(actions: &[TouchAction]) -> bool {
  actions.iter().any(|action| {
    matches!(
      action,
      TouchAction::Scroll {
        phase: ScrollPhase::End,
        ..
      }
    )
  })
}

/// The middle of the fingers; there is at least one.
fn middle(fingers: &[(u64, (f64, f64))]) -> (f64, f64) {
  let count = fingers.len().max(1) as f64;
  let (x, y) = fingers
    .iter()
    .fold((0.0, 0.0), |sum, (_, at)| (sum.0 + at.0, sum.1 + at.1));
  (x / count, y / count)
}

fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
  (a.0 - b.0).hypot(a.1 - b.1)
}

/// The velocity a scroll ends with, in physical pixels per second, when it is fast enough to leave momentum.
/// Measured from the oldest sample of the momentum's velocity window to the lift, so a finger that stopped
/// before it lifted leaves none.
fn lift_velocity(
  samples: &VecDeque<(Instant, (f64, f64))>,
  position: (f64, f64),
  now: Instant,
  scale: f64,
  momentum: &TouchMomentum,
) -> Option<(f64, f64)> {
  let (at, from) = samples
    .iter()
    .find(|(at, _)| now.saturating_duration_since(*at) <= momentum.velocity_window)?;
  let seconds = now.saturating_duration_since(*at).as_secs_f64();
  if seconds <= 0.0 {
    return None;
  }
  let velocity = ((position.0 - from.0) / seconds, (position.1 - from.1) / seconds);
  let speed = velocity.0.hypot(velocity.1);
  if speed < f64::from(momentum.min_speed) * scale {
    return None;
  }
  let limit = (f64::from(momentum.max_speed) * scale / speed).min(1.0);
  Some((velocity.0 * limit, velocity.1 * limit))
}

impl Tree {
  /// Gives the tree a finger's event as a touch screen reports it, `x` and `y` in physical pixels: the finger's own
  /// events first, to what it landed on (see [`touch_event`](Self::touch_event)), then, where the finger is the
  /// tree's (no handler took it, no gesture has it), the pointer it stands for: a press, a tap, a scroll with its
  /// momentum, a long press. Tells whose the finger was.
  ///
  /// This is the one way a finger reaches an app: a shell gives it every touch winit reports, the emulation of a
  /// phone on a desktop the mouse as fingers ([`App::emulate`](crate::app::App::emulate)), and MCP its gestures.
  /// What time brings (the press of a finger that rested, a long press, momentum, content springing back) comes
  /// with [`finger_tick`](Self::finger_tick).
  ///
  /// It happens now, or at the time of the tree's clock of presses where one is set
  /// ([`set_press_clock`](Self::set_press_clock)).
  pub fn finger(&mut self, id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32>) -> TouchRoute {
    let now = self.press_clock.unwrap_or_else(Instant::now);
    self.finger_at(id, phase, x, y, force, false, now)
  }

  /// [`finger`](Self::finger) of a finger or, where `pen`, of a pen, at a time of the caller's.
  #[allow(clippy::too_many_arguments)]
  pub(crate) fn finger_at(
    &mut self,
    id: u64,
    phase: TouchPhase,
    x: f32,
    y: f32,
    force: Option<f32>,
    pen: bool,
    now: Instant,
  ) -> TouchRoute {
    if phase == TouchPhase::Start {
      self.touch_pointer.pen = pen;
      // The ring of the focus is the keyboard's: a finger that lands takes it away, whether it taps or pans, as
      // a press of the mouse does.
      self.set_input_modality(super::focus_visible::InputModality::Pointer);
    }
    // A finger on a selection's handle drags it, and is nothing else's.
    let scale = self.scale_factor();
    if self.touch_text_finger(id, phase, x / scale, y / scale) {
      return TouchRoute::Taken;
    }
    let route = self.touch_event_at(id, phase, x, y, force, now);
    let scale = f64::from(self.scale_factor());
    let (x, y) = (f64::from(x), f64::from(y));
    // A finger that landed while another was pressing is none of the pointer's: lifted where it landed, it taps
    // what it is on, and the finger that is held goes on as it was.
    if route == TouchRoute::Pointer
      && let Some(tapped) = self.finger.beside(id, phase, (x, y), scale)
    {
      if tapped {
        self.tap_beside(x as f32, y as f32);
      }
      return route;
    }
    let actions = match route {
      TouchRoute::Pointer => {
        let momentum = self.touch_momentum();
        self.finger.set_momentum(momentum);
        // A finger that lands on content springing back holds it where it is.
        let springing = phase == TouchPhase::Start && self.touch_scroll_catch();
        let scrolls = phase == TouchPhase::Start && self.touch_scrolls_at(x as f32, y as f32);
        self.finger.touch(id, phase, (x, y), now, scale, springing, |_| scrolls)
      }
      // Two fingers pinch or rotate: what the first one did as the pointer ends without a click.
      TouchRoute::Gesture => self.finger.abandon(),
      TouchRoute::Taken => return route,
    };
    let lifted =
      ends_scroll(&actions) && (route != TouchRoute::Pointer || matches!(phase, TouchPhase::End | TouchPhase::Cancel));
    // Content the finger caught on its way is held, not at rest, until the finger lets go of it.
    if self.finger.holds_caught() {
      self.touch_scroll_caught();
    }
    self.apply_finger_actions(actions, false);
    if lifted {
      self.page_after_finger_scroll(now);
    }
    // What the finger scrolled is at rest when it lifted and left the content nothing to do.
    self.touch_scroll_rest(now);
    route
  }

  /// A tap of a finger beside the one that is the pointer, at the point in physical pixels: what it is on is
  /// clicked, the innermost element there that listens for a click, with nothing pressed or hovered on the way,
  /// since the pointer is the other finger's.
  fn tap_beside(&mut self, x: f32, y: f32) {
    let scale = self.scale_factor();
    let (x, y) = (x / scale, y / scale);
    self.rebuild_if_dirty();
    let target = {
      let (Some(root), Some(layout)) = (&self.root, &self.last_layout) else {
        return;
      };
      let mut hits = Vec::new();
      hit_test_tree(root, layout, 0.0, 0.0, x, y, &self.layout_engine.radii(), &mut hits);
      hits
        .iter()
        .find(|(node, _)| !node.events.on_click.is_empty())
        .map(|(node, _)| node.node_id())
    };
    if let Some(node_id) = target {
      ElementHandle { tree: self, node_id }.click();
    }
  }

  /// Runs what time brings a finger: its press after resting, its long press, the next step of its momentum, and
  /// content springing back from past an end or on its way to a page. A shell calls it every turn of its loop
  /// while [`finger_deadline`](Self::finger_deadline) says so; a test, at the times of its own clock.
  pub fn finger_tick(&mut self, now: Instant) {
    let actions = self.finger.tick(now);
    if !self.apply_finger_actions(actions, true)
      && let Some((end, velocity)) = self.finger.end_fling()
    {
      self.apply_finger_actions(vec![end], true);
      self.touch_scroll_bounce(velocity.0 as f32, velocity.1 as f32, now);
    }
    self.touch_tick(now);
  }

  /// When [`finger_tick`](Self::finger_tick) next has something to do: a finger's press or long press, a step of
  /// momentum, or of content springing back.
  pub fn finger_deadline(&self) -> Option<Instant> {
    self
      .finger
      .next_deadline()
      .into_iter()
      .chain(self.touch_animating().then(|| Instant::now() + SPRING_STEP))
      .min()
  }

  /// A finger's scroll just ended. A list that scrolls by pages has no momentum: it goes on to a page, from how
  /// fast the finger lifted.
  fn page_after_finger_scroll(&mut self, now: Instant) {
    if !self.touch_scroll_pages() {
      return;
    }
    let velocity = match self.finger.end_fling() {
      Some((end, velocity)) => {
        self.apply_finger_actions(vec![end], false);
        velocity
      }
      None => (0.0, 0.0),
    };
    self.touch_scroll_page(velocity.0 as f32, velocity.1 as f32, now);
  }

  /// Gives the tree what a finger came to. `false` when the actions scrolled and the last scroll moved nothing.
  fn apply_finger_actions(&mut self, actions: Vec<TouchAction>, momentum: bool) -> bool {
    let mut moved = true;
    for action in actions {
      match action {
        TouchAction::Move { x, y } => self.touch_pointer_move(x as f32, y as f32),
        TouchAction::Press { x, y } => self.touch_press(x as f32, y as f32),
        TouchAction::Release { x, y, tap } => {
          if !tap && !self.has_active_input_interaction() {
            self.touch_release_without_click();
          }
          self.touch_release(x as f32, y as f32);
        }
        TouchAction::Tap { x, y } => self.touch_tap(x as f32, y as f32, TAP_HIGHLIGHT),
        TouchAction::LongPress { x, y } => {
          if self.touch_long_press(x as f32, y as f32) {
            self.finger.long_press_taken();
          }
        }
        TouchAction::CancelPress { x, y } => self.touch_cancel_press(x as f32, y as f32),
        TouchAction::Settle => self.touch_scroll_settle(),
        TouchAction::ScrollTarget { x, y, dx, dy } => {
          self.touch_scroll_begin(x as f32, y as f32, dx as f32, dy as f32);
        }
        TouchAction::Scroll { x, y, dx, dy, phase } => {
          let scrolled = self.touch_scroll(x as f32, y as f32, dx as f32, dy as f32, phase, momentum);
          if matches!(phase, ScrollPhase::Scroll) {
            moved = scrolled;
          }
        }
      }
    }
    moved
  }
}