| Bring vidya in cfd3e36 nandi 20d ago | 1 | //! Vidya's C ABI, implemented on the Rust/egui semantic layer. |
| 2 | //! |
| 3 | //! This is a third backend behind the header in `raylib/include/vidya.h`, |
| 4 | //! alongside the direct-raylib and cimgui ones. It exports the same symbols |
| 5 | //! from a `cdylib` named `libvidya`, so Jolt — or any other FFI consumer — |
| 6 | //! switches backends by shared-library search path alone, with no binding |
| 7 | //! changes. |
| 8 | //! |
| 9 | //! Rules inherited from the ABI: |
| 10 | //! |
| 11 | //! * one UI context per process; |
| 12 | //! * every call stays on the thread that called `vidya_open` (enforced here: |
| 13 | //! the context lives in thread-local storage, so calls from other threads are |
| 14 | //! inert rather than unsound); |
| 15 | //! * only C integers, floats, pointers, and UTF-8 byte strings cross the |
| 16 | //! boundary, and nothing on this side retains caller memory past the call. |
| 17 | //! |
| 18 | //! Panics are caught at the boundary: unwinding into a C or Chez caller would |
| 19 | //! be undefined behaviour. |
| 20 | |
| 21 | #[cfg(target_os = "android")] |
| 22 | mod android; |
| 23 | mod app; |
| 24 | mod tree; |
| 25 | mod ui; |
| 26 | |
| 27 | use std::cell::RefCell; |
| 28 | use std::ffi::{c_char, c_float, c_int, CStr, CString}; |
| 29 | use std::panic::AssertUnwindSafe; |
| 30 | |
| 31 | use app::App; |
| 32 | use egui::Ui; |
| 33 | use tree::{Tree, Value}; |
| 34 | use vidya_core::{Mode, Theme}; |
| 35 | |
| 36 | thread_local! { |
| 37 | /// The process's UI context, owned by the thread that opened the window. |
| 38 | static APP: RefCell<Option<App>> = const { RefCell::new(None) }; |
| 39 | } |
| 40 | |
| 41 | fn guard<R>(fallback: R, f: impl FnOnce() -> R) -> R { |
| 42 | match std::panic::catch_unwind(AssertUnwindSafe(f)) { |
| 43 | Ok(value) => value, |
| 44 | Err(_) => { |
| 45 | eprintln!("vidya: panic caught at the FFI boundary"); |
| 46 | fallback |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | fn with_app<R: Copy>(fallback: R, f: impl FnOnce(&mut App) -> R) -> R { |
| 52 | guard(fallback, || { |
| 53 | APP.with_borrow_mut(|slot| match slot.as_mut() { |
| 54 | Some(app) => f(app), |
| 55 | None => fallback, |
| 56 | }) |
| 57 | }) |
| 58 | } |
| 59 | |
| 60 | /// Run `f` against the innermost open UI node. Inert outside a frame. |
| 61 | fn with_ui<R: Copy>(fallback: R, f: impl FnOnce(&mut Ui, &Theme) -> R) -> R { |
| 62 | with_app(fallback, |app| match app.ui() { |
| 63 | Some((ui, theme)) => f(ui, theme), |
| 64 | None => fallback, |
| 65 | }) |
| 66 | } |
| 67 | |
| 68 | /// # Safety |
| 69 | /// `ptr` is null or a NUL-terminated string valid for the duration of the call. |
| 70 | unsafe fn borrowed_str(ptr: *const c_char) -> String { |
| 71 | if ptr.is_null() { |
| 72 | String::new() |
| 73 | } else { |
| 74 | CStr::from_ptr(ptr).to_string_lossy().into_owned() |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Copy `value` into a caller buffer, truncated at a char boundary and always |
| 79 | /// NUL-terminated. |
| 80 | /// |
| 81 | /// # Safety |
| 82 | /// `buf` is null or writable for `capacity` bytes. |
| 83 | unsafe fn write_buffer(buf: *mut c_char, capacity: usize, value: &str) { |
| 84 | if buf.is_null() || capacity == 0 { |
| 85 | return; |
| 86 | } |
| 87 | let mut len = value.len().min(capacity - 1); |
| 88 | while len > 0 && !value.is_char_boundary(len) { |
| 89 | len -= 1; |
| 90 | } |
| 91 | std::ptr::copy_nonoverlapping(value.as_ptr().cast::<c_char>(), buf, len); |
| 92 | *buf.add(len) = 0; |
| 93 | } |
| 94 | |
| 95 | // ── Window and frame lifecycle ────────────────────────────────────────────── |
| 96 | |
| 97 | /// # Safety |
| 98 | /// `title` is null or a NUL-terminated UTF-8 string. |
| 99 | #[no_mangle] |
| 100 | pub unsafe extern "C" fn vidya_open(width: c_int, height: c_int, title: *const c_char) -> c_int { |
| 101 | let title = borrowed_str(title); |
| 102 | guard(0, || { |
| 103 | APP.with_borrow_mut(|slot| { |
| 104 | if slot.is_some() { |
| 105 | eprintln!("vidya: a window is already open"); |
| 106 | return 0; |
| 107 | } |
| 108 | match App::open(width, height, &title) { |
| 109 | Ok(app) => { |
| 110 | *slot = Some(app); |
| 111 | 1 |
| 112 | } |
| 113 | Err(e) => { |
| 114 | eprintln!("vidya: could not open a window: {e}"); |
| 115 | 0 |
| 116 | } |
| 117 | } |
| 118 | }) |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | #[no_mangle] |
| 123 | pub extern "C" fn vidya_close() { |
| 124 | guard((), || APP.with_borrow_mut(|slot| drop(slot.take()))); |
| 125 | } |
| 126 | |
| 127 | #[no_mangle] |
| 128 | pub extern "C" fn vidya_should_close() -> c_int { |
| 129 | // No window is a closed window, so a caller's loop still terminates. |
| 130 | with_app(1, |app| app.should_close() as c_int) |
| 131 | } |
| 132 | |
| 133 | #[no_mangle] |
| 134 | pub extern "C" fn vidya_set_target_fps(fps: c_int) { |
| 135 | with_app((), |app| app.set_target_fps(fps)); |
| 136 | } |
| 137 | |
| 138 | #[no_mangle] |
| 139 | pub extern "C" fn vidya_set_mode(mode: c_int) { |
| 140 | let mode = if mode == 1 { Mode::Light } else { Mode::Dark }; |
| 141 | with_app((), |app| app.set_mode(mode)); |
| 142 | } |
| 143 | |
| 144 | #[no_mangle] |
| 145 | pub extern "C" fn vidya_get_mode() -> c_int { |
| 146 | with_app(0, |app| match app.theme().mode { |
| 147 | Mode::Dark => 0, |
| 148 | Mode::Light => 1, |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | /// `atlas_size` is accepted for ABI compatibility and ignored: egui rasterizes |
| 153 | /// each requested size on demand instead of from one fixed atlas. |
| 154 | /// |
| 155 | /// # Safety |
| 156 | /// `path` is null or a NUL-terminated UTF-8 string. |
| 157 | #[no_mangle] |
| 158 | pub unsafe extern "C" fn vidya_load_font(path: *const c_char, _atlas_size: c_int) -> c_int { |
| 159 | let path = borrowed_str(path); |
| 160 | with_app(0, |app| app.load_font(&path) as c_int) |
| 161 | } |
| 162 | |
| 163 | #[no_mangle] |
| 164 | pub extern "C" fn vidya_begin_frame() { |
| 165 | with_app((), |app| app.begin_frame()); |
| 166 | } |
| 167 | |
| 168 | #[no_mangle] |
| 169 | pub extern "C" fn vidya_end_frame() { |
| 170 | with_app((), |app| app.end_frame()); |
| 171 | } |
| 172 | |
| 173 | // ── Containers ────────────────────────────────────────────────────────────── |
| 174 | |
| 175 | #[no_mangle] |
| 176 | pub extern "C" fn vidya_page_begin(max_width: c_float) { |
| 177 | with_app((), |app| { |
| 178 | let theme = app.theme().clone(); |
| 179 | app.stack.push_page(&theme, max_width); |
| 180 | }); |
| 181 | } |
| 182 | |
| 183 | #[no_mangle] |
| 184 | pub extern "C" fn vidya_page_end() { |
| 185 | with_app((), |app| app.stack.pop()); |
| 186 | } |
| 187 | |
| 188 | #[no_mangle] |
| 189 | pub extern "C" fn vidya_card_begin() { |
| 190 | with_app((), |app| { |
| 191 | let theme = app.theme().clone(); |
| 192 | app.stack.push_card(&theme); |
| 193 | }); |
| 194 | } |
| 195 | |
| 196 | #[no_mangle] |
| 197 | pub extern "C" fn vidya_card_end() { |
| 198 | with_app((), |app| app.stack.pop()); |
| 199 | } |
| 200 | |
| 201 | #[no_mangle] |
| 202 | pub extern "C" fn vidya_gap(pixels: c_float) { |
| 203 | with_ui((), |ui, _| ui::gap(ui, pixels)); |
| 204 | } |
| 205 | |
| 206 | #[no_mangle] |
| 207 | pub extern "C" fn vidya_separator() { |
| 208 | with_ui((), |ui, _| ui::separator(ui)); |
| 209 | } |
| 210 | |
| 211 | // ── Text roles ────────────────────────────────────────────────────────────── |
| 212 | |
| 213 | macro_rules! text_role { |
| 214 | ($name:ident, $call:path) => { |
| 215 | /// # Safety |
| 216 | /// `text` is null or a NUL-terminated UTF-8 string. |
| 217 | #[no_mangle] |
| 218 | pub unsafe extern "C" fn $name(text: *const c_char) { |
| 219 | let text = borrowed_str(text); |
| 220 | with_ui((), |ui, theme| $call(ui, theme, &text)); |
| 221 | } |
| 222 | }; |
| 223 | } |
| 224 | |
| 225 | text_role!(vidya_title, vidya_core::title); |
| 226 | text_role!(vidya_title_2, vidya_core::title_2); |
| 227 | text_role!(vidya_body, vidya_core::body); |
| 228 | text_role!(vidya_dim_label, vidya_core::dim_label); |
| 229 | |
| 230 | // ── Controls ──────────────────────────────────────────────────────────────── |
| 231 | |
| 232 | /// # Safety |
| 233 | /// `label` is null or a NUL-terminated UTF-8 string. |
| 234 | #[no_mangle] |
| 235 | pub unsafe extern "C" fn vidya_button(label: *const c_char, kind: c_int) -> c_int { |
| 236 | let label = borrowed_str(label); |
| 237 | with_ui(0, |ui, theme| ui::button(ui, theme, &label, kind) as c_int) |
| 238 | } |
| 239 | |
| 240 | /// Returns 1 when the value changed this frame, writing it back through |
| 241 | /// `checked`. |
| 242 | /// |
| 243 | /// # Safety |
| 244 | /// `label` is null or a NUL-terminated UTF-8 string; `checked` is null or a |
| 245 | /// writable `int`. |
| 246 | #[no_mangle] |
| 247 | pub unsafe extern "C" fn vidya_checkbox(label: *const c_char, checked: *mut c_int) -> c_int { |
| 248 | if checked.is_null() { |
| 249 | return 0; |
| 250 | } |
| 251 | let label = borrowed_str(label); |
| 252 | let current = *checked != 0; |
| 253 | let (value, changed) = with_ui((current, false), |ui, theme| { |
| 254 | ui::checkbox(ui, theme, current, &label) |
| 255 | }); |
| 256 | *checked = value as c_int; |
| 257 | changed as c_int |
| 258 | } |
| 259 | |
| 260 | /// FFI-friendly variant: returns the value after handling input. |
| 261 | /// |
| 262 | /// # Safety |
| 263 | /// `label` is null or a NUL-terminated UTF-8 string. |
| 264 | #[no_mangle] |
| 265 | pub unsafe extern "C" fn vidya_checkbox_value(label: *const c_char, checked: c_int) -> c_int { |
| 266 | let label = borrowed_str(label); |
| 267 | let current = checked != 0; |
| 268 | with_ui(current, |ui, theme| ui::checkbox(ui, theme, current, &label).0) as c_int |
| 269 | } |
| 270 | |
| 271 | /// # Safety |
| 272 | /// `label` is null or a NUL-terminated UTF-8 string. |
| 273 | #[no_mangle] |
| 274 | pub unsafe extern "C" fn vidya_status(label: *const c_char, live: c_int) { |
| 275 | let label = borrowed_str(label); |
| 276 | with_ui((), |ui, theme| ui::status(ui, theme, &label, live != 0)); |
| 277 | } |
| 278 | |
| 279 | /// Edit `text` in place. Returns 1 when the buffer changed this frame. |
| 280 | /// |
| 281 | /// # Safety |
| 282 | /// `text` is null or a NUL-terminated buffer writable for `capacity` bytes; |
| 283 | /// `placeholder` is null or a NUL-terminated UTF-8 string. |
| 284 | #[no_mangle] |
| 285 | pub unsafe extern "C" fn vidya_text_field( |
| 286 | text: *mut c_char, |
| 287 | capacity: usize, |
| 288 | placeholder: *const c_char, |
| 289 | ) -> c_int { |
| 290 | if text.is_null() || capacity == 0 { |
| 291 | return 0; |
| 292 | } |
| 293 | let placeholder = borrowed_str(placeholder); |
| 294 | let mut value = borrowed_str(text.cast_const()); |
| 295 | |
| 296 | let changed = with_ui(false, |ui, theme| { |
| 297 | ui::text_field(ui, theme, &mut value, &placeholder).changed() |
| 298 | }); |
| 299 | if changed { |
| 300 | write_buffer(text, capacity, &value); |
| 301 | } |
| 302 | changed as c_int |
| 303 | } |
| 304 | |
| 305 | // ── Retained node tree ────────────────────────────────────────────────────── |
| 306 | // |
| 307 | // The second half of this ABI, for reactive callers. See `tree.rs` for why it |
| 308 | // exists and `include/vidya_tree.h` for the contract. Everything below is inert |
| 309 | // until the caller builds a tree; a program using only the push/pop calls above |
| 310 | // never allocates one. |
| 311 | |
| 312 | thread_local! { |
| 313 | /// The node tree, on the same thread as the window by the same rule as |
| 314 | /// `APP`. Created on first use — a push/pop caller never pays for it. |
| 315 | static TREE: RefCell<Tree> = RefCell::new(Tree::default()); |
| 316 | |
| 317 | /// Backing store for the `const char *` returns below. Rust owns every |
| 318 | /// string that crosses this boundary, so it has to outlive the call that |
| 319 | /// returns it without leaking: one slot, overwritten by the next call. |
| 320 | static SCRATCH: RefCell<CString> = RefCell::new(CString::default()); |
| 321 | } |
| 322 | |
| 323 | fn with_tree<R: Copy>(fallback: R, f: impl FnOnce(&mut Tree) -> R) -> R { |
| 324 | guard(fallback, || TREE.with_borrow_mut(f)) |
| 325 | } |
| 326 | |
| 327 | /// Copy `value` into the scratch slot and return a pointer C can read until the |
| 328 | /// next string-returning call. Interior NULs truncate rather than fail. |
| 329 | fn scratch(value: &str) -> *const c_char { |
| 330 | let owned = CString::new(value).unwrap_or_else(|e| { |
| 331 | let mut bytes = e.into_vec(); |
| 332 | bytes.truncate(bytes.iter().position(|&b| b == 0).unwrap_or(0)); |
| 333 | CString::new(bytes).expect("truncated at the first NUL") |
| 334 | }); |
| 335 | SCRATCH.with_borrow_mut(|slot| { |
| 336 | *slot = owned; |
| 337 | slot.as_ptr() |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | #[no_mangle] |
| 342 | pub extern "C" fn vidya_tree_root() -> c_int { |
| 343 | with_tree(0, |tree| tree.root() as c_int) |
| 344 | } |
| 345 | |
| 346 | /// # Safety |
| 347 | /// `tag` is null or a NUL-terminated UTF-8 string. |
| 348 | #[no_mangle] |
| 349 | pub unsafe extern "C" fn vidya_node_new(tag: *const c_char) -> c_int { |
| 350 | let tag = borrowed_str(tag); |
| 351 | with_tree(0, |tree| tree.new_node(&tag) as c_int) |
| 352 | } |
| 353 | |
| 354 | #[no_mangle] |
| 355 | pub extern "C" fn vidya_node_free(node: c_int) { |
| 356 | with_tree((), |tree| tree.free_node(node.max(0) as u32)); |
| 357 | } |
| 358 | |
| 359 | #[no_mangle] |
| 360 | pub extern "C" fn vidya_node_exists(node: c_int) -> c_int { |
| 361 | with_tree(0, |tree| tree.exists(node.max(0) as u32) as c_int) |
| 362 | } |
| 363 | |
| 364 | /// # Safety |
| 365 | /// `key` and `value` are null or NUL-terminated UTF-8 strings. |
| 366 | #[no_mangle] |
| 367 | pub unsafe extern "C" fn vidya_node_set_str(node: c_int, key: *const c_char, value: *const c_char) { |
| 368 | let (key, value) = (borrowed_str(key), borrowed_str(value)); |
| 369 | with_tree((), |tree| { |
| 370 | tree.set(node.max(0) as u32, &key, Value::Str(value)) |
| 371 | }); |
| 372 | } |
| 373 | |
| 374 | /// # Safety |
| 375 | /// `key` is null or a NUL-terminated UTF-8 string. |
| 376 | #[no_mangle] |
| 377 | pub unsafe extern "C" fn vidya_node_set_num(node: c_int, key: *const c_char, value: f64) { |
| 378 | let key = borrowed_str(key); |
| 379 | with_tree((), |tree| { |
| 380 | tree.set(node.max(0) as u32, &key, Value::Num(value)) |
| 381 | }); |
| 382 | } |
| 383 | |
| 384 | /// # Safety |
| 385 | /// `key` is null or a NUL-terminated UTF-8 string. |
| 386 | #[no_mangle] |
| 387 | pub unsafe extern "C" fn vidya_node_set_bool(node: c_int, key: *const c_char, value: c_int) { |
| 388 | let key = borrowed_str(key); |
| 389 | with_tree((), |tree| { |
| 390 | tree.set(node.max(0) as u32, &key, Value::Bool(value != 0)) |
| 391 | }); |
| 392 | } |
| 393 | |
| 394 | /// Drop every prop, so a re-render starts from a clean slate rather than |
| 395 | /// inheriting props the new hiccup no longer sets. |
| 396 | #[no_mangle] |
| 397 | pub extern "C" fn vidya_node_clear_props(node: c_int) { |
| 398 | with_tree((), |tree| tree.clear_props(node.max(0) as u32)); |
| 399 | } |
| 400 | |
| 401 | /// The empty string for a prop that is unset or is not a string. |
| 402 | /// |
| 403 | /// # Safety |
| 404 | /// `key` is null or a NUL-terminated UTF-8 string. The returned pointer is |
| 405 | /// valid until the next string-returning call on this thread. |
| 406 | #[no_mangle] |
| 407 | pub unsafe extern "C" fn vidya_node_get_str(node: c_int, key: *const c_char) -> *const c_char { |
| 408 | let key = borrowed_str(key); |
| 409 | let value = TREE.with_borrow(|tree| match tree.get(node.max(0) as u32, &key) { |
| 410 | Some(Value::Str(s)) => s.clone(), |
| 411 | _ => String::new(), |
| 412 | }); |
| 413 | scratch(&value) |
| 414 | } |
| 415 | |
| 416 | /// # Safety |
| 417 | /// `key` is null or a NUL-terminated UTF-8 string. |
| 418 | #[no_mangle] |
| 419 | pub unsafe extern "C" fn vidya_node_get_num(node: c_int, key: *const c_char) -> f64 { |
| 420 | let key = borrowed_str(key); |
| 421 | with_tree(0.0, |tree| match tree.get(node.max(0) as u32, &key) { |
| 422 | Some(Value::Num(n)) => *n, |
| 423 | Some(Value::Bool(true)) => 1.0, |
| 424 | _ => 0.0, |
| 425 | }) |
| 426 | } |
| 427 | |
| 428 | /// # Safety |
| 429 | /// `key` is null or a NUL-terminated UTF-8 string. |
| 430 | #[no_mangle] |
| 431 | pub unsafe extern "C" fn vidya_node_get_bool(node: c_int, key: *const c_char) -> c_int { |
| 432 | let key = borrowed_str(key); |
| 433 | with_tree(0, |tree| { |
| 434 | (match tree.get(node.max(0) as u32, &key) { |
| 435 | Some(Value::Bool(b)) => *b, |
| 436 | Some(Value::Num(n)) => *n != 0.0, |
| 437 | _ => false, |
| 438 | }) as c_int |
| 439 | }) |
| 440 | } |
| 441 | |
| 442 | /// The canonical tag name a node was created with; `hbox` and `vbox` both |
| 443 | /// answer `box`. The empty string for a node that no longer exists. |
| 444 | /// |
| 445 | /// # Safety |
| 446 | /// The returned pointer is valid until the next string-returning call on this |
| 447 | /// thread. |
| 448 | #[no_mangle] |
| 449 | pub extern "C" fn vidya_node_tag(node: c_int) -> *const c_char { |
| 450 | let tag = TREE.with_borrow(|tree| tree.tag_name(node.max(0) as u32).to_owned()); |
| 451 | scratch(&tag) |
| 452 | } |
| 453 | |
| 454 | /// The subtree at `node` as hiccup text, for logging and bug reports; `node` 0 |
| 455 | /// means the root, so `vidya_tree_dump(0)` is the whole window. |
| 456 | /// |
| 457 | /// # Safety |
| 458 | /// The returned pointer is valid until the next string-returning call on this |
| 459 | /// thread. |
| 460 | #[no_mangle] |
| 461 | pub extern "C" fn vidya_tree_dump(node: c_int) -> *const c_char { |
| 462 | let node = node.max(0) as u32; |
| 463 | let text = TREE.with_borrow(|tree| { |
| 464 | let id = if node == 0 { tree.root() } else { node }; |
| 465 | tree.dump(id) |
| 466 | }); |
| 467 | scratch(&text) |
| 468 | } |
| 469 | |
| 470 | #[no_mangle] |
| 471 | pub extern "C" fn vidya_node_child_count(node: c_int) -> c_int { |
| 472 | with_tree(0, |tree| tree.child_count(node.max(0) as u32) as c_int) |
| 473 | } |
| 474 | |
| 475 | /// The `index`th child, or 0 when there is none. |
| 476 | #[no_mangle] |
| 477 | pub extern "C" fn vidya_node_child_at(node: c_int, index: c_int) -> c_int { |
| 478 | with_tree(0, |tree| { |
| 479 | tree.child_at(node.max(0) as u32, index.max(0) as usize) as c_int |
| 480 | }) |
| 481 | } |
| 482 | |
| 483 | #[no_mangle] |
| 484 | pub extern "C" fn vidya_node_append(parent: c_int, child: c_int) -> c_int { |
| 485 | with_tree(0, |tree| { |
| 486 | tree.append(parent.max(0) as u32, child.max(0) as u32) as c_int |
| 487 | }) |
| 488 | } |
| 489 | |
| 490 | /// Unparent `child` **and free it**, with everything under it. |
| 491 | /// |
| 492 | /// glimmer says nothing further about a widget it has removed, so this is where |
| 493 | /// a subtree's storage goes back. |
| 494 | #[no_mangle] |
| 495 | pub extern "C" fn vidya_node_remove(parent: c_int, child: c_int) { |
| 496 | with_tree((), |tree| { |
| 497 | tree.remove(parent.max(0) as u32, child.max(0) as u32) |
| 498 | }); |
| 499 | } |
| 500 | |
| 501 | /// Move `child` to sit immediately after `sibling`; `sibling` 0 means first. |
| 502 | #[no_mangle] |
| 503 | pub extern "C" fn vidya_node_insert_after(parent: c_int, child: c_int, sibling: c_int) -> c_int { |
| 504 | with_tree(0, |tree| { |
| 505 | tree.insert_after( |
| 506 | parent.max(0) as u32, |
| 507 | child.max(0) as u32, |
| 508 | sibling.max(0) as u32, |
| 509 | ) as c_int |
| 510 | }) |
| 511 | } |
| 512 | |
| 513 | /// Put `new_child` where `old_child` was, and free `old_child`. |
| 514 | #[no_mangle] |
| 515 | pub extern "C" fn vidya_node_replace(parent: c_int, old_child: c_int, new_child: c_int) -> c_int { |
| 516 | with_tree(0, |tree| { |
| 517 | tree.replace( |
| 518 | parent.max(0) as u32, |
| 519 | old_child.max(0) as u32, |
| 520 | new_child.max(0) as u32, |
| 521 | ) as c_int |
| 522 | }) |
| 523 | } |
| 524 | |
| 525 | /// Paint the whole tree as one frame: a `vidya_begin_frame`, the walk, and a |
| 526 | /// `vidya_end_frame`. Inert with no window open. |
| 527 | #[no_mangle] |
| 528 | pub extern "C" fn vidya_tree_frame() { |
| 529 | with_app((), |app| { |
| 530 | app.begin_frame(); |
| 531 | TREE.with_borrow_mut(|tree| { |
| 532 | if let Some((ui, theme)) = app.ui() { |
| 533 | tree.paint(ui, theme); |
| 534 | } |
| 535 | }); |
| 536 | app.end_frame(); |
| 537 | }); |
| 538 | } |
| 539 | |
| 540 | /// Dequeue one event, returning 1 while there was one. Its fields are read with |
| 541 | /// the accessors below, which describe the most recently dequeued event. |
| 542 | #[no_mangle] |
| 543 | pub extern "C" fn vidya_tree_poll_event() -> c_int { |
| 544 | with_tree(0, |tree| tree.poll() as c_int) |
| 545 | } |
| 546 | |
| 547 | #[no_mangle] |
| 548 | pub extern "C" fn vidya_tree_event_node() -> c_int { |
| 549 | with_tree(0, |tree| tree.current().map_or(0, |e| e.node) as c_int) |
| 550 | } |
| 551 | |
| 552 | /// The event's name — `click`, `change`, `toggled`, `activate` — or the empty |
| 553 | /// string when nothing has been dequeued. |
| 554 | /// |
| 555 | /// # Safety |
| 556 | /// The returned pointer is valid until the next string-returning call on this |
| 557 | /// thread. |
| 558 | #[no_mangle] |
| 559 | pub extern "C" fn vidya_tree_event_name() -> *const c_char { |
| 560 | let name = TREE.with_borrow(|tree| tree.current().map_or("", |e| e.name).to_owned()); |
| 561 | scratch(&name) |
| 562 | } |
| 563 | |
| 564 | /// # Safety |
| 565 | /// The returned pointer is valid until the next string-returning call on this |
| 566 | /// thread. |
| 567 | #[no_mangle] |
| 568 | pub extern "C" fn vidya_tree_event_text() -> *const c_char { |
| 569 | let text = TREE.with_borrow(|tree| tree.current().map_or(String::new(), |e| e.text.clone())); |
| 570 | scratch(&text) |
| 571 | } |
| 572 | |
| 573 | #[no_mangle] |
| 574 | pub extern "C" fn vidya_tree_event_num() -> f64 { |
| 575 | with_tree(0.0, |tree| tree.current().map_or(0.0, |e| e.num)) |
| 576 | } |
| 577 | |
| 578 | // ── Live frames ───────────────────────────────────────────────────────────── |
| 579 | |
| 580 | /// Hand the tree a frame of raw pixels under `key`, painted by any `:image` |
| 581 | /// whose `feed` prop names it. Answers 1 when the frame was accepted. |
| 582 | /// |
| 583 | /// This is the one thing an `:image` could not do: `src` decodes a file and |
| 584 | /// caches the texture by its path forever, which is right for a picture in a |
| 585 | /// message and useless for a source that produces a new picture thirty times a |
| 586 | /// second. A caller that has its own pixels — a camera, a video decoder, a |
| 587 | /// renderer — pushes them here instead, and the tag paints the latest. |
| 588 | /// |
| 589 | /// `rgba` is `width * height * 4` bytes, row-major, 8 bits a channel, |
| 590 | /// un-premultiplied. It is copied before this returns, so the caller may reuse |
| 591 | /// the buffer immediately; nothing on this side retains it. A length that |
| 592 | /// disagrees with the dimensions is refused rather than painted torn. |
| 593 | /// |
| 594 | /// Frames are coalesced, not queued: one that arrives before the last has been |
| 595 | /// painted replaces it. A source faster than the window costs no backlog. |
| 596 | /// |
| 597 | /// Like the rest of the tree ABI this must be called on the thread that opened |
| 598 | /// the window — a frame produced on a decoder thread crosses to the UI thread |
| 599 | /// on the caller's side, not this one. |
| 600 | /// |
| 601 | /// # Safety |
| 602 | /// `key` is null or a NUL-terminated UTF-8 string; `rgba` is null or valid for |
| 603 | /// reads of `width * height * 4` bytes for the duration of the call. |
| 604 | #[no_mangle] |
| 605 | pub unsafe extern "C" fn vidya_frame_rgba( |
| 606 | key: *const c_char, |
| 607 | width: c_int, |
| 608 | height: c_int, |
| 609 | rgba: *const u8, |
| 610 | ) -> c_int { |
| 611 | let key = borrowed_str(key); |
| 612 | if rgba.is_null() || width <= 0 || height <= 0 { |
| 613 | return 0; |
| 614 | } |
| 615 | let len = (width as usize) |
| 616 | .saturating_mul(height as usize) |
| 617 | .saturating_mul(4); |
| 618 | let pixels = std::slice::from_raw_parts(rgba, len); |
| 619 | with_tree(0, |tree| { |
| 620 | tree.set_frame(&key, width as u32, height as u32, pixels) as c_int |
| 621 | }) |
| 622 | } |
| 623 | |
| 624 | /// Forget the feed named `key` and release its texture, answering 1 when there |
| 625 | /// was one. Without this the last frame of a source that has stopped keeps |
| 626 | /// painting — the participant who left, still on the wall. |
| 627 | /// |
| 628 | /// # Safety |
| 629 | /// `key` is null or a NUL-terminated UTF-8 string. |
| 630 | #[no_mangle] |
| 631 | pub unsafe extern "C" fn vidya_frame_drop(key: *const c_char) -> c_int { |
| 632 | let key = borrowed_str(key); |
| 633 | with_tree(0, |tree| tree.drop_frame(&key) as c_int) |
| 634 | } |
| 635 | |
| 636 | // ── Clipboard ─────────────────────────────────────────────────────────────── |
| 637 | |
| 638 | /// Write the picture on the system clipboard to `path` as a PNG, answering 1 |
| 639 | /// when there was one and it was written. |
| 640 | /// |
| 641 | /// egui carries clipboard *text* into the frame as an event and nothing else, |
| 642 | /// so a pasted image has to be asked for rather than waited for: a caller |
| 643 | /// binds this to whatever gesture means paste for it, and reads the file. |
| 644 | /// PNG because that is what the `:image` node decodes. |
| 645 | /// |
| 646 | /// Unlike the rest of this ABI it needs no window and no particular thread — |
| 647 | /// it talks to the platform clipboard, not to egui. |
| 648 | /// |
| 649 | /// # Safety |
| 650 | /// `path` is null or a NUL-terminated UTF-8 string. |
| 651 | #[no_mangle] |
| 652 | pub unsafe extern "C" fn vidya_clipboard_image_png(path: *const c_char) -> c_int { |
| 653 | let path = borrowed_str(path); |
| 654 | guard(0, || { |
| 655 | if path.is_empty() { |
| 656 | return 0; |
| 657 | } |
| 658 | clipboard_image_png(&path) as c_int |
| 659 | }) |
| 660 | } |
| 661 | |
| 662 | #[cfg(not(target_os = "android"))] |
| 663 | fn clipboard_image_png(path: &str) -> bool { |
| 664 | let Ok(mut clipboard) = arboard::Clipboard::new() else { |
| 665 | return false; |
| 666 | }; |
| 667 | // An empty clipboard, text on it, or a format the platform will not hand |
| 668 | // over as pixels: all of them are "no picture to paste" to the caller. |
| 669 | let Ok(image) = clipboard.get_image() else { |
| 670 | return false; |
| 671 | }; |
| 672 | let Ok(file) = std::fs::File::create(path) else { |
| 673 | return false; |
| 674 | }; |
| 675 | let mut encoder = png::Encoder::new( |
| 676 | std::io::BufWriter::new(file), |
| 677 | image.width as u32, |
| 678 | image.height as u32, |
| 679 | ); |
| 680 | encoder.set_color(png::ColorType::Rgba); |
| 681 | encoder.set_depth(png::BitDepth::Eight); |
| 682 | let written = encoder |
| 683 | .write_header() |
| 684 | .and_then(|mut writer| writer.write_image_data(&image.bytes)) |
| 685 | .is_ok(); |
| 686 | // A half-written file is worse than none: the caller would upload it. |
| 687 | if !written { |
| 688 | let _ = std::fs::remove_file(path); |
| 689 | } |
| 690 | written |
| 691 | } |
| 692 | |
| 693 | /// Android has no clipboard of images to read, and arboard no backend for it. |
| 694 | #[cfg(target_os = "android")] |
| 695 | fn clipboard_image_png(_path: &str) -> bool { |
| 696 | false |
| 697 | } |
| 698 | |
| 699 | /// Hand a URL to whatever shows web pages here; 1 when something took it. |
| 700 | /// |
| 701 | /// A sign-in flow leaves the app for a browser and comes back, so the app needs |
| 702 | /// a way to say "open this". What that means is the platform's business, not |
| 703 | /// the caller's: an `xdg-open`/`open` on the desktop, and on Android an |
| 704 | /// ACTION_VIEW intent, which is a JNI call — a shelled-out `am start` is |
| 705 | /// refused there, since `am` names `com.android.shell` as its calling package |
| 706 | /// and that is not the app's uid. |
| 707 | /// |
| 708 | /// Like the clipboard call this needs no window and no particular thread. |
| 709 | /// |
| 710 | /// # Safety |
| 711 | /// `url` is null or a NUL-terminated UTF-8 string. |
| 712 | #[no_mangle] |
| 713 | pub unsafe extern "C" fn vidya_open_url(url: *const c_char) -> c_int { |
| 714 | let url = borrowed_str(url); |
| 715 | guard(0, || { |
| 716 | if url.is_empty() { |
| 717 | return 0; |
| 718 | } |
| 719 | open_url(&url) as c_int |
| 720 | }) |
| 721 | } |
| 722 | |
| 723 | #[cfg(not(target_os = "android"))] |
| 724 | fn open_url(url: &str) -> bool { |
| 725 | let opener = if cfg!(target_os = "macos") { |
| 726 | "open" |
| 727 | } else { |
| 728 | "xdg-open" |
| 729 | }; |
| 730 | // Spawned, not waited on: the browser outlives the call, and on some |
| 731 | // desktops the opener itself stays in the foreground for as long as it |
| 732 | // does. |
| 733 | std::process::Command::new(opener) |
| 734 | .arg(url) |
| 735 | .stdout(std::process::Stdio::null()) |
| 736 | .stderr(std::process::Stdio::null()) |
| 737 | .spawn() |
| 738 | .is_ok() |
| 739 | } |
| 740 | |
| 741 | /// `startActivity(new Intent(ACTION_VIEW, Uri.parse(url)))` on the activity the |
| 742 | /// glue holds. Any JNI failure — or a device with nothing that answers the |
| 743 | /// intent — is a plain false; the caller shows the URL instead. |
| 744 | #[cfg(target_os = "android")] |
| 745 | fn open_url(url: &str) -> bool { |
| 746 | use jni::objects::JObject; |
| 747 | use jni::{jni_sig, jni_str}; |
| 748 | |
| 749 | let Some(app) = android::android_app() else { |
| 750 | android::warn("open_url: no AndroidApp handle"); |
| 751 | return false; |
| 752 | }; |
| 753 | // SAFETY: the glue owns both handles for the life of the activity, and |
| 754 | // hands them out as raw pointers for exactly this. |
| 755 | let vm = unsafe { jni::JavaVM::from_raw(app.vm_as_ptr().cast()) }; |
| 756 | let activity_ptr = app.activity_as_ptr().cast(); |
| 757 | |
| 758 | let started: jni::errors::Result<()> = vm.attach_current_thread(|env| { |
| 759 | // SAFETY: the activity outlives this frame, and the reference is a |
| 760 | // borrow of the glue's own, not one this side owns. |
| 761 | let activity = unsafe { JObject::from_raw(env, activity_ptr) }; |
| 762 | let url = env.new_string(url)?; |
| 763 | let uri = env |
| 764 | .call_static_method( |
| 765 | jni_str!("android/net/Uri"), |
| 766 | jni_str!("parse"), |
| 767 | jni_sig!("(Ljava/lang/String;)Landroid/net/Uri;"), |
| 768 | &[(&url).into()], |
| 769 | )? |
| 770 | .l()?; |
| 771 | let action = env.new_string("android.intent.action.VIEW")?; |
| 772 | let intent = env.new_object( |
| 773 | jni_str!("android/content/Intent"), |
| 774 | jni_sig!("(Ljava/lang/String;Landroid/net/Uri;)V"), |
| 775 | &[(&action).into(), (&uri).into()], |
| 776 | )?; |
| 777 | env.call_method( |
| 778 | &activity, |
| 779 | jni_str!("startActivity"), |
| 780 | jni_sig!("(Landroid/content/Intent;)V"), |
| 781 | &[(&intent).into()], |
| 782 | )?; |
| 783 | // An ActivityNotFoundException is thrown, not returned. Leaving it |
| 784 | // pending would fail the next JNI call on this thread, whoever made |
| 785 | // it, so it is caught here and read as "nothing took the URL". |
| 786 | if env.exception_check() { |
| 787 | env.exception_clear(); |
| 788 | return Err(jni::errors::Error::JavaException); |
| 789 | } |
| 790 | Ok(()) |
| 791 | }); |
| 792 | |
| 793 | if let Err(err) = &started { |
| 794 | android::warn(&format!("vidya_open_url: {err}")); |
| 795 | } |
| 796 | started.is_ok() |
| 797 | } |