# ui/uiscene (vanilla-engine 0.4.0)

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

UI scene. (UIScene of the original ui/uiscene.js)
- A scene with the same common frame as GameScene (developer tools, touch routing, loading screen, safe area insets, view size change detection, canvas background fill).
- Holds its own LayoutSolver, and every tick attaches the solver to the UINodes in the tree (attach_pending_in_tree), solves once, then moves the values onto the nodes.
- Screen guide UINode (screen_node): top left fixed at (0, 0), width and height are edit variables corrected with suggest_value when the size changes. (UIKit's UIWindow.bounds)
- Safe area guide UINode (safe_area_layout_guide): inset from the screen guide by the safe area insets. It adjusts the insets by itself at layout.
  (UIKit's UIView.safeAreaLayoutGuide)
- In the Rust version, instead of inheritance, the scene holds a UISceneBase, implements the UIScene trait, then gets a Scene with one line of ui_scene!. (same form as GameScene, game_scene!)
  ```text
    struct MenuScene { ui_scene_base: UISceneBase }
    impl UIScene for MenuScene {
        fn get_ui_scene_base(&self) -> &UISceneBase { &self.ui_scene_base }
        fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase { &mut self.ui_scene_base }
        fn initialize(&mut self, engine: &Engine) { /* create nodes with UINode attached and add constraints with the get_safe_area_layout_guide anchors */ }
    }
    vanilla::ui_scene!(MenuScene);
  ```
- Differences from the original:
  - The original inherits Scene directly and carries the same code as GameScene separately. The Rust version holds the common frame as a GameSceneBase (without creating the safe area node)
    and adds only the solver and the two guides. So GameSceneBase's screen fade and play input can also be used. (not in the original UIScene)
  - The original creates the solver and guides in create. The Rust version does not need the engine, so it creates them at construction. The "apply the view size to the solver right away" at the end of the original load is done in initialize.
  - The safe area insets are LayoutMargins instead of a { top, left, bottom, right } object. Solver errors are returned as `Result<(), LayoutError>`.

## UISceneBase (struct) (Default)

Base of the UI scene.
- Holds a GameSceneBase and adds the solver, the screen guide and the safe area guide. A scene implementing UIScene holds it as a field.

Example: A header band attached to the safe area guide is placed on tick

```rust
use vanilla::{Engine, EngineConfiguration, SafeAreaInsets, UINode, UISceneBase, Vector2};

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(40.0, 0.0, 20.0, 10.0)));
let mut ui_scene_base = UISceneBase::new();
ui_scene_base.initialize(engine);

let guide_left = ui_scene_base.get_safe_area_layout_guide().left_anchor();
let guide_top = ui_scene_base.get_safe_area_layout_guide().top_anchor();
let guide_right = ui_scene_base.get_safe_area_layout_guide().right_anchor();
let node_tree = ui_scene_base.get_scene_base_mut().get_node_tree_mut();
let root_id = node_tree.get_root_id();
let bar_id = node_tree.create_child(root_id, "bar");
node_tree.add_component(bar_id, UINode::new());
node_tree.with_component_mut::<UINode, _>(bar_id, |bar, _tree| {
	bar.add_constraint(&bar.left_anchor().equal_to(guide_left.clone())).unwrap();
	bar.add_constraint(&bar.top_anchor().equal_to(guide_top.clone())).unwrap();
	bar.add_constraint(&bar.right_anchor().equal_to(guide_right.clone())).unwrap();
	bar.add_constraint(&bar.height_anchor().equal_to(50)).unwrap();
});

ui_scene_base.tick(0.016);
let bar_node = &ui_scene_base.get_scene_base().get_node_tree()[bar_id];
assert_eq!(bar_node.get_local_position(), Vector2::create(10.0, 40.0));
assert_eq!(bar_node.get_content_size(), Vector2::create(790.0, 50.0));
```

- `pub fn new() -> UISceneBase` (constructor, since 0.4.0): Constructor. (solver, screen guide, safe area guide. The insets default to 0, so both guides cover the same area)
  - returns UISceneBase: A new base. (the screen guide's top left is fixed at (0, 0), width and height are edit variables of strong strength)
- `pub fn get_game_scene_base(&self) -> &GameSceneBase` (method, since 0.4.0): Returns the common frame. (GameSceneBase features such as the loading screen, background color, fade)
  - returns &GameSceneBase: Reference to the held GameSceneBase.
- `pub fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase` (method, since 0.4.0): Returns the common frame. (for modification)
  - returns &mut GameSceneBase: Mutable reference to the held GameSceneBase.
- `pub fn get_scene_base(&self) -> &SceneBase` (method, since 0.4.0): Returns the common scene state.
  - returns &SceneBase: Reference to the scene common state (node tree, tweens, etc).
- `pub fn get_scene_base_mut(&mut self) -> &mut SceneBase` (method, since 0.4.0): Returns the common scene state. (mutable)
  - returns &mut SceneBase: Mutable reference to the scene common state.
- `pub fn set_view_scale_mode(&mut self, view_scale_mode: ViewScaleMode, engine: Option<&Engine>)` (method, since 0.4.0): Sets the ViewScaleMode. (applied right away if the engine is given, otherwise in initialize)
  - `view_scale_mode` ViewScaleMode: View scale mode.
  - `engine` Option<&Engine>: Engine to apply it to right away. If None, it is applied in initialize.
- `pub fn get_view_scale_mode(&self) -> ViewScaleMode` (method, since 0.4.0): Returns the current ViewScaleMode.
  - returns ViewScaleMode: Current ViewScaleMode. (default None)
- `pub fn set_loading_image_url(&mut self, url: &str)` (method, since 0.4.0): Sets the loading screen center image path. (before create)
  - `url` &str: Loading screen center image path. (if an empty string, only the gauge without an image)
- `pub fn set_loading_min_duration_ms(&mut self, milliseconds: f64)` (method, since 0.4.0): Sets the loading screen minimum display time. (milliseconds, before create)
  - `milliseconds` f64: Shortest time to show the loading screen. (milliseconds, default 3000)
- `pub fn set_scene_background_color(&mut self, color: impl Into<crate::base::color::Color>)` (method, since 0.4.0): Sets the canvas background color.
  - `color` impl Into<crate::base::color::Color>: Canvas background color. (a Color or text like "#rrggbb")
- `pub fn load(&mut self, engine: &Engine)` (method, since 0.4.0): Creation. (first thing in the scene's load, the front part of the original load + load_assets)
  - `engine` &Engine: Engine.
- `pub fn draw_on_load(&mut self, graphic: &mut Graphic)` (method, since 0.4.0): Draws the loading screen.
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn initialize(&mut self, engine: &Engine)` (method, since 0.4.0): Initialization. (ViewScaleMode, developer tools, and applying the current view size to the solver)
  - `engine` &Engine: Engine. (reads the view size and the safe area)
- `pub fn resize(&mut self, canvas_native_size: Vector2)` (method, since 0.4.0): Screen size changed. (solver layout after the common frame's layout)
  - `canvas_native_size` Vector2: The changed canvas size. (passed to the common frame, the solver layout reads the view manager's view size instead of this value)
- `pub fn layout(&mut self)` (method, since 0.4.0): Layout. (suggests the view size to the solver, rebuilds the guide constraints only when the safe area insets changed, solves, and moves the values onto the nodes)
- `pub fn tick(&mut self, time_delta: f64) -> bool` (method, since 0.4.0): Update. (common frame tick, layout if the view size changed, attaches the solver to new UINodes, solves, and moves the values onto the nodes. true if layout was redone)
  - `time_delta` f64: Time elapsed since the last frame. (seconds)
  - returns bool: true if the view size changed and layout was redone.
- `pub fn suggest_screen_size(&mut self, size: Vector2)` (method, since 0.4.0): Suggests the screen guide's width and height.
  - `size` Vector2: Width and height to give the screen guide. (view coordinates, solver errors are discarded. Node values change after solving)

  Example: Giving the screen size without an engine and reading the guide

  ```rust
  use vanilla::{UISceneBase, Vector2};
  
  let mut ui_scene_base = UISceneBase::new();
  ui_scene_base.suggest_screen_size(Vector2::create(1280.0, 720.0));
  ui_scene_base.get_solver().update_variables();
  assert!((ui_scene_base.get_screen_node().get_width() - 1280.0).abs() < 1e-6);
  assert!((ui_scene_base.get_safe_area_layout_guide().get_bottom() - 720.0).abs() < 1e-6);
  ```

- `pub fn get_safe_area_insets(&self) -> LayoutMargins` (method, since 0.4.0): Returns the safe area insets. (UIKit's UIView.safeAreaInsets)
  - returns LayoutMargins: Current safe area insets. (view coordinates, all 0 initially)
- `pub fn set_safe_area_insets(&mut self, insets: LayoutMargins) -> Result<(), LayoutError>` (method, since 0.4.0): Sets the safe area insets. (rebuilds the 4 guide constraints right away)
  - `insets` LayoutMargins: New insets. (view coordinates, changed back to the engine's value if they differ from what layout reads from the engine)
  - returns Result<(), LayoutError>: Ok(()). The LayoutError if removing or adding the guide constraints again fails.

  Example: Shrinking the guide with top 40, bottom 20 insets

  ```rust
  use vanilla::{LayoutMargins, UISceneBase, Vector2};
  
  let mut ui_scene_base = UISceneBase::new();
  ui_scene_base.suggest_screen_size(Vector2::create(400.0, 700.0));
  ui_scene_base.set_safe_area_insets(LayoutMargins::create(40.0, 0.0, 20.0, 0.0)).unwrap();
  ui_scene_base.get_solver().update_variables();
  let guide = ui_scene_base.get_safe_area_layout_guide();
  assert!((guide.get_top() - 40.0).abs() < 1e-6);
  assert!((guide.get_height() - 640.0).abs() < 1e-6);
  ```

- `pub fn rebuild_safe_area_layout_guide_constraints(&mut self) -> Result<(), LayoutError>` (method, since 0.4.0): Rebuilds the 4 safe area guide constraints. (removes the old constraints, builds them with the current insets and adds them again)
  - returns Result<(), LayoutError>: Ok(()). The LayoutError if removing the old constraints from the solver or adding the new ones fails.
- `pub fn get_dev_tools(&self) -> Option<&DevTools>` (method, since 0.4.0): Returns the developer tools. (the original UIScene.getDevTools, None before initialize or if EngineConfiguration::use_dev_tools is off)
  - returns Option<&DevTools>: Developer tools. None before initialize or when turned off.

  Example: A base without developer tools turned on

  ```rust
  use vanilla::UISceneBase;
  
  let ui_scene_base = UISceneBase::new();
  assert!(ui_scene_base.get_dev_tools().is_none());
  ```

- `pub fn get_dev_tools_mut(&mut self) -> Option<&mut DevTools>` (method, since 0.4.0): Returns the developer tools. (mutable)
  - returns Option<&mut DevTools>: Developer tools. (mutable) None before initialize or when turned off.
- `pub fn is_dev_tools_capturing_input(&self) -> bool` (method, since 0.4.0): Whether the developer tools are taking the input.
  - returns bool: true if the developer tools are visible and the press position is inside their panel. (false if the developer tools are off)
- `pub fn pre_draw(&self, graphic: &mut Graphic)` (method, since 0.4.0): Pre-draw. (the whole canvas in the background color, including outside the safe area)
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn post_draw(&mut self, graphic: &mut Graphic)` (method, since 0.4.0): Post-draw. (the developer tools over the screen)
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn get_solver(&self) -> &LayoutSolver` (method, since 0.4.0): Returns the solver. (a cheap handle, so clones are the same solver)
  - returns &LayoutSolver: Reference to the scene solver.
- `pub fn get_screen_node(&self) -> &UINode` (method, since 0.4.0): Returns the screen guide UINode. (not in the tree. left, top are 0, width, height are the view size)
  - returns &UINode: Reference to the screen guide UINode.
- `pub fn get_safe_area_layout_guide(&self) -> &UINode` (method, since 0.4.0): Returns the safe area guide UINode. (inset from the screen guide by the insets)
  - returns &UINode: Reference to the safe area guide UINode. (its anchors are read and used in node constraints)

## UIScene (trait) ('static)

UI scene. (the points that scenes inheriting the original UIScene override, same rules as GameScene)
- The Scene functions made by ui_scene! call the base (UISceneBase) first, then the function of the same name in this trait. Only post_draw calls the scene's first.

Example: A scene that places a title box at the top left inside the safe area

```rust
use vanilla::{Engine, EngineConfiguration, UINode, UIScene, UISceneBase};

struct MenuScene {
	ui_scene_base: UISceneBase,
}

impl UIScene for MenuScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let guide_left = self.ui_scene_base.get_safe_area_layout_guide().left_anchor();
		let guide_top = self.ui_scene_base.get_safe_area_layout_guide().top_anchor();
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();
		let title_id = node_tree.create_child(root_id, "title");
		node_tree.add_component(title_id, UINode::new());
		node_tree.with_component_mut::<UINode, _>(title_id, |title, _tree| {
			title.add_constraint(&title.left_anchor().equal_to(guide_left.add(16))).unwrap();
			title.add_constraint(&title.top_anchor().equal_to(guide_top.add(16))).unwrap();
			title.add_constraint(&title.width_anchor().equal_to(320)).unwrap();
			title.add_constraint(&title.height_anchor().equal_to(48)).unwrap();
		});
	}
}

vanilla::ui_scene!(MenuScene);

fn main() {
	let engine = Engine::new(EngineConfiguration::new());
	let menu_scene = MenuScene {
		ui_scene_base: UISceneBase::new(),
	};
	if let Err(error) = engine.run(Box::new(menu_scene)) {
		eprintln!("{}", error);
	}
}
```

- `fn get_ui_scene_base(&self) -> &UISceneBase` (method, since 0.4.0): Returns the base.
  - returns &UISceneBase: Reference to the UISceneBase the scene holds.
- `fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase` (method, since 0.4.0): Returns the base. (mutable)
  - returns &mut UISceneBase: Mutable reference to the UISceneBase the scene holds.
- `fn load_assets(&mut self)` (method, since 0.4.0): Loads the scene's assets. (overrides the original async loadAssets())
  - Take the engine with Engine::get_engine(). To load with await, hand the loading job to engine.spawn_scene_task(self, ...) and hand it to the scene common state's track_task.
- `fn draw_on_load(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Draws more on top of the loading screen.
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn initialize(&mut self, _engine: &Engine)` (method, since 0.4.0): Initialization. (after the base initialize)
  - `_engine` &Engine: Engine.
- `fn destroy(&mut self)` (method, since 0.4.0): Destroys.
- `fn layout(&mut self)` (method, since 0.4.0): Layout. (after the base does the solver layout)
- `fn tick(&mut self, _time_delta: f64)` (method, since 0.4.0): Update. (after the base tick)
  - `_time_delta` f64: Time elapsed since the last frame. (seconds)
- `fn pre_draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Pre-draw. (after the base)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Draw. (after drawing the node tree)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn post_draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Post-draw. (before the base's developer tools)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn finalize(&mut self, _engine: &Engine)` (method, since 0.4.0): Finalizes. (before unload when taking down, overrides the original Scene.finalize)
  - `_engine` &Engine: Engine.
- `fn unload(&mut self, _engine: &Engine)` (method, since 0.4.0): Unloads. (after finalize when taking down, overrides the original Scene.unload)
  - `_engine` &Engine: Engine.
- `fn on_page_process_restored(&mut self)` (method, since 0.4.0): Page process restore and visibility restore. (overrides the original onPageProcessRestored, onPageVisibilityRestored)
- `fn on_page_visibility_restored(&mut self)` (method, since 0.4.0): Page visibility restored. (overrides the original onPageVisibilityRestored)
- `fn touch_press(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch hooks of the scene. (overrides the original touchPress, touchMove, touchRelease, touchCancel, touchWheel, called by the engine after the base passes them to the UI and play input)
  - `_view_input_position` Vector2: Press position. (view coordinates)
- `fn touch_move(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch move. (when moved while held down, excluding the press frame)
  - `_view_input_position` Vector2: Current position. (view coordinates)
- `fn touch_release(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch release. (right after press if pressed and released within one frame)
  - `_view_input_position` Vector2: Release position. (view coordinates)
- `fn touch_cancel(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch cancelled.
  - `_view_input_position` Vector2: Last position. (view coordinates)
- `fn touch_wheel(&mut self, _view_input_position: Vector2, _wheel_delta: Vector2)` (method, since 0.4.0): Mouse wheel. (when there is wheel accumulated this frame)
  - `_view_input_position` Vector2: Pointer position. (view coordinates)
  - `_wheel_delta` Vector2: Wheel movement accumulated this frame. (pixels, x is positive to the right, y is positive when scrolling the content down)

## Functions and constants

- `macro_rules! ui_scene` (method, since 0.4.0): Makes a Scene for a scene implementing UIScene. (vanilla::ui_scene!(MenuScene);)
