# platform/desktop (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/platform/desktop/

Desktop platform. (Windows, Mac, Linux)
- Creates the window (winit) and a GL 3.3 core context (glutin), and runs one engine frame per window redraw request.
- Converts window events into the input manager's form. (keys use the same names as W3C KeyboardEvent.code, any mouse button is a touch as in the original, can be changed to left only)
- The engine core (EngineRunner) does not know about the window. Frames are called here, and the screen is presented after drawing.
- Text input (key characters, editing keys, IME composition) and the clipboard are handled by desktop/textinput.rs. The right button is a context menu request for input fields.
- Gamepad vibration on Mac is handled by desktop/gamepadhaptics.rs. (GameController and CoreHaptics, on other OSes gilrs vibrates)
- The last used device is recorded on every key, mouse and finger event. Keys to prevent (set_prevented_keys) and blocking the right-click menu are not used, since a window has no browser default actions to block.
  (same result as blocking them in Chrome. On Windows winit does not pass WM_SYSKEYUP of a menuless window to DefWindowProc, so Alt and F10 do not enter the system menu either)
- Page events: the window is occluded (Occluded, reported by Mac and X11), minimized (size 0 or is_minimized, which is how Windows reports it), the app is suspended (suspended, mobile),
  the Wayland frame callback has not come for over 3 seconds (occlusion on Chrome Linux Wayland, desktop/waylandframecallback.rs)
  If any one of these holds, Hidden; once all clear, Visible and on_page_visibility_restored. Focus is Focused / Blurred, mouse button and finger presses are PointerDown.
  Wayland's xdg_toplevel suspended state is held by winit and not reported, so it cannot be received.
- Wayland vertical sync: sets the EGL swap interval to 0 and waits up to 1/20 second for the previous frame callback before presenting. (with interval 1, Mesa stalls inside the swap on an occluded window)
- Canvas size (auto_resize_on_window_resize): the window is like a page whose canvas fills the window. When on, it fits visualViewport (the window minus the bottom covered by the on-screen keyboard) as in the original
  and applies ignore_virtual_keyboard_resize and the canvas aspect ratio limit. When off, it is the window size as is.
- On-screen keyboard: on Windows, like Chrome, focusing a platform input field with a finger shows the touch keyboard (InputPane) and removes the covered area from visualViewport. (desktop/windowsinputpane.rs)
  Mac and Linux do not shrink the viewport, like Chrome.
- Preserving the drawing buffer (preserve_drawing_buffer): captures the finished frame and redraws it at the start of the next frame. (desktop/preserveddrawingbuffer.rs)
- Page process restore (on_page_process_restored, the original resume after a Chromium freeze and bfcache): resumed after suspended, and waking from system sleep.
  Windows subclasses the window to receive PBT_APMRESUMEAUTOMATIC of WM_POWERBROADCAST. (desktop/windowsplatform.rs, the Windows monotonic clock keeps running during sleep so the clock cannot tell)
  Mac and Linux treat it as woken if between two frames the wall clock (SystemTime) advanced more than SYSTEM_SLEEP_GAP_SECONDS beyond the monotonic clock (Instant).
  (Rust Instant is CLOCK_UPTIME_RAW on Mac and CLOCK_MONOTONIC on Linux, so it stops during sleep. Rust notes that it does not guarantee this)
- Whether the primary input is a finger (is_coarse_pointer): Windows ports Chromium's (pointer: coarse) check and is true in tablet mode or on a touch device without a mouse.
  Mac is false, since Chromium always treats it as a mouse too. Linux and other Unixes, like Chromium, read touchscreens and
  mice and touchpads from the display server (Wayland wl_seat capabilities, X11 XInput device list) and are true if there is only a touchscreen. (desktop/linuxplatform.rs, the value read is used for 2 seconds)
- Key names: winit's SuperLeft, SuperRight become W3C's MetaLeft, MetaRight, and winit's Meta becomes W3C's Super.
- Image cursors (PointerCursor.register_image_cursor): reads the image file and makes a winit CustomCursor. On Mac the image size is the point size as is, so the 1x image is used;
  Windows and Linux use physical pixels, so the image and hotspot are scaled to the window scale (using the 2x image if present). While creating, or if creation fails, the CSS cursor given with it is used.
- Render scale upper limit (ViewManager.set_max_render_pixel_ratio): draws at the size reduced to that scale and stretches to the window size at the end of the frame. (desktop/renderscaler.rs)
  Input coordinates are converted to logical coordinates with the window's scale, so they do not depend on the render size.
- Canvas aspect ratio limit (EngineConfiguration.max_canvas_aspect_ratio): if the window is more elongated than that, the canvas (drawing area) is shrunk as in the original and centered in the window, and the rest is black.
  The canvas top-left is subtracted from input coordinates, and read_canvas_client_position returns that position.
- Query values of the page address (read_page_query_value) are read from the environment variable VANILLA_ followed by the name in upper snake case. (safeArea → VANILLA_SAFE_AREA)
- Capture mode (VANILLA_CAPTURE_PATH) runs with the window hidden. A hidden window has no redraw requests or vertical sync, so frames run right away in about_to_wait and pace themselves to the refresh rate.
  Occlusion notifications are not received. On Mac it does not take the Dock icon or focus either. To see the window, VANILLA_CAPTURE_SHOW_WINDOW=1.

Example: Read page query values, safe area and primary input (on desktop: environment variables, 0, no page)

```rust
use vanilla::platform;

let quality = platform::read_page_query_value("quality").unwrap_or_else(|| String::from("high"));
let safe_area_insets = platform::read_safe_area_insets();
let is_touch_first = platform::is_coarse_pointer();
println!("{} {:?} {}", quality, safe_area_insets, is_touch_first);
assert_eq!(safe_area_insets, [0.0, 0.0, 0.0, 0.0]);
assert_eq!(platform::read_client_native_size(), None);
assert!(!platform::is_text_field_focused());
```

## PlatformWindow (type)

Window handle held by the engine. (for changing the cursor and title)

```rust
pub type PlatformWindow = Rc<Window>
```

## Functions and constants

- `pub fn run(engine_runner: EngineRunner) -> Result<(), String>` (method, since 0.3.2): Starts. (does not return until the window is closed or exit_application is called)
  - `engine_runner` EngineRunner: Engine runner. (Engine::run makes it with the engine and the first scene and passes it)
  - returns Result<(), String>: Ok when the window closes and the event loop ends. Err(reason text) if the event loop could not be created or run, or creating the window or GL context failed.
- `pub fn set_cursor_visible(platform_window: Option<&PlatformWindow>, is_visible: bool)` (method, since 0.3.2): Sets cursor visibility.
  - `platform_window` Option<&PlatformWindow>: Window handle. (does nothing if None)
  - `is_visible` bool: true to show it.
- `pub fn set_cursor(platform_window: Option<&PlatformWindow>, cursor_value: &CursorValue)` (method, since 0.4.0): Sets the cursor shape. (CSS cursor name to a winit cursor icon, hidden if none, unknown names are the default arrow)
  - For an image cursor, sets the one already made if there is one. If not yet, asks the event loop to make it and uses the CSS cursor given with it in the meantime.
  - `platform_window` Option<&PlatformWindow>: Window handle. (does nothing if None)
  - `cursor_value` &CursorValue: Cursor value. (an image cursor if image_url is present, otherwise the CSS cursor name in fallback_name)
- `pub fn is_coarse_pointer() -> bool` (method, since 0.4.0): Whether the primary input is a finger. (Windows, like Chromium, is true in tablet mode or on a touch device without a mouse, Linux, like Chromium, is true if there is only a touchscreen without a mouse or touchpad, Mac treats the mouse as the primary input)
  - returns bool: true if the primary pointer is a finger. (always false on Mac)
- `pub fn is_text_field_focused() -> bool` (method, since 0.4.0): Whether the document's focus is on a text input. (desktop has no document so always false, the input manager checks engine input fields separately)
  - returns bool: Always false.
- `pub fn read_page_query_value(name: &str) -> Option<String>` (method, since 0.4.0): Query value of the page address. (desktop has no address, so it reads the environment variable VANILLA_ followed by the name in upper snake case, None if missing)
  - safeArea → VANILLA_SAFE_AREA, quality → VANILLA_QUALITY
  - `name` &str: Query name. (camel case, such as safeArea)
  - returns Option<String>: Value of that environment variable. None if missing or not Unicode.
- `pub fn read_canvas_client_position() -> Vector2` (method, since 0.4.0): Top-left of the canvas in screen (client) coordinates. (on desktop the window's logical coordinates are client coordinates, nonzero only when centered by the canvas aspect ratio limit)
  - returns Vector2: Top-left position of the canvas inside the window. (logical pixels, initially 0, 0)
- `pub fn save_capture_file(output_path: &str, png_bytes: &[u8]) -> Result<(), String>` (method, since 0.4.0): Saves the screen for verification. (writes it to a file)
  - `output_path` &str: File path to write. (VANILLA_CAPTURE_PATH, overwritten if it exists)
  - `png_bytes` &[u8]: PNG file bytes.
  - returns Result<(), String>: Ok if written. Err(I/O error text) if the file could not be written.
- `pub fn read_client_native_size() -> Option<Vector2>` (method, since 0.4.0): Full page size. (the original window.innerWidth, innerHeight, None on desktop since there is no page, and ViewManager uses the window's inner size)
  - returns Option<Vector2>: Always None.
- `pub fn read_safe_area_insets() -> [f64; 4]` (method, since 0.4.0): CSS env(safe-area-inset-*) safe area insets. (0 on desktop)
  - Chrome desktop is 0 too. Nonzero insets only come in through WebContentsImpl::SetDisplayCutoutSafeArea, and this function is inside #if BUILDFLAG(IS_ANDROID)
    and only Android (web_contents_android.cc) calls it. Elsewhere it is the Blink default "0px". (style_environment_variables.cc, the same for full screen on a MacBook with a notch)
  - returns [f64; 4]: Always [0, 0, 0, 0]. (same order as web: top, right, bottom, left)
- `pub fn read_heap_usage() -> Option<(f64, f64)>` (method, since 0.4.0): Heap usage. (bytes, (in use, reserved), None if it cannot be read. The memory pane of the developer tools, in place of usedJSHeapSize, totalJSHeapSize of the original performance.memory)
  - Desktop has no JavaScript heap, so it reads the heap of the system allocator Rust uses. (the Rust System allocator is malloc on Mac and Linux, HeapAlloc on the process heap on Windows)
  - Mac: size_in_use, size_allocated of malloc_zone_statistics (all zones).
  - Windows: cbAllocated, cbCommitted of HeapSummary of the process heap.
  - Linux (glibc): uordblks + hblkhd of mallinfo2 (in use, including large blocks reserved with mmap), arena + hblkhd (reserved). Available from glibc 2.33, so it is looked up at run time, and None if missing.
  - Other OSes are None.
  - returns Option<(f64, f64)>: (bytes in use, bytes reserved). None if HeapSummary failed on Windows, mallinfo2 is missing on Linux, or on other OSes.

  Example: Print heap usage in megabytes

  ```rust
  use vanilla::platform::desktop::read_heap_usage;
  
  if let Some((used_bytes, reserved_bytes)) = read_heap_usage() {
  	assert!(used_bytes > 0.0);
  	println!("{:.1} / {:.1} MB", used_bytes / 1048576.0, reserved_bytes / 1048576.0);
  }
  ```

- `pub fn read_heap_size_limit() -> Option<f64>` (method, since 0.4.0): Heap limit. (Bytes, the upper bound the heap can grow to, None if it cannot be read. The developer tools memory field, where the original has jsHeapSizeLimit of performance.memory)
  - The desktop has no JavaScript heap limit, so it reads the upper bound the operating system allows for this process's heap.
  - macOS, Linux: the process data segment limit (rlim_cur of getrlimit RLIMIT_DATA) if one is set, otherwise (infinite) the physical memory size.
    (macOS uses sysctl hw.memsize, Linux uses _SC_PHYS_PAGES times _SC_PAGESIZE from sysconf)
  - Windows: the smaller of the physical memory size (ullTotalPhys) and the virtual address size this process can use (ullTotalVirtual) from GlobalMemoryStatusEx.
  - Other OSes give None.
  - returns Option<f64>: Heap limit in bytes. None if the operating system function failed or on other OSes.

  Example: Printing the heap limit in megabytes

  ```rust
  use vanilla::platform::desktop::read_heap_size_limit;
  
  if let Some(limit_bytes) = read_heap_size_limit() {
  	assert!(limit_bytes > 0.0);
  	println!("{:.1} MB", limit_bytes / 1048576.0);
  }
  ```

- `pub fn exit_application()` (method, since 0.4.0): Exits the application. (on desktop the event loop ends on seeing the engine's exit request, so there is nothing else to do)
- `pub fn open_url(url: &str) -> bool` (method, since 0.4.0): Opens an outside URL. (original Engine.openUrl, opens with the OS default program)
  - macOS uses `open`, which goes through LaunchServices; Windows uses ShellExecuteW; other Unix uses xdg-open.
  - Only http, https, mailto and tel can be opened. (is_openable_url) Other forms are not opened and return false.
  - `url` &str: URL to open. (http, https, mailto or tel)
  - returns bool: True if the open was handed to the OS.
- `pub fn read_local_time(minute_offset: f64) -> crate::platform::LocalTime` (method, since 0.4.0): Read the local time. (same as the original Engine.readLocalTime, the calendar time of now plus a minute offset in this machine's time zone)
  - Mac and Linux use localtime_r, Windows uses SystemTimeToTzSpecificLocalTime. Daylight saving time at the shifted moment is applied. (same as the original's new Date(Date.now() + offset))
  - `minute_offset` f64: Minutes to add to now. (negative is the past, 0 is now)
  - returns crate::platform::LocalTime: The calendar time of the shifted moment in this machine's time zone.
- `pub fn set_title(platform_window: Option<&PlatformWindow>, title: &str)` (method, since 0.3.2): Sets the window title.
  - `platform_window` Option<&PlatformWindow>: Window handle. (does nothing if None)
  - `title` &str: Title text.
- `pub fn request_asset_bytes(asset_location: String, load_handle: AssetLoadHandle, _is_no_cache: bool)` (method, since 0.3.2): Reads asset bytes. (reads the file on the spot and finishes. It always reads anew without an engine cache, so it is the current content like a web fetch with is_no_cache on. Files read are recorded in resource usage)
  - `asset_location` String: File path to read. (made from the asset path by the engine)
  - `load_handle` AssetLoadHandle: Handle to finish with the bytes or error text once read.
  - `_is_no_cache` bool: Whether to read bypassing the cache. (desktop always bypasses it, so ignoring it is the same)
