# ui/touchrecognizer (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/ui/touchrecognizer/

Touch recognizer. (TouchRecognizer of the original ui/touchrecognizer.js)
- If a UIScrollView (or UISnapScrollView) is up the pressed node's parent chain, once the drag distance exceeds the threshold (10px), cancels the press on the pressed node and
  hands the scroll over by resending press → move to the scroll view from the initial press point. (dragging a button inside a scroll view still scrolls)
- If there is a scroll view among the parents, the press to the pressed node is delayed by 150ms. If it becomes a drag in the meantime, the press itself is never sent.
  A short tap sends the delayed press right away on release, followed by the release. (UIKit's delaysContentTouches)
- If the scroll view has set_passes_cross_axis_drag(true), a finger dragged more along the non-scrolling axis is not handed over.
- Differences from the original:
  - The original GameScene always uses it. The Rust version's SceneBase::tick_touch is the original TouchRaycaster (sends straight to the topmost node).
  ```text
    A scene that needs this gesture holds a TouchRecognizer and, instead of SceneBase::tick, calls the node update and this:
      self.scene_base.get_node_tree_mut().tick(engine, time_delta);
      self.touch_recognizer.tick_touch(self.scene_base.get_node_tree_mut(), engine);
    In that case SceneBase's first touch callback and get_touch_target are not used. (use this one's get_touch_target)
  ```
  - The original setTimeout(150ms) is counted by accumulating frame intervals (time not multiplied by the scale).
  - Touches handed to a scroll view go to all components of that node. (NodeTree::dispatch_touch)
  - tick_touch is split into wheel (tick_wheel) and press (tick_pointer). A scene that routes the wheel elsewhere (a window layer) calls mark_wheel_handled instead of tick_wheel. (GameSceneBase)

## TouchRecognizer (struct) (Default)

Touch recognizer.

Example: Hand touches over after the node update in a scene

```rust
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, TouchRecognizer};

struct MainScene {
	scene_base: SceneBase,
	touch_recognizer: TouchRecognizer,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn tick(&mut self, time_delta: f64) {
		let engine = Engine::get_engine().unwrap();
		self.scene_base.get_node_tree_mut().tick(engine, time_delta);
		self.touch_recognizer.tick_touch(self.scene_base.get_node_tree_mut(), engine);
		self.scene_base.tick_tweens(time_delta);
	}
}

fn main() {
	let engine = Engine::new(EngineConfiguration::new());
	let main_scene = MainScene {
		scene_base: SceneBase::new(),
		touch_recognizer: TouchRecognizer::new(),
	};
	if let Err(error) = engine.run(Box::new(main_scene)) {
		eprintln!("{}", error);
	}
}
```

- `pub fn new() -> TouchRecognizer` (constructor, since 0.3.2): Constructor.
  - returns TouchRecognizer: New recognizer with nothing pressed.
- `pub fn is_wheel_handled(&self) -> bool` (method, since 0.4.0): Whether a component (scroll area, etc.) consumed this frame's wheel. (read after tick_touch)
  - returns bool: true if a component consumed it or mark_wheel_handled was called.
- `pub fn get_touch_target(&self) -> Option<NodeId>` (method, since 0.3.2): Node currently receiving the press. (the scroll view node if the drag was handed over)
  - returns Option<NodeId>: Node receiving the press. None if not pressing or there is no pressable node at the press point.
- `pub fn is_touching(&self) -> bool` (method, since 0.3.2): Whether it is being held down. (From press until release or cancel)
  - returns bool: true if pressing. (true even if there is no node at the press point)
- `pub fn tick_touch(&mut self, node_tree: &mut NodeTree, engine: &Engine)` (method, since 0.3.2): Touch update. (in place of SceneBase::tick_touch. wheel → delayed press → press / move / release / cancel)
  - `node_tree` &mut NodeTree: Node tree to send touches to.
  - `engine` &Engine: Engine that reads input and time and is passed to components.
- `pub fn tick_wheel(&mut self, node_tree: &mut NodeTree, engine: &Engine) -> bool` (method, since 0.4.0): Wheel update. (regardless of pressing, from the frontmost scroll area or pressable node at that point toward its parents, NodeTree::dispatch_wheel_at, true if consumed)
  - `node_tree` &mut NodeTree: Node tree to send the wheel to.
  - `engine` &Engine: Engine to read the input position and wheel amount from.
  - returns bool: true if a component at that point consumed the wheel. (false if there is no wheel this frame)
- `pub fn mark_wheel_handled(&mut self)` (method, since 0.4.0): Marks this frame's wheel as consumed by another route (like a window layer). (called instead of tick_wheel)
- `pub fn tick_pointer(&mut self, node_tree: &mut NodeTree, engine: &Engine)` (method, since 0.4.0): Press update. (delayed press → press / move / release / cancel)
  - `node_tree` &mut NodeTree: Node tree to send touches to.
  - `engine` &Engine: Engine that reads input and time and is passed to components. (the delayed press is counted with frame intervals not multiplied by the scale)
- `pub fn update_press_delay(&mut self, node_tree: &mut NodeTree, engine: &Engine, elapsed_seconds: f64)` (method, since 0.3.2): Reduces the remaining time of the delayed press, and when it runs out sends the press to the pressed node. (in place of the original setTimeout)
  - Not sent if it turned into a drag in the meantime. Does nothing if there is no delayed press.
  - `node_tree` &mut NodeTree: Node tree to send the press to.
  - `engine` &Engine: Engine passed to components.
  - `elapsed_seconds` f64: Elapsed time. (seconds, the delay is 0.15 seconds)
- `pub fn touch_press(&mut self, node_tree: &mut NodeTree, engine: &Engine, view_input_position: Vector2)` (method, since 0.3.2): Touch press. (finds the hit node and the scroll view among its parents, and delays the press if there is a scroll view)
  - Without a scroll view, sends the press to the hit node right away.
  - `node_tree` &mut NodeTree: Node tree to find the hit node in and send the press to.
  - `engine` &Engine: Engine passed to components.
  - `view_input_position` Vector2: Press position. (view coordinates)
- `pub fn touch_move(&mut self, node_tree: &mut NodeTree, engine: &Engine, view_input_position: Vector2)` (method, since 0.3.2): Touch move.
  - If the drag was handed over, sends only to the scroll view.
  - If there is a scroll view and the threshold is exceeded, hands over: discards the delayed press (cancels the pressed node if already sent), then sends press (initial point) → move to the scroll view.
  - Otherwise, sends the move to the pressed node. (if the press has not been sent yet, the move is not sent either)
  - In a scroll view with set_passes_cross_axis_drag(true), a finger dragged more along the non-scrolling axis is not handed over, and a delayed press, if any, is sent right away.
  - `node_tree` &mut NodeTree: Node tree to send the move to.
  - `engine` &Engine: Engine passed to components.
  - `view_input_position` Vector2: Finger position. (view coordinates, treated as a drag once it moves more than 10 horizontally or vertically from the initial press point)

  Example: Drag on a button inside a scroll area to hand it over to the scroll area

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchRecognizer, UIButton, UIScrollView, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let scroll_id = node_tree.create_child(root_id, "Scroll");
  node_tree[scroll_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[scroll_id].set_content_size(Vector2::create(200.0, 100.0));
  let scroll_view = node_tree.add_component(scroll_id, UIScrollView::new()).expect("scroll view");
  scroll_view.set_scroll_content_size(Vector2::create(200.0, 400.0));
  let content_id = scroll_view.get_content().expect("content");
  let button_id = node_tree.create_child(content_id, "Row");
  node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[button_id].set_content_size(Vector2::create(200.0, 40.0));
  node_tree[button_id].add_component(Paint::new());
  let click_count = Rc::new(Cell::new(0));
  let click_count_for_event = click_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	click_count_for_event.set(click_count_for_event.get() + 1);
  }));
  
  let mut touch_recognizer = TouchRecognizer::new();
  touch_recognizer.touch_press(&mut node_tree, &engine, Vector2::create(50.0, 30.0));
  touch_recognizer.update_press_delay(&mut node_tree, &engine, 0.2);
  touch_recognizer.touch_move(&mut node_tree, &engine, Vector2::create(50.0, 0.0));
  assert_eq!(touch_recognizer.get_touch_target(), Some(scroll_id));
  node_tree.tick(&engine, 0.016);
  let scroll_offset = node_tree[scroll_id].get_component::<UIScrollView>().expect("scroll view").get_scroll_offset();
  assert_eq!(scroll_offset, Vector2::create(0.0, -30.0));
  touch_recognizer.touch_release(&mut node_tree, &engine, Vector2::create(50.0, 0.0));
  assert_eq!(click_count.get(), 0);
  ```

- `pub fn touch_release(&mut self, node_tree: &mut NodeTree, engine: &Engine, view_input_position: Vector2)` (method, since 0.3.2): Touch release. (to the scroll view if dragging, otherwise to the pressed node. If a delayed press remains, sends it first)
  - Clears the tracking state after sending.
  - `node_tree` &mut NodeTree: Node tree to send the release to.
  - `engine` &Engine: Engine passed to components.
  - `view_input_position` Vector2: Release position. (view coordinates)

  Example: Quickly tap a button inside a scroll area

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchRecognizer, UIButton, UIScrollView, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let scroll_id = node_tree.create_child(root_id, "Scroll");
  node_tree[scroll_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[scroll_id].set_content_size(Vector2::create(200.0, 100.0));
  let scroll_view = node_tree.add_component(scroll_id, UIScrollView::new()).expect("scroll view");
  scroll_view.set_scroll_content_size(Vector2::create(200.0, 400.0));
  let content_id = scroll_view.get_content().expect("content");
  let button_id = node_tree.create_child(content_id, "Row");
  node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[button_id].set_content_size(Vector2::create(200.0, 40.0));
  node_tree[button_id].add_component(Paint::new());
  let click_count = Rc::new(Cell::new(0));
  let click_count_for_event = click_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	click_count_for_event.set(click_count_for_event.get() + 1);
  }));
  
  let mut touch_recognizer = TouchRecognizer::new();
  let tap_position = Vector2::create(50.0, 20.0);
  touch_recognizer.touch_press(&mut node_tree, &engine, tap_position);
  assert_eq!(touch_recognizer.find_ancestor_scroll_view(&node_tree, Some(button_id)), Some(scroll_id));
  assert_eq!(touch_recognizer.get_touch_target(), Some(button_id));
  touch_recognizer.touch_release(&mut node_tree, &engine, tap_position);
  assert_eq!(click_count.get(), 1);
  assert!(!touch_recognizer.is_touching());
  ```

- `pub fn touch_cancel(&mut self, node_tree: &mut NodeTree, engine: &Engine, view_input_position: Vector2)` (method, since 0.3.2): Touch cancel. (if a delayed press remains, no cancel is sent to the pressed node)
  - Clears the tracking state after sending.
  - `node_tree` &mut NodeTree: Node tree to send the cancel to.
  - `engine` &Engine: Engine passed to components.
  - `view_input_position` Vector2: Canceled position. (view coordinates)
- `pub fn reset(&mut self)` (method, since 0.3.2): Clears the tracking state.
- `pub fn find_ancestor_scroll_view(&self, node_tree: &NodeTree, target_id: Option<NodeId>) -> Option<NodeId>` (method, since 0.3.2): The nearest node up the node's parent chain with a UIScrollView (or UISnapScrollView) attached. (None if none)
  - If the pressed node is a scroll bar, the scroll view it controls is skipped. (a scroll bar drag must not be handed to that scroll view)
  - `node_tree` &NodeTree: Node tree to search.
  - `target_id` Option<NodeId>: Pressed node. (starts from the parent, not itself)
  - returns Option<NodeId>: Nearest scroll view node. None if target_id is None or nothing is found.
