| 1 | //! C ABI of the Blitz renderer for the Swift glue (ios/DemoApp/Sources/BlitzRenderer.swift); |
| 2 | //! the contract is include/twidget_blitz.h. Strings returned by `twb_*` are |
| 3 | //! owned by the caller and released with `twb_string_free`. |
| 4 | |
| 5 | use crate::renderer::Renderer; |
| 6 | use crate::{fonts, messages, with_renderer}; |
| 7 | use serde_json::Value; |
| 8 | use std::ffi::{c_char, CStr, CString}; |
| 9 | use std::panic::catch_unwind; |
| 10 | use std::sync::OnceLock; |
| 11 | |
| 12 | /// Panics and refused fetches go to stderr (Xcode's console); nothing else logs at info. |
| 13 | struct StderrLogger; |
| 14 | impl log::Log for StderrLogger { |
| 15 | fn enabled(&self, m: &log::Metadata) -> bool { |
| 16 | m.level() <= log::Level::Warn |
| 17 | } |
| 18 | fn log(&self, r: &log::Record) { |
| 19 | if self.enabled(r.metadata()) { |
| 20 | eprintln!("twidget-blitz [{}] {}", r.level(), r.args()); |
| 21 | } |
| 22 | } |
| 23 | fn flush(&self) {} |
| 24 | } |
| 25 | |
| 26 | fn init_logging() { |
| 27 | static ONCE: OnceLock<()> = OnceLock::new(); |
| 28 | ONCE.get_or_init(|| { |
| 29 | let _ = log::set_logger(&StderrLogger).map(|()| log::set_max_level(log::LevelFilter::Warn)); |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | unsafe fn c_str(s: *const c_char) -> String { |
| 34 | if s.is_null() { |
| 35 | return String::new(); |
| 36 | } |
| 37 | CStr::from_ptr(s).to_string_lossy().into_owned() |
| 38 | } |
| 39 | |
| 40 | fn ret_string(s: String) -> *mut c_char { |
| 41 | CString::new(s).map(CString::into_raw).unwrap_or(std::ptr::null_mut()) |
| 42 | } |
| 43 | |
| 44 | /// `theme`: "dark" or anything else (light). Null on failure. |
| 45 | #[no_mangle] |
| 46 | pub unsafe extern "C" fn twb_create(width: f64, dpr: f64, theme: *const c_char) -> *mut Renderer { |
| 47 | init_logging(); |
| 48 | let dark = c_str(theme) == "dark"; |
| 49 | match catch_unwind(|| Renderer::new(width, dpr, dark, fonts())) { |
| 50 | Ok(r) => Box::into_raw(Box::new(r)), |
| 51 | Err(_) => { |
| 52 | log::error!("renderer creation panicked"); |
| 53 | std::ptr::null_mut() |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[no_mangle] |
| 59 | pub unsafe extern "C" fn twb_destroy(handle: *mut Renderer) { |
| 60 | if !handle.is_null() { |
| 61 | drop(Box::from_raw(handle)); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Host → renderer message (JSON). Returns a JSON array of renderer → host messages. |
| 66 | #[no_mangle] |
| 67 | pub unsafe extern "C" fn twb_receive(handle: *mut Renderer, json: *const c_char) -> *mut c_char { |
| 68 | let text = c_str(json); |
| 69 | ret_string(with_renderer(handle, "[]".to_string(), |r| match serde_json::from_str::<Value>(&text) { |
| 70 | Ok(msg) => messages(r.receive(&msg)), |
| 71 | Err(e) => messages(vec![serde_json::json!({ "type": "violation", "detail": format!("bad message: {e}") })]), |
| 72 | })) |
| 73 | } |
| 74 | |
| 75 | #[no_mangle] |
| 76 | pub unsafe extern "C" fn twb_set_width(handle: *mut Renderer, width: f64) -> *mut c_char { |
| 77 | ret_string(with_renderer(handle, "[]".to_string(), |r| { |
| 78 | let mut out = Vec::new(); |
| 79 | r.set_width(width, &mut out); |
| 80 | messages(out) |
| 81 | })) |
| 82 | } |
| 83 | |
| 84 | #[no_mangle] |
| 85 | pub unsafe extern "C" fn twb_set_theme(handle: *mut Renderer, theme: *const c_char) -> *mut c_char { |
| 86 | let dark = c_str(theme) == "dark"; |
| 87 | ret_string(with_renderer(handle, "[]".to_string(), |r| { |
| 88 | let mut out = Vec::new(); |
| 89 | r.set_theme(dark, &mut out); |
| 90 | messages(out) |
| 91 | })) |
| 92 | } |
| 93 | |
| 94 | /// A touch in CSS px. action: 0 down, 1 move, 2 up, 3 cancel. Returns renderer → host messages. |
| 95 | #[no_mangle] |
| 96 | pub unsafe extern "C" fn twb_touch(handle: *mut Renderer, action: i32, x: f64, y: f64, pointer: |
| 97 | ret_string(with_renderer(handle, "[]".to_string(), |r| messages(r.touch(action, x, y, pointer, primary)))) |
| 98 | } |
| 99 | |
| 100 | /// Physical size of the next render. |
| 101 | #[no_mangle] |
| 102 | pub unsafe extern "C" fn twb_size(handle: *mut Renderer, width: *mut u32, height: *mut u32) { |
| 103 | let (w, h) = with_renderer(handle, (0, 0), |r| r.viewport_px()); |
| 104 | if !width.is_null() { |
| 105 | *width = w; |
| 106 | } |
| 107 | if !height.is_null() { |
| 108 | *height = h; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Picks the rasteriser: "vello" (default) or "cg" (CoreGraphics/CoreText, Apple only). |
| 113 | /// False when the name is unknown or unavailable on this platform. |
| 114 | #[no_mangle] |
| 115 | pub unsafe extern "C" fn twb_set_backend(handle: *mut Renderer, name: *const c_char) -> bool { |
| 116 | let Some(backend) = crate::Backend::parse(&c_str(name)) else { return false }; |
| 117 | with_renderer(handle, false, |r| { |
| 118 | r.set_backend(backend); |
| 119 | true |
| 120 | }) |
| 121 | } |
| 122 | |
| 123 | /// The active rasteriser's name ("vello" | "cg"); static, not to be freed. |
| 124 | #[no_mangle] |
| 125 | pub unsafe extern "C" fn twb_backend(handle: *mut Renderer) -> *const c_char { |
| 126 | match with_renderer(handle, crate::Backend::Vello, |r| r.backend()) { |
| 127 | crate::Backend::Vello => c"vello".as_ptr(), |
| 128 | crate::Backend::CoreGraphics => c"cg".as_ptr(), |
| 129 | crate::Backend::DisplayList => c"canvas".as_ptr(), |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | #[no_mangle] |
| 134 | pub unsafe extern "C" fn twb_dirty(handle: *mut Renderer) -> bool { |
| 135 | with_renderer(handle, false, |r| r.dirty) |
| 136 | } |
| 137 | |
| 138 | /// Paints into `buffer` (at least width*height*4 bytes, premultiplied RGBA8). Returns the paint time in ms, negative on failure. |
| 139 | #[no_mangle] |
| 140 | pub unsafe extern "C" fn twb_render(handle: *mut Renderer, buffer: *mut u8, capacity: usize) -> f64 |
| 141 | if buffer.is_null() { |
| 142 | return -1.0; |
| 143 | } |
| 144 | with_renderer(handle, -1.0, |r| r.render_into(buffer, capacity)) |
| 145 | } |
| 146 | |
| 147 | /// Diagnostics: the font collection (family count, emoji mapping). Release with `twb_string_free`. |
| 148 | #[no_mangle] |
| 149 | pub extern "C" fn twb_font_report() -> *mut c_char { |
| 150 | init_logging(); |
| 151 | ret_string(match catch_unwind(crate::font_report) { |
| 152 | Ok(s) => s, |
| 153 | Err(_) => "font report panicked".to_string(), |
| 154 | }) |
| 155 | } |
| 156 | |
| 157 | #[no_mangle] |
| 158 | pub unsafe extern "C" fn twb_string_free(s: *mut c_char) { |
| 159 | if !s.is_null() { |
| 160 | drop(CString::from_raw(s)); |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Caller-owned bytes in the renderer's heap (the wasm glue writes its UTF-8 |
| 165 | /// strings and takes its pixel buffer here); release with `twb_free` and the same length. |
| 166 | #[no_mangle] |
| 167 | pub extern "C" fn twb_alloc(len: usize) -> *mut u8 { |
| 168 | let mut v: Vec<u8> = Vec::with_capacity(len.max(1)); |
| 169 | let p = v.as_mut_ptr(); |
| 170 | std::mem::forget(v); |
| 171 | p |
| 172 | } |
| 173 | |
| 174 | #[no_mangle] |
| 175 | pub unsafe extern "C" fn twb_free(p: *mut u8, len: usize) { |
| 176 | if !p.is_null() { |
| 177 | drop(Vec::from_raw_parts(p, 0, len.max(1))); |
| 178 | } |
| 179 | } |
| 180 | |