Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
AP10: the app's icon counts what's waiting in the Inbox on Windows too: raea-page-window's dock.badge sets an overlay icon on the window's taskbar button (ITaskbarList3::SetOverlayIcon, win.rs), as the Dock's badge does on the Mac. badge.rs draws it, pure and tested everywhere: a red circle or pill with the count in a 3x5 pixel font at the small-icon size the taskbar asks for, 9+ above nine, cleared at nothing. win.rs type-checks for x86_64-pc-windows-msvc (windows 0.62, already in the lock); notify's nested if is collapsed for clippy
shinyobjectz87ccba76c148
diff --git a/Cargo.lock b/Cargo.lockindex 34c511df..1741ebac 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14571,6 +14571,7 @@ dependencies = ["raea-runtime-js","raw-window-handle","serde_json",+ "windows 0.62.2",][[package]]diff --git a/engine/page/window/Cargo.toml b/engine/page/window/Cargo.tomlindex 16339463..60a69e98 100644--- a/engine/page/window/Cargo.toml+++ b/engine/page/window/Cargo.toml@@ -4,11 +4,11 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "raea's desktop window around a page: its chrome (--chrome inset: the page under a transparent title bar, window.drag and window.zoom) and what a Mac app does that a page can't (the clipboard, links, notifications, the dock badge, raea:// links)"+description = "raea's desktop window around a page: its chrome (--chrome inset: the page under a transparent title bar, window.drag and window.zoom) and what a desktop app does that a page can't (the clipboard, links, notifications, the Dock badge or taskbar overlay, raea:// links)"[features]# on screen (raea-page-host's --window): AppKit's calls are made; without it they are recorded and answered-window = ["bevy/bevy_winit", "dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:raw-window-handle", "dep:block2"]+window = ["bevy/bevy_winit", "dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:raw-window-handle", "dep:block2", "dep:windows"][dependencies]bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_window"] }@@ -23,3 +23,8 @@ objc2-foundation = { version = "0.3", optional = true, default-features = false,raw-window-handle = { version = "0.6", optional = true }# completion handlers for notificationsblock2 = { version = "0.6", optional = true }++# native.rs dock.badge on Windows: the taskbar button's overlay icon (win.rs)+[target.'cfg(windows)'.dependencies]+windows = { version = "0.62", optional = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }+raw-window-handle = { version = "0.6", optional = true }diff --git a/engine/page/window/src/badge.rs b/engine/page/window/src/badge.rsnew file mode 100644index 00000000..77eee14a--- /dev/null+++ b/engine/page/window/src/badge.rs@@ -0,0 +1,128 @@+//! The badge drawn over the app's taskbar button on Windows (native.rs dock.badge; the Mac's Dock draws its own): a+//! red pill holding the count in a pixel font, crisp at the small-icon size the taskbar asks for (16 px at 100%, 20,+//! 24 and 32 as the display scales). Pure, so it's tested on every system.++/// What the badge says for the page's text: a count up to 9, "9+" above, a dot (empty) for anything else; None clears it.+pub fn label(text: &str) -> Option<String> {+ let t = text.trim();+ if t.is_empty() || t == "0" {+ return None;+ }+ Some(match t.parse::<u64>() {+ Ok(n) if n <= 9 => n.to_string(),+ Ok(_) => "9+".into(),+ Err(_) => String::new(),+ })+}++/// 3x5 glyphs, a row a nibble (the low 3 bits, left to right)+fn glyph(c: char) -> [u8; 5] {+ match c {+ '0' => [7, 5, 5, 5, 7],+ '1' => [2, 6, 2, 2, 7],+ '2' => [7, 1, 7, 4, 7],+ '3' => [7, 1, 7, 1, 7],+ '4' => [5, 5, 7, 1, 1],+ '5' => [7, 4, 7, 1, 7],+ '6' => [7, 4, 7, 5, 7],+ '7' => [7, 1, 1, 1, 1],+ '8' => [7, 5, 7, 5, 7],+ '9' => [7, 5, 7, 1, 7],+ '+' => [0, 2, 7, 2, 0],+ _ => [0; 5],+ }+}++const RED: [u8; 3] = [0xe5, 0x48, 0x4d];++/// `label` on a `size` x `size` badge, top row first, as BGRA with straight alpha (what a 32-bit icon holds): a circle+/// for one character, a pill for two, its edge antialiased; the characters white, each pixel of the font `size / 8`.+pub fn pixels(label: &str, size: u32) -> Vec<u8> {+ let s = size.max(8) as f32;+ let n = label.chars().count();+ // the pill's half width and height and its corner radius, centred+ let (hw, hh) = if n > 1 { (s / 2.0, s * 0.36) } else { (s / 2.0, s / 2.0) };+ // a circle for one character; for two, corners tight enough that the glyphs' own corners stay inside at 16 px+ let r = if n > 1 { hh * 0.55 } else { hh };+ let scale = (size / 8).max(1);+ let (gw, gh) = (3 * scale, 5 * scale);+ let tw = n as u32 * gw + n.saturating_sub(1) as u32 * scale;+ let (x0, y0) = (size.saturating_sub(tw) / 2, size.saturating_sub(gh) / 2);+ let dot = n == 0;+ let mut out = vec![0u8; (size * size * 4) as usize];+ for y in 0..size {+ for x in 0..size {+ let (px, py) = (x as f32 + 0.5 - s / 2.0, y as f32 + 0.5 - s / 2.0);+ // signed distance to the rounded box (a dot: a circle half the size)+ let d = if dot {+ (px * px + py * py).sqrt() - s / 4.0+ } else {+ let (qx, qy) = (px.abs() - (hw - r), py.abs() - (hh - r));+ (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r+ };+ let a = (0.5 - d).clamp(0.0, 1.0);+ if a <= 0.0 {+ continue;+ }+ let ink = !dot && x >= x0 && y >= y0 && x < x0 + tw && y < y0 + gh && {+ let (lx, ly) = (x - x0, (y - y0) / scale);+ let (k, col) = (lx / (gw + scale), (lx % (gw + scale)) / scale);+ col < 3 && glyph(label.chars().nth(k as usize).unwrap_or(' '))[ly as usize] >> (2 - col) & 1 == 1+ };+ let [r, g, b] = if ink { [255; 3] } else { RED };+ let i = ((y * size + x) * 4) as usize;+ out[i..i + 4].copy_from_slice(&[b, g, r, (a * 255.0).round() as u8]);+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::{label, pixels};++ #[test]+ fn says_a_count_up_to_nine_then_nine_plus_and_clears_at_nothing() {+ assert_eq!(label(""), None);+ assert_eq!(label("0"), None);+ assert_eq!(label("3").as_deref(), Some("3"));+ assert_eq!(label("12").as_deref(), Some("9+"));+ assert_eq!(label("new").as_deref(), Some(""));+ }++ /// the badge as text: '#' white, 'o' red, '.' clear+ fn art(label: &str, size: u32) -> Vec<String> {+ let p = pixels(label, size);+ (0..size as usize)+ .map(|y| {+ (0..size as usize)+ .map(|x| {+ let i = (y * size as usize + x) * 4;+ match (p[i + 3], p[i + 2]) {+ (0, _) => '.',+ (_, 255) => '#',+ _ => 'o',+ }+ })+ .collect()+ })+ .collect()+ }++ #[test]+ fn draws_the_count_white_on_a_red_badge_crisp_at_sixteen_pixels() {+ let a = art("7", 16);+ // a round badge: clear corners, red at the middle of each edge+ assert_eq!(&a[0][0..1], ".");+ assert_eq!(a[8].chars().next(), Some('o'));+ // the 7 at 2 px a font pixel: its top bar 6 px wide, then its stem down the right+ assert!(a.iter().any(|r| r.contains("######")), "{a:#?}");+ let stem = a.iter().filter(|r| r.contains("oo##o") || r.ends_with("##ooooo") || r.contains("##oo")).count();+ assert!(stem >= 8, "{a:#?}");+ // two characters fit inside a pill, none cut at the edge+ for r in art("9+", 16) {+ assert!(!r.starts_with('#') && !r.ends_with('#'), "{r}");+ }+ assert_eq!(pixels("9+", 32).len(), 32 * 32 * 4);+ }+}diff --git a/engine/page/window/src/lib.rs b/engine/page/window/src/lib.rsindex 5855a642..b393bc81 100644--- a/engine/page/window/src/lib.rs+++ b/engine/page/window/src/lib.rs@@ -1,8 +1,11 @@//! raea's desktop window around a page (raea-page-host --window, the window raea.app runs): its chrome (chrome.rs) and//! the native calls a page makes through host calls (native.rs).+pub mod badge;pub mod chrome;pub mod native;+#[cfg(all(windows, feature = "window"))]+mod win;use bevy::prelude::*;diff --git a/engine/page/window/src/native.rs b/engine/page/window/src/native.rsindex 171afd75..41ffbca7 100644--- a/engine/page/window/src/native.rs+++ b/engine/page/window/src/native.rs@@ -5,7 +5,7 @@//! app.open {url} an http(s) or mailto link, in the person's browser//! notify {title, body} a macOS notification (asked for once, the first time: notify.permission)//! notify.permission -> bool macOS's prompt, or its answer if already given-//! dock.badge {text} the dock icon's badge ("" clears it)+//! dock.badge {text} the Dock icon's badge, on Windows the taskbar button's overlay ("" clears it)//! app.urls -> string[] raea:// links opened since the last ask, the app brought to the front for each//! native.log -> {...} what was done, for tests//!@@ -117,10 +117,8 @@ fn run(live: bool, name: &str, a: &Value, answer: Answer) {}"notify" => {let (title, body) = (text(a, "title"), text(a, "body"));- if live {- if let Err(e) = mac::notify(&title, &body) {- return answer.err(e);- }+ if live && let Err(e) = mac::notify(&title, &body) {+ return answer.err(e);}log(|l| l.notified.push(json!({"title": title, "body": body})));answer.ok(json!(true))@@ -136,6 +134,9 @@ fn run(live: bool, name: &str, a: &Value, answer: Answer) {let t = text(a, "text");if live {mac::badge(&t);+ // the taskbar button's overlay (win.rs)+ #[cfg(all(windows, feature = "window"))]+ crate::win::badge(&t);}log(|l| l.badge = t);answer.ok(json!(true))diff --git a/engine/page/window/src/win.rs b/engine/page/window/src/win.rsnew file mode 100644index 00000000..ced78484--- /dev/null+++ b/engine/page/window/src/win.rs@@ -0,0 +1,63 @@+//! dock.badge on Windows (native.rs): the badge badge.rs draws, as an overlay icon on the window's taskbar button+//! (ITaskbarList3::SetOverlayIcon), Windows's counterpart of the Dock's badge. Nothing to clear is cleared; anything+//! that fails (no taskbar button yet, no COM) leaves the button as it was. Called on the main thread (drain).++use windows::Win32::Foundation::HWND;+use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateBitmap, CreateDIBSection, DIB_RGB_COLORS, DeleteObject};+use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx};+use windows::Win32::UI::Shell::{ITaskbarList3, TaskbarList};+use windows::Win32::UI::WindowsAndMessaging::{CreateIconIndirect, DestroyIcon, GetSystemMetrics, HICON, ICONINFO, SM_CXSMICON};+use windows::core::PCWSTR;++pub fn badge(text: &str) {+ let Some(hwnd) = primary() else { return };+ let label = super::badge::label(text);+ // SAFETY: COM and GDI calls on the main thread with a live window's handle; the icon is the taskbar's copy once set+ unsafe {+ // winit has already made this thread's apartment (OLE, for drag and drop): this only counts it again+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ let Ok(bar) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER) else { return };+ if bar.HrInit().is_err() {+ return;+ }+ let Some(label) = label else {+ let _ = bar.SetOverlayIcon(hwnd, HICON::default(), PCWSTR::null());+ return;+ };+ let size = GetSystemMetrics(SM_CXSMICON).clamp(16, 64) as u32;+ let Some(icon) = icon(&super::badge::pixels(&label, size), size) else { return };+ let said: Vec<u16> = format!("{} new in the Inbox", if label.is_empty() { "Something" } else { &label }).encode_utf16().chain([0]).collect();+ let _ = bar.SetOverlayIcon(hwnd, icon, PCWSTR(said.as_ptr()));+ let _ = DestroyIcon(icon);+ }+}++/// The primary window's handle, once winit has made it.+fn primary() -> Option<HWND> {+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ bevy::winit::WINIT_WINDOWS.with_borrow(|ww| {+ let w = ww.windows.values().next()?;+ let RawWindowHandle::Win32(h) = w.window_handle().ok()?.as_raw() else { return None };+ Some(HWND(h.hwnd.get() as *mut core::ffi::c_void))+ })+}++/// A 32-bit icon (straight alpha, its mask unused) from `size` x `size` BGRA pixels, top row first.+unsafe fn icon(bgra: &[u8], size: u32) -> Option<HICON> {+ let bmi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: size_of::<BITMAPINFOHEADER>() as u32, biWidth: size as i32, biHeight: -(size as i32), biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };+ let mut bits: *mut core::ffi::c_void = core::ptr::null_mut();+ // SAFETY: the section is size x size x 4 bytes, the length of `bgra` (badge::pixels)+ unsafe {+ let color = CreateDIBSection(None, &bmi, DIB_RGB_COLORS, &mut bits, None, 0).ok()?;+ if bits.is_null() || bgra.len() != (size * size * 4) as usize {+ let _ = DeleteObject(color.into());+ return None;+ }+ core::ptr::copy_nonoverlapping(bgra.as_ptr(), bits.cast::<u8>(), bgra.len());+ let mask = CreateBitmap(size as i32, size as i32, 1, 1, None);+ let made = CreateIconIndirect(&ICONINFO { fIcon: true.into(), xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color }).ok();+ let _ = DeleteObject(color.into());+ let _ = DeleteObject(mask.into());+ made+ }+}