# platform/web (vanilla-engine 0.4.0)

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

웹 플랫폼. (wasm32)
- 원본처럼 캔버스를 창 안쪽에 꽉 채우고, 원본과 같은 옵션으로 WebGL2 컨텍스트를 얻는다.
- request_animation_frame 콜백마다 엔진 프레임 하나. (브라우저가 수직 동기에 맞춰 부르고, 콜백이 끝나면 화면을 넘긴다)
- 키보드, 마우스, 손가락을 받는다. 입력 필드의 글 입력(숨긴 DOM <input>, IME 조합, 문맥 메뉴)과 클립보드는 web/textinput.rs 가 맡는다.
- 키를 누르면 입력 매니저의 막을 키(set_prevented_keys)면 글자 입력칸에 쓰는 중이 아닐 때 기본 동작을 막는다. 마지막으로 쓴 장치를 키, 마우스, 손가락 사건마다 적는다.
- 오디오: 원본 engine.js 처럼 click / touchstart / keydown(설정하면 touchend / pointerup 도)은 user gesture 로 보고
  engine.resume_on_user_gesture(), focus 와 페이지가 다시 보일 때는 engine.resume() 을 부른다.
- 페이지: visibilitychange, blur, focus, pointerdown 을 엔진의 페이지 이벤트로 넘기고, 다시 보이면 on_page_visibility_restored,
  문서 resume 과 pageshow(persisted) 면 on_page_process_restored 를 부른다. (원본 setupAllDocumentEvents)
- 최대 FPS 는 원본처럼 세기 시작한 뒤 처리한 프레임 수로 차례를 정한다. (platform/framelimiter.rs, 90 Hz 에서 60 FPS 도 평균 60)
- 캔버스의 webglcontextlost, webglcontextrestored 에서 원본 WebGLStateCache 처럼 GL 상태 기억을 잊는다.
- 키, 마우스, 손가락, 페이지 사건은 프레임 콜백 안에서 다시 들어와도(게임 코드의 dispatchEvent, focus() 같은 것) 겹쳐 빌리지 않는다.
  바로 빌릴 수 있으면 그 자리에서 처리하고, 못 빌리면 줄에 쌓았다가 프레임 콜백 끝에 온 차례대로 처리한다. (platform/eventqueue.rs)
- exit_application: 원본처럼 Capacitor 의 App.exitApp, 없으면 window.close 를 시도한다.

예제: 페이지 쿼리 값, 세이프 에어리어, 주된 손 읽기 (데스크탑과 같은 이름으로 부른다)

```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);
```

## PlatformWindow (type)

엔진이 들고 있는 창 손잡이. (커서를 바꿀 때)

```rust
pub type PlatformWindow = web_sys::HtmlCanvasElement
```

## Functions and constants

- `pub fn set_cursor_visible(platform_window: Option<&PlatformWindow>, is_visible: bool)` (method, since 0.3.2): 커서 보이기 설정.
  - 캔버스의 cursor 스타일을 감출 때 none, 보일 때 빈 값(브라우저 기본)으로 쓴다.
  - `platform_window` Option<&PlatformWindow>: 엔진 캔버스. (None 이면 아무것도 하지 않는다)
  - `is_visible` bool: 보이려면 true.
- `pub fn set_cursor(platform_window: Option<&PlatformWindow>, cursor_value: &CursorValue)` (method, since 0.4.0): 커서 모양 설정. (캔버스의 cursor 스타일에 CSS 값을 쓴다, 빈 값이면 브라우저의 기본, 그림 커서는 CSS 값에 그림이 든다)
  - `platform_window` Option<&PlatformWindow>: 엔진 캔버스. (None 이면 아무것도 하지 않는다)
  - `cursor_value` &CursorValue: 커서 값. (css_value 를 그대로 쓴다)
- `pub fn is_coarse_pointer() -> bool` (method, since 0.4.0): 주된 손이 손가락인지. (CSS 의 pointer: coarse)
  - returns bool: matchMedia("(pointer: coarse)") 가 맞으면 true. window 가 없거나 읽지 못하면 false.
- `pub fn is_text_field_focused() -> bool` (method, since 0.4.0): 문서의 초점이 글자 입력칸에 있는지. (글자 종류의 input, textarea, contenteditable, select)
  - returns bool: document.activeElement 가 글자 입력칸이면 true. (button, checkbox 같은 input 은 false, 초점이 없으면 false)
- `pub fn read_page_query_value(name: &str) -> Option<String>` (method, since 0.4.0): 페이지 주소의 쿼리 값. (원본처럼 location.search 를 URLSearchParams 로 읽어 처음 값, 없으면 None)
  - `name` &str: 쿼리 이름. (safeArea 같은)
  - returns Option<String>: 그 이름의 첫 값. 쿼리에 없거나 window, location, URLSearchParams 를 읽지 못하면 None.
- `pub fn read_canvas_client_position() -> Vector2` (method, since 0.4.0): 화면(client) 좌표에서 캔버스의 왼쪽 위. (원본 canvas.getBoundingClientRect() 의 left, top, 캔버스가 없으면 0)
  - returns Vector2: 캔버스의 왼쪽 위 자리. (CSS 픽셀, 엔진 캔버스가 아직 없으면 0, 0)
- `pub fn save_capture_file(file_name: &str, png_bytes: &[u8]) -> Result<(), String>` (method, since 0.4.0): 검증용 화면 저장. (원본처럼 내려받기, PNG 를 Blob 주소로 만들어 a 요소의 download 로 누른다)
  - `file_name` &str: 내려받을 파일 이름. (a 요소의 download 값)
  - `png_bytes` &[u8]: PNG 파일 바이트.
  - returns Result<(), String>: 내려받기를 눌렀으면 Ok. window, document, body, Blob, URL.createObjectURL 이 없거나 DOM 호출이 실패하면 Err(까닭 글).
- `pub fn read_client_native_size() -> Option<Vector2>` (method, since 0.4.0): 페이지 전체 크기. (원본 window.innerWidth, innerHeight)
  - returns Option<Vector2>: 창 안쪽 크기. (CSS 픽셀) window 가 없거나 값을 읽지 못하면 None.
- `pub fn read_safe_area_insets() -> [f64; 4]` (method, since 0.4.0): CSS env(safe-area-inset-*) 세이프 에어리어 인셋. (원본 viewManager.readSafeAreaFromEnvironment, CSS 픽셀 [위, 오른쪽, 아래, 왼쪽])
  - 숨은 요소의 padding 에 env() 를 걸고 계산된 값을 parseFloat 로 읽는다. 문서나 body 가 없으면 0.
  - returns [f64; 4]: [위, 오른쪽, 아래, 왼쪽] 인셋. (CSS 픽셀, 읽지 못한 칸은 0)
- `pub fn set_title(_platform_window: Option<&PlatformWindow>, title: &str)` (method, since 0.3.2): 창 제목 설정. (문서 제목)
  - `_platform_window` Option<&PlatformWindow>: 엔진 캔버스. (쓰지 않는다, 데스크탑과 같은 꼴을 맞춘 것)
  - `title` &str: 제목 글. (document.title)
- `pub fn request_asset_bytes(asset_location: String, load_handle: AssetLoadHandle, is_no_cache: bool)` (method, since 0.3.2): 애셋 바이트 읽기. (fetch 로 받고, 받으면 끝낸다. 그 사이 프레임은 계속 돈다)
  - 응답의 content-type 을 손잡이에 적는다. (원본 Material.loadImageDescription 의 response.headers.get("content-type"))
  - 응답이 그림 형(image/...)이거나 주소가 그림 확장자(png, jpg, gif, webp, bmp, ico, svg, avif 등)면 끝내기 전에 원본처럼 브라우저가 풀게 해 손잡이에 둔다.
    (ImageAsset, AssetLoader 가 그대로 쓴다) 원본 HTMLImageElement 처럼 응답의 content-type 을 그대로 형으로 넘겨, 브라우저가 SVG 는 그 형(image/svg+xml)으로,
    그 밖의 그림은 내용으로 가린다. 머리가 없는 응답만 확장자의 형을 쓴다. data: 주소는 fetch 가 주소의 형을 content-type 으로 준다.
  - 그림으로 풀어야 하는 손잡이(ImageAsset, AssetLoader 의 그림)는 형과 확장자가 그림이 아니어도 형 없이 브라우저가 내용으로 가려 푼다. (원본 img.src 와 같다, 웹에는 엔진 해독기가 없다)
  - `asset_location` String: 받을 주소. (엔진이 애셋 경로로 만든 것, data: 주소도 된다)
  - `load_handle` AssetLoadHandle: 다 받으면 바이트나 오류 글로 끝낼 손잡이.
  - `is_no_cache` bool: true 면 fetch 에 cache: "no-cache" 를 붙인다. (원본 TextAsset)
- `pub fn run(engine_runner: EngineRunner) -> Result<(), String>` (method, since 0.3.2): 시작. (캔버스와 WebGL2 를 잡고 request_animation_frame 을 걸어 둔 뒤 바로 돌아온다)
  - `engine_runner` EngineRunner: 엔진 실행자. (Engine::run 이 엔진과 첫 씬으로 만들어 넘긴다)
  - returns Result<(), String>: 프레임 콜백을 걸었으면 Ok. 캔버스나 WebGL2 컨텍스트를 얻지 못했거나 사건 리스너를 달지 못했으면 Err(까닭 글).
- `pub fn exit_application()` (method, since 0.4.0): 응용 프로그램 종료. (원본 exitApplication: Capacitor 네이티브면 App 플러그인으로 끝내고, 아니면 창 닫기를 시도한다)
  - 둘 다 환경에 따라 거부될 수 있으며 실패해도 오류를 내지 않는다. 엔진은 종료 요청을 적어 다음 프레임부터 돌지 않는다.
- `pub fn open_url(url: &str) -> bool` (method, since 0.4.0): 바깥 주소 열기. (원본 Engine.openUrl, window.open(주소, "_blank", "noopener") 로 새 탭에 연다)
  - 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열린다. 브라우저의 팝업 차단 규칙이다.
  - 열 수 있는 것은 http, https, mailto, tel 뿐이다. (is_openable_url) 그 밖의 꼴은 열지 않고 false.
  - `url` &str: 열 주소. (http, https, mailto, tel 꼴)
  - returns bool: 브라우저에 열기를 넘겼으면 true.
- `pub fn read_local_time(minute_offset: f64) -> crate::platform::LocalTime` (method, since 0.4.0): 현지 시각 읽기. (원본 Engine.readLocalTime, new Date(Date.now() + 오프셋 분) 의 현지 달력 시각)
  - `minute_offset` f64: 지금에 더할 분. (음수는 과거, 0 이면 지금)
  - returns crate::platform::LocalTime: 더한 때를 브라우저 시간대로 본 달력 시각.
