plat/lib.rs
1// plat -- the platform layer: one module per OS with the same functions [src/plat]
2//
3// process: entry point (calls the app's jfgui_main), args(), arg_value(name), exit(code),
4// std_start() (feature std: the start of a program with std, from its fn main),
5// write_stdout / write_stderr, time_us(), sleep_ms(ms), date()
6// environment: env(name) (= getenv), setenv(name, Some / None), config_dir(), temp_dir(), cwd()
7// folders: user_dir(DIR_DOCUMENTS ..) (desktop, documents, downloads, pictures, music,
8// videos: Known Folders / XDG user dirs), log_dir() (dirs.rs)
9// files: read_file(path), write_file(path, data) (native: exclusive sibling + rename),
10// File::open(path, FO_*) / open_temp(dir) -> read_at / write_at / size / sync,
11// file_exists(path) (0 / 1 file / 2 dir), mkdir (with parents), delete, rename,
12// trash (into the recycle bin / freedesktop trash; trash.rs),
13// file_exists_checked(path) (Some(0) missing, None error), FileLock::acquire(path),
14// AtomicFile::create(path) -> write_at / commit (write_file in pieces),
15// dir_list(path, f(name, is_dir, size_lo)) -- checked against the app's
16// permissions first (guarded.rs); a refused path behaves like a missing one
17// policy: the app's permissions (apps/NAME/PERMISSIONS): install, the fs / process /
18// url / plugin / print checks, grants for the user's files (policy.rs)
19// boot: the app's name, app:// and its manifest at start-up (rt::main! through
20// rt::boot; ui::main! calls the parts itself) (boot.rs)
21// vfs: "scheme://path" names in every file function: app:// (the bundled assets),
22// config:// data:// cache:// logs:// (the app's folders), documents:// and the
23// other user folders, mem://, mounted providers
24// (MemFs, DirFs, Overlay, Sub, Bundle); data_dir(), cache_dir() (vfs.rs);
25// display_name(path); Android content:// (ContentFs, DocHost) (content.rs);
26// persistent_name(path): a chosen file's name that lasts across restarts (Flatpak's
27// documents portal: linux_docs.rs)
28// secret: secret_set / secret_get / secret_delete / secret_available: passwords, tokens and
29// keys in the system's store (Credential Manager + DPAPI, Secret Service; needs
30// `secrets` in the manifest) (secret.rs)
31// instance: claim(app) -> Primary / Forwarded / Alone, take() -> requests of later starts
32// (the app's single instance; pipe / abstract socket per user) (instance.rs)
33// spell: sys_spell_find / sys_spell_languages, SysSpeller (check, suggest): the system's
34// spell checker (Windows ISpellChecker, macOS NSSpellChecker, iOS UITextChecker;
35// elsewhere none) (spell.rs)
36// tray: tray_set / tray_remove (the symbol in the notification area, its menu), notify /
37// notify_close (system notifications), tray_take() -> events (tray.rs)
38// power: inhibit(reason, INHIBIT_SUSPEND | INHIBIT_IDLE) -> Option<Inhibit> (no standby /
39// screen saver while the guard lives), inhibited() (power.rs)
40// autostart: autostart_set(on, args) / autostart_get() / autostart_entry() (Run key, XDG
41// autostart, Background portal, MSIX StartupTask; needs `autostart` in the manifest)
42// (autostart.rs)
43// pkg: packaged() (MSIX, Flatpak, AppImage, Snap or a plain program), msix_updates (App
44// Installer), FlatpakMonitor / flatpak_spawn_latest (the Flatpak portal),
45// restart_appimage (pkg.rs)
46// taskbar: taskbar_progress / taskbar_badge / taskbar_tasks (the taskbar button: progress,
47// overlay / count, jump list; ITaskbarList3, Unity LauncherEntry), app_user_model_id
48// / set_app_user_model_id (Windows: the app's explicit id) (taskbar.rs)
49// assoc: assoc_register / assoc_conflicts / assoc_unregister: the app's PACKAGE file types
50// and URL schemes for this program without a setup (HKCU\Software\Classes; .desktop,
51// shared-mime-info, mimeapps.list), file_uri_path; default_browser_status /
52// default_browser_request (PACKAGE browser=1) (assoc.rs)
53// recent: recent_add / recent_list / recent_remove / recent_clear: the system's recent files
54// (SHAddToRecentDocs and the jump list; recently-used.xbel) (recent.rs)
55// audio: Stream (open / open_fill, write, start / pause / stop, volume, latency, the default
56// device followed), play / play_file (WAV, Ogg Vorbis), sound(SOUND_*): the system's
57// sounds (WASAPI, PulseAudio protocol, WebAudio, AAudio) (audio.rs)
58// screen: monitors() (rect, work area, dpi, refresh, primary; SET_MONITORS), pick_start (a
59// pixel's colour anywhere), capture_start (pictures of the screen) (screen.rs)
60// hotkey: hotkey_register / hotkey_unregister / hotkey_take: global shortcuts (RegisterHotKey,
61// XGrabKey, the GlobalShortcuts portal) (hotkey.rs)
62// threads: thread_spawn(stack, f) -> Thread (join), thread_yield(), Sem (post / wait),
63// wake() (any thread: E_WAKE on the UI thread), wait_events(deadline, on_event)
64// (headless), cpu_count(), mem_total(); the windows, the clipboard, the dialogs and
65// the portals belong to the UI thread, the first one that uses them: other threads
66// panic (ui_only.rs)
67// pool: thr_init / thr_count / thr_shutdown / thr_self, parallel_for, Job (pool.rs)
68// task: async execution: Executor (ui() in the event loop, new() / block_on), Task,
69// spawn_blocking (a pool for blocking work), sleep, CancelToken, Progress, join /
70// select (task.rs)
71// aio: files without blocking: read_file / write_file / copy_file with progress and
72// cancellation, Reader / Writer chunk by chunk (AtomicFile underneath) (aio.rs)
73// sync: Mutex, Condvar, RwLock, channel (futex / WaitOnAddress) (sync.rs)
74// rand: fill_random, random_bytes, random_u64 (the OS CSPRNG) (rand.rs)
75// net: TcpListener, TcpStream, UdpSocket, SocketAddr, resolve (net.rs)
76// fs: stat / lstat / read_dir / links / set_times / free_space /
77// write_file_private / local_zone_id (fs.rs)
78// cpu: cpu_features() (CPU_*), cpu_brand() (cpu.rs)
79// crash: crash_hook(Some(f)): f(&CrashInfo) before exit code 3 -- hardware faults (VEH /
80// signals, the stderr line of ASMLIB) and panics; crash_test() crashes on purpose
81// windows: the window-indexed API of the assembly (win_create / win_show / win_present /
82// wait ..., popups, clipboard, drops, pen, cursors; consts.rs, evq.rs, pwin0.rs)
83// dnd: drag and drop between programs: DragData (files, text, URLs, HTML, image),
84// the drop target hook, the pending drop, drag_start (dragging out) (dnd.rs)
85// (plat-shared) print(job) + page layout / PDF writer (print.rs; win_print.rs,
86// linux_print.rs), plugin libraries lib_open / lib_sym / lib_close / lib_seg and
87// the crash guard guard_call / guard_run / guard_tag (plib.rs; win_lib.rs,
88// linux_elfload.rs, linux_guard.rs), monitor_icc / monitor_key (icc.rs), the
89// portal's file dialog / OpenURI / Print (linux_portal.rs)
90// (jxl-module) the loadable JPEG XL writer module: jxlenc_set_path / jxlenc_ready /
91// jxlenc_encode (modhost.rs; the records in modabi.rs)
92//
93// The layer knows events, pixel rows, files and threads only -- no UI, no gfx. One of the
94// four library crates that may contain `unsafe` (rt, simd, plat, gpu); nothing unsafe leaves it
95// but dl_sym and dl_close (a symbol of a library loaded at run time is the caller's to trust).
96#![no_std]
97#[cfg(feature = "std")]
98extern crate std;
99
100extern crate alloc;
101
102/// Owned native child processes with pipes and process-tree lifetime management.
103#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
104pub mod process;
105/// Mutex, Condvar, RwLock and bounded channels for worker threads.
106#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
107pub mod sync;
108/// TCP and UDP sockets (IPv4 / IPv6) with timeouts, numeric names.
109#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
110pub mod net;
111/// Metadata, directory listings, links, times, free space, owner-only files, the local zone.
112#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
113pub mod fs;
114/// Running as a system service (Windows service control manager, systemd units).
115#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
116pub mod service;
117/// Changes below folders as they happen (continuous data protection).
118#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
119pub mod watch;
120/// The operating system's trusted certificate authorities (TLS clients of public servers).
121#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
122pub mod certs;
123// The system's cryptographic random numbers (fill_random, random_bytes): Windows, Linux, Apple
124// and Android; not in the browser (there the page's crypto.getRandomValues).
125#[cfg(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android"))]
126mod rand;
127#[cfg(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android"))]
128pub use rand::*;
129
130use alloc::string::String;
131
132#[cfg(not(any(jfgui_glibc, feature = "std")))] pub use rt::os::exit; pub use rt::os::{write_stderr, write_stdout};
133// a program with std (feature std): its exit and the symbol its fn main calls
134#[cfg(feature = "std")]
135mod hosted;
136#[cfg(feature = "std")]
137pub use hosted::{exit, jfgui_std_start};
138#[cfg(all(feature = "std", any(target_arch = "wasm32", target_os = "android")))]
139pub use hosted::std_start;
140// the library's version (the root Cargo.toml, docs/VERSIONING.md); the app's own: rt::app_version!()
141pub use rt::{VERSION, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH};
142
143mod cpu;
144mod capabilities;
145pub use capabilities::*;
146/// The app's permissions (apps/NAME/PERMISSIONS) and their checks.
147pub mod policy;
148/// OS sandbox derived from the manifest: Landlock + seccomp (Linux), mitigation policies (Windows).
149pub mod sandbox;
150#[cfg(target_os = "linux")]
151#[path = "linux_sandbox.rs"]
152mod linux_sandbox;
153#[cfg(windows)]
154#[path = "win_sandbox.rs"]
155mod win_sandbox;
156/// What build_rs.py builds into a program (name, assets, manifest), set up at start-up.
157pub mod boot;
158/// One file namespace: app://, config://, data://, cache://, mem:// and mounted providers.
159pub mod vfs;
160pub use vfs::display_name;
161/// The documents of other apps as files: Android's content:// names (the name logic on all
162/// platforms, tested with a host in memory).
163pub mod content;
164/// Passwords, tokens and keys in the system's secret store (Credential Manager, Secret Service).
165pub mod secret;
166/// One running instance per app and user; later starts hand over their arguments.
167pub mod instance;
168/// The system's spell checker (Windows ISpellChecker, macOS NSSpellChecker, iOS UITextChecker);
169/// Hunspell files are the spell crate's.
170pub mod spell;
171/// The app's symbol in the notification area and system notifications.
172pub mod tray;
173/// The app's menus in the system's own menu bar (macOS).
174pub mod sysmenu;
175/// Keeping the computer awake: no standby, no screen saver while a guard lives.
176pub mod power;
177pub use power::{INHIBIT_IDLE, INHIBIT_SUSPEND, Inhibit, inhibit, inhibited};
178
179pub mod sensors;
180
181/// Android: while `on`, the back key reaches the app as Esc (a page of the app goes back, a popup
182/// closes; `UIC_ESCAPE` when nothing took it) instead of ending the activity. Elsewhere nothing:
183/// there Esc is a key of its own
184pub fn back_trap(on: bool) {
185 #[cfg(target_os = "android")]
186 web::system_host::back_trap(on);
187 #[cfg(not(target_os = "android"))]
188 let _ = on;
189}
190
191/// Android: the runtime ended (ui.quit): the activity goes and its process with it, a new start
192/// needs a new runtime; iOS: the process ends (UIKit's loop never returns). Elsewhere nothing:
193/// there the main loop ends the program
194pub fn app_finish() {
195 #[cfg(target_os = "android")]
196 web::system_host::app_finish();
197 #[cfg(target_os = "ios")]
198 apple::ios::finish();
199}
200
201/// (ui touch.rs) the host's main pointer is a finger at the start (Android, iOS; a phone's browser:
202/// `pointer: coarse`; a Windows tablet in slate posture): no scroll bars from the first frame on; the
203/// next pointer event decides again
204pub fn touch_primary() -> bool {
205 #[cfg(target_arch = "wasm32")]
206 return web::touch_primary();
207 #[cfg(any(target_os = "android", target_os = "ios"))]
208 return true;
209 #[cfg(windows)]
210 return win_touch_primary();
211 #[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios", windows)))]
212 false
213}
214
215/// (ui touch.rs) a text field got the focus through a finger (show) or lost it: the on-screen keyboard
216/// of window w. Windows: InputPane; Wayland: text-input follows the focus by itself (the compositor's
217/// keyboard); elsewhere the host's job (Android, the browser) or nothing there is to ask (X11)
218pub fn touch_keyboard(w: i32, show: bool) {
219 #[cfg(windows)]
220 win_touch_keyboard(w, show);
221 #[cfg(not(windows))]
222 let _ = (w, show);
223}
224
225/// (ui touch.rs) a finger's gesture reached a widget (a tap, a drag), or it did not (a scroll):
226/// Android and iOS ask after the finger lifted whether the keyboard has to follow
227pub fn touch_reached(reached: bool) {
228 #[cfg(any(target_os = "android", target_os = "ios"))]
229 web::system_host::touch_reached(reached);
230 #[cfg(not(any(target_os = "android", target_os = "ios")))]
231 let _ = reached;
232}
233
234/// (ui touch.rs) a finger rested long enough: the host's feedback (Android: performLongClick)
235pub fn touch_long_press() {
236 #[cfg(target_os = "android")]
237 web::system_host::touch_long_press();
238}
239
240/// where a window the user moves may be (x, y; w its width; screen the area's size; dpi for the
241/// margin): the title bar stays on the screen, at least 48 DIP of the window at each side
242pub fn reach_clamp(p: [i32; 2], w: i32, screen: [i32; 2], dpi: i32) -> [i32; 2] {
243 let m = 48 * dpi / 96;
244 [p[0].clamp(m.min(w) - w, (screen[0] - m).max(m.min(w) - w)), p[1].clamp(0, (screen[1] - m).max(0))]
245}
246/// Starting the app when the user logs in (Run key, XDG autostart, Background portal, an MSIX
247/// package's StartupTask).
248pub mod autostart;
249/// The package the program runs from (MSIX, Flatpak, AppImage, Snap) and what its package
250/// system offers for updates (App Installer, the Flatpak portal).
251pub mod pkg;
252// the few WinRT calls (StartupTask, Package) through raw COM
253#[cfg(windows)]
254mod win_winrt;
255pub use autostart::{AUTOSTART_WAIT_MS, AutostartError, autostart_entry, autostart_get, autostart_set};
256/// The app's taskbar / dock button: progress, a badge, the jump list's tasks.
257pub mod taskbar;
258/// The app's file types and URL schemes registered without a setup (developer builds); a web
259/// browser's default (default_browser_status / default_browser_request).
260pub mod assoc;
261pub use assoc::{BrowserStatus, default_browser_request, default_browser_status};
262/// The system's list of recently used files (jump lists, recently-used.xbel).
263pub mod recent;
264pub use recent::{recent_add, recent_clear, recent_list, recent_remove};
265/// Sound output: streams, short sounds from memory or files, the system's own sounds.
266#[cfg_attr(target_vendor = "apple", allow(dead_code))] // no sound backend on Apple yet: the mixer waits for it
267pub mod audio;
268/// The monitors, a pixel's colour anywhere on the screen, pictures of the screen.
269pub mod screen;
270pub use screen::{Monitor, monitors};
271/// Global keyboard shortcuts: chords that reach the app while another program has the keyboard.
272pub mod hotkey;
273pub use hotkey::{Chord, HotkeyError, HotkeyEvent, hotkey_register, hotkey_take, hotkey_unregister};
274// what the desktop integration shares on Linux (the session-bus link, the .desktop id)
275#[cfg(target_os = "linux")]
276mod linux_desk;
277// the damage regions of the X11 / Wayland presents
278#[cfg(target_os = "linux")]
279mod linux_damage;
280// the copy of a present's dirty rectangles into the window's pixels (Windows, X11, Wayland): in
281// row bands on the pool when large, past the caches at 4K
282#[cfg(any(windows, target_os = "linux"))]
283mod present_copy;
284#[cfg(any(windows, target_os = "linux"))]
285pub use present_copy::present_copy_bench;
286// the log: levels, a ring for crash reports, stderr, a rotating file
287mod log;
288pub use log::*;
289// the accessibility tree for screen readers (AT-SPI2, UI Automation)
290pub mod a11y;
291// the system settings the UI follows (theme, accent, contrast, motion, text scale, timing)
292mod settings;
293pub use settings::{HcColors, SysSettings, sys_settings, sys_settings_env, font_hint_parse, font_rgba_parse,
294 Titlebar, titlebar_layout_parse, titlebar_action_parse, TB_BTN_CLOSE, TB_BTN_MIN, TB_BTN_MAX,
295 TB_ACT_NONE, TB_ACT_MAXIMIZE, TB_ACT_MINIMIZE, TB_ACT_LOWER, TB_ACT_MENU,
296 FONT_HINT_NONE, FONT_HINT_SLIGHT, FONT_HINT_MEDIUM, FONT_HINT_FULL,
297 FONT_RGBA_NONE, FONT_RGBA_RGB, FONT_RGBA_BGR, FONT_RGBA_VRGB, FONT_RGBA_VBGR};
298// the user's languages and regional format (BCP 47 tags)
299mod locale;
300pub use locale::{locale_tag, system_languages, system_locale};
301mod guarded;
302pub use guarded::*;
303// the user's folders (documents, downloads, pictures ...) and the folder of logs
304mod dirs;
305pub use dirs::*;
306// moving files to the trash instead of deleting them
307mod trash;
308mod control_stream;
309#[cfg(not(any(target_arch = "wasm32", target_os = "android")))]
310pub use control_stream::*;
311#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
312pub mod control_ipc;
313#[cfg_attr(all(any(target_arch = "wasm32", target_os = "android"), not(web_threads)), path = "web_pool.rs")]
314mod pool;
315/// Async execution: executors in the event loop and for block_on, a pool for blocking work,
316/// timers, cancellation, progress, joins.
317pub mod task;
318/// Files without blocking the caller: chunked reads, atomic writes and copies with progress and
319/// cancellation.
320pub mod aio;
321pub use cpu::*;
322pub use pool::*;
323
324#[cfg(windows)]
325mod win;
326#[cfg(windows)]
327pub use win::*;
328// a managed program on the runtime another application ships; values of HKLM
329#[cfg(windows)]
330mod win_clr;
331#[cfg(windows)]
332pub use win_clr::*;
333
334#[cfg(target_os = "linux")]
335mod linux;
336#[cfg(target_os = "linux")]
337pub use linux::*;
338
339// macOS and iOS through libSystem (docs/APPLE.md)
340#[cfg(target_vendor = "apple")]
341mod apple;
342#[cfg(target_vendor = "apple")]
343pub use apple::*;
344
345/// Host-driven boundary shared by browser workers, the native Android adapter and the iOS host
346/// (apple_ios.rs: only the host part there, docs/APPLE.md AP5).
347#[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios"))]
348#[cfg_attr(target_os = "ios", allow(dead_code))] // (iOS: the host part only, the rest is the browser's)
349pub mod web;
350#[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios"))]
351pub use web::*;
352
353mod clipdrop;
354// drag and drop between programs (the shared part; win_dnd.rs, linux_x11_dnd.rs, linux_wl_clip.rs)
355#[cfg_attr(target_os = "ios", allow(dead_code))] // no drags between programs on iOS yet
356mod dnd;
357pub use dnd::*;
358// clipboard_platform: reusable rich clipboard framing.
359mod cliprich;
360pub use cliprich::*;
361mod consts;
362// the UI thread's own state: UiOnly<T> lets only the UI thread at it (a safe call on another
363// thread panics instead of racing)
364#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
365mod ui_only;
366// (E3) drawn cursors for the shapes Windows and X11 have none of (Wayland's own images, macOS'
367// zoom and cell)
368#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
369mod cursor_art;
370mod evq;
371mod ime;
372pub use ime::*;
373#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), path = "web_icc.rs")]
374mod icc;
375mod pwin0;
376pub use clipdrop::*;
377pub use consts::*;
378pub use evq::*;
379pub use icc::*;
380pub use pwin0::*;
381// plat-shared: printing (print.rs + win_print.rs / linux_print.rs), plugin libraries and the
382// crash guard (plib.rs + win_lib.rs / linux_elfload.rs, linux_guard.rs; x86-64 and ARM64)
383#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), path = "web_lib.rs")]
384mod plib;
385mod print;
386pub use plib::*;
387pub use print::*;
388// jxl-module: loadable modules, the host side (the JPEG XL writer jxlenc; modhost.rs, modabi.rs)
389#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), path = "web_modhost.rs")]
390mod modhost;
391pub use modhost::*;
392
393/// one platform event (the EV_* record): type, button, modifiers, window index (0 = the
394/// main window), position (px; E_RESIZE: size), data
395#[derive(Clone, Copy, Default)]
396pub struct Event {
397 pub typ: u8,
398 pub btn: u8,
399 pub mods: u8,
400 pub win: u8,
401 pub x: i32,
402 pub y: i32,
403 pub data: u32,
404}
405
406/// the pixels to present: rows of 32-bit B, G, R, x
407pub struct Frame<'a> {
408 pub px: &'a [u8],
409 pub w: i32,
410 pub h: i32,
411 pub stride: i32,
412}
413
414// ---- files
415pub const FO_READ: u32 = 0; // existing file, read only
416pub const FO_WRITE: u32 = 1; // create or truncate, read + write
417pub const FO_RW: u32 = 2; // open or create (contents kept), read + write
418
419/// a date and time (date(): Windows local time, Linux UTC)
420#[derive(Clone, Copy, Default, Debug)]
421pub struct Date {
422 pub year: u16,
423 pub month: u16,
424 pub day: u16,
425 pub hour: u16,
426 pub min: u16,
427 pub sec: u16,
428 pub ms: u16,
429 pub wday: u16, // 0 = Sunday
430}
431
432/// The name under which a file the user chose stays reachable after a restart, for a list of
433/// recent files or a session (ui.recent_add keeps this one). A document of Flatpak's
434/// documents portal (`$XDG_RUNTIME_DIR/doc/ID/NAME`) is asked for its lasting form
435/// (`Documents.Add`, persistent; linux_docs.rs): `<mount>/<ID>/<NAME>` of the portal's answer.
436/// Where the portal reaches the real file that is a lasting document of it; for a document
437/// of its own mount the portal answers that document's own ID, so inside the sandbox the name
438/// stays as the dialog gave it (the portal's file dialog makes lasting documents, "Open with"
439/// session ones). Every other name comes back unchanged: Android keeps the grant of a
440/// `content://` document and the browser the handle of a `/handles/` file when the user
441/// chooses it, and OS paths need nothing. The name must be readable under the app's
442/// permissions.
443pub fn persistent_name(name: &str) -> String {
444 #[cfg(target_os = "linux")]
445 if crate::policy::fs_allowed(name, crate::policy::FS_READ) {
446 if let Some(p) = crate::linux_docs::persistent(name) {
447 return p;
448 }
449 }
450 String::from(name)
451}
452
453// (E8) the files of the last file_dialog with FD_MULTI
454static FD_PATHS: rt::sync::SpinLock<alloc::vec::Vec<String>> = rt::sync::SpinLock::new(alloc::vec::Vec::new());
455
456/// (E8) the files the last system file dialog with FD_MULTI chose (its first is also in
457/// file_dialog's path; Ctrl / Shift in the dialog choose more); one entry after a dialog that
458/// chose one file, empty after a cancelled one. Windows and Linux's portal choose several, the
459/// other systems' dialogs one (docs/GUIDE.md section 7)
460pub fn file_dialog_paths() -> alloc::vec::Vec<String> {
461 FD_PATHS.lock().clone()
462}
463
464// (backends) the answer of a dialog: every chosen file
465#[allow(dead_code)]
466pub(crate) fn fd_paths_set(v: alloc::vec::Vec<String>) {
467 *FD_PATHS.lock() = v;
468}
469
470/// The answer of a system file dialog that answers later (file_dialog -> FD_PENDING: only
471/// Android's picker and the browser's, web.rs, and iOS's, apple_ios_services.rs): None while it
472/// is open, then once (1 chosen / 0 not, index, path).
473#[cfg(not(any(target_os = "android", target_arch = "wasm32", target_os = "ios")))]
474pub fn file_dialog_poll() -> Option<(i32, u32, String)> {
475 None
476}
477
478/// the argument after `name` on the command line (argument 0, the program, is skipped) [arg_value]
479pub fn arg_value(name: &str) -> Option<String> {
480 let a = args();
481 let i = a.iter().skip(1).position(|x| x == name)? + 1;
482 a.get(i + 1).cloned()
483}
484
485/// the library's options that take a value (`--size 800x600`): a program whose plain
486/// arguments are files skips the value after these
487pub const VALUE_OPTS: &[&str] = &[
488 "--size", "--scale", "--auto-close", "--anim", "--theme", "--accent", "--theme-file", "--contrast", "--text-scale",
489 "--lang", "--shot", "--script", "--threads", "--simd",
490];
491
492// ---- crashes (docs/modules/CRASH.md)
493pub use rt::crash::{CK_ACCESS, CK_BUS, CK_DIVIDE, CK_ILLEGAL, CK_OTHER, CK_PANIC, CK_STACK, CrashHook, CrashInfo};
494
495/// f(&CrashInfo) runs in the crash handler, after the stderr line, before exit code 3; also
496/// for panics (CK_PANIC) [plat_crash_hook]
497pub fn crash_hook(f: Option<CrashHook>) {
498 rt::crash::set_hook(f)
499}
500
501/// a deliberate crash for tests: `mov eax, 16` (5 bytes), then a 4-byte write to address 0x10
502/// -- the faulting instruction is at crash_test + 5
503#[unsafe(naked)]
504#[cfg(target_arch = "x86_64")]
505pub extern "C" fn crash_test() -> ! {
506 core::arch::naked_asm!("mov eax, 16", "mov dword ptr [rax], eax", "ud2")
507}
508
509/// (plat-win) crash_test called from a known place (call rel32): the return address
510/// crash_test_caller + 5 must be among CrashInfo::frames (plattest's call chain check)
511#[unsafe(naked)]
512#[cfg(target_arch = "x86_64")]
513pub extern "C" fn crash_test_caller() -> ! {
514 core::arch::naked_asm!("call {0}", "ud2", sym crash_test)
515}
516
517/// Deliberate trap for browser runtime diagnostics.
518#[cfg(target_arch = "wasm32")]
519pub extern "C" fn crash_test() -> ! { core::arch::wasm32::unreachable() }
520/// Deliberate trap through the compatibility caller API.
521#[cfg(target_arch = "wasm32")]
522pub extern "C" fn crash_test_caller() -> ! { crash_test() }
523
524/// a deliberate crash for tests on ARM64 (Apple, Linux, Windows): x0 = 16, then a 4-byte write to address 0x10 --
525/// the faulting instruction is at crash_test + 4
526#[unsafe(naked)]
527#[cfg(all(target_arch = "aarch64", any(target_vendor = "apple", target_os = "linux", windows)))]
528pub extern "C" fn crash_test() -> ! {
529 core::arch::naked_asm!("mov x0, #16", "str w0, [x0]", "brk #0")
530}
531
532/// crash_test called from a known place (bl): the return address crash_test_caller + 4 must be
533/// among CrashInfo::frames
534#[unsafe(naked)]
535#[cfg(all(target_arch = "aarch64", any(target_vendor = "apple", target_os = "linux", windows)))]
536pub extern "C" fn crash_test_caller() -> ! {
537 core::arch::naked_asm!("bl {0}", "brk #0", sym crash_test)
538}
539
540/// Deliberate termination on Android, where no hardware exception translator is installed.
541#[cfg(all(target_os = "android", not(target_arch = "x86_64")))]
542pub extern "C" fn crash_test() -> ! { rt::os::exit(3) }
543/// Compatibility caller for the Android diagnostic termination.
544#[cfg(all(target_os = "android", not(target_arch = "x86_64")))]
545pub extern "C" fn crash_test_caller() -> ! { crash_test() }