JFLib

plat/web.rs#

Source: lib/plat/web.rs

Shared browser/Android/iOS host adapter. The host exchanges bounded buffers and queued events;
app state stays in the same Rust UI/runtime used by native applications.
iOS (docs/APPLE.md AP5): the host is Rust too (apple_ios.rs: UIKit, which never returns from
UIApplicationMain); only the host part is used there -- the windows, the input, the requests,
the system host --, time, arguments, environment, threads, files, clipboard and the pickers are
the native ones of apple*.rs.
Android differs where its system offers more: real files on internal storage
(android_files.rs), the documents of other apps as content:// names, the system clipboard and
the persisted grants (android_host.rs), the system's file picker behind file_dialog
(FD_PENDING, file_dialog_poll), download() as "save a copy" through the picker, real threads,
semaphores and the wake-up through the host's looper (android_thread.rs: the pool, task and aio run
on threads there, not between frames).
The browser with the File System Access API (Chromium; the host says so, HOST_HANDLES):
file_dialog shows the system's pickers too and answers later; the chosen file is the user's
own, bound to a path /handles/ID/NAME (web/handles.js keeps the handle in IndexedDB), and every
change of it is written back (write_back: the request of persist); reopen() reads it again
after a reload.  Without the API: the library's own dialog over the virtual files, export
through download().
/// Persist a virtual file to browser storage; payload: u32 path byte count, path, file bytes.
REQUEST_PERSIST: u32 = 1
/// Export/download a file; same payload framing as persistence.
REQUEST_DOWNLOAD: u32 = 2
/// Open a browser file picker; payload is a UTF-8 extension filter.
REQUEST_OPEN: u32 = 3
/// Read browser clipboard text asynchronously.
REQUEST_CLIP_READ: u32 = 4
/// Write browser clipboard text; payload is UTF-8.
REQUEST_CLIP_WRITE: u32 = 5
/// Update the DOM composition element's caret rectangle (three little-endian i32 values).
REQUEST_IME: u32 = 6
/// Update the browser pointer shape (one little-endian u32 CUR value).
REQUEST_CURSOR: u32 = 7
/// Update the document title (UTF-8).
REQUEST_TITLE: u32 = 8
/// Open an explicitly requested HTTP(S)/mailto URL; payload is UTF-8.
REQUEST_URL: u32 = 9
/// Mirror explicit in-app control activation/revocation to the host (one boolean byte).
REQUEST_AGENT: u32 = 10
/// The differences of the accessibility tree for the host's mirror (web_a11y.rs, a11y_wire.rs).
REQUEST_A11Y: u32 = 11
/// (Android) the system's file picker for file_dialog: u32 flags, the suggested name, the
/// content:// URI it starts at (may be empty), u32 count, the extensions (one string each,
/// "png"); answered by jfgui_file_result with the chosen content:// URI
REQUEST_FILE_DIALOG: u32 = 12
/// (browser) commit a change of the secret store (secret.rs, web_secret.rs): u32 op (1 set,
/// 2 delete), app, service, account and for set the value, each as u32 length + bytes; the
/// host encrypts and stores it in order and completes with 2, or an error
REQUEST_SECRET: u32 = 13
/// (browser, Android) the share sheet (share.rs, web_share.rs): the title, the text, the link (u32
/// length + UTF-8 each), u32 count, per file its name and its bytes (u32 length + bytes each); the
/// host completes with 2 (shared), -4 (closed without a target), anything else (failed)
REQUEST_SHARE: u32 = 34
/// (Android) a print job for the system's PrintManager (android_print.rs): the title (u32 length +
/// UTF-8), u32 paper (PAPER_*), u32 flags (PJF_LANDSCAPE), u32 pages (0 unknown), then the PDF;
/// detached: refused at once (-3) when there is no print service, completed later with 2 (the
/// system took the job), -4 (cancelled in its dialog) or a failure
REQUEST_PRINT: u32 = 35
/// (browser) read a file of the user's own (/handles/..) again: the path (UTF-8); the host asks
/// for the permission the handle needs (from the user's gesture), imports the file and
/// completes with 2
REQUEST_REOPEN: u32 = 20
/// (browser) sound output (audio.rs, web_audio.rs, web/audio.js): five u32, op (1 open, 2 close,
/// 3 play, 4 pause, 5 flush), stream id, rate, channels, latency frames; no completion
REQUEST_AUDIO: u32 = 14
/// (browser) the app holds unsaved work (one byte, 1 / 0): the page asks before the tab is
/// closed or reloaded (loader.js beforeunload)
REQUEST_UNSAVED: u32 = 22
  • fn set_unsaved(on: bool) set_unsaved(on) -- tell the page whether closing the tab would lose unsaved work

  • enum RequestStatus Completion state of one browser operation; durable and exported are distinct outcomes.

    • Pending -- The host has not completed the operation.
    • Durable -- Browser storage confirmed this exact file revision was committed.
    • Exported -- The host completed a download/export, not an origin-storage commit.
    • Completed -- A transient operation such as clipboard access completed.
    • Denied -- The user or browser denied access.
    • Quota -- Browser storage quota was exhausted.
    • Unsupported -- This browser lacks the requested service.
    • Cancelled -- User cancellation.
    • Failed -- Other host I/O failure.
  • trait WebApplication An owned app runtime registered once when the browser entrypoint returns.

    • fn frame_delay(&self) -> u32 Milliseconds until a timer or animation needs a host tick; input wakes immediately.
    • fn input(&mut self, time_ms: u32) Drain queued input without presenting intermediate frames; default runtimes may tick.
    • fn tick(&mut self, time_ms: u32) Process queued input, advance timers and render one frame.
    • fn control(&mut self, line: &[u8]) -> Option<String> Process one explicitly enabled agent request, returning its UTF-8 response.
    • fn set_control_enabled(&mut self, _enabled: bool) Synchronize runtime visibility and command state when the host changes activation.
    • fn surface_gone(&mut self) -> bool (Android) the surface of the GPU output went away -> a frame waits for the host's canvas.
    • fn gpu_test(&mut self, _op: u32) -> Option<String> (Android, the browser; tests) the GPU output: 0 its counters, 1 lose the device, 2 settle, 3 a full frame.
  • fn install(app: Box<dyn WebApplication>) -> bool Install the owned runtime. Returns false if an app is already registered.

  • fn persist(path: &str) -> Option<u32> Request durable origin storage for the current virtual-file revision. A file of the user's own (/handles/.., chosen in the system's picker) is written back to that file instead (Durable once the browser closed the write); its change already started that request, which is returned while it is pending or done.

  • fn reopen(path: &str) -> Option<u32> Read a file of the user's own (/handles/.., chosen in the system's picker before) again, e.g. after a reload: the host asks for the permission the browser wants again (call it from the user's click or key), imports the file's current bytes and completes (Completed; Denied, Failed when the file is gone, Unsupported without such a file). None: refused by the permissions or no request slot.

  • fn persist(path: &str) -> Option<u32> Android: the file is on internal storage already; its data is synced (fsync) and the request is Durable (Failed for a missing file) at once.

  • fn download(path: &str) -> Option<u32> Request a browser download; success means export, not durable origin storage. Android: "save a copy" through the system's picker (the user chooses where).

  • fn pick_file(extensions: &str) -> Option<u32> Request file selection. The host imports selected files before completing the request. Android: the chosen document arrives as its content:// name in a drop (E_DROP).

  • fn request_status(id: u32) -> Option<RequestStatus> Query an operation. Old terminal results expire when the 256-entry history fills.

  • fn forget_request(id: u32) -> bool Remove a completed operation once its result has been consumed.

  • fn capabilities() -> Capabilities Services supplied by this browser session, including dynamically granted host services.

  • fn args() -> Vec<String> App start arguments copied from the host, with a synthetic executable name first.

  • fn time_us() -> u64 Monotonic microseconds from the host's performance clock.

  • fn sleep_ms(_ms: u32) No blocking sleep occurs in the browser; callers must return to their step loop.

  • fn env(name: &str) -> Option<String> Read a per-instance virtual environment setting.

  • fn getenv(name: &str) -> Option<String> Alias for the shared environment API.

  • fn setenv(name: &str, value: Option<&str>) -> bool Set a per-instance environment value without changing the browser or OS environment.

  • fn date() -> (Date, bool) Host-supplied UTC calendar, updated independently from the monotonic clock.

  • fn date() -> (Date, bool) (Android) the date and time in UTC from the system's clock, as on Linux; the flag is true (UTC). The calendar jfgui_date sets is the browser's: no Android host calls it.

  • fn unix_time_ns() -> i64 (Android) wall-clock time: nanoseconds since 1970-01-01 00:00 UTC (Bionic's CLOCK_REALTIME)

  • fn unix_time_ns() -> i64 Wall-clock time from the host calendar: nanoseconds since 1970-01-01 00:00 UTC.

  • fn theme() -> i32 Theme requested by the host: 0 light, 1 dark, or -1 unspecified (jfgui_THEME, else the system's scheme the host reported: prefers-color-scheme, Android's night mode).

  • fn cpu_count() -> u32 Available compute workers in a shared-memory bundle, otherwise one app worker.

  • fn mem_total() -> u64 Current WASM linear-memory allocation; zero when the embedded host does not report RAM.

  • fn thread_yield() Cooperative yield is achieved by returning from the current runtime step.

  • struct Thread Browser thread handle placeholder; spawning native threads is unsupported.

impl Thread

  • fn join(self) Wait for it (no thread was started in the browser).

  • fn thread_spawn(_stack: usize, _f: Box<dyn FnOnce() + Send>) -> Option<Thread> Reject native thread creation. Use Job for cooperative background work.

  • struct Sem(AtomicU32) Nonblocking counting semaphore used only by portable try-wait paths.

impl Sem

  • fn new(initial: u32) -> Option<Self> Create a logical semaphore inside this worker.

  • fn post(&self, count: u32) Add available units.

  • fn wait(&self, _timeout: i32) -> bool Try to take a unit; browser execution never blocks on another thread.

  • fn wake() Coalesce job/repaint notifications without occupying the bounded input ring.

  • fn wait(_deadline_us: u64) -> u32 Poll available events; the host schedules future ticks.

  • fn wait_events(_deadline_us: u64, on_event: &mut dyn FnMut(&Event)) -> u32 Dispatch already queued events without blocking the browser worker.

  • fn read_stdin(_bytes: &mut [u8]) -> Result<usize, u32> Browser MessagePort replaces process stdin.

  • fn file_dialog(flags: u32, path: &mut String, extensions: &[&str]) -> (i32, u32) The browser: with the File System Access API (Chromium) the system's pickers -- FD_OPEN showOpenFilePicker, FD_SAVE showSaveFilePicker (the suggested name from path, the types from the extensions; a /handles/.. path starts beside that file). They answer later: (FD_PENDING, 0) now, file_dialog_poll() once the user is done; the answer is a path /handles/ID/NAME bound to the chosen file (opened: imported already), whose changes are written back. One picker at a time ((0, 0) while one is open). FD_FOLDER and browsers without the API: (-1, 0), the library's own dialog over the virtual files.

  • fn file_dialog(flags: u32, path: &mut String, extensions: &[&str]) -> (i32, u32) Android: the system's picker (Storage Access Framework) -- FD_OPEN ACTION_OPEN_DOCUMENT, FD_SAVE ACTION_CREATE_DOCUMENT (the suggested name from path, the type of the selected extension), FD_FOLDER ACTION_OPEN_DOCUMENT_TREE. It answers later: (FD_PENDING, 0) now, file_dialog_poll() once the user is done (the UI wakes up then); the chosen document comes as its content:// name, its grant kept across restarts. One picker at a time: a second call while one is open answers (0, 0). (-1, 0) when the host has no picker.

  • fn file_dialog_poll() -> Option<(i32, u32, String)> The answer of the picker file_dialog opened: None while it is open (or there is none), then once (1, 0, the content:// name / the /handles/ path) or (0, 0, "") for cancelled / failed.

  • fn print(_job: &mut crate::PrintJob<'_>) -> i32 Native printing is disabled until a browser print adapter has been connected (Android: android_print.rs).

  • fn open_folder(_path: &str) -> i32 Operating-system folder launch is unavailable.

  • fn open_url(url: &str) -> i32 Request an explicitly selected web URL; the host still enforces user-gesture restrictions.

  • fn spawn_self(_args: &[&str]) -> i32 Process spawning is unavailable in the browser.

  • fn restart_self(_args: &[&str]) -> i32 Process spawning is unavailable in the browser.

  • fn pen_devices() -> i32 Number of pen devices is not exposed by browser pointer events.

  • fn ime_pos(x: i32, y: i32, height: i32) Update the DOM IME/composition caret position in physical pixels.

  • fn clip_set_many(entries: &[(u32, &[u8])]) -> bool Set the local multi-format clipboard; browser system text writes are asynchronous requests. Android: text and HTML (an image: its PNG) go to the system's clipboard at once; the richer forms stay in the app and count while the system's clip is still this one.

  • fn clip_set(format: u32, bytes: &[u8]) -> bool Set one instance-local clipboard representation. Android: CLIP_IMAGE (the record of ui::clip_set_image) and CLIP_PNG go to the system's clipboard as a PNG.

  • fn clip_get(format: u32) -> Option<Vec<u8>> Read an available clipboard representation; the host refreshes text before paste input. Android: text, HTML and images from the system's clipboard; the app's own richer forms while the system's clip is the one it set.

  • fn clip_has(format: u32) -> bool Whether an instance-local clipboard representation is present (Android: on the system's clipboard, or the app's own form of its clip).

  • extern "C" fn jfgui_buffer(len: u32) -> usize Reserve the reusable host input buffer (at most 256 MiB); zero means allocation failure.

  • extern "C" fn jfgui_start(width: i32, height: i32, dpi: i32, args_len: u32) -> i32 Start once. Inbox contains newline-separated arguments, excluding the synthetic program name.

  • extern "C" fn jfgui_present_us() -> f64 Microseconds spent presenting so far (present_time: the windows' copies, the composition, the hand-over to the host); for measurements.

  • extern "C" fn jfgui_present_frames() -> u64 (Android) frames shown so far, through the platform or the GPU (present_time).

  • extern "C" fn jfgui_gpu_test(op: u32) -> u32 (Android, the browser; tests) the GPU output: its counters as a line (GalleryGpuInstrumentation, apps/gallery/tests/gpu_web.mjs); op: 1 lose the device, 2 settle, 3 the next frame draws everything. -> the length, the bytes in the response buffer.

  • extern "C" fn jfgui_tick(time_ms: u32) Advance the owned runtime and cooperative jobs, then submit the composed framebuffer.

  • extern "C" fn jfgui_input(time_ms: u32) Drain input in order, deferring expensive rasterization until the batch's next tick.

  • extern "C" fn jfgui_frame_delay() -> u32 Idle host scheduling hint (0: the next frame now). The host must still wake immediately for new input.

  • extern "C" fn jfgui_finger(phase: u32, id: u32, x: i32, y: i32, age_ms: u32) -> u32 The host's raw finger (crate::finger's job here, where the windows live in one surface): phase 0 down, 1 move, 2 up, 3 cancel; id the host's small number of this finger; x, y px of the canvas; age_ms how old the sample is now. The host calls jfgui_input after a batch. -> 1 queued

  • extern "C" fn jfgui_event( typ: u32, button: u32, mods: u32, window: u32, x: i32, y: i32, data: u32, ) -> u32 Enqueue a bounded platform event; pointer/resize events update virtual window routing. The lifecycle comes this way too: E_POWER with data 2 when the page was hidden / Android's activity stopped (onStop), 3 when it is visible / started again (UIC_SUSPEND 2 / 0).

  • extern "C" fn jfgui_env(len: u32) -> u32 Set a per-instance environment value from the host before jfgui_start; inbox: UTF-8 "NAME=value" (the host's languages arrive as LANGUAGE=de-DE:en-US). 1 = set.

  • extern "C" fn jfgui_text(len: u32) -> u32 Enqueue committed UTF-8 from the host composition element; uncommitted IME text stays in the DOM. The text goes as commits (whole strings, not one ring slot per character) -> the characters queued: fewer when the queue is full (the host calls again with the rest after jfgui_input), none without a window that takes text.

  • extern "C" fn jfgui_control(len: u32) -> u32 Process one MessagePort/JavaScript agent request only after explicit activation.

  • extern "C" fn jfgui_response() -> usize Address of the current response, valid until the next control request.

  • fn set_agent_enabled(enabled: bool) Disable browser control immediately; reactivation must be explicit in application UI/startup.

  • extern "C" fn jfgui_agent(enabled: u32) -> u32 Explicitly enable or revoke browser automation after app startup.

  • extern "C" fn jfgui_capabilities(bits: u32) Grant only browser-supported dynamic services; native plugins/IPC/threads cannot be granted.

  • extern "C" fn jfgui_date( year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32, millis: u32, weekday: u32, ) -> u32 Refresh UTC calendar fields, validated before replacing the last host value.

  • extern "C" fn jfgui_import(path_len: u32, total_len: u32, dropped: u32, durable: u32) -> u32 Import path + file bytes from the inbox. Selected files can be announced through E_DROP.

  • extern "C" fn jfgui_clipboard(format: u32, len: u32) -> u32 Update a browser clipboard representation before delivering the corresponding paste key.

  • extern "C" fn jfgui_file_result(id: u32, status: i32, len: u32) -> u32 The answer of the system's picker: the inbox holds the chosen content:// URI (Android) or the /handles/ path bound to the chosen file (browser; an opened file was imported first) (status 2), a negative status as in jfgui_complete (-4 cancelled). A file_dialog request keeps the name for file_dialog_poll; pick_file's becomes a drop (E_DROP). 1 = taken.

  • extern "C" fn jfgui_complete(id: u32, status: i32) -> u32 Confirm a host operation: 0 durable, 1 exported, 2 completed; negatives are explicit errors.

Source: docs/API.md in the JFLib repository.