A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat: add mascot feature for special moments in the dock
CristianOlivera1044fcd968c44
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5baf35f..de2f80a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,13 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- A pixel crab comes out for moments worth it, and only then: it hops with a+ heart under an AI provider whose limit just reset, trembles with a drop+ past 90 %, falls asleep at 100 %, scurries along the dock when the charger+ is plugged in, and dozes off on it when energy saver starts. Hover over it+ and it reacts. An auto-hidden dock comes up for the moment, as the macOS+ Dock does. While no crab is out it costs nothing; its acts run in the system+ compositor. It can be turned off in Settings → Dock.- Fixed (issue #8): apps pinned from a Windows shortcut with arguments, suchas `wscript.exe "script.vbs"`, a browser profile or a web app, opened theprogram alone. They now open through their shortcut, exactly as from@@ -21,6 +28,14 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Un cangrejo pixelado aparece en los momentos que lo merecen, y solo+ entonces: salta con un corazón bajo el proveedor de IA cuyo límite se acaba+ de reiniciar, tiembla con una gota al pasar del 90 %, se duerme al llegar al+ 100 %, cruza el dock corriendo al enchufar el cargador y se echa una siesta+ encima al activarse el ahorro de energía. Si pasas el puntero por encima,+ reacciona. El dock oculto sube durante ese momento, como hace el Dock de+ macOS. Mientras no hay cangrejo no consume nada; sus escenas las ejecuta el+ compositor del sistema. Se desactiva en Ajustes → Dock.- Corregido (issue #8): las apps fijadas desde un acceso directo de Windows conargumentos, como `wscript.exe "script.vbs"`, un perfil de navegador o unaapp web, abrían solo el programa. Ahora se abren a través de su accesodiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex ac27f95..66e9b42 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -91,6 +91,7 @@ use crate::{drop::DropTarget,flight::{Flight, Snapshot},gfx::{Gfx, LabelBrush},+ mascot,menu::{self, MenuItem},menubar::MenuBar,multi_window_view::MultiWindowView,@@ -193,6 +194,11 @@ fn millis(duration: std::time::Duration) -> u32 {/// moment the next look is due (see `schedule_update`).const UPDATE_TIMER: usize = 12;const PREVIEW_TIMER: usize = 13;+/// While the crab is out (a few seconds): is its act over, is the pointer on it.+const MASCOT_TIMER: usize = 14;+const MASCOT_POLL_MS: u32 = 50;+/// The charger act at most this often, however many times it is plugged.+const CHARGING_AGAIN: std::time::Duration = std::time::Duration::from_secs(10 * 60);const PREVIEW_DWELL_MS: u32 = 420;const UPDATE_EVERY: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);/// After the dock starts, the look waits this long, so it never slows signing in.@@ -547,6 +553,12 @@ struct App {hovered: Option<usize>,preview_candidate: Option<String>,preview: Option<MultiWindowView>,+ /// The crab, while it is out (see `perform`).+ mascot: Option<mascot::Mascot>,+ /// Charging and energy saver at the last power change.+ power_seen: Option<(Option<bool>, bool)>,+ /// When the charger act last played.+ charging_shown: Option<Instant>,/// Horizontal cursor position relative to the resting dock.cursor: f32,/// 0 = resting, 1 = full magnification.@@ -1754,8 +1766,118 @@ impl App {}}+ /// The crab plays `act` (see `mascot`), unless it is out already, it is+ /// turned off, or something runs full screen.+ fn perform(&mut self, act: mascot::Act, place: mascot::Place) {+ if !self.config.mascot || self.mascot.is_some() || self.fullscreen {+ return;+ }+ let scale = self.stage.as_ref().map_or(1.0, |stage| stage.scale);+ let Some(mascot) = mascot::Mascot::play(&self.gfx, act, place, scale) else {+ return;+ };+ self.mascot = Some(mascot);+ // SAFETY: A timer on our own window, killed when the act ends.+ unsafe {+ SetTimer(Some(self.input), MASCOT_TIMER, MASCOT_POLL_MS, None);+ }+ }++ /// The top edge of the dock, for the crab to walk on. An auto-hidden+ /// dock comes up for the act and goes down after it, as the macOS Dock+ /// does when something asks for attention.+ fn dock_edge(&mut self) -> Option<mascot::Place> {+ let stage = self.stage.as_ref()?;+ let margin = (stage.icon / 2.0) as i32;+ let place = mascot::Place::Along {+ left: stage.dock_origin.x - margin,+ right: stage.dock_origin.x + stage.layout.width as i32 + margin,+ top: stage.dock_origin.y,+ };+ if self.config.auto_hide && self.slide.target > 0.5 {+ // SAFETY: Our own timer.+ unsafe {+ let _ = KillTimer(Some(self.input), HIDE_TIMER);+ }+ self.slide.target = 0.0;+ self.last_frame = Instant::now();+ let _ = self.place_windows();+ let _ = self.render();+ }+ Some(place)+ }++ fn mascot_tick(&mut self) -> Result<()> {+ let Some(mascot) = &mut self.mascot else {+ return Ok(());+ };+ if mascot.finished() {+ self.mascot = None;+ // SAFETY: Our own timer.+ unsafe {+ let _ = KillTimer(Some(self.input), MASCOT_TIMER);+ }+ return self.hide_if_unused();+ }+ let mut point = POINT::default();+ // SAFETY: A valid output for the pointer position.+ if unsafe { GetCursorPos(&mut point) }.is_ok() {+ mascot.poke(&self.gfx, point);+ }+ Ok(())+ }++ /// A moment found by the menu bar (an AI plan's figure): the crab comes+ /// out under that provider.+ fn take_bar_cue(&mut self) {+ let cue = self.menubar.as_mut().and_then(MenuBar::take_cue);+ if let Some((act, point)) = cue {+ self.perform(+ act,+ mascot::Place::Under {+ x: point.x,+ top: point.y,+ },+ );+ }+ }++ /// The charger plugged in, or energy saver turned on: the crab walks+ /// along the dock. Only on the change itself, never at startup.+ fn power_moment(&mut self) {+ let now = (+ muelle_shell::system::battery().map(|battery| battery.charging),+ muelle_shell::system::energy_saver_on(),+ );+ let Some(before) = self.power_seen.replace(now) else {+ return;+ };+ let act = if now.1 && !before.1 {+ Some(mascot::Act::Sleepy)+ } else if now.0 == Some(true)+ && before.0 == Some(false)+ && self+ .charging_shown+ .is_none_or(|shown| shown.elapsed() >= CHARGING_AGAIN)+ {+ self.charging_shown = Some(Instant::now());+ Some(mascot::Act::Charging)+ } else {+ None+ };+ if let Some(act) = act+ && self.config.mascot+ && self.mascot.is_none()+ && !self.fullscreen+ && let Some(place) = self.dock_edge()+ {+ self.perform(act, place);+ }+ }+fn hide_if_unused(&mut self) -> Result<()> {if !self.config.auto_hide+ || self.mascot.is_some()|| self.hovering|| self.drag.is_some()|| self.switching@@ -3023,9 +3145,12 @@ pub fn menu_bar_dismiss_island() {/// Redraws the menu bar from what it reads on each draw (input language,/// clock), without asking the network or audio again.pub fn menu_bar_refresh() {- with_app("barra superior", |app| match &mut app.menubar {- Some(bar) => bar.refresh(&app.gfx),- None => Ok(()),+ with_app("barra superior", |app| {+ if let Some(bar) = &mut app.menubar {+ bar.refresh(&app.gfx)?;+ }+ app.take_bar_cue();+ Ok(())});}@@ -3037,9 +3162,12 @@ pub fn menu_bar_privacy_changed() {}pub fn menu_bar_tick() {- with_app("barra superior", |app| match &mut app.menubar {- Some(bar) => bar.tick(&app.gfx),- None => Ok(()),+ with_app("barra superior", |app| {+ if let Some(bar) = &mut app.menubar {+ bar.tick(&app.gfx)?;+ }+ app.take_bar_cue();+ Ok(())});}@@ -3206,6 +3334,10 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->WM_POWERBROADCAST if w.0 == PBT_APMPOWERSTATUSCHANGE || w.0 == PBT_POWERSETTINGCHANGE => {// SAFETY: `hwnd` is our window; scheduling the same timer resets it.unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };+ with_app("energía", |app| {+ app.power_moment();+ Ok(())+ });}WM_TIMER if w.0 == BIN_TIMER => {// SAFETY: `hwnd` is this live window on its owning UI thread.@@ -3246,6 +3378,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->WM_TIMER if w.0 == SPRING_TIMER => {with_app_then("arrastre sobre una app", App::spring_open);}+ WM_TIMER if w.0 == MASCOT_TIMER => with_app("cangrejo", App::mascot_tick),WM_TIMER if w.0 == PREVIEW_TIMER => with_app("selector de ventanas", App::preview_tick),WM_TIMER if w.0 == HIDE_TIMER => {// SAFETY: Same as above.@@ -3494,6 +3627,13 @@ pub fn run() -> Result<()> {hovered: None,preview_candidate: None,preview: None,+ mascot: None,+ // Read now, so the first change after starting already counts.+ power_seen: Some((+ muelle_shell::system::battery().map(|battery| battery.charging),+ muelle_shell::system::energy_saver_on(),+ )),+ charging_shown: None,cursor: 0.0,amount: Spring::at(0.0, HOVER_OMEGA),last_frame: Instant::now(),diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex 65c44df..dbc4fb6 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -17,6 +17,7 @@ mod drop;mod flight;mod gfx;mod guard;+mod mascot;mod media;mod menu;mod menubar;diff --git a/apps/dock/src/mascot.rs b/apps/dock/src/mascot.rsnew file mode 100644index 0000000..0f58fdf--- /dev/null+++ b/apps/dock/src/mascot.rs@@ -0,0 +1,875 @@+//! The crab: a pixel-art mascot that comes out only for moments worth it+//! (an AI plan resetting or running out, the charger plugged in, energy+//! saver starting) and plays a short act, then leaves.+//!+//! Cost: nothing while it is away. An act creates a small click-through+//! window, hands the whole choreography to the compositor as keyframe+//! animations (the body slides smoothly, the legs step at 8 fps, as pixel+//! art does) and is destroyed when it ends. The dock only checks, every+//! 50 ms of those few seconds, whether the pointer is on the crab, so it can+//! react.++use std::time::{Duration, Instant};++use anyhow::Result;+use muelle_shell::icons::IconImage;+use windows::{+ Foundation::TimeSpan,+ UI::Composition::{+ CompositionEasingFunction, CompositionStretch, ContainerVisual,+ Desktop::DesktopWindowTarget, SpriteVisual, Visual,+ },+ Win32::{+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},+ UI::WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, SW_SHOWNOACTIVATE,+ ShowWindow, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP,+ },+ },+ core::{HSTRING, Interface, h, w},+};+use windows_numerics::{Vector2, Vector3};++use crate::gfx::Gfx;++/* --------------------------------------------------------------- Sprites */++/// Sprite cells. `.` is transparent.+fn color(cell: u8) -> Option<[u8; 3]> {+ Some(match cell {+ b'k' | b'e' => [43, 20, 18],+ b'o' => [232, 116, 64],+ b'h' => [255, 214, 160],+ b'd' => [204, 84, 44],+ b'p' => [244, 140, 140],+ b'm' => [226, 70, 60],+ b'b' => [70, 160, 235],+ b'B' => [170, 215, 250],+ b'r' => [236, 72, 72],+ b'R' => [255, 150, 150],+ b'z' => [235, 238, 245],+ _ => return None,+ })+}++const WIDTH: usize = 22;++/// The body, 22 cells wide, without a face.+const BODY: [&str; 12] = [+ "....kkkkkkkkkkkkkk....",+ "...khhooooooooooook...",+ "...khoooooooooooook...",+ "...kooooooooooooook...",+ "...kooooooooooooook...",+ "kkkkooooooooooooookkkk",+ "kooooooooooooooooooook",+ "kooooooooooooooooooook",+ "kkkkooooooooooooookkkk",+ "...kooooooooooooook...",+ "...kooooooooooooook...",+ "...kddddddddddddddk...",+];++/// The legs standing, and mid-step (the first and third lifted).+const LEGS: [[&str; 3]; 2] = [+ [+ "...kddkkddkkddkkddk...",+ "...kddkkddkkddkkddk...",+ "...kkkkkkkkkkkkkkkk...",+ ],+ [+ "...kddkkddkkddkkddk...",+ "...kkkkkddkkkkkkddk...",+ ".......kkkk....kkkk...",+ ],+];++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Face {+ Neutral,+ Happy,+ Love,+ Sad,+ Sleep,+}++impl Face {+ #[cfg(test)]+ const ALL: [Self; 5] = [+ Self::Neutral,+ Self::Happy,+ Self::Love,+ Self::Sad,+ Self::Sleep,+ ];++ /// (row, column, cell) drawn over the body.+ fn marks(self) -> &'static [(usize, usize, u8)] {+ match self {+ Self::Neutral => &[+ (5, 7, b'e'),+ (6, 7, b'e'),+ (7, 7, b'e'),+ (5, 14, b'e'),+ (6, 14, b'e'),+ (7, 14, b'e'),+ ],+ Self::Happy => &[+ (6, 6, b'e'),+ (5, 7, b'e'),+ (6, 8, b'e'),+ (6, 13, b'e'),+ (5, 14, b'e'),+ (6, 15, b'e'),+ (7, 10, b'e'),+ (7, 11, b'e'),+ (8, 10, b'm'),+ (8, 11, b'm'),+ ],+ Self::Love => &[+ (5, 6, b'e'),+ (6, 7, b'e'),+ (7, 6, b'e'),+ (5, 15, b'e'),+ (6, 14, b'e'),+ (7, 15, b'e'),+ (7, 4, b'p'),+ (7, 5, b'p'),+ (7, 16, b'p'),+ (7, 17, b'p'),+ ],+ Self::Sad => &[+ (6, 6, b'e'),+ (7, 7, b'e'),+ (6, 8, b'e'),+ (6, 13, b'e'),+ (7, 14, b'e'),+ (6, 15, b'e'),+ (8, 15, b'b'),+ (9, 15, b'b'),+ ],+ Self::Sleep => &[+ (6, 6, b'e'),+ (6, 7, b'e'),+ (6, 8, b'e'),+ (6, 13, b'e'),+ (6, 14, b'e'),+ (6, 15, b'e'),+ (8, 10, b'm'),+ (8, 11, b'm'),+ ],+ }+ }+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Emote {+ Heart,+ Drop,+ Sleep,+}++impl Emote {+ fn rows(self) -> &'static [&'static str] {+ match self {+ Self::Heart => &[+ ".kk.kk.", "krRkrrk", "krrrrrk", ".krrrk.", "..krk..", "...k...",+ ],+ Self::Drop => &["..k..", ".kbk.", "kbBbk", "kbbbk", ".kkk."],+ // Light, outlined in `emote_image`: readable on any wallpaper.+ Self::Sleep => &[+ "....zzzz", "......z.", "zzz..z..", "..z.zzzz", ".z......", "zzz.....",+ ],+ }+ }+}++/// The crab with `face`, legs standing or mid-step, `cell` pixels a cell.+fn crab_image(face: Face, step: bool, cell: u32) -> IconImage {+ let mut grid: Vec<Vec<u8>> = BODY+ .iter()+ .chain(LEGS[usize::from(step)].iter())+ .map(|row| {+ let mut row = row.as_bytes().to_vec();+ row.resize(WIDTH, b'.');+ row+ })+ .collect();+ for &(row, column, cell) in face.marks() {+ grid[row][column] = cell;+ }+ paint(&grid, cell)+}++fn emote_image(emote: Emote, cell: u32) -> IconImage {+ let rows: Vec<Vec<u8>> = emote+ .rows()+ .iter()+ .map(|row| row.as_bytes().to_vec())+ .collect();+ if emote == Emote::Sleep {+ return paint(&outlined(&rows), cell);+ }+ paint(&rows, cell)+}++/// `grid` with a one-cell dark outline around everything drawn, the grid+/// growing a cell on each side to hold it.+fn outlined(grid: &[Vec<u8>]) -> Vec<Vec<u8>> {+ let height = grid.len() + 2;+ let width = grid.iter().map(Vec::len).max().unwrap_or(0) + 2;+ let drawn = |y: usize, x: usize| {+ y >= 1+ && x >= 1+ && grid+ .get(y - 1)+ .and_then(|row| row.get(x - 1))+ .is_some_and(|&cell| cell != b'.')+ };+ (0..height)+ .map(|y| {+ (0..width)+ .map(|x| {+ if drawn(y, x) {+ grid[y - 1][x - 1]+ } else if (y.saturating_sub(1)..=y + 1)+ .any(|ny| (x.saturating_sub(1)..=x + 1).any(|nx| drawn(ny, nx)))+ {+ b'k'+ } else {+ b'.'+ }+ })+ .collect()+ })+ .collect()+}++/// Paints a grid, each cell a `cell` x `cell` square: whole pixels, so the+/// compositor shows it crisp.+fn paint(grid: &[Vec<u8>], cell: u32) -> IconImage {+ let columns = grid.iter().map(Vec::len).max().unwrap_or(0) as u32;+ let (width, height) = (columns * cell, grid.len() as u32 * cell);+ let mut bgra = vec![0u8; (width * height * 4) as usize];+ for (y, row) in grid.iter().enumerate() {+ for (x, &value) in row.iter().enumerate() {+ let Some([r, g, b]) = color(value) else {+ continue;+ };+ for dy in 0..cell {+ let line = (y as u32 * cell + dy) * width;+ for dx in 0..cell {+ let at = ((line + x as u32 * cell + dx) * 4) as usize;+ bgra[at..at + 4].copy_from_slice(&[b, g, r, 255]);+ }+ }+ }+ }+ IconImage {+ width,+ height,+ bgra,+ }+}++/* ------------------------------------------------------------------ Acts */++/// Why the crab comes out.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Act {+ /// An AI plan's limit reset: back to 0 %.+ Fresh,+ /// It passed 90 %.+ Nervous,+ /// It reached 100 %.+ Exhausted,+ /// The charger was plugged in.+ Charging,+ /// Energy saver started.+ Sleepy,+}++/// Where the act happens, in screen pixels.+#[derive(Clone, Copy, Debug)]+pub enum Place {+ /// Below a point of the menu bar's island: `x` is the centre, `top` the+ /// bar's bottom edge.+ Under { x: i32, top: i32 },+ /// Walking on an edge (the top of the dock): `top` is the edge.+ Along { left: i32, right: i32, top: i32 },+}++/// One act, in seconds and cells, independent of the screen.+struct Script {+ seconds: f32,+ /// (time, x) of the crab's left edge, in pixels from the window's left.+ path: Vec<(f32, f32)>,+ /// (start, height in cells) of each hop, 0.45 s long.+ hops: Vec<(f32, f32)>,+ /// Trembling, from..to.+ shake: Option<(f32, f32)>,+ /// From each time on, this face.+ faces: Vec<(f32, Face)>,+ /// Intervals in which the legs step.+ walking: Vec<(f32, f32)>,+ /// The emote and when it shows.+ emote: Option<(Emote, f32, f32)>,+}++const POP: f32 = 0.28;+const STEP_FPS: f32 = 8.0;+const HOP: f32 = 0.45;++impl Script {+ fn new(act: Act, width: f32, crab: f32) -> Self {+ // Under the island the crab stands still, centred.+ let centre = (width - crab) / 2.0;+ match act {+ Act::Fresh => Self {+ seconds: 3.0,+ path: vec![(0.0, centre)],+ hops: vec![(0.35, 5.0), (0.85, 4.0), (1.55, 6.0)],+ shake: None,+ faces: vec![(0.0, Face::Happy), (1.5, Face::Love)],+ walking: Vec::new(),+ emote: Some((Emote::Heart, 1.5, 2.65)),+ },+ Act::Nervous => Self {+ seconds: 2.8,+ path: vec![(0.0, centre)],+ hops: Vec::new(),+ shake: Some((0.35, 2.2)),+ faces: vec![(0.0, Face::Neutral), (0.35, Face::Sad)],+ walking: Vec::new(),+ emote: Some((Emote::Drop, 0.4, 2.4)),+ },+ Act::Exhausted => Self {+ seconds: 3.6,+ path: vec![(0.0, centre)],+ hops: vec![(0.3, 2.0)],+ shake: None,+ faces: vec![(0.0, Face::Sad), (1.0, Face::Sleep)],+ walking: Vec::new(),+ emote: Some((Emote::Sleep, 1.1, 3.25)),+ },+ // Scurries in from the left, stops halfway for a happy hop, and+ // runs off to the right.+ Act::Charging => {+ let middle = width * 0.55 - crab / 2.0;+ Self {+ seconds: 4.6,+ path: vec![+ (0.0, 0.0),+ (1.9, middle),+ (2.9, middle),+ (4.6, width - crab),+ ],+ hops: vec![(2.0, 6.0), (3.0, 3.0)],+ shake: None,+ faces: vec![(0.0, Face::Happy), (2.0, Face::Love), (2.9, Face::Happy)],+ walking: vec![(0.0, 1.9), (2.9, 4.6)],+ emote: Some((Emote::Heart, 2.05, 3.0)),+ }+ }+ // Shuffles in slowly from the right, stops and falls asleep.+ Act::Sleepy => {+ let rest = width * 0.62 - crab / 2.0;+ Self {+ seconds: 5.4,+ path: vec![(0.0, width - crab), (2.6, rest), (5.4, rest)],+ hops: Vec::new(),+ shake: None,+ faces: vec![(0.0, Face::Neutral), (2.7, Face::Sleep)],+ walking: vec![(0.0, 2.6)],+ emote: Some((Emote::Sleep, 2.9, 5.1)),+ }+ }+ }+ }++ /// The crab's left edge at `t`.+ fn x_at(&self, t: f32) -> f32 {+ let Some(first) = self.path.first() else {+ return 0.0;+ };+ let mut previous = *first;+ for &(time, x) in &self.path {+ if t <= time {+ let span = (time - previous.0).max(f32::EPSILON);+ let progress = ((t - previous.0) / span).clamp(0.0, 1.0);+ return previous.1 + (x - previous.1) * progress;+ }+ previous = (time, x);+ }+ previous.1+ }++ fn face_at(&self, t: f32) -> Face {+ self.faces+ .iter()+ .rev()+ .find(|(from, _)| t >= *from)+ .map_or(Face::Neutral, |(_, face)| *face)+ }++ fn step_at(&self, t: f32) -> bool {+ self.walking+ .iter()+ .any(|(from, to)| t >= *from && t < *to && ((t - from) * STEP_FPS) as u32 % 2 == 1)+ }+}++/* ---------------------------------------------------------------- Mascot */++pub struct Mascot {+ hwnd: HWND,+ _target: DesktopWindowTarget,+ hop: ContainerVisual,+ poke_heart: SpriteVisual,+ script: Script,+ started: Instant,+ /// The window's top-left corner on screen, and the crab's size.+ origin: POINT,+ crab: (f32, f32),+ crab_top: f32,+ cell: f32,+ last_poke: Option<Instant>,+}++impl Mascot {+ /// Plays `act` at `place`. `scale` is the monitor's (1.0 at 100 %).+ pub fn play(gfx: &Gfx, act: Act, place: Place, scale: f32) -> Option<Self> {+ match Self::build(gfx, act, place, scale) {+ Ok(mascot) => Some(mascot),+ Err(error) => {+ eprintln!("muelle: cangrejo: {error:#}");+ None+ }+ }+ }++ fn build(gfx: &Gfx, act: Act, place: Place, scale: f32) -> Result<Self> {+ let cell_px = (scale * 1.6).round().max(2.0) as u32;+ let cell = cell_px as f32;+ let crab = (+ (WIDTH as u32 * cell_px) as f32,+ ((BODY.len() + 3) as u32 * cell_px) as f32,+ );+ // Room above the crab for hops and the emote.+ let headroom = 14.0 * cell;+ let height = crab.1 + headroom;+ let (rect, crab_top) = match place {+ Place::Under { x, top } => {+ let width = crab.0 + 8.0 * cell;+ let left = x - (width / 2.0) as i32;+ // Hangs a little below the bar.+ let top = top + cell as i32;+ (+ RECT {+ left,+ top,+ right: left + width as i32,+ bottom: top + height as i32,+ },+ headroom,+ )+ }+ Place::Along { left, right, top } => {+ // Feet one cell into the edge, as if standing on its rim.+ let bottom = top + cell as i32;+ (+ RECT {+ left,+ top: bottom - height as i32,+ right,+ bottom,+ },+ headroom,+ )+ }+ };+ let width = (rect.right - rect.left) as f32;+ let script = Script::new(act, width, crab.0);++ let hwnd = create_window(rect)?;+ let built = || -> Result<(DesktopWindowTarget, ContainerVisual, SpriteVisual)> {+ // SAFETY: `hwnd` is the live window created above.+ let target = unsafe {+ gfx.compositor+ .cast::<ICompositorDesktopInterop>()?+ .CreateDesktopWindowTarget(hwnd, true)?+ };+ let (root, hop, poke_heart) = choreograph(gfx, &script, crab, crab_top, cell)?;+ target.SetRoot(&root)?;+ Ok((target, hop, poke_heart))+ };+ let (target, hop, poke_heart) = match built() {+ Ok(parts) => parts,+ Err(error) => {+ // SAFETY: Our own window, created above.+ unsafe {+ let _ = DestroyWindow(hwnd);+ }+ return Err(error);+ }+ };+ // SAFETY: Our own window; shown without taking the focus.+ unsafe {+ let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);+ }+ Ok(Self {+ hwnd,+ _target: target,+ hop,+ poke_heart,+ script,+ started: Instant::now(),+ origin: POINT {+ x: rect.left,+ y: rect.top,+ },+ crab,+ crab_top,+ cell,+ last_poke: None,+ })+ }++ /// `true` once the act is over and the crab can go.+ pub fn finished(&self) -> bool {+ self.started.elapsed() >= Duration::from_secs_f32(self.script.seconds)+ }++ /// The pointer at `point`: if it is on the crab, a hop and a heart.+ pub fn poke(&mut self, gfx: &Gfx, point: POINT) {+ let t = self.started.elapsed().as_secs_f32();+ // Not while popping in or out.+ if t < POP || t > self.script.seconds - POP {+ return;+ }+ if self+ .last_poke+ .is_some_and(|last| last.elapsed() < Duration::from_millis(900))+ {+ return;+ }+ let left = self.origin.x as f32 + self.script.x_at(t);+ let top = self.origin.y as f32 + self.crab_top;+ let (x, y) = (point.x as f32, point.y as f32);+ if x < left+ || x >= left + self.crab.0+ || y < top - 3.0 * self.cell+ || y >= top + self.crab.1+ {+ return;+ }+ self.last_poke = Some(Instant::now());+ let _ = react(gfx, &self.hop, &self.poke_heart, self.cell);+ }+}++impl Drop for Mascot {+ fn drop(&mut self) {+ // SAFETY: Our own window, destroyed once.+ unsafe {+ let _ = DestroyWindow(self.hwnd);+ }+ }+}++/// The visual tree and its animations:+///+/// root → path (slides along the act's path)+/// ├ hop (hops, trembles, pops in and out)+/// │ └ one sprite per face and leg pose, switched on and off+/// ├ emote (rises and fades)+/// └ poke heart (only on a poke)+fn choreograph(+ gfx: &Gfx,+ script: &Script,+ crab: (f32, f32),+ crab_top: f32,+ cell: f32,+) -> Result<(ContainerVisual, ContainerVisual, SpriteVisual)> {+ let c = &gfx.compositor;+ let seconds = script.seconds;+ let duration = TimeSpan {+ Duration: (seconds as f64 * 1e7) as i64,+ };+ let at = |t: f32| (t / seconds).clamp(0.0, 1.0);+ let linear: CompositionEasingFunction = c.CreateLinearEasingFunction()?.cast()?;+ let out: CompositionEasingFunction = c+ .CreateCubicBezierEasingFunction(Vector2::new(0.2, 0.9), Vector2::new(0.3, 1.0))?+ .cast()?;+ let cell_px = cell as u32;++ let root = c.CreateContainerVisual()?;+ root.SetRelativeSizeAdjustment(Vector2::new(1.0, 1.0))?;+ let path = c.CreateContainerVisual()?;+ path.SetSize(Vector2::new(crab.0, crab_top + crab.1))?;+ root.Children()?.InsertAtTop(&path)?;++ // The walk: the left edge along the path, linear between its points.+ let slide = c.CreateVector3KeyFrameAnimation()?;+ slide.SetDuration(duration)?;+ for &(time, x) in &script.path {+ slide.InsertKeyFrameWithEasingFunction(at(time), Vector3::new(x, 0.0, 0.0), &linear)?;+ }+ if script.path.len() == 1 {+ path.SetOffset(Vector3::new(script.path[0].1, 0.0, 0.0))?;+ } else {+ path.StartAnimation(h!("Offset"), &slide)?;+ }++ // Hops, trembling, and the pop in and out (scale from the feet).+ let hop = c.CreateContainerVisual()?;+ hop.SetSize(Vector2::new(crab.0, crab.1))?;+ hop.SetOffset(Vector3::new(0.0, crab_top, 0.0))?;+ hop.SetCenterPoint(Vector3::new(crab.0 / 2.0, crab.1, 0.0))?;+ path.Children()?.InsertAtTop(&hop)?;++ let lift = c.CreateVector3KeyFrameAnimation()?;+ lift.SetDuration(duration)?;+ lift.InsertKeyFrame(0.0, Vector3::new(0.0, crab_top, 0.0))?;+ for &(start, height) in &script.hops {+ let up = Vector3::new(0.0, crab_top - height * cell, 0.0);+ let down = Vector3::new(0.0, crab_top, 0.0);+ lift.InsertKeyFrameWithEasingFunction(at(start), down, &linear)?;+ lift.InsertKeyFrameWithEasingFunction(at(start + HOP * 0.45), up, &out)?;+ lift.InsertKeyFrameWithEasingFunction(at(start + HOP), down, &linear)?;+ }+ if let Some((from, to)) = script.shake {+ // A cell either way, twelve times a second.+ let mut t = from;+ let mut side = 1.0;+ lift.InsertKeyFrameWithEasingFunction(at(from), Vector3::new(0.0, crab_top, 0.0), &linear)?;+ while t < to {+ t += 1.0 / 12.0;+ lift.InsertKeyFrameWithEasingFunction(+ at(t),+ Vector3::new(side * cell * 0.5, crab_top, 0.0),+ &linear,+ )?;+ side = -side;+ }+ lift.InsertKeyFrameWithEasingFunction(+ at(t + 0.05),+ Vector3::new(0.0, crab_top, 0.0),+ &linear,+ )?;+ }+ lift.InsertKeyFrame(1.0, Vector3::new(0.0, crab_top, 0.0))?;+ hop.StartAnimation(h!("Offset"), &lift)?;++ let pop = c.CreateVector3KeyFrameAnimation()?;+ pop.SetDuration(duration)?;+ pop.InsertKeyFrame(0.0, Vector3::new(0.0, 0.0, 1.0))?;+ pop.InsertKeyFrameWithEasingFunction(at(POP * 0.7), Vector3::new(1.15, 1.15, 1.0), &out)?;+ pop.InsertKeyFrameWithEasingFunction(at(POP), Vector3::new(1.0, 1.0, 1.0), &linear)?;+ pop.InsertKeyFrameWithEasingFunction(at(seconds - POP), Vector3::new(1.0, 1.0, 1.0), &linear)?;+ pop.InsertKeyFrameWithEasingFunction(at(seconds), Vector3::new(0.0, 0.0, 1.0), &linear)?;+ hop.StartAnimation(h!("Scale"), &pop)?;++ // Faces and steps: every pose the act uses is a sprite, shown only+ // while it is current. Sampled at the step rate, cut, not faded.+ let mut poses: Vec<(Face, bool)> = Vec::new();+ let samples = (seconds * STEP_FPS).ceil() as u32 + 1;+ let timeline: Vec<(f32, (Face, bool))> = (0..samples)+ .map(|index| {+ let t = (index as f32 / STEP_FPS).min(seconds);+ (t, (script.face_at(t), script.step_at(t)))+ })+ .collect();+ for (_, pose) in &timeline {+ if !poses.contains(pose) {+ poses.push(*pose);+ }+ }+ let poses_layer = hop.Children()?;+ for pose in &poses {+ let sprite = sprite(gfx, &crab_image(pose.0, pose.1, cell_px))?;+ poses_layer.InsertAtTop(&sprite)?;+ let shown = c.CreateScalarKeyFrameAnimation()?;+ shown.SetDuration(duration)?;+ let mut current = timeline.first().map(|(_, first)| first == pose);+ shown.InsertKeyFrame(0.0, if current == Some(true) { 1.0 } else { 0.0 })?;+ for (t, at_pose) in &timeline {+ let visible = at_pose == pose;+ if Some(visible) != current {+ let value = if visible { 1.0 } else { 0.0 };+ shown.InsertKeyFrameWithEasingFunction(+ (at(*t) - 0.0005).max(0.0),+ if visible { 0.0 } else { 1.0 },+ &linear,+ )?;+ shown.InsertKeyFrameWithEasingFunction(at(*t), value, &linear)?;+ current = Some(visible);+ }+ }+ sprite.StartAnimation(h!("Opacity"), &shown)?;+ }++ // The emote rises from above the head and fades.+ if let Some((emote, from, to)) = script.emote {+ let sprite = sprite(gfx, &emote_image(emote, cell_px))?;+ let size = sprite.Size()?;+ let x = (crab.0 - size.X) / 2.0+ + if emote == Emote::Sleep {+ 4.0 * cell+ } else {+ 0.0+ };+ let start = crab_top - size.Y - cell;+ sprite.SetOffset(Vector3::new(x, start, 0.0))?;+ path.Children()?.InsertAtTop(&sprite)?;+ let rise = c.CreateVector3KeyFrameAnimation()?;+ rise.SetDuration(duration)?;+ rise.InsertKeyFrame(0.0, Vector3::new(x, start, 0.0))?;+ rise.InsertKeyFrameWithEasingFunction(at(from), Vector3::new(x, start, 0.0), &linear)?;+ rise.InsertKeyFrameWithEasingFunction(+ at(to),+ Vector3::new(x, start - 5.0 * cell, 0.0),+ &out,+ )?;+ rise.InsertKeyFrame(1.0, Vector3::new(x, start - 5.0 * cell, 0.0))?;+ sprite.StartAnimation(h!("Offset"), &rise)?;+ let fade = c.CreateScalarKeyFrameAnimation()?;+ fade.SetDuration(duration)?;+ fade.InsertKeyFrame(0.0, 0.0)?;+ fade.InsertKeyFrameWithEasingFunction(at(from), 0.0, &linear)?;+ fade.InsertKeyFrameWithEasingFunction(at(from + 0.15), 1.0, &linear)?;+ fade.InsertKeyFrameWithEasingFunction(at(to - 0.3), 1.0, &linear)?;+ fade.InsertKeyFrameWithEasingFunction(at(to), 0.0, &linear)?;+ fade.InsertKeyFrame(1.0, 0.0)?;+ sprite.StartAnimation(h!("Opacity"), &fade)?;+ }++ let poke_heart = sprite(gfx, &emote_image(Emote::Heart, cell_px))?;+ poke_heart.SetOpacity(0.0)?;+ path.Children()?.InsertAtTop(&poke_heart)?;+ Ok((root, hop, poke_heart))+}++/// A poke: a quick hop and a heart above the head.+fn react(gfx: &Gfx, hop: &ContainerVisual, heart: &SpriteVisual, cell: f32) -> Result<()> {+ let c = &gfx.compositor;+ let duration = TimeSpan {+ Duration: 6_500_000,+ };+ let base = hop.Offset()?;+ // The hop container's own animation keeps running; this one adds a+ // short squash and stretch on top, through the scale.+ let squash = c.CreateVector3KeyFrameAnimation()?;+ squash.SetDuration(TimeSpan {+ Duration: 3_500_000,+ })?;+ squash.InsertKeyFrame(0.0, Vector3::new(1.0, 1.0, 1.0))?;+ squash.InsertKeyFrame(0.25, Vector3::new(1.12, 0.86, 1.0))?;+ squash.InsertKeyFrame(0.6, Vector3::new(0.92, 1.12, 1.0))?;+ squash.InsertKeyFrame(1.0, Vector3::new(1.0, 1.0, 1.0))?;+ hop.StartAnimation(h!("Scale"), &squash)?;++ let size = heart.Size()?;+ let hop_size = hop.Size()?;+ let x = (hop_size.X - size.X) / 2.0;+ let start = base.Y - size.Y - cell;+ let rise = c.CreateVector3KeyFrameAnimation()?;+ rise.SetDuration(duration)?;+ rise.InsertKeyFrame(0.0, Vector3::new(x, start, 0.0))?;+ rise.InsertKeyFrame(1.0, Vector3::new(x, start - 6.0 * cell, 0.0))?;+ heart.StartAnimation(h!("Offset"), &rise)?;+ let fade = c.CreateScalarKeyFrameAnimation()?;+ fade.SetDuration(duration)?;+ fade.InsertKeyFrame(0.0, 1.0)?;+ fade.InsertKeyFrame(0.65, 1.0)?;+ fade.InsertKeyFrame(1.0, 0.0)?;+ heart.StartAnimation(h!("Opacity"), &fade)?;+ Ok(())+}++/// A sprite showing `image` at its exact size, never smoothed.+fn sprite(gfx: &Gfx, image: &IconImage) -> Result<SpriteVisual> {+ let c = &gfx.compositor;+ let brush = c.CreateSurfaceBrushWithSurface(&gfx.image_surface(image)?)?;+ brush.SetStretch(CompositionStretch::None)?;+ brush.SetBitmapInterpolationMode(+ windows::UI::Composition::CompositionBitmapInterpolationMode::NearestNeighbor,+ )?;+ let sprite = c.CreateSpriteVisual()?;+ sprite.SetBrush(&brush)?;+ sprite.SetSize(Vector2::new(image.width as f32, image.height as f32))?;+ let _: &Visual = &sprite.cast()?;+ Ok(sprite)+}++fn create_window(rect: RECT) -> Result<HWND> {+ static CLASS: std::sync::OnceLock<()> = std::sync::OnceLock::new();+ let class = w!("MuelleMascot");+ // SAFETY: The class is registered once; the window is destroyed by+ // `Mascot::drop`, or by the caller if building the act fails.+ unsafe {+ let instance = GetModuleHandleW(None)?;+ CLASS.get_or_init(|| {+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(mascot_proc),+ hInstance: instance.into(),+ lpszClassName: class,+ ..Default::default()+ });+ });+ // Click-through: the crab never takes a click from what is under it.+ Ok(CreateWindowExW(+ WS_EX_LAYERED+ | WS_EX_TRANSPARENT+ | WS_EX_NOREDIRECTIONBITMAP+ | WS_EX_TOPMOST+ | WS_EX_TOOLWINDOW+ | WS_EX_NOACTIVATE,+ class,+ &HSTRING::new(),+ WS_POPUP,+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,+ None,+ None,+ Some(instance.into()),+ None,+ )?)+ }+}++unsafe extern "system" fn mascot_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {+ // SAFETY: Default handling for our own window.+ unsafe { DefWindowProcW(hwnd, msg, w, l) }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sprites_should_be_rectangular_and_faces_inside_the_body() {+ for row in BODY.iter().chain(LEGS.iter().flatten()) {+ assert!(row.len() <= WIDTH + 1, "{row}");+ }+ for face in Face::ALL {+ for &(row, column, _) in face.marks() {+ assert!(row < BODY.len() && column < WIDTH, "{face:?}");+ assert_ne!(BODY[row].as_bytes()[column], b'.', "{face:?} off the body");+ }+ }+ }++ #[test]+ fn script_should_place_the_crab_along_its_path() {+ let script = Script::new(Act::Charging, 1000.0, 44.0);+ assert_eq!(script.x_at(0.0), 0.0);+ assert!((script.x_at(script.seconds) - (1000.0 - 44.0)).abs() < 0.01);+ assert_eq!(script.face_at(2.5), Face::Love);+ assert!(!script.step_at(2.5), "it stands still while hopping");+ }+}diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex d3e636b..529b730 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -59,6 +59,7 @@ use windows_numerics::{Vector2, Vector3};use crate::{app,gfx::{Gfx, Ink, LabelBrush},+ mascot,media::{self, Control as MediaControl, Track},scene::Theme,strings,@@ -252,6 +253,10 @@ pub struct MenuBar {bounds: RECT,status: Status,usage: Option<UsageMonitor>,+ /// Where each provider sits in the closed island, as screen x.+ usage_anchors: Vec<(Provider, i32)>,+ /// A moment for the crab, waiting for the dock (see `take_cue`).+ cue: Option<(mascot::Act, i32)>,media: Option<media::Watch>,panel: Option<Island>,visual_height: i32,@@ -953,6 +958,8 @@ impl MenuBar {privacy: Privacy::default(),},usage: usage_enabled.then(|| UsageMonitor::new(hwnd.0 as isize, USAGE_CHANGED)),+ usage_anchors: Vec::new(),+ cue: None,media: media::Watch::start(hwnd, MEDIA_CHANGED),panel: None,visual_height: 0,@@ -1361,11 +1368,34 @@ impl MenuBar {if self.look.as_ref() == Some(&look) {return Ok(());}+ let moment = self+ .look+ .as_ref()+ .and_then(|old| usage_moment(&old.usage, &look.usage, &look.active_providers));self.build(gfx, &look)?;self.look = Some(look);+ if let Some((provider, act)) = moment+ && let Some(&(_, x)) = self.usage_anchors.iter().find(|(p, _)| *p == provider)+ {+ self.cue = Some((act, x));+ }Ok(())}+ /// A moment worth the crab, found by the last update: the act and the+ /// screen x of the provider in the island. Taken once.+ pub fn take_cue(&mut self) -> Option<(mascot::Act, POINT)> {+ let (act, x) = self.cue.take()?;+ let shown = self.visible && (!self.auto_hide || self.revealed);+ shown.then_some((+ act,+ POINT {+ x,+ y: self.bounds.bottom,+ },+ ))+ }+fn build(&mut self, gfx: &Gfx, look: &Look) -> Result<()> {let c = &gfx.compositor;let scale = look.scale;@@ -1632,7 +1662,12 @@ impl MenuBar {}}Island::Usage => {- draw_compact_usage(gfx, &content, geometry, bar_height, &providers)?+ let anchors =+ draw_compact_usage(gfx, &content, geometry, bar_height, &providers)?;+ self.usage_anchors = anchors+ .into_iter()+ .map(|(provider, x)| (provider, look.screen.left + (span.left + x) as i32))+ .collect();}}let (left, right) = match kind {@@ -2195,13 +2230,43 @@ fn island_surface(Ok(content)}+/// Draws the providers in the closed island and returns where each one's+/// figure sits (its centre, from the segment's left edge), for the crab.+/// The moment an AI plan's figure crosses a line worth showing, comparing+/// the previous update with this one: a limit reset to 0 % (after being in+/// use), past 90 %, or at 100 %. Nothing on the first figures after starting,+/// which have nothing to compare with.+fn usage_moment(+ old: &usage::Snapshot,+ new: &usage::Snapshot,+ active: &ActiveProviders,+) -> Option<(Provider, mascot::Act)> {+ Provider::ALL+ .into_iter()+ .filter(|p| active.has(*p))+ .find_map(|provider| {+ let before = old.get(provider).main_window()?.used_percent;+ let now = new.get(provider).main_window()?.used_percent;+ let act = if now >= 100 && before < 100 {+ mascot::Act::Exhausted+ } else if now >= 90 && before < 90 {+ mascot::Act::Nervous+ } else if now <= 1 && before >= 20 {+ mascot::Act::Fresh+ } else {+ return None;+ };+ Some((provider, act))+ })+}+fn draw_compact_usage(gfx: &Gfx,content: &VisualCollection,geometry: IslandGeometry,bar_height: f32,providers: &[IslandProvider<'_>],-) -> Result<()> {+) -> Result<Vec<(Provider, f32)>> {let c = &gfx.compositor;let px = |v| geometry.px(v);let ink = geometry.ink();@@ -2219,9 +2284,15 @@ fn draw_compact_usage(icon.width,icon.height,)?;- return Ok(());+ let centre = geometry.width / 2.0;+ return Ok(providers+ .iter()+ .map(|(provider, ..)| (*provider, centre))+ .collect());}+ let mut anchors = Vec::with_capacity(providers.len());for (index, (provider, usage, accent)) in providers.iter().enumerate() {+ anchors.push((*provider, inset + (index as f32 + 0.5) * half));// When space is tight the full list is still available in the panel.if half < px(20.0) {break;@@ -2287,7 +2358,7 @@ fn draw_compact_usage()?;}}- Ok(())+ Ok(anchors)}fn track_title(track: &Track) -> &str {@@ -2457,3 +2528,46 @@ mod island_tests {Ok(())}}++#[cfg(test)]+mod mascot_tests {+ use super::*;+ use crate::usage::{ProviderUsage, Snapshot, State, Window};++ fn at(percent: Option<u8>) -> Snapshot {+ let mut snapshot = Snapshot::default();+ if let Some(percent) = percent {+ snapshot.providers[Provider::Claude as usize] = ProviderUsage {+ state: State::Ready,+ windows: vec![Window {+ label: None,+ minutes: 300,+ used_percent: percent,+ resets_at: None,+ }],+ fetched_at: None,+ };+ }+ snapshot+ }++ fn moment(before: Option<u8>, now: Option<u8>) -> Option<mascot::Act> {+ let mut active = ActiveProviders::default();+ active.0[Provider::Claude as usize] = true;+ usage_moment(&at(before), &at(now), &active).map(|(_, act)| act)+ }++ #[test]+ fn usage_moment_should_fire_only_when_a_line_is_crossed() {+ assert_eq!(moment(Some(60), Some(0)), Some(mascot::Act::Fresh));+ assert_eq!(moment(Some(85), Some(91)), Some(mascot::Act::Nervous));+ assert_eq!(moment(Some(95), Some(100)), Some(mascot::Act::Exhausted));+ // Straight to 100 is "exhausted", not "nervous".+ assert_eq!(moment(Some(50), Some(100)), Some(mascot::Act::Exhausted));+ // Staying above a line, a small reset, or the first figure: nothing.+ assert_eq!(moment(Some(92), Some(95)), None);+ assert_eq!(moment(Some(10), Some(0)), None);+ assert_eq!(moment(None, Some(0)), None);+ assert_eq!(moment(None, Some(100)), None);+ }+}diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex 7bfc3f1..d48f273 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -276,6 +276,13 @@ export function App() {onChange={(bounceOnOpen) => update({ bounceOnOpen })}/></Row>+ <Row label={t.mascot} hint={t.mascotHint}>+ <Toggle+ label={t.mascot}+ checked={config.mascot}+ onChange={(mascot) => update({ mascot })}+ />+ </Row><Row label={t.showIndicators}><Togglelabel={t.showIndicators}diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex 48a8f9a..e1b0a5c 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -19,6 +19,7 @@ export interface Config {showIndicators: boolean;showRecents: boolean;bounceOnOpen: boolean;+ mascot: boolean;checkUpdates: boolean;autoUpdate: boolean;language: Language;diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex 88da713..9733ee0 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -42,6 +42,8 @@"showRecents": "Show recent apps","showRecentsHint": "The last three you opened that are not pinned.","bounceOnOpen": "Animate opening apps",+ "mascot": "Crab on special moments",+ "mascotHint": "A pixel crab comes out when an AI plan resets or runs out, when you plug in the charger, or when energy saver starts. Hover over it.","reset": "Restore defaults","resetHint": "Back to the out-of-the-box look and behavior. Your pinned apps stay.","resetConfirmHint": "Click again to confirm.",diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonindex 8cf015b..15bd556 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -42,6 +42,8 @@"showRecents": "Mostrar apps recientes","showRecentsHint": "Las tres últimas que abriste sin tenerlas fijadas.","bounceOnOpen": "Animar al abrir apps",+ "mascot": "Cangrejo en momentos especiales",+ "mascotHint": "Un cangrejo pixelado aparece cuando un plan de IA se reinicia o se agota, al enchufar el cargador o al activarse el ahorro de energía. Pasa el puntero por encima.","reset": "Restablecer valores","resetHint": "Vuelve al aspecto y comportamiento de fábrica. Tus apps fijadas se mantienen.","resetConfirmHint": "Pulsa otra vez para confirmar.",diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex 2060e44..df40723 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -67,6 +67,9 @@ pub struct Config {pub show_recents: bool,/// Icons bounce while the app they open is starting.pub bounce_on_open: bool,+ /// The crab comes out for moments worth it (an AI plan resetting or+ /// running out, the charger, energy saver).+ pub mascot: bool,/// Settings asks GitHub Releases for a newer version when it opens. The/// only network access in Muelle, so it can be turned off.pub check_updates: bool,@@ -130,6 +133,7 @@ impl Default for Config {show_indicators: true,show_recents: true,bounce_on_open: true,+ mascot: true,check_updates: true,auto_update: true,language: Language::Auto,diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rsindex 8aeafb3..4927deb 100644--- a/crates/muelle-shell/src/system.rs+++ b/crates/muelle-shell/src/system.rs@@ -35,17 +35,21 @@ pub fn uses_light_theme() -> bool {/// `false` there.#[must_use]pub fn transparency_enabled() -> bool {- use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};if !is_windows_11() {return false;}+ // Missing means never changed, and the default is on.+ !energy_saver_on() && personalize(w!("EnableTransparency")) != Some(0)+}++/// `true` while energy saver (battery saver on Windows 10) is on.+#[must_use]+pub fn energy_saver_on() -> bool {+ use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};const SAVER_ON: u8 = 1;let mut status = SYSTEM_POWER_STATUS::default();// SAFETY: `status` is a valid structure the call fills in.- let saver = unsafe { GetSystemPowerStatus(&mut status) }.is_ok()- && status.SystemStatusFlag & SAVER_ON != 0;- // Missing means never changed, and the default is on.- !saver && personalize(w!("EnableTransparency")) != Some(0)+ unsafe { GetSystemPowerStatus(&mut status) }.is_ok() && status.SystemStatusFlag & SAVER_ON != 0}/// The input language of the window in front as two capital lettersdiff --git a/spikes/src/bin/spike_mascot.rs b/spikes/src/bin/spike_mascot.rsnew file mode 100644index 0000000..3b6f44b--- /dev/null+++ b/spikes/src/bin/spike_mascot.rs@@ -0,0 +1,100 @@+//! Plays one of the crab's acts (the real `mascot.rs` and `gfx.rs`) on the+//! screen and saves frames of it, to review the choreography. Usage:+//! `spike_mascot <fresh|nervous|exhausted|charging|sleepy> <out folder>`.++#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]++#[path = "../../../apps/dock/src/gfx.rs"]+mod gfx;+#[path = "../../../apps/dock/src/mascot.rs"]+mod mascot;++use std::{+ io::Write,+ time::{Duration, Instant},+};++use muelle_shell::screen;+use windows::Win32::{+ Foundation::RECT,+ System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ },+ UI::{+ HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},+ WindowsAndMessaging::{DispatchMessageW, MSG, PM_REMOVE, PeekMessageW},+ },+};++fn main() {+ let act = match std::env::args().nth(1).as_deref() {+ Some("nervous") => mascot::Act::Nervous,+ Some("exhausted") => mascot::Act::Exhausted,+ Some("charging") => mascot::Act::Charging,+ Some("sleepy") => mascot::Act::Sleepy,+ _ => mascot::Act::Fresh,+ };+ let out = std::path::PathBuf::from(std::env::args().nth(2).expect("out folder"));+ std::fs::create_dir_all(&out).unwrap();+ unsafe {+ let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ let _queue = CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })+ .unwrap();+ let gfx = gfx::Gfx::new().unwrap();+ let (place, area) = match act {+ mascot::Act::Charging | mascot::Act::Sleepy => (+ mascot::Place::Along {+ left: 560,+ right: 1360,+ top: 900,+ },+ RECT {+ left: 540,+ top: 760,+ right: 1380,+ bottom: 920,+ },+ ),+ _ => (+ mascot::Place::Under { x: 960, top: 300 },+ RECT {+ left: 860,+ top: 290,+ right: 1060,+ bottom: 460,+ },+ ),+ };+ let mut crab = mascot::Mascot::play(&gfx, act, place, 1.25).expect("play");+ let start = Instant::now();+ let marks = [0.15, 0.35, 0.7, 1.2, 1.8, 2.4, 3.1, 4.2];+ let mut next = 0;+ let mut msg = MSG::default();+ while !crab.finished() {+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {+ DispatchMessageW(&msg);+ }+ let t = start.elapsed().as_secs_f32();+ if next < marks.len() && t >= marks[next] {+ if let Some(shot) = screen::capture(area) {+ let path = out.join(format!("{next}_{:.2}.bgra", marks[next]));+ let mut file = std::fs::File::create(path).unwrap();+ file.write_all(&((area.right - area.left) as u32).to_le_bytes())+ .unwrap();+ file.write_all(&((area.bottom - area.top) as u32).to_le_bytes())+ .unwrap();+ file.write_all(&shot.bgra).unwrap();+ }+ next += 1;+ }+ std::thread::sleep(Duration::from_millis(5));+ let _ = &mut crab;+ }+ println!("act over after {:.2} s", start.elapsed().as_secs_f32());+ }+}