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
use rxrust::ops::filter_map::FilterMapOp;

use super::EventCommon;
use crate::{
  data_widget::compose_child_as_data_widget, impl_compose_child_for_listener, impl_listener,
  impl_query_self_only, prelude::*,
};
use std::{
  convert::Infallible,
  time::{Duration, Instant},
};

mod from_mouse;
const MULTI_TAP_DURATION: Duration = Duration::from_millis(250);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PointerId(usize);

/// The pointer is a hardware-agnostic device that can target a specific set of
/// screen coordinates. Having a single event model for pointers can simplify
/// creating Web sites and applications and provide a good user experience
/// regardless of the user's hardware. However, for scenarios when
/// device-specific handling is desired, pointer events defines a pointerType
/// property to inspect the device type which produced the event.
/// Reference: <https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events#term_pointer_event>
#[derive(Debug, Clone)]
pub struct PointerEvent {
  /// A unique identifier for the pointer causing the event.
  pub id: PointerId,
  /// The width (magnitude on the X axis), in pixels, of the contact geometry of
  /// the pointer.
  pub width: f32,
  /// the height (magnitude on the Y axis), in pixels, of the contact geometry
  /// of the pointer.
  pub height: f32,
  /// the normalized pressure of the pointer input in the range of 0 to 1, where
  /// 0 and 1 represent the minimum and maximum pressure the hardware is capable
  /// of detecting, respectively. tangentialPressure
  /// The normalized tangential pressure of the pointer input (also known as
  /// barrel pressure or cylinder stress) in the range -1 to 1, where 0 is the
  /// neutral position of the control.
  pub pressure: f32,
  /// The plane angle (in degrees, in the range of -90 to 90) between the Y–Z
  /// plane and the plane containing both the pointer (e.g. pen stylus) axis and
  /// the Y axis.
  pub tilt_x: f32,
  /// The plane angle (in degrees, in the range of -90 to 90) between the X–Z
  /// plane and the plane containing both the pointer (e.g. pen stylus) axis and
  /// the X axis.
  pub tilt_y: f32,
  /// The clockwise rotation of the pointer (e.g. pen stylus) around its major
  /// axis in degrees, with a value in the range 0 to 359.
  pub twist: f32,
  ///  Indicates the device type that caused the event (mouse, pen, touch, etc.)
  pub point_type: PointerType,
  /// Indicates if the pointer represents the primary pointer of this pointer
  /// type.
  pub is_primary: bool,

  pub common: EventCommon,
}

bitflags! {
  #[derive(Default)]
  pub struct MouseButtons: u8 {
    /// Primary button (usually the left button)
    const PRIMARY = 0b0000_0001;
    /// Secondary button (usually the right button)
    const SECONDARY = 0b0000_0010;
    /// Auxiliary button (usually the mouse wheel button or middle button)
    const AUXILIARY = 0b0000_0100;
    /// 4th button (typically the "Browser Back" button)
    const FOURTH = 0b0000_1000;
    /// 5th button (typically the "Browser Forward" button)
    const FIFTH = 0b0001_0000;
  }
}

#[derive(Debug, Clone, PartialEq)]
pub enum PointerType {
  /// The event was generated by a mouse device.
  Mouse,
  /// The event was generated by a pen or stylus device.
  Pen,
  /// The event was generated by a touch, such as a finger.
  Touch,
}

impl std::borrow::Borrow<EventCommon> for PointerEvent {
  #[inline]
  fn borrow(&self) -> &EventCommon { &self.common }
}

impl std::borrow::BorrowMut<EventCommon> for PointerEvent {
  #[inline]
  fn borrow_mut(&mut self) -> &mut EventCommon { &mut self.common }
}

impl std::ops::Deref for PointerEvent {
  type Target = EventCommon;
  #[inline]
  fn deref(&self) -> &Self::Target { &self.common }
}

impl std::ops::DerefMut for PointerEvent {
  #[inline]
  fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common }
}

#[derive(Declare)]
pub struct PointerDownListener {
  #[declare(builtin, convert=custom)]
  on_pointer_down: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

#[derive(Declare)]
pub struct PointerUpListener {
  #[declare(builtin, convert=custom)]
  on_pointer_up: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

#[derive(Declare)]
pub struct PointerMoveListener {
  #[declare(builtin, convert=custom)]
  on_pointer_move: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

#[derive(Declare)]
pub struct TapListener {
  #[declare(builtin, convert=custom)]
  on_tap: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

#[derive(Declare)]
pub struct PointerCancelListener {
  #[declare(builtin, convert=custom)]
  pub on_pointer_cancel: MutRefItemSubject<'static, PointerEvent, Infallible>,
}
#[derive(Declare)]
pub struct PointerEnterListener {
  #[declare(builtin, convert=custom)]
  on_pointer_enter: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

#[derive(Declare)]
pub struct PointerLeaveListener {
  #[declare(builtin, convert=custom)]
  pub on_pointer_leave: MutRefItemSubject<'static, PointerEvent, Infallible>,
}

macro_rules! impl_pointer_listener {
  ($listener:ident, $declarer: ident, $field: ident, $event_ty: ident, $stream_name: ident) => {
    impl_listener!($listener, $declarer, $field, $event_ty, $stream_name);
    impl_compose_child_for_listener!($listener);
  };
}

impl_pointer_listener!(
  PointerDownListener,
  PointerDownListenerDeclarer,
  on_pointer_down,
  PointerEvent,
  point_down_stream
);

impl_pointer_listener!(
  PointerUpListener,
  PointerUpListenerDeclarer,
  on_pointer_up,
  PointerEvent,
  point_up_stream
);

impl_pointer_listener!(
  PointerMoveListener,
  PointerMoveListenerDeclarer,
  on_pointer_move,
  PointerEvent,
  pointer_move_stream
);

impl_pointer_listener!(
  PointerCancelListener,
  PointerCancelListenerDeclarer,
  on_pointer_cancel,
  PointerEvent,
  pointer_cancel_stream
);

impl_pointer_listener!(
  PointerEnterListener,
  PointerEnterListenerDeclarer,
  on_pointer_enter,
  PointerEvent,
  pointer_enter_stream
);

impl_pointer_listener!(
  PointerLeaveListener,
  PointerLeaveListenerDeclarer,
  on_pointer_leave,
  PointerEvent,
  pointer_leave_stream
);

impl TapListenerDeclarer {
  pub fn on_tap(mut self, handler: impl for<'r> FnMut(&'r mut PointerEvent) + 'static) -> Self {
    self.tap_subject().subscribe(handler);
    self
  }

  pub fn on_x_times_tap(
    mut self,
    (times, handler): (usize, impl for<'r> FnMut(&'r mut PointerEvent) + 'static),
  ) -> Self {
    self
      .tap_subject()
      .filter_map(x_times_tap_map_filter(times, MULTI_TAP_DURATION))
      .subscribe(handler);
    self
  }

  pub fn on_double_tap(self, handler: impl for<'r> FnMut(&'r mut PointerEvent) + 'static) -> Self {
    self.on_x_times_tap((2, handler))
  }

  pub fn on_triple_tap(self, handler: impl for<'r> FnMut(&'r mut PointerEvent) + 'static) -> Self {
    self.on_x_times_tap((3, handler))
  }

  fn tap_subject(&mut self) -> MutRefItemSubject<'static, PointerEvent, Infallible> {
    self.on_tap.get_or_insert_with(Default::default).clone()
  }
}

impl Query for TapListener {
  impl_query_self_only!();
}

impl TapListener {
  /// Return an observable stream of this event.
  pub fn tap_steam(&self) -> MutRefItemSubject<'static, PointerEvent, Infallible> {
    self.on_tap.clone()
  }

  /// Return an observable stream of double tap event
  #[inline]
  pub fn double_tap_stream(
    &self,
  ) -> FilterMapOp<
    MutRefItemSubject<'static, PointerEvent, Infallible>,
    impl FnMut(&mut PointerEvent) -> Option<&mut PointerEvent>,
    &mut PointerEvent,
  > {
    self.x_times_tap_stream(2, MULTI_TAP_DURATION)
  }

  /// Return an observable stream of tripe tap event
  #[inline]
  pub fn triple_tap_stream(
    &self,
  ) -> FilterMapOp<
    MutRefItemSubject<'static, PointerEvent, Infallible>,
    impl FnMut(&mut PointerEvent) -> Option<&mut PointerEvent>,
    &mut PointerEvent,
  > {
    self.x_times_tap_stream(2, MULTI_TAP_DURATION)
  }

  /// Return an observable stream of x-tap event that user tapped 'x' times in
  /// the specify duration `dur`.
  pub fn x_times_tap_stream(
    &self,
    x: usize,
    dur: Duration,
  ) -> FilterMapOp<
    MutRefItemSubject<'static, PointerEvent, Infallible>,
    impl FnMut(&mut PointerEvent) -> Option<&mut PointerEvent>,
    &mut PointerEvent,
  > {
    self.tap_steam().filter_map(x_times_tap_map_filter(x, dur))
  }
}

fn x_times_tap_map_filter(
  x: usize,
  dur: Duration,
) -> impl FnMut(&mut PointerEvent) -> Option<&mut PointerEvent> {
  assert!(x > 0);
  struct TapInfo {
    pointer_id: PointerId,
    stamps: Vec<Instant>,
  }

  let mut type_info: Option<TapInfo> = None;
  move |e: &mut PointerEvent| {
    let now = Instant::now();
    match &mut type_info {
      Some(info) if info.pointer_id == e.id => {
        if info.stamps.len() + 1 == x {
          if now.duration_since(info.stamps[0]) <= dur {
            // emit x-tap event and reset the tap info
            type_info = None;
            Some(e)
          } else {
            // remove the expired tap
            info.stamps.remove(0);
            info.stamps.push(now);
            None
          }
        } else {
          info.stamps.push(now);
          None
        }
      }
      _ => {
        type_info = Some(TapInfo { pointer_id: e.id, stamps: vec![now] });
        None
      }
    }
  }
}
impl EventListener for TapListener {
  type Event = PointerEvent;
  #[inline]
  fn dispatch(&self, event: &mut PointerEvent) { self.on_tap.clone().next(event) }
}

impl ComposeChild for TapListener {
  type Child = Widget;
  #[inline]
  fn compose_child(this: State<Self>, child: Self::Child) -> Widget {
    let widget = dynamic_compose_focus_node(child);
    compose_child_as_data_widget(widget, this)
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::test::MockBox;
  use futures::executor::LocalPool;
  use std::{cell::RefCell, rc::Rc};
  use winit::event::{DeviceId, ElementState, ModifiersState, MouseButton, WindowEvent};

  fn env(times: usize) -> (Window, Rc<RefCell<usize>>) {
    let size = Size::new(400., 400.);
    let count = Rc::new(RefCell::new(0));
    let c_count = count.clone();
    let w = widget! {
      MockBox {
        size,
        on_x_times_tap: (times, move |_| *c_count.borrow_mut() += 1)
      }
    };
    let mut wnd = Window::default_mock(w, Some(size));
    wnd.draw_frame();

    (wnd, count)
  }

  #[test]
  fn double_tap() {
    let (mut wnd, count) = env(2);

    let mut local_pool = LocalPool::new();
    let device_id = unsafe { DeviceId::dummy() };
    observable::interval(Duration::from_millis(10), local_pool.spawner())
      .take(8)
      .subscribe(move |i| {
        wnd.processes_native_event(WindowEvent::MouseInput {
          device_id,
          state: if i % 2 == 0 {
            ElementState::Pressed
          } else {
            ElementState::Released
          },
          button: MouseButton::Left,
          modifiers: ModifiersState::default(),
        });
      });

    local_pool.run();

    assert_eq!(*count.borrow(), 2);

    let (mut wnd, count) = env(2);
    observable::interval(Duration::from_millis(251), local_pool.spawner())
      .take(8)
      .subscribe(move |i| {
        wnd.processes_native_event(WindowEvent::MouseInput {
          device_id,
          state: if i % 2 == 0 {
            ElementState::Pressed
          } else {
            ElementState::Released
          },
          button: MouseButton::Left,
          modifiers: ModifiersState::default(),
        });
      });

    local_pool.run();
    assert_eq!(*count.borrow(), 0);
  }

  #[test]
  fn tripe_tap() {
    let (mut wnd, count) = env(3);

    let mut local_pool = LocalPool::new();
    let device_id = unsafe { DeviceId::dummy() };
    observable::interval(Duration::from_millis(10), local_pool.spawner())
      .take(12)
      .subscribe(move |i| {
        wnd.processes_native_event(WindowEvent::MouseInput {
          device_id,
          state: if i % 2 == 0 {
            ElementState::Pressed
          } else {
            ElementState::Released
          },
          button: MouseButton::Left,
          modifiers: ModifiersState::default(),
        });
      });

    local_pool.run();

    assert_eq!(*count.borrow(), 2);
  }
}