//! Application, windows, entities and event dispatch, shaped like gpui: //! //! ```ignore //! Application::new().run(|cx: &mut App| { //! cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Counter { n: 0 })).unwrap(); //! }); //! ``` use std::any::{Any, TypeId}; use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use crate::element::{AnyElement, IntoElement, Listener, Listeners, SharedString}; use crate::events::*; use crate::geometry::{point, px, size, Bounds, Pixels, Size}; use crate::layout::{id_key, layout, Content, Frame, Key, LayoutCaches, UiState}; use crate::prof::{self, span, Phase}; use crate::window_kind::{WindowDecorations, WindowKind}; use crate::paint::{paint_frame, Painter}; use crate::selection::{Cx, Selector}; use crate::widgets::{WKind, Widgets}; use blenderui_sys as sys; // ========================================================================== // Entities /// State owned by the app (gpui's `Entity`): a `Copy` handle (slot index /// and generation) into the app's entity slots. No reference counting. pub struct Entity { id: u32, generation: u32, _t: PhantomData T>, } impl Clone for Entity { fn clone(&self) -> Self { *self } } impl Copy for Entity {} /// One entity's storage. The value is moved out while it is being updated. struct Slot { generation: u32, value: Option>, } impl Entity { /// Read the value. pub fn read<'a>(&self, cx: &'a App) -> &'a T { let slot = &cx.entities[self.id as usize]; assert!(slot.generation == self.generation, "entity was released"); slot.value.as_ref().expect("entity is being built or updated") .downcast_ref::().expect("entity type") } /// Mutate the value with a [`Context`] for it. The value is taken out of /// its slot meanwhile, so `cx` stays fully usable (except for updating /// this same entity again, which panics). pub fn update(&self, cx: &mut App, f: impl FnOnce(&mut T, &mut Context) -> R) -> R { let slot = &mut cx.entities[self.id as usize]; assert!(slot.generation == self.generation, "entity was released"); let mut value = slot.value.take().expect("entity is being built or already being updated"); let r = { let v = value.downcast_mut::().expect("entity type"); let mut ctx = Context { app: cx, entity: *self }; f(v, &mut ctx) }; cx.entities[self.id as usize].value = Some(value); r } /// Same entity? pub fn entity_id(&self) -> usize { self.id as usize } pub fn downgrade(&self) -> WeakEntity { WeakEntity { entity: *self } } } /// A handle that may outlive its entity (gpui's `WeakEntity`). pub struct WeakEntity { entity: Entity, } impl Clone for WeakEntity { fn clone(&self) -> Self { *self } } impl Copy for WeakEntity {} impl WeakEntity { /// The entity, if it hasn't been released. pub fn upgrade_in(&self, cx: &App) -> Option> { let slot = cx.entities.get(self.entity.id as usize)?; (slot.generation == self.entity.generation).then_some(self.entity) } /// Update if still alive. pub fn update(&self, cx: &mut App, f: impl FnOnce(&mut T, &mut Context) -> R) -> Option { self.upgrade_in(cx).map(|e| e.update(cx, f)) } } /// The app, seen from inside an entity (gpui's `Context`); derefs to [`App`]. pub struct Context<'a, T> { app: &'a mut App, entity: Entity, } impl Deref for Context<'_, T> { type Target = App; fn deref(&self) -> &App { self.app } } impl DerefMut for Context<'_, T> { fn deref_mut(&mut self) -> &mut App { self.app } } impl Context<'_, T> { /// This entity. pub fn entity(&self) -> Entity { self.entity } pub fn weak_entity(&self) -> WeakEntity { self.entity.downgrade() } /// Re-render the windows showing this entity. pub fn notify(&mut self) { self.app.notify_all(); } /// Turn a method-like closure into an element listener (gpui's `cx.listener`). pub fn listener( &self, f: impl Fn(&mut T, &E, &mut Window, &mut Context) + 'static, ) -> impl Fn(&E, &mut Window, &mut App) + 'static { let weak = self.entity.downgrade(); move |e: &E, window: &mut Window, cx: &mut App| { weak.update(cx, |this, cx| f(this, e, window, cx)); } } } /// A view: something that renders an element tree (gpui's `Render`). pub trait Render: 'static + Sized { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement; } // ========================================================================== // The application /// Window identity. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct WindowId(pub usize); /// A typed window handle (gpui's `WindowHandle`). pub struct WindowHandle { pub id: WindowId, entity: Entity, } impl Clone for WindowHandle { fn clone(&self) -> Self { WindowHandle { id: self.id, entity: self.entity } } } impl WindowHandle { /// The root view of the window. pub fn root(&self) -> Entity { self.entity } /// Update the root view with its window. pub fn update(&self, cx: &mut App, f: impl FnOnce(&mut V, &mut Window, &mut Context) -> R) -> Option { let mut w = cx.windows.get_mut(self.id.0)?.take()?; let notified = cx.notified; let r = self.entity.update(cx, |v, cx| f(v, &mut w, cx)); if cx.notified != notified { w.refresh(); // `cx.notify()` ran while this window was out of the list } cx.windows[self.id.0] = Some(w); Some(r) } } /// How a window opens (gpui's `WindowBounds`). #[derive(Clone, Copy, Debug)] pub enum WindowBounds { Windowed(Bounds), Maximized(Bounds), Fullscreen(Bounds), } /// How the window's background shows (gpui's `WindowBackgroundAppearance`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum WindowBackgroundAppearance { #[default] Opaque, /// Per-pixel alpha: only the elements show. On Windows the window has no frame. Transparent, } #[derive(Clone, Debug, Default)] pub struct TitlebarOptions { pub title: Option, } /// Options for [`App::open_window`] (gpui's `WindowOptions`). #[derive(Clone, Debug, Default)] pub struct WindowOptions { pub window_bounds: Option, pub titlebar: Option, pub is_resizable: Option, pub window_min_size: Option>, /// Draw this window on the GPU (Direct3D 11 / OpenGL 3.3) instead of the software /// raster; `None` follows [`Application::gpu`] / the `BUI_GPU` variable. pub gpu: Option, pub window_background: WindowBackgroundAppearance, pub kind: WindowKind, pub window_decorations: WindowDecorations, } /// The application entry point (gpui's `Application`). pub struct Application { headless: bool, gpu: Option, slug: Option, keep_alive: bool, theme: Option, } impl Default for Application { fn default() -> Self { Application::new() } } impl Application { /// Native windows. pub fn new() -> Application { Application { headless: false, gpu: None, slug: None, keep_alive: false, theme: None } } /// Draw every window on the GPU (Direct3D 11 on Windows): the same /// pixels as the software raster, with rasterization off the CPU. Falls /// back to software where no device exists. The `BUI_GPU` environment /// variable (1/0) overrides this. pub fn gpu(mut self, on: bool) -> Application { self.gpu = Some(on); self } /// How the GPU renderer draws text: `true` for Slug (glyph outlines in /// the pixel shader, sharp at any size), `false` for a per-glyph bitmap /// atlas like Blender's (less GPU work). Defaults to the `slug` feature; /// `BUI_SLUG=1`/`0` overrides. See also [`crate::set_slug`]. pub fn slug(mut self, on: bool) -> Application { self.slug = Some(on); self } /// Blender's `"dark"` (default) or `"light"` theme for every window (see /// [`crate::set_theme`]); the `BUI_THEME` variable applies otherwise. pub fn theme(mut self, name: &str) -> Application { self.theme = Some(name.to_string()); self } /// Keep the event loop running with no windows open, until /// [`App::quit`]: for apps driven from another thread ([`App::ui_sender`]). pub fn keep_alive(mut self, on: bool) -> Application { self.keep_alive = on; self } /// Off-screen windows (tests, screenshots, CI): nothing is shown, the /// `simulate_*` and `draw` methods drive it. pub fn headless() -> Application { Application { headless: true, gpu: None, slug: None, keep_alive: false, theme: None } } /// Run `f`, then the event loop until every window is closed. pub fn run(self, f: impl FnOnce(&mut App)) { // the C kit keeps global state: one application at a time per process static KIT: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _guard = KIT.lock().unwrap_or_else(|e| e.into_inner()); let headless = self.headless || unsafe { sys::BK_window_supported() } == 0; if let Some(on) = self.gpu { unsafe { sys::BUI_gpu_set_default(on as c_int) }; } if let Some(on) = self.slug { crate::set_slug(on); } if let Some(t) = &self.theme { crate::set_theme(t); } if headless { // off-screen windows have no monitor DPI: BUI_UI_SCALE (e.g. 2 for // retina-sharp screenshots) sets the resolution scale if let Some(s) = std::env::var("BUI_UI_SCALE").ok().and_then(|v| v.parse::().ok()) { unsafe { sys::BK_set_scale(s) }; } } let mut app = App::create(headless); f(&mut app); app.flush(); if headless { app.shutdown(); return; } // the app stays on this stack frame; kit callbacks reach it through APP APP.with(|a| a.set(&mut app as *mut App)); unsafe { sys::BK_window_set_keep_alive(self.keep_alive as c_int) }; // SAFETY: plain message loop; `app` isn't touched here until it returns. unsafe { sys::BK_window_run() }; APP.with(|a| a.set(std::ptr::null_mut())); app.shutdown(); } } thread_local! { /// The app while the native loop runs (it lives on `Application::run`'s stack). static APP: Cell<*mut App> = const { Cell::new(std::ptr::null_mut()) }; /// Set while a callback holds the app (a re-entrant callback must not). static BUSY: Cell = const { Cell::new(false) }; /// Kit events, handled in order once the app is free. static QUEUE: Cell> = const { Cell::new(VecDeque::new()) }; } fn queue_push(ev: RawEvent) { QUEUE.with(|q| { let mut v = q.take(); v.push_back(ev); q.set(v); }); } fn queue_pop() -> Option { QUEUE.with(|q| { let mut v = q.take(); let ev = v.pop_front(); q.set(v); ev }) } struct RawEvent { window: usize, node: *mut sys::BKNode, kind: c_int, text: String, a: f64, b: f64, } /// The application state (gpui's `App`). pub struct App { windows: Vec>>, entities: Vec, headless: bool, globals: HashMap>, pub(crate) propagate: bool, /// Work sent from other threads ([`UiSender`]). remote: Option<(std::sync::mpsc::Sender, std::sync::mpsc::Receiver)>, /// Called when the user closes a window. close_hooks: Vec>, /// Called when a window gets or loses the keyboard focus. activation_hooks: Vec>, /// Counts `notify_all` calls (see `WindowHandle::update`). notified: u64, } type RemoteJob = Box; /// Runs closures on the UI thread from any thread ([`App::ui_sender`]): /// the UI loop wakes, runs them in order, then re-renders what they changed. #[derive(Clone)] pub struct UiSender { tx: std::sync::mpsc::Sender, } impl UiSender { /// Queue `f` for the UI thread. False when the app has ended. pub fn send(&self, f: impl FnOnce(&mut App) + Send + 'static) -> bool { let ok = self.tx.send(Box::new(f)).is_ok(); // SAFETY: posts a message; callable from any thread. unsafe { sys::BK_window_wake() }; ok } } unsafe extern "C" fn on_wake() { let ran = with_running_app(|app| { app.drain(); app.flush(); }); if !ran { // a callback further up holds the app: try again on the next turn unsafe { sys::BK_window_wake() }; } } impl App { fn create(headless: bool) -> App { crate::motion::start_clock(!headless); App { windows: Vec::new(), entities: Vec::new(), headless, globals: HashMap::new(), propagate: true, remote: None, close_hooks: Vec::new(), activation_hooks: Vec::new(), notified: 0 } } /// Create an entity (gpui's `cx.new`). pub fn new(&mut self, build: impl FnOnce(&mut Context) -> T) -> Entity { let id = self.entities.len() as u32; self.entities.push(Slot { generation: 0, value: None }); let entity = Entity { id, generation: 0, _t: PhantomData }; let v = build(&mut Context { app: self, entity }); self.entities[id as usize].value = Some(Box::new(v)); entity } /// Drop an entity's value. Its handles become dead: `WeakEntity::update` /// skips them, `Entity::read` / `update` panic. pub fn release(&mut self, entity: Entity) { if let Some(slot) = self.entities.get_mut(entity.id as usize).filter(|s| s.generation == entity.generation) { slot.value = None; slot.generation += 1; } } /// Open a window whose root view is built by `build`. pub fn open_window( &mut self, options: WindowOptions, build: impl FnOnce(&mut Window, &mut App) -> Entity, ) -> Result, String> { let bounds = match options.window_bounds { Some(WindowBounds::Windowed(b) | WindowBounds::Maximized(b) | WindowBounds::Fullscreen(b)) => b, None => Bounds { origin: point(px(0.0), px(0.0)), size: size(px(1024.0), px(700.0)) }, }; let title = options.titlebar.as_ref().and_then(|t| t.title.clone()) .map(|t| t.to_string()).unwrap_or_else(|| "BUI".into()); let id = self.windows.len(); let mut w = Window::create(id, &title, bounds.size.width.0, bounds.size.height.0, self.headless)?; if let Some(n) = &w.native { unsafe { if let Some(WindowBounds::Maximized(_)) = options.window_bounds { sys::BK_window_wm(*n, c"state".as_ptr(), 1.0, 0.0); } if options.is_resizable == Some(false) { sys::BK_window_wm(*n, c"resizable".as_ptr(), 0.0, 0.0); } if let Some(m) = options.window_min_size { sys::BK_window_wm(*n, c"minsize".as_ptr(), (m.width.0 * w.scale) as f64, (m.height.0 * w.scale) as f64); } if options.window_background == WindowBackgroundAppearance::Transparent { sys::BK_window_wm(*n, c"transparent".as_ptr(), 1.0, 0.0); } for (key, a, b) in options.kind.requests(options.window_decorations) { sys::BK_window_wm(*n, key.as_ptr(), a, b); } if options.gpu == Some(true) { sys::BK_window_set_gpu(*n, 1); } } } let entity = build(&mut w, self); let view = entity; w.view = Some(Box::new(move |window: &mut Window, cx: &mut App| { view.update(cx, |v, cx| v.render(window, cx).into_any_element()) })); w.dirty = true; self.windows.push(Some(Box::new(w))); if !self.headless { self.with_window(id, |w, app| w.rebuild(app)); if let Some(n) = self.window(WindowId(id)).and_then(|w| w.native) { unsafe { sys::BK_window_show(n) }; } } Ok(WindowHandle { id: WindowId(id), entity }) } /// Mark every window for re-render. pub fn notify_all(&mut self) { self.notified = self.notified.wrapping_add(1); for w in self.windows.iter_mut().flatten() { w.refresh(); } } /// A handle other threads use to run code on this (the UI) thread. pub fn ui_sender(&mut self) -> UiSender { if self.remote.is_none() { self.remote = Some(std::sync::mpsc::channel()); if !self.headless { unsafe { sys::BK_window_wake_init(Some(on_wake)) }; } } UiSender { tx: self.remote.as_ref().map(|(tx, _)| tx.clone()).unwrap() } } /// Run work queued by [`UiSender`]s and re-render what changed (for a /// loop that isn't the native one, e.g. headless apps driven by /// another thread). pub fn run_pending(&mut self) { self.drain(); self.flush(); } /// Call `f` whenever the user closes a window. pub fn on_window_closed(&mut self, f: impl FnMut(WindowId, &mut App) + 'static) { self.close_hooks.push(Box::new(f)); } /// Call `f` with `true` when a window gets the keyboard focus and `false` when it /// loses it (gpui's `observe_window_activation`). pub fn on_window_activation(&mut self, f: impl FnMut(WindowId, bool, &mut App) + 'static) { self.activation_hooks.push(Box::new(f)); } /// Close a window (as if the user had). pub fn close_window(&mut self, id: WindowId) { if let Some(w) = self.windows.get_mut(id.0).and_then(|w| w.as_deref_mut()) { w.closed = true; if let Some(n) = w.native { unsafe { sys::BK_window_close(n) }; } } } /// Stop the event loop. pub fn quit(&mut self) { unsafe { sys::BK_window_quit() }; } /// Stop the current event from reaching ancestors. pub fn stop_propagation(&mut self) { self.propagate = false; } /// Activate the app (no-op: windows come to the front when shown). pub fn activate(&mut self, _ignoring_other_apps: bool) {} pub fn set_global(&mut self, g: G) { self.globals.insert(TypeId::of::(), Box::new(g)); } pub fn global(&self) -> &G { self.try_global().expect("global not set") } pub fn try_global(&self) -> Option<&G> { self.globals.get(&TypeId::of::()).and_then(|g| g.downcast_ref()) } pub fn global_mut(&mut self) -> &mut G { self.globals.get_mut(&TypeId::of::()).and_then(|g| g.downcast_mut()).expect("global not set") } pub fn window(&self, id: WindowId) -> Option<&Window> { self.windows.get(id.0)?.as_deref() } fn with_window(&mut self, id: usize, f: impl FnOnce(&mut Window, &mut App) -> R) -> Option { let mut w = self.windows.get_mut(id)?.take()?; let r = f(&mut w, self); self.windows[id] = Some(w); Some(r) } /// Handle queued kit events, then re-render what changed. fn drain(&mut self) { while let Some(ev) = queue_pop() { self.with_window(ev.window, |w, app| w.dispatch(ev, app)); } // work from other threads (UiSender) loop { let job = match &self.remote { Some((_, rx)) => rx.try_recv().ok(), None => None, }; match job { Some(f) => f(self), None => break, } } } /// Re-render dirty windows now (headless) or soon (native: next loop turn). fn flush(&mut self) { self.drain(); // windows whose signals were written (hooks) for id in crate::hooks::take_dirty() { if id == usize::MAX { self.notify_all(); } else if let Some(w) = self.windows.get_mut(id).and_then(|w| w.as_deref_mut()) { w.refresh(); } } for id in 0..self.windows.len() { let Some(w) = self.windows[id].as_deref_mut() else { continue }; if !w.dirty && !w.scrolled && !w.motion_frame && !w.sel_repaint { continue; } match w.native { // animation: rebuild right before the next (vsync-paced) render Some(n) if w.animation_frame => { w.animation_frame = false; w.frame_pending = true; unsafe { sys::BK_window_request_frame(n, c_int::from(w.vsync)) }; } // the requested frame rebuilds the window at its paced time Some(n) if !w.timer_pending && !w.frame_pending => { w.timer_pending = true; unsafe { sys::BK_window_timer(n, 0) }; } Some(_) => {} None => { self.with_window(id, |w, app| w.update(app)); } } } } fn shutdown(&mut self) { for w in self.windows.iter_mut().flatten() { w.destroy(); } self.windows.clear(); } // -- automation (tests, screenshots) -------------------------------------------------- /// Render a window off-screen: (width, height, 0x00RRGGBB pixels) in device pixels. /// Images it shows are decoded first (the frame waits for the kit's /// image workers), so the pixels are deterministic. pub fn draw(&mut self, id: WindowId) -> (usize, usize, Vec) { self.flush(); let Some(w) = self.windows.get_mut(id.0).and_then(|w| w.as_deref_mut()) else { return (0, 0, Vec::new()); }; let (pw, ph) = w.phys; // A native window's raster is what it presents next, and the pixels the kit compares frames with // belong to it: drawing into it here would take the damage of frames nobody presented, and // leave their old pixels on the screen. It gets its own raster, and the window repaints all. let own = w.native.is_some(); // SAFETY: the raster is sized to the window; pixels are copied out. let px = unsafe { if !own && w.raster.is_null() { w.raster = sys::BUI_raster_create(pw, ph); } let target = if own { sys::BUI_raster_create(pw, ph) } else { w.raster }; let _s = span(Phase::Widgets); sys::BK_render(w.ctx, target, pw, ph, 1); // decodes this frame asked for: wait, then draw what arrived let mut st = sys::BKImageStats::default(); sys::BK_image_stats(&raw mut st); for _ in 0..10_000 { if st.pending == 0 { break; } std::thread::sleep(std::time::Duration::from_micros(200)); sys::BK_image_stats(&raw mut st); } if sys::BK_image_poll() > 0 { sys::BK_render(w.ctx, target, pw, ph, 0); } let p = sys::BUI_raster_pixels(target); let px = std::slice::from_raw_parts(p, (pw * ph) as usize).to_vec(); if own { sys::BUI_raster_free(target); sys::BK_node_relayout(w.root); // the window's own next render covers everything again } px }; self.flush(); // configure events from the render (pw as usize, ph as usize, px) } /// A frame the way a native window draws it, and the same frame in full: what the kit repaints /// where something changed (on the pixels of the last frame), and a fresh render of everything. /// They must be equal; a difference is a damaged region that was lost. (Tests: draw once first.) #[doc(hidden)] pub fn draw_partial_and_full(&mut self, id: WindowId) -> (usize, usize, Vec, Vec, Vec<[i32; 4]>) { self.flush(); let Some(w) = self.windows.get_mut(id.0).and_then(|w| w.as_deref_mut()) else { return (0, 0, Vec::new(), Vec::new(), Vec::new()); }; let (pw, ph) = w.phys; // SAFETY: the rasters are sized to the window; pixels are copied out. let (partial, full, damage) = unsafe { if w.raster.is_null() { w.raster = sys::BUI_raster_create(pw, ph); } sys::BK_render(w.ctx, w.raster, pw, ph, 0); let p = sys::BUI_raster_pixels(w.raster); let partial = std::slice::from_raw_parts(p, (pw * ph) as usize).to_vec(); // what a window's present would copy to the screen let mut rects: *const [c_int; 4] = std::ptr::null(); let n = sys::BUI_raster_damage(w.raster, &raw mut rects); let damage = if rects.is_null() { Vec::new() } else { std::slice::from_raw_parts(rects, n as usize).to_vec() }; let fresh = sys::BUI_raster_create(pw, ph); sys::BK_render(w.ctx, fresh, pw, ph, 1); let p = sys::BUI_raster_pixels(fresh); let full = std::slice::from_raw_parts(p, (pw * ph) as usize).to_vec(); sys::BUI_raster_free(fresh); (partial, full, damage) }; self.flush(); (pw as usize, ph as usize, partial, full, damage) } /// Bring a window's layout up to date (what `element_bounds` reads) without drawing it: a native /// window draws itself on its next frame, and [`draw`](Self::draw) would be a second, unpresented one. /// /// An off-screen window has no loop of its own: it is drawn, which is also what lays the kit out. pub fn layout(&mut self, id: WindowId) { let native = self.windows.get(id.0).and_then(|w| w.as_deref()).is_some_and(|w| w.native.is_some()); if native { self.flush(); self.with_window(id.0, |w, app| w.update(app)); } else { self.draw(id); } } /// Move every window's CSS animation clock forward by `d`. Headless /// windows' clocks stand still otherwise, so tests step animations and /// transitions deterministically; native windows add `d` to real time. pub fn advance_clock(&mut self, d: std::time::Duration) { crate::motion::advance(d.as_secs_f64()); for w in self.windows.iter_mut().flatten() { w.clock.advance(d); if w.caches.anim.any() { w.dirty = true; } else if crate::motion::active() { w.request_motion_frame(); } } self.flush(); } /// Bounds (logical pixels) of the element with `.id(id)`. pub fn element_bounds(&mut self, window: WindowId, id: &str) -> Option> { self.flush(); let w = self.window(window)?; let f = w.frame.as_ref()?; f.by_key().get(&id_key(id)).map(|&i| f.nodes[i].bounds) } fn input(&mut self, window: WindowId, f: impl FnOnce(*mut sys::BKContext, f32)) { self.flush(); if let Some(w) = self.window(window) { if w.frame.is_none() { return; } f(w.ctx, w.scale); } self.flush(); } /// Move the pointer to (x, y) in logical pixels. pub fn simulate_mouse_move(&mut self, window: WindowId, x: f32, y: f32) { self.input(window, |ctx, s| unsafe { sys::BK_motion(ctx, (x * s) as c_int, (y * s) as c_int, 0); }); } /// Press and release the left button at (x, y). pub fn simulate_click(&mut self, window: WindowId, x: f32, y: f32) { self.simulate_mouse_move(window, x, y); self.input(window, |ctx, s| unsafe { sys::BK_press(ctx, (x * s) as c_int, (y * s) as c_int, 0); }); self.input(window, |ctx, s| unsafe { sys::BK_release(ctx, (x * s) as c_int, (y * s) as c_int, sys::BK_BUTTON1); }); } /// Click at (x, y) with modifier keys held (`ctrl`, `shift`). pub fn simulate_click_with(&mut self, window: WindowId, x: f32, y: f32, ctrl: bool, shift: bool) { let mods = c_int::from(shift) | (c_int::from(ctrl) << 1); self.simulate_mouse_move(window, x, y); self.input(window, |ctx, s| unsafe { sys::BK_press(ctx, (x * s) as c_int, (y * s) as c_int, mods); }); self.input(window, |ctx, s| unsafe { sys::BK_release(ctx, (x * s) as c_int, (y * s) as c_int, sys::BK_BUTTON1 | mods); }); } /// Press the left button at (x, y) (and hold it: see [`simulate_release`](Self::simulate_release)). pub fn simulate_press(&mut self, window: WindowId, x: f32, y: f32) { self.simulate_mouse_move(window, x, y); self.input(window, |ctx, s| unsafe { sys::BK_press(ctx, (x * s) as c_int, (y * s) as c_int, 0); }); } /// Let go of the left button at (x, y). pub fn simulate_release(&mut self, window: WindowId, x: f32, y: f32) { self.input(window, |ctx, s| unsafe { sys::BK_release(ctx, (x * s) as c_int, (y * s) as c_int, sys::BK_BUTTON1); }); } /// Press at `from`, drag to `to` and release there. pub fn simulate_drag(&mut self, window: WindowId, from: (f32, f32), to: (f32, f32)) { self.simulate_mouse_move(window, from.0, from.1); self.input(window, |ctx, s| unsafe { sys::BK_press(ctx, (from.0 * s) as c_int, (from.1 * s) as c_int, 0); }); for k in 1..=4 { let t = k as f32 / 4.0; let (x, y) = (from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t); self.input(window, |ctx, s| unsafe { sys::BK_motion(ctx, (x * s) as c_int, (y * s) as c_int, sys::BK_BUTTON1); }); } self.input(window, |ctx, s| unsafe { sys::BK_release(ctx, (to.0 * s) as c_int, (to.1 * s) as c_int, sys::BK_BUTTON1); }); } /// A key with modifier keys held. pub fn simulate_key_with(&mut self, window: WindowId, text: &str, keysym: &str, ctrl: bool, shift: bool) { let mods = c_int::from(shift) | (c_int::from(ctrl) << 1); let (t, k) = (CString::new(text).unwrap_or_default(), CString::new(keysym).unwrap_or_default()); self.input(window, |ctx, _| unsafe { sys::BK_key(ctx, t.as_ptr(), k.as_ptr(), mods); }); } /// Scroll the wheel at (x, y): positive `lines` scroll the content up. pub fn simulate_scroll(&mut self, window: WindowId, x: f32, y: f32, lines: i32) { self.simulate_mouse_move(window, x, y); self.input(window, |ctx, s| unsafe { sys::BK_wheel(ctx, (x * s) as c_int, (y * s) as c_int, lines, 0); }); } /// A touch drag at (x, y): the content moves `dy` logical pixels down (negative: up), exactly. pub fn simulate_scroll_px(&mut self, window: WindowId, x: f32, y: f32, dy: f32) { self.simulate_mouse_move(window, x, y); self.input(window, |ctx, s| unsafe { sys::BK_scroll_px(ctx, (x * s) as c_int, (y * s) as c_int, 0.0, dy * s, 0); }); } /// Type text / press a key (`keysym` as in Tk: "Return", "BackSpace", "a" ...). pub fn simulate_key(&mut self, window: WindowId, text: &str, keysym: &str) { let (t, k) = (CString::new(text).unwrap_or_default(), CString::new(keysym).unwrap_or_default()); self.input(window, |ctx, _| unsafe { sys::BK_key(ctx, t.as_ptr(), k.as_ptr(), 0); }); } } // ========================================================================== // Kit callbacks unsafe extern "C" fn on_emit(data: *mut c_void, node: *mut sys::BKNode, kind: c_int, ref_: *mut c_void, a: c_double, b: c_double) { crate::screen::kit_event(node, kind, a, b); // areas made and freed: known at once let text = if ref_.is_null() || kind < sys::BK_EV_PRESS { String::new() } else { // SAFETY: raw events carry a C string in `ref`. unsafe { CStr::from_ptr(ref_ as *const c_char) }.to_string_lossy().into_owned() }; queue_push(RawEvent { window: data as usize, node, kind, text, a, b }); with_running_app(|app| app.flush()); } static FRAMES_PRESENTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Frames drawn by every window so far (full renders and redraws of moving /// values alike): a frame counter for benchmarks and overlays, readable from /// any thread. pub fn frames_presented() -> u64 { FRAMES_PRESENTED.load(std::sync::atomic::Ordering::Relaxed) } unsafe extern "C" fn on_timer(data: *mut c_void, _win: *mut sys::BKWindow, _id: c_int) { let id = data as usize; let ran = with_running_app(|app| { app.drain(); app.with_window(id, |w, app| { w.timer_pending = false; w.update(app); }); app.flush(); }); if !ran { // the app is busy (re-entrant callback): try again next turn unsafe { sys::BK_window_timer(_win, 1) }; } } unsafe extern "C" fn on_frame(data: *mut c_void, _win: *mut sys::BKWindow) { // BUI_PROFILE: wall time between frames, i.e. rebuild + kit render + present thread_local! { static LAST: std::cell::Cell> = const { std::cell::Cell::new(None) }; } if prof::on() { let now = std::time::Instant::now(); if let Some(t) = LAST.with(|l| l.replace(Some(now))) { prof::add(Phase::FrameInterval, (now - t).as_secs_f64() * 1000.0); } } let id = data as usize; with_running_app(|app| { app.drain(); app.with_window(id, |w, app| { w.frame_pending = false; w.update(app); }); app.flush(); }); } unsafe extern "C" fn on_close(data: *mut c_void, _win: *mut sys::BKWindow) -> c_int { let id = data as usize; with_running_app(|app| { if let Some(w) = app.windows.get_mut(id).and_then(|w| w.as_deref_mut()) { w.closed = true; } run_hooks(app, |a| &mut a.close_hooks, |h, app| h(WindowId(id), app)); }); 1 } unsafe extern "C" fn on_focus(data: *mut c_void, _win: *mut sys::BKWindow, active: c_int) { let id = data as usize; with_running_app(|app| { run_hooks(app, |a| &mut a.activation_hooks, |h, app| h(WindowId(id), active != 0, app)); }); } /// Call each hook; hooks a hook adds run from the next call. fn run_hooks(app: &mut App, list: fn(&mut App) -> &mut Vec>, mut call: impl FnMut(&mut H, &mut App)) { let mut hooks = std::mem::take(list(app)); hooks.iter_mut().for_each(|h| call(h, app)); hooks.append(list(app)); *list(app) = hooks; } /// Run `f` with the app, unless there is none (before the loop, headless) /// or a callback further up the stack already holds it. fn with_running_app(f: impl FnOnce(&mut App)) -> bool { let app = APP.with(Cell::get); if app.is_null() || BUSY.with(Cell::get) { return false; } BUSY.with(|b| b.set(true)); // SAFETY: `app` points at the live App on `Application::run`'s stack, // which isn't touched while the loop runs; BUSY keeps this `&mut` unique. f(unsafe { &mut *app }); BUSY.with(|b| b.set(false)); true } unsafe extern "C" fn noop(_: *mut c_void) {} unsafe extern "C" { /// The C runtime's `free`, for strings the kit allocates (the clipboard). fn free(p: *mut c_void); } // ========================================================================== // Windows type ViewFn = Box AnyElement>; /// A window (gpui's `Window`): its kit context, layout and interaction state. pub struct Window { id: usize, ctx: *mut sys::BKContext, canvas: *mut sys::BKNode, /// The canvases over the first one (see `Painter`: items that overlap a /// widget are drawn on a canvas above it), made as needed. overlays: Vec<*mut sys::BKNode>, /// `canvas`, then `overlays`: what `Painter::flush` fills. canvases: Vec<*mut sys::BKNode>, root: *mut sys::BKNode, opaque: bool, native: Option<*mut sys::BKWindow>, raster: *mut sys::BuiRaster, phys: (i32, i32), scale: f32, view: Option, frame: Option, /// Styles, text widths, images, the author sheet and the taffy tree: /// kept across frames. caches: LayoutCaches, /// The display list, reused every frame. painter: Painter, state: UiState, widgets: Widgets, /// Blender screens (`blenderui::screen`): their kit nodes, by element key. screens: crate::screen::Screens, dirty: bool, /// Only scroll offsets changed since the last frame: it is placed again, not rendered /// (when [`scroll_free`](Self::scroll_free)). scrolled: bool, /// The last render did not depend on scroll positions: nothing read them (`scroll_offset`, /// `bounds_of`), nothing animates and no container sticks to its end. scroll_free: bool, /// A view read a scroll position or a placement this render (it must render again to follow it). scroll_read: std::cell::Cell, timer_pending: bool, frame_pending: bool, animation_frame: bool, /// The next frame is Motion's values alone: a redraw (no render or layout). motion_frame: bool, /// CSS animation time (virtual in headless windows). clock: crate::anim::Clock, vsync: bool, closed: bool, title: String, cursor: i32, pointer: (f32, f32), pressed: Vec, press_button: MouseButton, /// A scrollbar thumb being dragged: the container and where on the thumb it was grabbed. sb_drag: Option<(Key, f32)>, /// `data-stick="bottom"` containers: the scroll range last frame (to see when content grew). stuck: HashMap, /// The text selection (see `selection`). selector: Selector, /// The press in progress changed only the text selection: nothing answers to it, so it and its /// release render nothing (the selection is drawn on the frame as it is). press_quiet: bool, /// The next `present` shows the frame it already showed (a selection change): its text boxes are /// the same, so the selection's index of them stays. same_frame: bool, /// The selection changed: the next frame paints it again (no render, no layout). sel_repaint: bool, /// Called when the selection changes, with the selected text if any. selection_hooks: Vec, &mut Window, &mut App)>>, } impl Window { fn create(id: usize, title: &str, w: f32, h: f32, headless: bool) -> Result { // SAFETY: building a fresh kit tree; pointers stay owned by this window. unsafe { let root = sys::BK_node_new(c"frame".as_ptr()); let canvas = sys::BK_node_new(c"canvas".as_ptr()); if root.is_null() || canvas.is_null() { return Err("kit nodes unavailable".into()); } sys::BK_node_add(root, canvas, -1); sys::BK_geom_set_manager(canvas, sys::BK_GEOM_PLACE); sys::BK_geom_set(canvas, c"relwidth".as_ptr(), 1.0); sys::BK_geom_set(canvas, c"relheight".as_ptr(), 1.0); sys::BK_set_num(canvas, c"events".as_ptr(), 1.0); let ctx = sys::BK_context_new(root); let host = sys::BKHost { data: id as *mut c_void, request: Some(noop), set_cursor: None, warp: None, clipboard_get: None, clipboard_set: None, schedule: None, emit: Some(on_emit), }; sys::BK_context_set_host(ctx, &host); let mut win = Window { id, ctx, canvas, overlays: Vec::new(), canvases: vec![canvas], root, opaque: false, native: None, raster: std::ptr::null_mut(), phys: (w.round() as i32, h.round() as i32), scale: 1.0, view: None, frame: None, caches: LayoutCaches::default(), painter: Painter::new(), state: UiState::default(), widgets: Widgets::new(), screens: crate::screen::Screens::default(), dirty: true, scrolled: false, scroll_free: false, scroll_read: std::cell::Cell::new(false), timer_pending: false, frame_pending: false, animation_frame: false, motion_frame: false, clock: crate::anim::Clock::new(!headless), vsync: true, closed: false, title: title.to_owned(), cursor: 0, pointer: (-1.0, -1.0), pressed: Vec::new(), press_button: MouseButton::Left, sb_drag: None, stuck: HashMap::new(), selector: Selector::default(), press_quiet: false, same_frame: false, sel_repaint: false, selection_hooks: Vec::new(), }; if headless { win.scale = sys::BK_scale().max(1.0); win.phys = ((w * win.scale).round() as i32, (h * win.scale).round() as i32); } else { let t = CString::new(title).unwrap_or_default(); let n = sys::BK_window_new(ctx, t.as_ptr(), w.round() as c_int, h.round() as c_int); if n.is_null() { return Err("could not create a native window".into()); } let cb = sys::BKWindowCallbacks { data: id as *mut c_void, on_timer: Some(on_timer), on_close: Some(on_close), on_frame: Some(on_frame), on_focus: Some(on_focus) }; sys::BK_window_set_callbacks(n, &cb); win.scale = sys::BK_scale().max(0.5); win.phys = ((w * win.scale).round() as i32, (h * win.scale).round() as i32); win.native = Some(n); } win.caches.text.set_scale(win.scale); Ok(win) } } fn destroy(&mut self) { self.widgets.free_all(); unsafe { if let Some(n) = self.native.take() { sys::BK_window_free(n); } if !self.raster.is_null() { sys::BUI_raster_free(self.raster); self.raster = std::ptr::null_mut(); } } } /// Window id. pub fn window_handle(&self) -> WindowId { WindowId(self.id) } /// Re-render on the next turn. /// Render again on the next display refresh (gpui's /// `request_animation_frame`): call it from `render` to animate. pub fn request_animation_frame(&mut self) { self.animation_frame = true; self.dirty = true; } /// Pace animation frames to the display (default `true`). With `false` /// frames render as fast as the CPU allows (benchmarks). pub fn set_vsync(&mut self, on: bool) { self.vsync = on; } /// Whether CSS animations or transitions were running at the last /// render (the window keeps requesting frames while they are). pub fn is_animating(&self) -> bool { self.caches.anim.running() } /// Whether the window will render again (something changed or is /// animating). False for an idle window. pub fn needs_render(&self) -> bool { self.dirty || self.scrolled } /// Frames presented to the native window so far. pub fn presented_frames(&self) -> u64 { self.native.map_or(0, |n| unsafe { sys::BK_window_frames(n) } as u64) } pub fn refresh(&mut self) { self.dirty = true; } /// Content size in logical pixels. pub fn viewport_size(&self) -> Size { size(px(self.phys.0 as f32 / self.scale), px(self.phys.1 as f32 / self.scale)) } pub fn bounds(&self) -> Bounds { Bounds { origin: point(px(0.0), px(0.0)), size: self.viewport_size() } } /// Device pixels per logical pixel. pub fn scale_factor(&self) -> f32 { self.scale } /// Whether frames are drawn on the GPU right now (it turns on a few /// frames after start, once the device is ready). pub fn is_gpu(&self) -> bool { // SAFETY: `native` is a live kit window owned by this Window. self.native.map(|n| unsafe { sys::BK_window_gpu(n) } != 0).unwrap_or(false) } pub fn set_window_title(&mut self, title: &str) { if self.title != title { self.title = title.to_owned(); if let Some(n) = self.native { let t = CString::new(title).unwrap_or_default(); unsafe { sys::BK_window_set_title(n, t.as_ptr()) }; } } } /// Pointer position in logical pixels. pub fn mouse_position(&self) -> crate::geometry::Point { point(px(self.pointer.0), px(self.pointer.1)) } /// The `.id()` of the focused element, if any. pub fn focused_id(&self) -> Option<&str> { self.state.focused_id.as_deref() } /// Focus the element with `.id(id)` (keyboard events go to it). pub fn focus_id(&mut self, id: &str) { let key = id_key(id); self.state.focused = Some(key); self.state.focus_path = [key].into_iter().collect(); self.state.focused_id = Some(id.to_owned()); self.dirty = true; } /// Is the element with `.id(id)` hovered? pub fn is_hovered(&self, id: &str) -> bool { self.state.hovered.contains(&id_key(id)) } /// Scroll offset of a scroll container with `.id(id)`. pub fn scroll_offset(&self, id: &str) -> (f32, f32) { self.scroll_read.set(true); self.state.scroll.get(&id_key(id)).copied().unwrap_or((0.0, 0.0)) } pub fn set_scroll_offset(&mut self, id: &str, x: f32, y: f32) { self.state.scroll.insert(id_key(id), (x, y)); self.dirty = true; } /// Bounds (logical pixels) of the element with `.id(id)` as of the last /// frame. Works while rendering (views read where they were last /// placed); inside an event listener the frame is lent out, so a view /// keeps what it read while rendering. pub fn bounds_of(&self, id: &str) -> Option> { self.scroll_read.set(true); // placements move with scroll let f = self.frame.as_ref()?; f.by_key().get(&id_key(id)).map(|&i| f.nodes[i].bounds) } /// Put `text` on the clipboard. pub fn write_clipboard(&mut self, text: &str) { let c = CString::new(text.replace('\0', "")).unwrap_or_default(); // SAFETY: a live context and a NUL-terminated string the kit copies. unsafe { sys::BK_clipboard_set(self.ctx, c.as_ptr()) }; } /// The clipboard's text (what [`write_clipboard`](Self::write_clipboard) and the user's copies put there). pub fn read_clipboard(&self) -> Option { // SAFETY: a live context; the kit returns a malloc'd NUL-terminated string (or NULL) we free. unsafe { let p = sys::BK_clipboard_get(self.ctx); if p.is_null() { return None; } let s = CStr::from_ptr(p).to_string_lossy().into_owned(); free(p.cast()); Some(s) } } // -- text selection ------------------------------------------------------------------------ /// The text selected in the window's elements (press and drag, double-click, `Ctrl+A`), if any: /// block boundaries are newlines, whitespace is as rendered. Text fields keep their own selection. pub fn selected_text(&mut self) -> Option { let f = self.frame.as_ref()?; self.selector.text(f, &self.caches.styles) } /// Select all the selectable text (like `Ctrl+A` on a page). pub fn select_all(&mut self) { if let Some(f) = &self.frame { if self.selector.select_all(f, &self.caches.styles) { self.dirty = true; } } } /// Drop the selection (like `Escape`). pub fn clear_selection(&mut self) { if self.selector.clear() { self.dirty = true; } } /// Call `f` with the selected text (None: nothing selected) whenever the user changes the selection: /// pressing, dragging, `Ctrl+A`, `Escape`, clicking away. Not for [`select_all`](Self::select_all) /// and [`clear_selection`](Self::clear_selection): their caller knows. pub fn on_selection_change(&mut self, f: impl FnMut(Option<&str>, &mut Window, &mut App) + 'static) { self.selection_hooks.push(Box::new(f)); } /// The cursor the window shows over its elements now (the kit's cursor id: 0 arrow, 3 I-beam ...). #[doc(hidden)] pub const fn cursor_style(&self) -> i32 { self.cursor } /// A text field (the kit's editor) has the keyboard. fn text_field_focused(&self) -> bool { // SAFETY: a live context. unsafe { !sys::BK_focus(self.ctx).is_null() } } /// The selection changed by the user: draw it (the frame again, no render) and tell the hooks. fn selection_changed(&mut self, app: &mut App, repaint: bool) { if repaint { // at the next frame, as a redraw of Motion's values is: a native window draws what is // presented from its frame callback self.sel_repaint = true; self.animation_frame = true; } if self.selection_hooks.is_empty() { return; } let text = self.selected_text(); let mut hooks = std::mem::take(&mut self.selection_hooks); for h in &mut hooks { h(text.as_deref(), self, app); } hooks.append(&mut self.selection_hooks); self.selection_hooks = hooks; } /// Nothing on screen answers to a press on `path` or to the focus moving to it: no listeners, /// `.active()` / `.focus()` refinements or Motion props on it, its ancestors or the element that /// loses the focus, and no `:active` / `:focus` rule in the sheet. fn press_is_quiet(&self, path: &[Key]) -> bool { let Some(f) = &self.frame else { return false }; let plain = |k: &Key| f.by_key().get(k).and_then(|&i| f.el(i)).is_none_or(|e| !e.reactive); !self.caches.state_rules && path.iter().all(plain) && self.state.focused.as_ref().is_none_or(plain) } fn select_press(&mut self, x: f32, y: f32, shift: bool) -> bool { let Some(f) = &self.frame else { return false }; let hit = f.hit_box(x, y, &self.caches.styles); let mut cx = Cx { frame: f, styles: &self.caches.styles, text: &mut self.caches.text }; self.selector.press(&mut cx, x, y, hit, shift) } fn select_drag(&mut self, x: f32, y: f32) -> bool { let Some(f) = &self.frame else { return false }; let mut cx = Cx { frame: f, styles: &self.caches.styles, text: &mut self.caches.text }; self.selector.drag_to(&mut cx, x, y) } /// `Ctrl+A`, `Ctrl+C` and `Escape` on the document's selection: not while a text field has the /// keyboard (it owns them). (`Ctrl` is the Command key on macOS: the kit maps it.) fn selection_key(&mut self, ks: &Keystroke, app: &mut App) { if self.text_field_focused() { return; } let ctrl = ks.modifiers.control && !ks.modifiers.alt; let changed = match ks.key.to_ascii_lowercase().as_str() { "escape" => self.selector.clear(), "a" if ctrl => self.frame.as_ref().is_some_and(|f| self.selector.select_all(f, &self.caches.styles)), "c" if ctrl => { if let Some(t) = self.selected_text() { self.write_clipboard(&t); } false } _ => false, }; if changed { self.selection_changed(app, true); } } /// One UI unit (Blender's `UI_UNIT_Y`, a row of widgets) in logical pixels. pub fn ui_unit(&self) -> f32 { // SAFETY: a constant query. unsafe { sys::BK_unit() as f32 / self.scale } } fn viewport(&self) -> (f32, f32) { (self.phys.0 as f32 / self.scale, self.phys.1 as f32 / self.scale) } // -- render ----------------------------------------------------------------------------- fn rebuild(&mut self, app: &mut App) { // the view is moved out while it renders (it gets `&mut Window`) let Some(view) = self.view.take() else { return }; self.dirty = false; self.scrolled = false; self.scroll_read.set(false); let root = { let _s = span(Phase::Render); crate::hooks::begin(self.id); let mut root = view(self, app); crate::element::resolve_deferred(&mut root, self, app); root }; if self.view.is_none() { self.view = Some(view); } let vp = self.viewport(); let (canvas, scale) = (self.canvas, self.scale); let widgets = &mut self.widgets; let recycle = self.frame.take().unwrap_or_default(); self.caches.anim.begin(self.clock.now()); let mut frame = layout(root, vp, &self.state, &mut self.caches, recycle, &mut |key, ask| match ask { crate::widgets::WidgetAsk::Ensure(spec) => widgets.ensure(canvas, key, spec, scale), crate::widgets::WidgetAsk::Height(w) => (0.0, widgets.height_for(key, w, scale)), }); // CSS animations / transitions still moving: render again next frame; // Motion's values alone: redraw (nothing running: no frames, so an // idle window costs no CPU) let (css, motion) = self.caches.anim.end(); // `@container`: sizes changed under a query, or an element came into // view (`whileInView`): render once more let (in_view, flipped) = self.caches.anim.after_layout(&frame, &self.caches.styles, vp); // useScroll: the values follow the scroll; what they move draws again let scrolled = crate::motion::update_scroll(&frame); if flipped { // a layout animation starts where the element was seen: this frame too self.caches.anim.redraw_motion(&mut frame, &mut self.caches.styles, vp); } let container_changed = self.caches.after_layout(&frame) | in_view; // screens: their kit nodes go where their elements are (the kit reports what moves) self.screens.after_layout(&frame, self.scale); // `data-stick="bottom"`: a scroll container that grew goes to its end // (`"bottom"`: only if it was at the end; `"always"`: whatever it showed) let mut stuck = false; let mut sticks = false; for i in 0..frame.nodes.len() { let Some(mode) = frame.attr(i, "data-stick") else { continue }; sticks = true; let always = mode == "always"; let n = &frame.nodes[i]; let (key, range, pos) = (n.key, n.scroll_range.1, n.scroll_pos.1); let prev = self.stuck.insert(key, range).unwrap_or(0.0); if range > prev + 0.5 && (always || pos >= prev - 2.0) && pos < range - 0.5 { self.state.scroll.insert(key, (n.scroll_pos.0, range)); stuck = true; } } self.scroll_free = !sticks && !self.scroll_read.get() && !self.caches.anim.tracks_placement(); self.present(app, frame, None); if stuck { self.dirty = true; } // state of components that didn't render is freed; effects run now crate::hooks::end(); if container_changed { self.dirty = true; } if css { self.request_animation_frame(); } else if motion || scrolled { self.request_motion_frame(); } } /// A frame of Motion's values alone: the last frame's elements, with /// their values set again and painted (no render, cascade or layout). fn redraw(&mut self, app: &mut App) { self.motion_frame = false; let Some(mut frame) = self.frame.take() else { return }; let vp = self.viewport(); if !self.caches.anim.redraw_motion(&mut frame, &mut self.caches.styles, vp) { self.frame = Some(frame); self.dirty = true; return self.rebuild(app); } // no layout ran: the widgets are the last frame's self.widgets.keep(); // the boxes the values changed: only they are painted again let dirty = self.caches.anim.take_redrawn(); self.present(app, frame, Some(&dirty)); self.caches.anim.give_redrawn(dirty); if crate::motion::active() { self.request_motion_frame(); } } /// A frame after scrolling alone: the last frame placed again with the new offsets and painted /// (no render, cascade or layout), unless something follows the scroll positions: then a render. fn scroll_frame(&mut self, app: &mut App) { self.scrolled = false; let vp = self.viewport(); let placed = self.scroll_free && match self.frame.take() { Some(mut frame) => { let ok = crate::layout::replace(&mut frame, vp, &self.state, &mut self.caches); self.frame = Some(frame); ok } None => false, }; if !placed { self.dirty = true; return self.rebuild(app); } let Some(frame) = self.frame.take() else { return }; self.widgets.keep(); // no layout ran: the widgets are the last frame's self.same_frame = true; // the same boxes: the selection's index of them stays self.present(app, frame, None); } /// Draw again on the next display refresh, for Motion's values alone. fn request_motion_frame(&mut self) { self.motion_frame = true; self.animation_frame = true; } /// Render the window when it needs it: in full, or a redraw. fn update(&mut self, app: &mut App) { if self.dirty { self.rebuild(app); } else if self.scrolled { self.scroll_frame(app); } else if self.sel_repaint { // the selection alone: the frame again, painted if let Some(frame) = self.frame.take() { self.widgets.keep(); // no layout ran: the widgets are the last frame's self.same_frame = true; self.present(app, frame, None); } } else if self.motion_frame { self.redraw(app); } } /// Paint `frame` and show it (the widgets placed, the hover updated). /// `dirty`: a redraw's boxes to paint again (the rest kept), when it can. fn present(&mut self, app: &mut App, frame: Frame, dirty: Option<&[bool]>) { FRAMES_PRESENTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.sel_repaint = false; // whatever is painted has the selection let vp = self.viewport(); let scale = self.scale; // a selection follows its text into the new frame (and goes with it) if !std::mem::take(&mut self.same_frame) { self.selector.invalidate(); } self.painter.sel = self.selector.paint(&frame, &self.caches.styles); { let _s = span(Phase::Paint); let gpu = self.is_gpu(); let p = &mut self.painter; p.set_gpu(gpu); let kept = dirty.is_some_and(|d| p.repaint(&frame, &self.caches.styles, &mut self.caches.text, d, vp, app)); if !kept { p.reset(); paint_frame(&frame, &self.caches.styles, &mut self.caches.text, p, vp, self.scale, app); } } { let _s = span(Phase::Flush); self.grow_canvases(self.painter.segment_count()); self.painter.flush(&self.canvases, scale); } let _rest = span(Phase::Widgets); let mut at = HashMap::new(); // empty (no allocation) without form widgets if frame.nodes.iter().any(|n| matches!(n.content, Content::Widget(_))) { let order = self.painter.widget_order(); for n in &frame.nodes { if matches!(n.content, Content::Widget(_)) { let (seg, rank) = order.get(&n.key).copied().unwrap_or((0, u32::MAX)); at.insert(n.key, (n.bounds, n.clip, n.visible, seg, rank)); } } } self.widgets.place(&at, &self.canvases, scale); // an opaque background covers the window: the kit can skip its clear let styles = &self.caches.styles; let opaque = frame.nodes.first() .is_some_and(|h| styles[h.style].background.a >= 1.0 && styles[h.style].opacity >= 1.0); if opaque != self.opaque { self.opaque = opaque; unsafe { sys::BK_set_num(self.root, c"opaque".as_ptr(), opaque as i32 as f64) }; } if let Some(t) = frame.title.clone() { self.set_window_title(&t); } self.frame = Some(frame); self.update_hover(app, false); drop(_rest); prof::frame_done(); } // -- events ------------------------------------------------------------------------------ /// At least `n` canvases (the ones over the first are made here, above /// the rest, and take the pointer only where they have items). fn grow_canvases(&mut self, n: usize) { while self.canvases.len() < n { // SAFETY: a fresh canvas added to our root, like the first one. let c = unsafe { let c = sys::BK_node_new(c"canvas".as_ptr()); sys::BK_node_add(self.root, c, -1); sys::BK_geom_set_manager(c, sys::BK_GEOM_PLACE); sys::BK_geom_set(c, c"relwidth".as_ptr(), 1.0); sys::BK_geom_set(c, c"relheight".as_ptr(), 1.0); sys::BK_set_num(c, c"events".as_ptr(), 1.0); sys::BK_set_num(c, c"hititems".as_ptr(), 1.0); sys::BK_set_num(c, c"cursor".as_ptr(), f64::from(self.cursor)); c }; self.overlays.push(c); self.canvases.push(c); } } /// Element keys from the root to the deepest element under the pointer. fn path_at(&self, x: f32, y: f32) -> Vec { let Some(f) = &self.frame else { return Vec::new() }; f.hit_path(x, y, &self.caches.styles).into_iter().map(|i| f.nodes[i].key).collect() } /// Call the listeners `pick` selects, from element `key` up to the root. /// The frame is moved out of the window meanwhile, so listeners can take /// `&mut Window` while the frame lends them out: no copies, no `Rc`. fn emit(&mut self, app: &mut App, key: Key, e: &E, pick: impl Fn(&Listeners) -> Vec<&Listener>) { let Some(frame) = self.frame.take() else { return }; app.propagate = true; let mut cur = frame.by_key().get(&key).copied(); 'up: while let Some(i) = cur { if let Some(ls) = frame.el(i).and_then(|e| e.listeners.as_deref()) { for l in pick(ls) { l(e, self, app); if !app.propagate { break 'up; } } } cur = frame.nodes[i].parent; } app.propagate = true; if self.frame.is_none() { self.frame = Some(frame); } } /// The element keys under the pointer, and (when the pointer moved: `measure`) whether it is over /// text that can be selected. fn hover_target(&mut self, measure: bool) -> (Vec, Option) { let Some(f) = &self.frame else { return (Vec::new(), Some(false)) }; let (x, y) = self.pointer; let hit = f.hit_box(x, y, &self.caches.styles); let path = f.path_to(hit).into_iter().map(|i| f.nodes[i].key).collect(); let over = measure.then(|| hit.is_some_and(|i| { let mut cx = Cx { frame: f, styles: &self.caches.styles, text: &mut self.caches.text }; crate::selection::is_text(&mut cx, i, x, y) })); (path, over) } /// The pointer's cursor: that of the deepest element under it that sets one /// (`cursor: auto` sets none), else the text cursor over selectable text. /// `over_text` None: not measured (a frame, not a pointer move): keep the I-beam if it showed. fn set_cursor(&mut self, path: &[Key], over_text: Option) { let Some(f) = &self.frame else { return }; let text = over_text.unwrap_or(self.cursor == crate::style::CURSOR_TEXT); let cursor = path.iter().rev() .find_map(|k| f.by_key().get(k).and_then(|&i| self.caches.styles[f.nodes[i].style].cursor)) .unwrap_or(if text { crate::style::CURSOR_TEXT } else { 0 }); if cursor != self.cursor { self.cursor = cursor; for &c in &self.canvases { unsafe { sys::BK_set_num(c, c"cursor".as_ptr(), cursor as f64) }; } } } fn update_hover(&mut self, app: &mut App, fire: bool) { let (path, over_text) = self.hover_target(fire); self.set_cursor(&path, over_text); let now: std::collections::HashSet = path.iter().copied().collect(); if now == self.state.hovered { return; } let entered: Vec = now.difference(&self.state.hovered).copied().collect(); let left: Vec = self.state.hovered.difference(&now).copied().collect(); // a restyle (a render) only where something answers to the pointer: a `:hover` rule in the // sheet, or a `.hover()` refinement / Motion props on an element it entered or left let restyle = self.frame.as_ref().is_some_and(|f| { entered.iter().chain(&left).any(|k| { f.by_key().get(k).is_some_and(|&i| self.caches.state_rules || f.el(i).is_none_or(|e| e.reactive)) }) }); self.state.hovered = now; if fire { // hover listeners don't bubble: each element hears its own enter / leave for (keys, on) in [(left, false), (entered, true)] { for k in keys { let Some(frame) = self.frame.take() else { return }; let el = frame.by_key().get(&k).and_then(|&i| frame.el(i)); if let Some(ls) = el.and_then(|e| e.listeners.as_deref()) { for l in &ls.hover { l(&on, self, app); } } if self.frame.is_none() { self.frame = Some(frame); } } } } if restyle { self.dirty = true; } } fn pointer_event(&self, text: &str) -> (Modifiers, MouseButton) { let mut it = text.split_whitespace().map(|v| v.parse::().unwrap_or(0)); let mods = it.next().unwrap_or(0); let button = match it.next().unwrap_or(1) { 2 => MouseButton::Middle, 3 => MouseButton::Right, _ => MouseButton::Left, }; (Modifiers::from_kit(mods), button) } /// Focus the element `key` (path: its ancestors, for `:focus-within`). fn set_focus(&mut self, path: &[Key]) { self.state.focused = path.last().copied(); self.state.focus_path = path.iter().copied().collect(); self.state.focused_id = self.frame.as_ref().and_then(|f| { let i = *f.by_key().get(path.last()?)?; f.el(i)?.id.as_ref().map(|s| s.to_string()) }); } fn dispatch(&mut self, ev: RawEvent, app: &mut App) { if !self.canvases.contains(&ev.node) { if let Some(target) = self.screens.target(ev.node) { self.screen_event(&target, &ev, app); return; } self.widget_event(ev, app); return; } // a text field took the focus: its own selection counts, the document's goes if self.selector.has_selection() && self.text_field_focused() && self.selector.clear() { self.selection_changed(app, true); } let (x, y) = (ev.a as f32 / self.scale, ev.b as f32 / self.scale); match ev.kind { sys::BK_EV_CONFIGURE => { let phys = (ev.a as i32, ev.b as i32); if phys != self.phys && phys.0 > 0 && phys.1 > 0 { self.phys = phys; self.dirty = true; } } sys::BK_EV_MOTION | sys::BK_EV_ENTER => { self.pointer = (x, y); if self.sb_drag.is_some() { self.drag_scrollbar(y); return; } if self.caches.anim.pointer_move(x, y) { self.request_motion_frame(); // a drag: a redraw, no render } self.update_hover(app, true); if self.select_drag(x, y) { self.selection_changed(app, true); } let (modifiers, _) = self.pointer_event(&ev.text); let pressed = (!self.pressed.is_empty()).then_some(self.press_button); let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: pressed, modifiers }; if let Some(deepest) = self.state_deepest() { self.emit(app, deepest, &e, |l| l.mouse_move.iter().collect()); } } sys::BK_EV_LEAVE => { self.pointer = (-1.0, -1.0); self.update_hover(app, true); } sys::BK_EV_PRESS | sys::BK_EV_DOUBLE => { self.pointer = (x, y); let (modifiers, button) = self.pointer_event(&ev.text); let path = self.path_at(x, y); if button == MouseButton::Left && self.grab_scrollbar(&path, x, y) { return; } let selected = button == MouseButton::Left && self.select_press(x, y, modifiers.shift); let quiet = self.press_is_quiet(&path); self.press_quiet = quiet; self.press_button = button; self.state.active = path.iter().copied().collect(); self.set_focus(&path); self.pressed = path.clone(); self.dirty |= !quiet; self.caches.anim.pointer_down(&path, x, y); let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 } }; if let Some(&deepest) = path.last() { self.emit(app, deepest, &e, |l| l.mouse_down.iter() .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); } if selected { // a press that renders draws the selection with it; a quiet one draws it now self.selection_changed(app, quiet); } } sys::BK_EV_RELEASE => { if self.sb_drag.take().is_some() { return; } let (modifiers, button) = self.pointer_event(&ev.text); let path = self.path_at(x, y); let up = MouseUpEvent { button, position: point(px(x), px(y)), modifiers }; if let Some(&deepest) = path.last() { self.emit(app, deepest, &up, |l| l.mouse_up.iter() .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); } // click: the deepest element under both press and release let common = self.pressed.iter().zip(&path).take_while(|(a, b)| a == b) .map(|(a, _)| *a).last(); self.pressed.clear(); self.state.active.clear(); self.dirty |= !std::mem::take(&mut self.press_quiet); self.caches.anim.pointer_up(); // a press that selected text is a selection, not a click (as in a browser) let dragged = button == MouseButton::Left && self.selector.release(); if let (Some(target), MouseButton::Left, false) = (common, button, dragged) { self.toggle_details(target); let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: 1 }; let e = ClickEvent { down, up }; self.emit(app, target, &e, |l| l.click.iter().collect()); } } sys::BK_EV_WHEEL => { let (modifiers, _) = self.pointer_event(&ev.text); let (px_, py_) = self.pointer; // `b`: the exact device pixels of a touch drag (BK_scroll_px), 0 for a wheel notch let pixels = (ev.b != 0.0).then(|| ev.b as f32 / self.scale); let e = ScrollWheelEvent { position: point(px(px_), px(py_)), delta: ev.a as f32, pixels, modifiers }; let path = self.path_at(px_, py_); if let Some(&deepest) = path.last() { self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); } self.scroll_by(&path, -pixels.unwrap_or(ev.a as f32 * 40.0), modifiers.shift); } sys::BK_EV_KEY | sys::BK_EV_KEYRELEASE => { let mut parts = ev.text.splitn(2, '\t'); let ch = parts.next().unwrap_or("").to_owned(); let key = parts.next().unwrap_or("").to_owned(); let ks = Keystroke { key, key_char: (!ch.is_empty()).then_some(ch), modifiers: Modifiers::from_kit(ev.a as i32) }; let target = self.state.focused.or_else(|| self.state_deepest()) .unwrap_or(crate::layout::ROOT_KEY); if ev.kind == sys::BK_EV_KEY { self.selection_key(&ks, app); let page = match ks.key.to_ascii_lowercase().as_str() { "pagedown" => 1.0, "pageup" => -1.0, _ => 0.0, }; self.emit(app, target, &KeyDownEvent { keystroke: ks }, |l| l.key_down.iter().collect()); if page != 0.0 { self.scroll_page(page); } } else { self.emit(app, target, &KeyUpEvent { keystroke: ks }, |l| l.key_up.iter().collect()); } } _ => {} } } fn state_deepest(&self) -> Option { self.path_at(self.pointer.0, self.pointer.1).last().copied() } /// `` clicks open and close their `
`. fn toggle_details(&mut self, target: Key) { let Some(f) = &self.frame else { return }; let mut cur = f.by_key().get(&target).copied(); while let Some(i) = cur { if f.el(i).is_some_and(|e| e.tag == "summary") { let details = f.nodes[i].parent.filter(|&p| f.el(p).is_some_and(|e| e.tag == "details")); if let Some(p) = details { let key = f.nodes[p].key; let open = self.state.details_open.get(&key).copied() .unwrap_or(f.attr(p, "open").is_some()); self.state.details_open.insert(key, !open); self.dirty = true; } return; } cur = f.nodes[i].parent; } } /// PageUp / PageDown: a page of the innermost scroll container under the pointer. fn scroll_page(&mut self, dir: f32) { let path = self.path_at(self.pointer.0, self.pointer.1); let Some(f) = &self.frame else { return }; let page = path.iter().rev() .filter_map(|k| f.by_key().get(k)) .map(|&i| &f.nodes[i]) .find(|n| n.scroll_range.1 > 0.0) .map(|n| n.bounds.size.height * 0.9); if let Some(page) = page { self.scroll_by(&path, dir * page, false); } } /// The vertical scrollbar of a container along `path`: (key, thumb top, thumb height, track top, track height). fn scrollbar_at(&self, path: &[Key], x: f32) -> Option<(Key, f32, f32, f32, f32)> { let f = self.frame.as_ref()?; for key in path.iter().rev() { let Some(&i) = f.by_key().get(key) else { continue }; let n = &f.nodes[i]; let ry = n.scroll_range.1; let b = n.bounds; if ry <= 0.0 || x < b.origin.x + b.size.width - 10.0 || x > b.origin.x + b.size.width { continue; } let h = b.size.height; let th = (h * h / (h + ry)).max(16.0); let ty = b.origin.y + (h - th) * (n.scroll_pos.1 / ry); return Some((*key, ty, th, b.origin.y, h)); } None } /// A press on a scrollbar starts a drag (on the track it first centers the thumb there). fn grab_scrollbar(&mut self, path: &[Key], x: f32, y: f32) -> bool { let Some((key, ty, th, _, _)) = self.scrollbar_at(path, x) else { return false }; let grab = if y >= ty && y <= ty + th { y - ty } else { th / 2.0 }; self.sb_drag = Some((key, grab)); self.drag_scrollbar(y); true } fn drag_scrollbar(&mut self, y: f32) { let Some((key, grab)) = self.sb_drag else { return }; let Some(f) = &self.frame else { return }; let Some(&i) = f.by_key().get(&key) else { return }; let n = &f.nodes[i]; let (rx, ry) = n.scroll_range; let h = n.bounds.size.height; let th = (h * h / (h + ry)).max(16.0); let free = (h - th).max(1.0); let sy = (((y - grab - n.bounds.origin.y) / free) * ry).clamp(0.0, ry); let sx = n.scroll_pos.0.clamp(0.0, rx); self.state.scroll.insert(key, (sx, sy)); self.scrolled = true; } /// Scroll the innermost scroll container along `path` that can move. fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool) { let Some(f) = &self.frame else { return }; for key in path.iter().rev() { let Some(&i) = f.by_key().get(key) else { continue }; let n = &f.nodes[i]; let (rx, ry) = n.scroll_range; let (sx, sy) = n.scroll_pos; let (nx, ny) = if horizontal || ry <= 0.0 { ((sx + dy).clamp(0.0, rx), sy) } else { (sx, (sy + dy).clamp(0.0, ry)) }; let (nx, ny) = snap(f, &self.caches.styles, i, (sx, sy), (nx, ny)); if (nx, ny) != (sx, sy) { self.state.scroll.insert(*key, (nx, ny)); self.scrolled = true; return; } } } /// A screen's kit event: the layout changed, an area wants a window, a region was resized /// (a `change` on its element), or areas and regions moved (the content follows: a render). fn screen_event(&mut self, target: &crate::screen::Target, ev: &RawEvent, app: &mut App) { if let Some((key, e)) = crate::screen::change_event(target, &self.screens, ev.node, ev.kind, ev.a, ev.b) { self.emit(app, key, &e, |l| l.change.iter().collect()); } self.dirty = true; } /// Syncs a `` with its kit nodes and places its areas' elements (`screen.rs`). pub(crate) fn sync_screen(&mut self, div: &mut crate::element::Div, spec: &crate::screen::Spec) { if let Some(made) = self.screens.sync(self.canvas, self.scale, div, spec) { // a new screen: its layout reaches `change` listeners as every later one does (the // areas a JavaScript screen renders come from it) queue_push(RawEvent { window: self.id, node: made, kind: sys::BK_EV_CHANGE, text: String::new(), a: 0.0, b: 0.0 }); } } fn widget_event(&mut self, ev: RawEvent, app: &mut App) { if self.widgets.syncing { return; } let Some(key) = self.widgets.key_of(ev.node) else { return }; match ev.kind { sys::BK_EV_CHANGE => { let e = self.widgets.read(key); let kind = self.widgets.nodes.get(&key).map(|w| w.spec.kind); match kind { Some(WKind::Checkbox) => { self.state.checked.insert(key, e.checked); } Some(WKind::Radio) if e.checked => { self.state.checked.insert(key, true); for other in self.widgets.radio_group(key) { self.state.checked.insert(other, false); self.widgets.set_value(other, 0.0); } } _ => {} } self.emit(app, key, &e, |l| l.input.iter().collect()); self.emit(app, key, &e, |l| l.change.iter().collect()); self.dirty = true; } sys::BK_EV_CLICK => { let (x, y) = self.pointer; let down = MouseDownEvent { button: MouseButton::Left, position: point(px(x), px(y)), modifiers: Modifiers::default(), click_count: 1 }; let up = MouseUpEvent { button: MouseButton::Left, position: point(px(x), px(y)), modifiers: Modifiers::default() }; self.emit(app, key, &ClickEvent { down, up }, |l| l.click.iter().collect()); self.dirty = true; } _ => {} } } } /// Marker so `Window` is not `Send` (it holds raw kit pointers). #[allow(dead_code)] struct NotSend(PhantomData<*const ()>); /// `scroll-snap-type`: the scroll position `to` (moving from `from`) of /// container `i` moved to its children's snap positions: the next one in /// the direction of travel (`mandatory`), or the nearest when it's within a /// third of the view (`proximity`). fn snap(f: &crate::layout::Frame, styles: &crate::layout::StyleStore, i: usize, from: (f32, f32), to: (f32, f32)) -> (f32, f32) { let n = &f.nodes[i]; let c = &styles[n.style]; if c.snap_axes == 0 { return to; } let (rx, ry) = n.scroll_range; let view = n.bounds; let mut out = to; for axis in 0..2 { if c.snap_axes & (1 << axis) == 0 { continue; } let (cur, target, range, view_len) = if axis == 0 { (from.0, to.0, rx, view.size.width) } else { (from.1, to.1, ry, view.size.height) }; if target == cur { continue; } // snap positions of the children, in scroll coordinates let mut points: Vec = Vec::new(); for k in f.children_of(i) { let kc = &styles[f.nodes[k].style]; let align = if axis == 0 { kc.snap_align.0 } else { kc.snap_align.1 }; if align == 0 { continue; } let b = f.nodes[k].bounds; let (start, len, vstart) = if axis == 0 { (b.origin.x + cur, b.size.width, view.origin.x) } else { (b.origin.y + cur, b.size.height, view.origin.y) }; let rel = start - vstart; let p = match align { 1 => rel, 2 => rel + len / 2.0 - view_len / 2.0, _ => rel + len - view_len, }; points.push(p.clamp(0.0, range)); } if points.is_empty() { continue; } let forward = target > cur; let pick = if c.snap_mandatory { if forward { points.iter().copied().filter(|p| *p > cur + 0.5).fold(f32::INFINITY, f32::min) } else { points.iter().copied().filter(|p| *p < cur - 0.5).fold(f32::NEG_INFINITY, f32::max) } } else { let near = points.iter().copied().min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs())); near.filter(|p| (p - target).abs() <= view_len / 3.0).unwrap_or(target) }; let v = if pick.is_finite() { pick } else { target }; if axis == 0 { out.0 = v; } else { out.1 = v; } } out }