Skip to content

A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.

feat: add media volume and no output strings in multiple languages

CristianOlivera14842a4b91b41
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f036a2c..dfc5b06 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,14 @@ copia la sección de la versión que se publica a la release de GitHub.
### English
+- Music now shows circular Windows media artwork in the island and its popup,
+ with a bundled offline fallback. The popup adds system volume and mute controls;
+ the thumb and percentage respond immediately, with coalesced audio writes and
+ retained visuals. Audio events avoid unrelated system queries and full redraws
+ for percentage-only changes. Release/cancellation does not steal app focus.
+- Dock and island-style previews use the current monitor's wallpaper when available.
+ Notch/bubble illustrations have clearer content and unobstructed selection marks. Nested
+ options and sliders have fewer icons, and the GitHub star is filled yellow.
- Settings now illustrate Dock placement, island styles and Genie speeds, with
native keyboard-selectable options, clearer icons and shorter descriptions.
A permanent sidebar link opens Muelle on GitHub to explore and star the project.
@@ -80,6 +88,15 @@ copia la sección de la versión que se publica a la release de GitHub.
### Español
+- La isla y el popup de música muestran la carátula circular de Windows, con
+ una imagen incluida como respaldo. El popup incorpora volumen del sistema y
+ silencio: tirador y porcentaje responden al instante, reutilizando sus visuales
+ y agrupando las escrituras de audio. Los cambios de porcentaje evitan consultas
+ ajenas al audio y redibujar la barra. El arrastre no roba el foco.
+- Las previews del Dock y de estilos de isla usan el fondo del monitor actual.
+ Muesca y burbuja tienen contenido más claro y la marca de selección queda fuera
+ de la imagen. Si el fondo no está disponible, mantienen el fondo ilustrado.
+ Se quitan iconos de subopciones y sliders; la estrella de GitHub es amarilla.
- Ajustes incorpora vistas de la posición del Dock, los estilos de isla y la
velocidad del genio, con selección por teclado, iconos y textos más breves.
Un enlace fijo al pie del sidebar abre Muelle en GitHub para conocer y apoyar
diff --git a/Cargo.lock b/Cargo.lock
index 314ed01..ec09fbd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2313,8 +2313,10 @@ version = "0.1.17"
name = "muelle-settings"
version = "0.1.17"
dependencies = [
+ "base64 0.23.1",
"muelle-config",
"muelle-shell",
+ "png",
"serde",
"serde_json",
"tauri",
diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.toml
index 29347c6..305ba67 100644
--- a/apps/dock/Cargo.toml
+++ b/apps/dock/Cargo.toml
@@ -35,6 +35,7 @@ windows = { workspace = true, features = [
"Graphics",
"Graphics_DirectX",
"Media_Control",
+ "Storage_Streams",
"System",
"UI",
"UI_Composition",
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index bfc61ba..60abaf3 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -4643,6 +4643,29 @@ pub fn menu_bar_clicked(x: f32, y: f32) {
});
}
+pub fn menu_bar_volume_press(x: f32, y: f32) {
+ with_app("volumen", |app| {
+ if let Some(bar) = &mut app.menubar {
+ bar.press_volume(&app.gfx, x, y)?;
+ }
+ Ok(())
+ });
+}
+
+pub fn menu_bar_volume_release(x: Option<f32>) -> bool {
+ with_app_value("volumen", |app| match &mut app.menubar {
+ Some(bar) => bar.release_volume(x),
+ None => Ok(false),
+ })
+}
+
+pub fn menu_bar_volume_flush() {
+ with_app("volumen", |app| match &mut app.menubar {
+ Some(bar) => bar.flush_volume(),
+ None => Ok(()),
+ });
+}
+
pub fn menu_bar_media_changed() {
with_app("reproducción", |app| match &mut app.menubar {
Some(bar) => bar.media_changed(&app.gfx),
@@ -4650,6 +4673,13 @@ pub fn menu_bar_media_changed() {
});
}
+pub fn menu_bar_audio_changed() {
+ with_app("audio", |app| match &mut app.menubar {
+ Some(bar) => bar.audio_changed(&app.gfx),
+ None => Ok(()),
+ });
+}
+
pub fn menu_bar_accessories_changed() {
with_app("accesorios", |app| match &mut app.menubar {
Some(bar) => bar.accessories_changed(&app.gfx),
diff --git a/apps/dock/src/media.rs b/apps/dock/src/media.rs
index 0c22aca..3801de9 100644
--- a/apps/dock/src/media.rs
+++ b/apps/dock/src/media.rs
@@ -1,9 +1,10 @@
//! Windows media sessions are read on a dedicated MTA worker. Event callbacks
//! only mark the state dirty and wake the worker, even during bursts.
+use muelle_shell::{icons::IconImage, imagery};
use std::{
sync::{
- Arc, Mutex,
+ Arc, Mutex, OnceLock,
atomic::{AtomicIsize, AtomicU8, Ordering},
mpsc::{self, Receiver, SyncSender},
},
@@ -17,6 +18,7 @@ use windows::{
GlobalSystemMediaTransportControlsSessionManager as Manager,
GlobalSystemMediaTransportControlsSessionPlaybackStatus as Status,
},
+ Storage::Streams::{DataReader, IRandomAccessStreamReference},
Win32::{
Foundation::{HWND, LPARAM, WPARAM},
System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize},
@@ -38,7 +40,7 @@ pub enum Control {
Next,
}
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Default, PartialEq)]
pub struct Track {
generation: u64,
pub title: String,
@@ -47,6 +49,62 @@ pub struct Track {
pub previous: bool,
pub toggle: bool,
pub next: bool,
+ pub artwork: Option<Arc<IconImage>>,
+}
+
+#[cfg(test)]
+impl Track {
+ pub fn test_fixture() -> Self {
+ Self {
+ title: "A deliberately long track title for clipping".into(),
+ artist: "Artist".into(),
+ playing: true,
+ previous: true,
+ toggle: true,
+ next: true,
+ ..Default::default()
+ }
+ }
+}
+
+/// The supplied fallback is bundled, so it works offline and after installation.
+pub fn artwork(track: &Track) -> Option<&IconImage> {
+ static FALLBACK: OnceLock<Option<IconImage>> = OnceLock::new();
+ track.artwork.as_deref().or_else(|| {
+ FALLBACK
+ .get_or_init(|| {
+ imagery::decode(
+ include_bytes!("../../../assets/media-fallback.png"),
+ 128,
+ 1_000_000,
+ )
+ .map(imagery::circular)
+ })
+ .as_ref()
+ })
+}
+
+fn read_artwork(thumbnail: IRandomAccessStreamReference) -> Option<Arc<IconImage>> {
+ let stream =
+ complete_with_timeout(thumbnail.OpenReadAsync().ok()?, Duration::from_millis(400))?;
+ let size = stream.Size().ok()?;
+ // Reject oversized streams before allocating or asking Windows to decode.
+ if size == 0 || size > 2 * 1024 * 1024 {
+ return None;
+ }
+ let reader = DataReader::CreateDataReader(&stream.GetInputStreamAt(0).ok()?).ok()?;
+ if complete_with_timeout(
+ reader.LoadAsync(size as u32).ok()?,
+ Duration::from_millis(400),
+ )? != size as u32
+ {
+ return None;
+ }
+ let mut bytes = vec![0; size as usize];
+ reader.ReadBytes(&mut bytes).ok()?;
+ imagery::decode(&bytes, 128, 16_000_000)
+ .map(imagery::circular)
+ .map(Arc::new)
}
#[derive(Clone)]
@@ -120,15 +178,27 @@ impl Drop for Watch {
}
}
-fn complete<T: RuntimeType + Send>(operation: IAsyncOperation<T>) -> Option<T> {
+fn complete<T: RuntimeType>(operation: IAsyncOperation<T>) -> Option<T> {
+ complete_with_timeout(operation, TIMEOUT)
+}
+
+fn complete_with_timeout<T: RuntimeType>(
+ operation: IAsyncOperation<T>,
+ timeout: Duration,
+) -> Option<T> {
let (send, receive) = mpsc::channel();
operation
- .when(move |result| {
- let _ = send.send(result);
- })
+ .SetCompleted(&windows_future::AsyncOperationCompletedHandler::<T>::new(
+ move |_, _| {
+ // Only a wake-up crosses threads. Non-agile streams and all other
+ // WinRT results are retrieved on the worker's original apartment.
+ let _ = send.send(());
+ Ok(())
+ },
+ ))
.ok()?;
- match receive.recv_timeout(TIMEOUT) {
- Ok(result) => result.ok(),
+ match receive.recv_timeout(timeout) {
+ Ok(()) => operation.GetResults().ok(),
Err(_) => {
let _ = operation.Cancel();
None
@@ -142,6 +212,7 @@ struct Current {
playback_event: Option<i64>,
title: String,
artist: String,
+ artwork: Option<Arc<IconImage>>,
}
impl Current {
@@ -166,10 +237,12 @@ impl Current {
playback_event,
title: String::new(),
artist: String::new(),
+ artwork: None,
}
}
fn update_track(&mut self) {
+ self.artwork = None;
if let Some(properties) = self
.session
.TryGetMediaPropertiesAsync()
@@ -184,6 +257,7 @@ impl Current {
.Artist()
.map(|value| value.to_string_lossy())
.unwrap_or_default();
+ self.artwork = properties.Thumbnail().ok().and_then(read_artwork);
}
}
@@ -199,6 +273,7 @@ impl Current {
generation,
title: self.title.clone(),
artist: self.artist.clone(),
+ artwork: self.artwork.clone(),
playing,
previous: controls.IsPreviousEnabled().unwrap_or(false),
next: controls.IsNextEnabled().unwrap_or(false),
@@ -341,6 +416,70 @@ fn run(
mod native_probe {
use super::*;
+ #[test]
+ #[ignore = "Read-only artwork probe of the current Windows media session"]
+ fn native_artwork_stream_stays_on_its_apartment_and_fallback_decodes()
+ -> windows::core::Result<()> {
+ unsafe {
+ RoInitialize(RO_INIT_MULTITHREADED)?;
+ }
+ let result = (|| {
+ use windows::{
+ Storage::Streams::{
+ DataWriter, InMemoryRandomAccessStream, RandomAccessStreamReference,
+ },
+ core::Interface,
+ };
+ let check_stream = || -> Option<()> {
+ let stream = InMemoryRandomAccessStream::new().ok()?;
+ let writer =
+ DataWriter::CreateDataWriter(&stream.GetOutputStreamAt(0).ok()?).ok()?;
+ writer
+ .WriteBytes(include_bytes!("../../../assets/media-fallback.png"))
+ .ok()?;
+ complete(writer.StoreAsync().ok()?)?;
+ let reference = RandomAccessStreamReference::CreateFromStream(&stream).ok()?;
+ let image = read_artwork(reference.cast().ok()?)?;
+ assert!(image.width > 0 && image.width <= 128 && image.width == image.height);
+ Some(())
+ };
+ assert!(
+ check_stream().is_some(),
+ "Known local thumbnail stream did not decode"
+ );
+ let fallback = artwork(&Track::default())
+ .is_some_and(|image| image.width > 0 && image.width <= 128);
+ let Some(manager) = Manager::RequestAsync().ok().and_then(complete) else {
+ return fallback;
+ };
+ if let Ok(session) = manager.GetCurrentSession() {
+ let (wake, _inbox) = mpsc::sync_channel(1);
+ let events = Events {
+ wake,
+ dirty: Arc::new(AtomicU8::new(0)),
+ };
+ let mut current = Current::new(session, &events);
+ current.update_track();
+ if let Some(image) = &current.artwork {
+ assert!(image.width <= 128 && image.height <= 128);
+ eprintln!("Windows media artwork: {}x{}", image.width, image.height);
+ } else {
+ eprintln!(
+ "Current session provides no readable artwork; bundled fallback is available"
+ );
+ }
+ } else {
+ eprintln!("No active media session; bundled fallback is available");
+ }
+ fallback
+ })();
+ unsafe {
+ RoUninitialize();
+ }
+ assert!(result);
+ Ok(())
+ }
+
#[test]
#[ignore = "Requires the Windows media session service"]
fn windows_media_manager_responds_in_mta() -> windows::core::Result<()> {
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index f827803..13243cf 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -14,7 +14,7 @@
//! Status items, right to left as on a Mac: clock, control center, search,
//! network, volume, battery, then Task View and Widgets. Search, Task View and
//! Widgets appear only if the user has them on the Windows taskbar. Network
-//! and volume changes arrive as `STATUS_CHANGED`; nothing polls.
+//! and volume changes arrive through separate notifications; nothing polls.
use anyhow::Result;
use muelle_config::{IslandStyle, Language};
@@ -27,7 +27,10 @@ use muelle_shell::{
watch::RegistryWatch,
};
use std::{
- sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering},
+ },
time::{Duration, Instant},
};
use windows::{
@@ -35,8 +38,9 @@ use windows::{
UI::{
Color,
Composition::{
- CompositionBatchTypes, CompositionBrush, CompositionScopedBatch, Compositor,
- ContainerVisual, Desktop::DesktopWindowTarget, SpriteVisual, VisualCollection,
+ CompositionBatchTypes, CompositionBrush, CompositionRoundedRectangleGeometry,
+ CompositionScopedBatch, CompositionSurfaceBrush, Compositor, ContainerVisual,
+ Desktop::DesktopWindowTarget, ShapeVisual, SpriteVisual, VisualCollection,
},
},
Win32::{
@@ -46,15 +50,17 @@ use windows::{
LibraryLoader::GetModuleHandleW, SystemInformation::GetLocalTime,
WinRT::Composition::ICompositorDesktopInterop,
},
- UI::Input::KeyboardAndMouse::{TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent},
+ UI::Input::KeyboardAndMouse::{
+ GetCapture, ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent,
+ },
UI::WindowsAndMessaging::{
CallNextHookEx, CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, HHOOK,
HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MSLLHOOKSTRUCT,
PBT_POWERSETTINGCHANGE, PostMessageW, RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE,
SWP_SHOWWINDOW, SetCursor, SetTimer, SetWindowPos, SetWindowsHookExW,
- UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN,
- WM_MOUSEMOVE, WM_NCHITTEST, WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE,
- WM_TIMECHANGE, WM_TIMER, WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE,
+ UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP, WM_CAPTURECHANGED, WM_LBUTTONDOWN,
+ WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NCHITTEST, WM_RBUTTONDOWN, WM_SETCURSOR,
+ WM_SETTINGCHANGE, WM_TIMECHANGE, WM_TIMER, WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE,
WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
},
},
@@ -82,6 +88,10 @@ const ITEM_GAP: f32 = 16.0;
const HIT_SLOP: f32 = 7.0;
const MEDIA_CHANGED: u32 = WM_APP + 28;
+const VOLUME_CAPTURE_LOST: u32 = WM_APP + 31;
+const AUDIO_CHANGED: u32 = WM_APP + 32;
+const AUDIO_TICK: u32 = WM_APP + 33;
+const VOLUME_TIMER: usize = 4;
const ACCESSORIES_CHANGED: u32 = WM_APP + 30;
const CLOCK_TIMER: usize = 1;
@@ -107,7 +117,7 @@ const WM_POWERBROADCAST: u32 = 0x0218;
const WM_MOUSELEAVE: u32 = 0x02A3;
/// AppBar notifications need a message id; the bar ignores them.
const APPBAR_CALLBACK: u32 = WM_APP + 20;
-/// Posted by the network and audio watches.
+/// Posted by the network watch; audio uses its own coalesced notification.
const STATUS_CHANGED: u32 = WM_APP + 21;
/// Posted by the bar to itself to update from the message loop.
const TICK: u32 = WM_APP + 22;
@@ -120,6 +130,7 @@ const REGISTRY_CHANGED: u32 = WM_APP + 25;
const SPI_SETWORKAREA: usize = 0x002F;
/// A `TICK` is already posted.
static TICK_PENDING: AtomicBool = AtomicBool::new(false);
+static AUDIO_TICK_PENDING: AtomicBool = AtomicBool::new(false);
static TRIGGERS_LEFT: AtomicI32 = AtomicI32::new(0);
static TRIGGERS_RIGHT: AtomicI32 = AtomicI32::new(0);
static PANEL_LEFT: AtomicI32 = AtomicI32::new(0);
@@ -240,7 +251,7 @@ fn accessory_readings(snapshot: &AccessorySnapshot) -> [Option<AccessoryReading>
impl Look {
fn panel_height(&self) -> f32 {
match self.panel {
- Some(Island::Music) => 136.0,
+ Some(Island::Music) => 184.0,
Some(Island::Usage) => {
74.0 + island_providers(self)
.iter()
@@ -274,6 +285,8 @@ impl Span {
enum IslandAction {
Toggle(Island),
Media(MediaControl),
+ Volume(Span),
+ Mute,
Refresh,
OpenCodeConnectionHelp,
OpenCodeConsole,
@@ -296,6 +309,58 @@ struct ExitAnimation {
completed: i64,
}
+/// Only these retained visuals move during a volume gesture. Album artwork,
+/// track labels and the rest of the menu bar keep their existing visual tree.
+struct VolumeControls {
+ fill: CompositionRoundedRectangleGeometry,
+ knob: ShapeVisual,
+ value: SpriteVisual,
+ geometry: IslandGeometry,
+ left: f32,
+ width: f32,
+ position_percent: Option<u8>,
+ label_percent: u8,
+}
+
+impl VolumeControls {
+ fn move_to(&mut self, percent: u8) -> Result<()> {
+ if self.position_percent == Some(percent) {
+ return Ok(());
+ }
+ let px = |v| self.geometry.px(v);
+ let filled = self.width * f32::from(percent) / 100.0;
+ self.fill.SetSize(Vector2::new(filled, px(4.0)))?;
+ self.fill
+ .SetCornerRadius(Vector2::new(px(2.0).min(filled / 2.0), px(2.0)))?;
+ self.knob.SetOffset(Vector3::new(
+ self.left + filled - px(5.0),
+ px(160.0) - px(5.0),
+ 0.0,
+ ))?;
+ self.position_percent = Some(percent);
+ Ok(())
+ }
+
+ fn paint(&mut self, gfx: &Gfx, percent: u8) -> Result<()> {
+ self.move_to(percent)?;
+ if self.label_percent != percent {
+ let label = gfx.text_brush_sized(
+ &format!("{percent}%"),
+ self.geometry.scale,
+ 10.5,
+ false,
+ self.geometry.ink(),
+ )?;
+ self.value
+ .SetBrush(&label.brush.cast::<CompositionBrush>()?)?;
+ self.value
+ .SetSize(Vector2::new(label.width, label.height))?;
+ self.label_percent = percent;
+ }
+ Ok(())
+ }
+}
+
impl Drop for ExitAnimation {
fn drop(&mut self) {
let _ = self.batch.RemoveCompleted(self.completed);
@@ -334,6 +399,15 @@ pub struct MenuBar {
media: Option<media::Watch>,
/// "Show what is playing": off, nothing listens to media sessions.
media_enabled: bool,
+ cover: Option<(
+ Option<Arc<muelle_shell::icons::IconImage>>,
+ CompositionSurfaceBrush,
+ )>,
+ volume_drag: Option<Span>,
+ pending_volume: Option<u8>,
+ volume_target: Option<u8>,
+ volume_controls: Option<VolumeControls>,
+ suppress_volume_release: bool,
panel: Option<Island>,
visual_height: i32,
triggers_span: Span,
@@ -353,11 +427,16 @@ pub struct MenuBar {
unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
match msg {
- WM_LBUTTONDOWN => launcher::note_menu_bar_press(),
+ WM_LBUTTONDOWN => {
+ launcher::note_menu_bar_press();
+ app::menu_bar_volume_press((l.0 & 0xFFFF) as i16 as f32, (l.0 >> 16) as i16 as f32);
+ }
WM_LBUTTONUP => {
let x = (l.0 & 0xFFFF) as i16;
let y = (l.0 >> 16) as i16;
- app::menu_bar_clicked(f32::from(x), f32::from(y));
+ if !app::menu_bar_volume_release(Some(f32::from(x))) {
+ app::menu_bar_clicked(f32::from(x), f32::from(y));
+ }
}
WM_MOUSEMOVE => {
let x = (l.0 & 0xFFFF) as i16;
@@ -366,12 +445,36 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
}
WM_MOUSELEAVE => app::menu_bar_check_pointer(),
WM_TIMER if w.0 == POINTER_TIMER => app::menu_bar_check_pointer(),
+ WM_TIMER if w.0 == VOLUME_TIMER => app::menu_bar_volume_flush(),
+ WM_CAPTURECHANGED => {
+ // Avoid reentering the app borrow inside Set/ReleaseCapture.
+ unsafe {
+ let _ = PostMessageW(Some(hwnd), VOLUME_CAPTURE_LOST, WPARAM(0), LPARAM(0));
+ }
+ }
+ VOLUME_CAPTURE_LOST => {
+ // A delayed notification must not cancel a newer drag.
+ if unsafe { GetCapture() } != hwnd {
+ app::menu_bar_volume_release(None);
+ }
+ }
WM_TIMER if w.0 == HIDE_ANIMATION_TIMER => app::menu_bar_finish_hide(None),
HIDE_ANIMATION_DONE => app::menu_bar_finish_hide(Some(w.0)),
DISMISS_ISLAND => app::menu_bar_dismiss_island(),
REGISTRY_CHANGED => app::menu_bar_registry_changed(),
ACCESSORIES_CHANGED => app::menu_bar_accessories_changed(),
MEDIA_CHANGED => app::menu_bar_media_changed(),
+ AUDIO_CHANGED => {
+ if !AUDIO_TICK_PENDING.swap(true, Ordering::Relaxed) {
+ unsafe {
+ let _ = PostMessageW(Some(hwnd), AUDIO_TICK, WPARAM(0), LPARAM(0));
+ }
+ }
+ }
+ AUDIO_TICK => {
+ AUDIO_TICK_PENDING.store(false, Ordering::Relaxed);
+ app::menu_bar_audio_changed();
+ }
WM_SETCURSOR => {
// SAFETY: Keep the standard arrow throughout the bar and popups.
if let Ok(arrow) = unsafe { LoadCursorW(None, IDC_ARROW) } {
@@ -513,6 +616,27 @@ pub(crate) fn add_rounded_box(
fill: Color,
border: Option<Color>,
) -> Result<()> {
+ retained_rounded_box(
+ compositor, layers, x, y, width, height, radius, fill, border,
+ )
+ .map(|_| ())
+}
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "Same rectangle/color inputs as add_rounded_box; retain geometry for small UI updates"
+)]
+fn retained_rounded_box(
+ compositor: &Compositor,
+ layers: &VisualCollection,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ radius: f32,
+ fill: Color,
+ border: Option<Color>,
+) -> Result<(ShapeVisual, CompositionRoundedRectangleGeometry)> {
let geometry = compositor.CreateRoundedRectangleGeometry()?;
let inset = if border.is_some() { 0.5 } else { 0.0 };
geometry.SetOffset(Vector2 { X: inset, Y: inset })?;
@@ -542,7 +666,7 @@ pub(crate) fn add_rounded_box(
})?;
visual.Shapes()?.Append(&shape)?;
layers.InsertAtTop(&visual)?;
- Ok(())
+ Ok((visual, geometry))
}
#[expect(
@@ -1006,6 +1130,12 @@ impl MenuBar {
.then(|| media::Watch::start(hwnd, MEDIA_CHANGED))
.flatten(),
media_enabled,
+ cover: None,
+ volume_drag: None,
+ pending_volume: None,
+ volume_target: None,
+ volume_controls: None,
+ suppress_volume_release: false,
panel: None,
visual_height: 0,
triggers_span: Span::default(),
@@ -1016,8 +1146,9 @@ impl MenuBar {
privacy_watch: status::watch_privacy(hwnd.0 as isize, REGISTRY_CHANGED),
settings_watch: status::watch_taskbar_settings(hwnd.0 as isize, REGISTRY_CHANGED),
_saver_watch: muelle_shell::power::SaverWatch::new(hwnd.0 as isize),
- audio: AudioWatch::new(hwnd.0 as isize, STATUS_CHANGED),
+ audio: AudioWatch::new(hwnd.0 as isize, AUDIO_CHANGED),
};
+ AUDIO_TICK_PENDING.store(false, Ordering::Relaxed);
bar.update_status();
bar.refresh(gfx)?;
bar.schedule_next_minute();
@@ -1040,6 +1171,9 @@ impl MenuBar {
}
pub fn set_visible(&mut self, visible: bool) -> Result<()> {
+ if !visible {
+ self.release_volume(None)?;
+ }
if self.visible == visible {
return Ok(());
}
@@ -1129,6 +1263,9 @@ impl MenuBar {
/// The pointer reached the top edge or left the bar.
pub fn hover(&mut self, gfx: &Gfx, inside: bool) -> Result<()> {
+ if self.volume_drag.is_some() && !inside {
+ return Ok(());
+ }
if !inside && self.panel.take().is_some() {
self.refresh(gfx)?;
}
@@ -1298,6 +1435,25 @@ impl MenuBar {
fn pointer_left_at(&mut self, gfx: &Gfx, point: POINT) -> Result<()> {
let x = (point.x - self.bounds.left) as f32;
+ if let Some(span) = self.volume_drag {
+ self.queue_volume(span, x);
+ // A nonactivating background window may not receive mouse-up
+ // outside its visible bounds. Reuse the existing popup pointer
+ // check to finish the gesture without ever stealing app focus.
+ let pressed = unsafe {
+ use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SWAPBUTTON};
+ let primary = if GetSystemMetrics(SM_SWAPBUTTON) == 0 {
+ 0x01
+ } else {
+ 0x02
+ };
+ windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState(primary) < 0
+ };
+ if pressed {
+ return self.paint_volume_preview(gfx);
+ }
+ self.release_volume(Some(x))?;
+ }
let within_bar = point.x >= self.bounds.left
&& point.x < self.bounds.right
&& point.y >= self.bounds.top
@@ -1319,6 +1475,10 @@ impl MenuBar {
/// Leaving the island sideways still stays inside the full-width bar window.
pub fn pointer_moved(&mut self, gfx: &Gfx, x: f32, y: f32) -> Result<()> {
+ if let Some(span) = self.volume_drag {
+ self.queue_volume(span, x);
+ return self.paint_volume_preview(gfx);
+ }
let span = if y < (self.bounds.bottom - self.bounds.top) as f32 {
self.triggers_span
} else {
@@ -1331,6 +1491,7 @@ impl MenuBar {
}
pub fn dismiss_island(&mut self, gfx: &Gfx) -> Result<()> {
+ self.release_volume(None)?;
if self.panel.take().is_some() {
self.refresh(gfx)?;
}
@@ -1475,6 +1636,42 @@ impl MenuBar {
self.refresh(gfx)
}
+ /// Audio notifications never requery the network, registry, providers or
+ /// clock. A default-device change still restarts the accessory reader.
+ pub fn audio_changed(&mut self, gfx: &Gfx) -> Result<()> {
+ let volume = self.audio.as_mut().and_then(AudioWatch::volume);
+ if self
+ .audio
+ .as_ref()
+ .is_some_and(AudioWatch::take_default_changed)
+ && self.accessories_enabled
+ {
+ self.status.volume = volume;
+ self.restart_accessories(gfx)?;
+ }
+ self.apply_volume_reading(gfx, volume)
+ }
+
+ fn apply_volume_reading(&mut self, gfx: &Gfx, volume: Option<Volume>) -> Result<()> {
+ self.status.volume = volume;
+ if let Some(look) = &self.look
+ && same_volume_indicator(look.status.volume, volume)
+ {
+ if let Some(volume) = volume
+ && let Some(controls) = &mut self.volume_controls
+ {
+ controls.paint(gfx, self.volume_target.unwrap_or(volume.percent))?;
+ }
+ if let Some(look) = &mut self.look {
+ look.status.volume = volume;
+ }
+ return Ok(());
+ }
+ // Availability, mute and speaker-glyph changes affect the status bar's
+ // layout. Those rare transitions continue through the normal renderer.
+ self.refresh(gfx)
+ }
+
fn update_status(&mut self) {
self.status = Status {
network: status::network(),
@@ -1544,6 +1741,13 @@ impl MenuBar {
}
return Ok(());
}
+ IslandAction::Volume(_) => return Ok(()), // Handled on press/drag.
+ IslandAction::Mute => {
+ if let Some(audio) = &mut self.audio {
+ audio.toggle_mute()?;
+ }
+ self.update_status();
+ }
}
return self.refresh(gfx);
}
@@ -1662,6 +1866,9 @@ impl MenuBar {
}
fn apply_look(&mut self, gfx: &Gfx, look: Look) -> Result<()> {
+ if look.panel != Some(Island::Music) {
+ self.release_volume(None)?;
+ }
if self.look.as_ref() == Some(&look) {
return Ok(());
}
@@ -1894,6 +2101,7 @@ impl MenuBar {
}
self.island_hits.clear();
+ self.volume_controls = None;
self.triggers_span = Span::default();
self.panel_span = Span::default();
self.draw_island(gfx, look, &layers, width, height, left_end, right)?;
@@ -1953,6 +2161,31 @@ impl MenuBar {
) -> Result<()> {
let px = |logical: f32| (logical * look.scale).round();
let style = look.widgets.island_style;
+ let cover = if let Some(track) = &look.track {
+ let cached =
+ self.cover
+ .as_ref()
+ .is_some_and(|(source, _)| match (source, &track.artwork) {
+ (Some(old), Some(new)) => Arc::ptr_eq(old, new),
+ (None, None) => true,
+ _ => false,
+ });
+ if !cached {
+ self.cover = media::artwork(track)
+ .map(|image| {
+ let surface = gfx.image_surface(image)?;
+ Ok::<_, anyhow::Error>((
+ track.artwork.clone(),
+ gfx.compositor.CreateSurfaceBrushWithSurface(&surface)?,
+ ))
+ })
+ .transpose()?;
+ }
+ self.cover.as_ref().map(|(_, brush)| brush.clone())
+ } else {
+ self.cover = None;
+ None
+ };
let prepared_music = if style == IslandStyle::Bubble
&& let Some(track) = &look.track
{
@@ -2039,6 +2272,7 @@ impl MenuBar {
geometry.width,
compact_height,
track,
+ cover.as_ref(),
)?,
IslandStyle::Bubble => {
if let Some(prepared) = &prepared_music {
@@ -2046,10 +2280,10 @@ impl MenuBar {
gfx,
&content,
geometry,
- geometry.width,
compact_height,
track,
prepared,
+ cover.as_ref(),
)?;
}
}
@@ -2097,7 +2331,7 @@ impl MenuBar {
match kind {
Island::Music => {
if let Some(track) = &look.track {
- self.draw_player(gfx, &content, geometry, track)?;
+ self.draw_player(gfx, &content, geometry, track, cover.as_ref())?;
}
}
Island::Usage => {
@@ -2265,6 +2499,7 @@ impl MenuBar {
layers: &VisualCollection,
geometry: IslandGeometry,
track: &Track,
+ cover: Option<&CompositionSurfaceBrush>,
) -> Result<()> {
let px = |v| geometry.px(v);
let c = &gfx.compositor;
@@ -2300,27 +2535,9 @@ impl MenuBar {
IslandAction::Toggle(Island::Music),
));
let tile = px(34.0);
- add_rounded_box(
- c,
- layers,
- px(25.0),
- px(46.0),
- tile,
- tile,
- px(10.0),
- geometry.control_fill(),
- None,
- )?;
- let note = gfx.glyph_brush(&[('\u{E8D6}', 1.0)], geometry.scale, ink)?;
- add_visual(
- c,
- layers,
- &note.brush.cast()?,
- px(25.0) + (tile - note.width) / 2.0,
- px(46.0) + (tile - note.height) / 2.0,
- note.width,
- note.height,
- )?;
+ if let Some(cover) = cover {
+ add_visual(c, layers, &cover.cast()?, px(25.0), px(46.0), tile, tile)?;
+ }
let available = geometry.width - px(91.0);
let title = gfx.text_brush_fitted(
track_title(track),
@@ -2406,8 +2623,235 @@ impl MenuBar {
.push(geometry.hit(x, y, size, size, IslandAction::Media(control)));
}
}
+ add_panel_text(
+ gfx,
+ layers,
+ strings::text().media_volume,
+ px(25.0),
+ px(135.0),
+ geometry.scale,
+ 10.5,
+ false,
+ ink,
+ 0.65,
+ )?;
+ if let Some(volume) = self.status.volume {
+ let symbol = if volume.muted {
+ glyph::MUTE
+ } else {
+ glyph::VOLUME[volume.level.min(3) as usize]
+ };
+ let label = gfx.glyph_brush(&[(symbol, 1.0)], geometry.scale, ink)?;
+ add_visual(
+ c,
+ layers,
+ &label.brush.cast()?,
+ px(25.0),
+ px(160.0) - label.height / 2.0,
+ label.width,
+ label.height,
+ )?;
+ self.island_hits.push(geometry.hit(
+ px(18.0),
+ px(148.0),
+ px(32.0),
+ px(27.0),
+ IslandAction::Mute,
+ ));
+ let left = px(59.0);
+ let width = (geometry.width - left - px(66.0)).max(px(1.0));
+ let percent = self.volume_target.unwrap_or(volume.percent);
+ add_rounded_box(
+ c,
+ layers,
+ left,
+ px(158.0),
+ width,
+ px(4.0),
+ px(2.0),
+ geometry.control_fill(),
+ None,
+ )?;
+ let (_, fill) = retained_rounded_box(
+ c,
+ layers,
+ left,
+ px(158.0),
+ width,
+ px(4.0),
+ px(2.0),
+ if geometry.light {
+ rgba(40, 48, 58, 220)
+ } else {
+ rgba(240, 244, 250, 235)
+ },
+ None,
+ )?;
+ let dot = px(10.0);
+ let (knob, _) = retained_rounded_box(
+ c,
+ layers,
+ left - dot / 2.0,
+ px(160.0) - dot / 2.0,
+ dot,
+ dot,
+ dot / 2.0,
+ rgba(245, 247, 250, 255),
+ Some(geometry.border()),
+ )?;
+ let label =
+ gfx.text_brush_sized(&format!("{percent}%"), geometry.scale, 10.5, false, ink)?;
+ let value = add_visual(
+ c,
+ layers,
+ &label.brush.cast()?,
+ geometry.width - px(51.0),
+ px(153.0),
+ label.width,
+ label.height,
+ )?;
+ value.SetOpacity(0.8)?;
+ let mut controls = VolumeControls {
+ fill,
+ knob,
+ value,
+ geometry,
+ left,
+ width,
+ position_percent: None,
+ label_percent: percent,
+ };
+ controls.move_to(percent)?;
+ self.volume_controls = Some(controls);
+ self.island_hits.push(geometry.hit(
+ left - px(6.0),
+ px(147.0),
+ width + px(12.0),
+ px(29.0),
+ IslandAction::Volume(Span {
+ left: geometry.left + left,
+ right: geometry.left + left + width,
+ }),
+ ));
+ } else {
+ add_panel_text(
+ gfx,
+ layers,
+ strings::text().media_no_output,
+ px(25.0),
+ px(155.0),
+ geometry.scale,
+ 11.0,
+ false,
+ ink,
+ 0.5,
+ )?;
+ }
+ Ok(())
+ }
+
+ pub fn press_volume(&mut self, gfx: &Gfx, x: f32, y: f32) -> Result<()> {
+ self.suppress_volume_release = false;
+ let Some(hit) = self
+ .island_hits
+ .iter()
+ .find(|hit| hit.at(x, y) && matches!(hit.action, IslandAction::Volume(_)))
+ else {
+ return Ok(());
+ };
+ let IslandAction::Volume(span) = hit.action else {
+ return Ok(());
+ };
+ self.volume_drag = Some(span);
+ // SAFETY: Capture only for a live slider drag, never to activate the bar.
+ unsafe {
+ SetCapture(self.hwnd);
+ }
+ self.queue_volume(span, x);
+ self.paint_volume_preview(gfx)
+ }
+
+ fn paint_volume_preview(&mut self, gfx: &Gfx) -> Result<()> {
+ if let Some(percent) = self.volume_target
+ && let Some(controls) = &mut self.volume_controls
+ {
+ controls.paint(gfx, percent)?;
+ }
+ Ok(())
+ }
+
+ fn queue_volume(&mut self, span: Span, x: f32) {
+ let percent = volume_percent(span, x);
+ self.volume_target = Some(percent);
+ if let Some(controls) = &mut self.volume_controls {
+ // Optimistic GPU-only feedback is independent of endpoint latency.
+ // Audio writes still proceed if device loss interrupts this paint;
+ // the existing graphics heartbeat owns recovery.
+ let _ = controls.move_to(percent);
+ }
+ if self.pending_volume == Some(percent)
+ || (self.pending_volume.is_none()
+ && self
+ .status
+ .volume
+ .is_some_and(|v| v.percent == percent && !v.muted))
+ {
+ return;
+ }
+ let arm = self.pending_volume.is_none();
+ self.pending_volume = Some(percent);
+ if arm {
+ // At most 30 endpoint writes/second during dragging; no idle timer.
+ unsafe {
+ SetTimer(Some(self.hwnd), VOLUME_TIMER, 33, None);
+ }
+ }
+ }
+
+ pub fn flush_volume(&mut self) -> Result<()> {
+ // SAFETY: Our own short-lived drag timer.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), VOLUME_TIMER);
+ }
+ if let Some(percent) = self.pending_volume.take()
+ && let Some(audio) = &mut self.audio
+ {
+ audio.set_percent(percent)?;
+ }
Ok(())
}
+
+ pub fn release_volume(&mut self, x: Option<f32>) -> Result<bool> {
+ let Some(span) = self.volume_drag.take() else {
+ return Ok(x.is_some() && std::mem::take(&mut self.suppress_volume_release));
+ };
+ self.suppress_volume_release = true;
+ if let Some(x) = x {
+ self.queue_volume(span, x);
+ }
+ // Clear state first: ReleaseCapture posts a capture-lost notification.
+ unsafe {
+ if GetCapture() == self.hwnd {
+ let _ = ReleaseCapture();
+ }
+ }
+ if let Err(error) = self.flush_volume() {
+ muelle_shell::log::line(&format!("ajustar volumen: {error:#}"));
+ }
+ self.volume_target = None;
+ Ok(true)
+ }
+}
+
+fn volume_percent(span: Span, x: f32) -> u8 {
+ if span.width() <= 0.0 || !x.is_finite() {
+ return 0;
+ }
+ (((x - span.left) / span.width()).clamp(0.0, 1.0) * 100.0).round() as u8
+}
+
+fn same_volume_indicator(old: Option<Volume>, new: Option<Volume>) -> bool {
+ old.map(|v| (v.level, v.muted)) == new.map(|v| (v.level, v.muted))
}
#[derive(Clone, Copy)]
@@ -3048,31 +3492,31 @@ fn draw_compact_player(
width: f32,
height: f32,
track: &Track,
+ cover: Option<&CompositionSurfaceBrush>,
) -> Result<()> {
let c = &gfx.compositor;
let px = |v| geometry.px(v);
let ink = geometry.ink();
- let note = gfx.glyph_brush(
- &[('\u{E8D6}', if track.playing { 1.0 } else { 0.66 })],
- geometry.scale,
- ink,
- )?;
- let x = px(23.0) + note.width;
+ let side = px(18.0).min(height).min(width);
+ let x = px(23.0) + side;
let show_title = width > x + px(18.0);
let note_x = if show_title {
px(18.0)
} else {
- (width - note.width) / 2.0
+ (width - side) / 2.0
};
- add_visual(
- c,
- layers,
- &note.brush.cast()?,
- note_x,
- (height - note.height) / 2.0,
- note.width,
- note.height,
- )?;
+ if let Some(cover) = cover {
+ add_visual(
+ c,
+ layers,
+ &cover.cast()?,
+ note_x,
+ (height - side) / 2.0,
+ side,
+ side,
+ )?
+ .SetOpacity(if track.playing { 1.0 } else { 0.7 })?;
+ }
if show_title {
let label = gfx.text_brush_fitted(
track_title(track),
@@ -3096,7 +3540,7 @@ fn draw_compact_player(
}
struct BubbleMusic {
- note: LabelBrush,
+ artwork_size: f32,
label: LabelBrush,
width: f32,
}
@@ -3104,55 +3548,60 @@ struct BubbleMusic {
fn prepare_bubble_music(gfx: &Gfx, look: &Look, track: &Track) -> Result<BubbleMusic> {
let px = |v: f32| (v * look.scale).round();
let ink = if look.light { Ink::Dark } else { Ink::Light };
- let note = gfx.glyph_brush(
- &[('\u{E8D6}', if track.playing { 1.0 } else { 0.66 })],
- look.scale,
- ink,
- )?;
+ let artwork_size = px(18.0);
let left_pad = px(10.0);
let gap = px(6.0);
let right_pad = px(8.0);
- let max_text = (px(BUBBLE_MUSIC_WIDTH) - left_pad - note.width - gap - right_pad).max(px(18.0));
+ let max_text =
+ (px(BUBBLE_MUSIC_WIDTH) - left_pad - artwork_size - gap - right_pad).max(px(18.0));
let label = gfx.text_brush_fitted(track_title(track), look.scale, 11.5, true, ink, max_text)?;
- let width = (left_pad + note.width + gap + label.width + right_pad)
+ let width = (left_pad + artwork_size + gap + label.width + right_pad)
.min(px(BUBBLE_MUSIC_WIDTH))
.ceil();
- Ok(BubbleMusic { note, label, width })
+ Ok(BubbleMusic {
+ artwork_size,
+ label,
+ width,
+ })
}
fn draw_bubble_player(
gfx: &Gfx,
layers: &VisualCollection,
geometry: IslandGeometry,
- width: f32,
height: f32,
track: &Track,
prepared: &BubbleMusic,
+ cover: Option<&CompositionSurfaceBrush>,
) -> Result<()> {
+ let width = geometry.width;
let c = &gfx.compositor;
let px = |v| geometry.px(v);
let ink = geometry.ink();
- let note = &prepared.note;
+ let side = prepared.artwork_size.min(height).min(width);
let left_pad = px(10.0);
let gap = px(6.0);
let right_pad = px(8.0);
- let text_x = left_pad + note.width + gap;
+ let text_x = left_pad + side + gap;
let max_label_width = width - text_x - right_pad;
let show_title = max_label_width >= px(18.0);
let note_x = if show_title {
left_pad
} else {
- (width - note.width) / 2.0
+ (width - side) / 2.0
};
- add_visual(
- c,
- layers,
- &note.brush.cast()?,
- note_x,
- (height - note.height) / 2.0,
- note.width,
- note.height,
- )?;
+ if let Some(cover) = cover {
+ add_visual(
+ c,
+ layers,
+ &cover.cast()?,
+ note_x,
+ (height - side) / 2.0,
+ side,
+ side,
+ )?
+ .SetOpacity(if track.playing { 1.0 } else { 0.7 })?;
+ }
if show_title {
let fitted;
let label = if prepared.label.width <= max_label_width {
@@ -3207,6 +3656,221 @@ impl Drop for MenuBar {
mod island_tests {
use super::*;
+ #[test]
+ fn volume_coordinates_clamp_and_round_at_both_ends() {
+ let span = Span {
+ left: 100.0,
+ right: 300.0,
+ };
+ for (x, expected) in [
+ (-100.0, 0),
+ (100.0, 0),
+ (200.0, 50),
+ (299.0, 100),
+ (500.0, 100),
+ (f32::NAN, 0),
+ ] {
+ assert_eq!(volume_percent(span, x), expected);
+ }
+ assert_eq!(volume_percent(Span::default(), 1.0), 0);
+ }
+
+ #[test]
+ fn percentage_changes_keep_the_same_indicator_but_mute_and_device_changes_do_not() {
+ let volume = Volume {
+ level: 2,
+ muted: false,
+ percent: 40,
+ };
+ assert!(same_volume_indicator(
+ Some(volume),
+ Some(Volume {
+ percent: 60,
+ ..volume
+ })
+ ));
+ assert!(!same_volume_indicator(
+ Some(volume),
+ Some(Volume {
+ muted: true,
+ ..volume
+ })
+ ));
+ assert!(!same_volume_indicator(
+ Some(volume),
+ Some(Volume { level: 3, ..volume })
+ ));
+ assert!(!same_volume_indicator(Some(volume), None));
+ assert!(!same_volume_indicator(None, Some(volume)));
+ }
+
+ #[test]
+ #[ignore = "Native compositor coverage; hidden test window, no audio writes"]
+ fn native_music_artwork_and_volume_fit_both_styles_and_release_drag_state() -> Result<()> {
+ use anyhow::Context;
+ use windows::Win32::System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ };
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let gfx = Gfx::new()?;
+ let mut bar = MenuBar::create(&gfx, true, false, false, MenuBarWidgets::default())?;
+ bar.set_visible(false)?;
+ bar.audio = None; // This fixture can never change the user's audio.
+ bar.status.volume = Some(Volume {
+ level: 2,
+ muted: false,
+ percent: 42,
+ });
+ let mut look = bar.look.clone().context("initial look")?;
+ look.status = bar.status;
+ look.panel = Some(Island::Music);
+ look.track = Some(Track::test_fixture());
+ for style in [IslandStyle::Notch, IslandStyle::Bubble] {
+ look.widgets.island_style = style;
+ for scale in [1.0, 1.25, 1.5, 2.0] {
+ look.scale = scale;
+ for (light, glass) in [(true, true), (false, true), (true, false), (false, false)] {
+ look.light = light;
+ look.glass = glass;
+ bar.build(&gfx, &look)?;
+ assert!(bar.cover.is_some());
+ let brush = bar.cover.as_ref().context("missing cover")?.1.clone();
+ bar.build(&gfx, &look)?;
+ assert_eq!(bar.cover.as_ref().context("cached cover")?.1, brush);
+ let volume = bar
+ .island_hits
+ .iter()
+ .find(|hit| matches!(hit.action, IslandAction::Volume(_)))
+ .context("missing volume hit")?;
+ let (left, top, right, bottom) = volume.bounds;
+ assert!(left >= bar.panel_span.left && right <= bar.panel_span.right);
+ assert!(
+ top >= HEIGHT * scale
+ && bottom <= (HEIGHT + PANEL_GAP + look.panel_height()) * scale + 1.0
+ );
+ assert!(
+ bar.island_hits
+ .iter()
+ .any(|hit| matches!(hit.action, IslandAction::Mute))
+ );
+ }
+ }
+ }
+ let image = Arc::new(muelle_shell::icons::IconImage {
+ width: 8,
+ height: 8,
+ bgra: [20, 40, 80, 255].repeat(64),
+ });
+ look.track.as_mut().context("track")?.artwork = Some(image.clone());
+ bar.build(&gfx, &look)?;
+ assert!(
+ bar.cover
+ .as_ref()
+ .and_then(|(source, _)| source.as_ref())
+ .is_some_and(|source| Arc::ptr_eq(source, &image))
+ );
+ // Compare the old full redraw path with retained updates without ever
+ // writing the real audio endpoint. Tree identity is the regression
+ // assertion; timings are informational, not a flaky speed threshold.
+ let started = Instant::now();
+ for step in 0..64 {
+ bar.status.volume = Some(Volume {
+ level: 2,
+ muted: false,
+ percent: 40 + step % 20,
+ });
+ look.status = bar.status;
+ bar.build(&gfx, &look)?;
+ }
+ let full_redraw = started.elapsed();
+ bar.look = Some(look.clone());
+ let root = bar.surface.Children()?.First()?.Current()?;
+ let started = Instant::now();
+ for step in 0..64 {
+ bar.apply_volume_reading(
+ &gfx,
+ Some(Volume {
+ level: 2,
+ muted: false,
+ percent: 40 + step % 20,
+ }),
+ )?;
+ assert_eq!(bar.surface.Children()?.First()?.Current()?, root);
+ assert_eq!(
+ bar.volume_controls
+ .as_ref()
+ .context("retained volume")?
+ .label_percent,
+ 40 + step % 20
+ );
+ }
+ eprintln!(
+ "64 volume updates: full redraw {:?}, retained {:?} (no audio writes)",
+ full_redraw,
+ started.elapsed()
+ );
+ let span = Span {
+ left: 100.0,
+ right: 300.0,
+ };
+ bar.volume_drag = Some(span); // No SetCapture in a test.
+ bar.queue_volume(span, 140.0);
+ bar.pointer_moved(&gfx, 260.0, 0.0)?;
+ assert_eq!(bar.pending_volume, Some(80));
+ assert_eq!(
+ bar.volume_controls
+ .as_ref()
+ .context("immediate percentage")?
+ .label_percent,
+ 80
+ );
+ assert_eq!(
+ bar.volume_controls
+ .as_ref()
+ .context("immediate thumb")?
+ .position_percent,
+ Some(80)
+ );
+ // An endpoint acknowledgement must not drag the thumb backwards while
+ // a newer pointer target is still waiting for its coalesced write.
+ bar.apply_volume_reading(
+ &gfx,
+ Some(Volume {
+ level: 2,
+ muted: false,
+ percent: 50,
+ }),
+ )?;
+ assert_eq!(
+ bar.volume_controls
+ .as_ref()
+ .context("optimistic thumb")?
+ .position_percent,
+ Some(80)
+ );
+ assert_eq!(bar.surface.Children()?.First()?.Current()?, root);
+ assert!(bar.release_volume(Some(300.0))?);
+ assert!(bar.pending_volume.is_none() && bar.volume_drag.is_none());
+ assert!(!bar.release_volume(None)?);
+ assert!(bar.release_volume(Some(200.0))?); // Late up after capture loss/timer.
+ assert!(!bar.release_volume(Some(200.0))?);
+ bar.status.volume = None;
+ bar.build(&gfx, &look)?;
+ assert!(
+ !bar.island_hits
+ .iter()
+ .any(|hit| matches!(hit.action, IslandAction::Volume(_) | IslandAction::Mute))
+ );
+ Ok(())
+ }
+
#[test]
#[ignore = "Requires Windows desktop composition; keeps the test bar hidden"]
fn opencode_connection_help_is_clickable_and_inactive_codex_stays_hidden() -> Result<()> {
diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rs
index 5733254..95cc94a 100644
--- a/apps/dock/src/strings.rs
+++ b/apps/dock/src/strings.rs
@@ -45,6 +45,8 @@ pub struct Strings {
pub usage_updated: &'static str,
pub usage_used: &'static str,
pub media_title: &'static str,
+ pub media_volume: &'static str,
+ pub media_no_output: &'static str,
pub folder_empty: &'static str,
pub folder_unavailable: &'static str,
pub change_folder: &'static str,
@@ -95,6 +97,8 @@ const ES: Strings = Strings {
usage_updated: "Actualizado hace",
usage_used: "usado",
media_title: "Reproducción",
+ media_volume: "Volumen del sistema",
+ media_no_output: "Sin dispositivo de salida",
folder_empty: "(vacía)",
folder_unavailable: "Carpeta no disponible",
change_folder: "&Cambiar de carpeta…",
@@ -142,6 +146,8 @@ const EN: Strings = Strings {
usage_updated: "Updated",
usage_used: "used",
media_title: "Now playing",
+ media_volume: "System volume",
+ media_no_output: "No output device",
folder_empty: "(empty)",
folder_unavailable: "Folder unavailable",
change_folder: "&Change Folder…",
@@ -189,6 +195,8 @@ const FR: Strings = Strings {
usage_updated: "Actualisé il y a",
usage_used: "utilisé",
media_title: "En cours de lecture",
+ media_volume: "Volume du système",
+ media_no_output: "Aucun périphérique de sortie",
folder_empty: "(vide)",
folder_unavailable: "Dossier introuvable",
change_folder: "&Changer de dossier…",
diff --git a/apps/settings/src-tauri/Cargo.toml b/apps/settings/src-tauri/Cargo.toml
index a37eb7f..6f15a1e 100644
--- a/apps/settings/src-tauri/Cargo.toml
+++ b/apps/settings/src-tauri/Cargo.toml
@@ -21,6 +21,8 @@ tauri-plugin-updater = "2"
tauri-plugin-single-instance = "2"
# `generate_context!` emits serde_json values for plugin settings.
serde_json = "1"
+base64 = "0.23"
+png = "0.18"
[features]
# Serve the bundled front end instead of the Vite dev server. On by default so
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index 2eb0000..5467e69 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -181,6 +181,43 @@ async fn open_repository() -> Result<(), String> {
.map_err(|error| error.to_string())?
}
+/// A small data URI, never a path or screenshot of the user's desktop.
+#[tauri::command]
+async fn wallpaper_preview(window: tauri::WebviewWindow) -> Option<String> {
+ let hwnd = window.hwnd().ok()?.0 as isize;
+ tauri::async_runtime::spawn_blocking(move || {
+ use base64::Engine;
+ let image = muelle_shell::imagery::wallpaper_preview(hwnd)?;
+ let mut rgba = image.bgra;
+ for pixel in rgba.as_chunks_mut::<4>().0 {
+ // Wallpaper decodes are opaque in normal use. Unpremultiply when
+ // a PNG wallpaper does carry alpha, before encoding straight RGBA.
+ let alpha = u32::from(pixel[3]);
+ pixel.swap(0, 2);
+ for value in &mut pixel[..3] {
+ *value = (u32::from(*value) * 255)
+ .checked_div(alpha)
+ .unwrap_or(0)
+ .min(255) as u8;
+ }
+ }
+ let mut bytes = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut bytes, image.width, image.height);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
+ }
+ Some(format!(
+ "data:image/png;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(bytes)
+ ))
+ })
+ .await
+ .ok()
+ .flatten()
+}
+
/// Downloads the signed installer and runs it; the installer stops the dock,
/// replaces both apps and starts the dock again. This process exits.
#[tauri::command]
@@ -298,7 +335,8 @@ fn main() {
check_update,
install_update,
open_release_notes,
- open_repository
+ open_repository,
+ wallpaper_preview
])
.run(tauri::generate_context!());
if let Err(error) = result {
diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsx
index e1c2f17..d056ca3 100644
--- a/apps/settings/src/App.tsx
+++ b/apps/settings/src/App.tsx
@@ -18,6 +18,7 @@ import {
windowsAnimations,
installUpdate,
loadConfig,
+ loadWallpaperPreview,
openReleaseNotes,
openRepository,
pickFolder,
@@ -94,6 +95,12 @@ export function App() {
const [updateState, setUpdateState] = useState<UpdateState>({ kind: "checking" });
const [confirmingReset, setConfirmingReset] = useState(false);
const [projectError, setProjectError] = useState(false);
+ const [wallpaper, setWallpaper] = useState<string | null>(null);
+ useEffect(() => {
+ let alive = true;
+ loadWallpaperPreview().then((image) => { if (alive) setWallpaper(image); });
+ return () => { alive = false; };
+ }, []);
/** "Later" hides the banner until Settings is opened again. */
const [bannerDismissed, setBannerDismissed] = useState(false);
const pending = useRef<Partial<Config> | null>(null);
@@ -305,20 +312,18 @@ export function App() {
label={t.dockPosition}
value={config.dockPosition}
options={[
- { value: "left", label: t.dockPositionLeft, preview: <DockPreview position="left" iconSize={config.iconSize} /> },
- { value: "bottom", label: t.dockPositionBottom, preview: <DockPreview position="bottom" iconSize={config.iconSize} /> },
- { value: "right", label: t.dockPositionRight, preview: <DockPreview position="right" iconSize={config.iconSize} /> },
+ { value: "left", label: t.dockPositionLeft, preview: <DockPreview position="left" iconSize={config.iconSize} wallpaper={wallpaper} /> },
+ { value: "bottom", label: t.dockPositionBottom, preview: <DockPreview position="bottom" iconSize={config.iconSize} wallpaper={wallpaper} /> },
+ { value: "right", label: t.dockPositionRight, preview: <DockPreview position="right" iconSize={config.iconSize} wallpaper={wallpaper} /> },
]}
onChange={(dockPosition) => update({ dockPosition })}
/>
- <Row icon={<SettingIcon name="size" />} label={t.size}>
+ <Row label={t.size}>
<Slider
label={t.size}
value={config.iconSize}
min={ICON_SIZE.min}
max={ICON_SIZE.max}
- before={<SettingIcon name="indicators" size={14} />}
- after={<SettingIcon name="indicators" size={22} />}
onChange={(iconSize) => update({ iconSize })}
/>
</Row>
@@ -329,14 +334,12 @@ export function App() {
onChange={(magnification) => update({ magnification })}
/>
</Row>
- <SubRow icon={<SettingIcon name="magnification" />} label={t.magnifiedSize} open={config.magnification}>
+ <SubRow label={t.magnifiedSize} open={config.magnification}>
<Slider
label={t.magnifiedSize}
value={config.magnifiedSize}
min={config.iconSize}
max={MAX_MAGNIFIED_SIZE}
- before={<SettingIcon name="indicators" size={14} />}
- after={<SettingIcon name="indicators" size={22} />}
onChange={(magnifiedSize) => update({ magnifiedSize })}
/>
</SubRow>
@@ -440,21 +443,21 @@ export function App() {
onChange={(menuBar) => update({ menuBar })}
/>
</Row>
- <SubRow icon={<SettingIcon name="hide" />} label={t.menuBarAutoHide} hint={t.menuBarAutoHideHint} open={config.menuBar}>
+ <SubRow label={t.menuBarAutoHide} hint={t.menuBarAutoHideHint} open={config.menuBar}>
<Toggle
label={t.menuBarAutoHide}
checked={config.menuBarAutoHide}
onChange={(menuBarAutoHide) => update({ menuBarAutoHide })}
/>
</SubRow>
- <SubRow icon={<SettingIcon name="music" />} label={t.menuBarMusic} hint={t.menuBarMusicHint} open={config.menuBar}>
+ <SubRow label={t.menuBarMusic} hint={t.menuBarMusicHint} open={config.menuBar}>
<Toggle
label={t.menuBarMusic}
checked={config.menuBarMusic}
onChange={(menuBarMusic) => update({ menuBarMusic })}
/>
</SubRow>
- <SubRow icon={<SettingIcon name="ai" />} label={t.aiUsage} hint={t.aiUsageHint} open={config.menuBar}>
+ <SubRow label={t.aiUsage} hint={t.aiUsageHint} open={config.menuBar}>
<Toggle
label={t.aiUsage}
checked={config.aiUsage}
@@ -471,13 +474,13 @@ export function App() {
hideLabel
value={config.menuBarIslandStyle}
options={[
- { value: "notch", label: t.islandStyleNotch, preview: <IslandPreview style="notch" /> },
- { value: "bubble", label: t.islandStyleBubble, preview: <IslandPreview style="bubble" /> },
+ { value: "notch", label: t.islandStyleNotch, preview: <IslandPreview style="notch" wallpaper={wallpaper} /> },
+ { value: "bubble", label: t.islandStyleBubble, preview: <IslandPreview style="bubble" wallpaper={wallpaper} /> },
]}
onChange={(menuBarIslandStyle) => update({ menuBarIslandStyle })}
/>
</SubRow>
- <SubRow icon={<SettingIcon name="headphones" />} label={t.accessoryBattery} hint={t.accessoryBatteryHint} open={config.menuBar}>
+ <SubRow label={t.accessoryBattery} hint={t.accessoryBatteryHint} open={config.menuBar}>
<Toggle
label={t.accessoryBattery}
checked={config.accessoryBattery}
@@ -553,7 +556,7 @@ export function App() {
onChange={(checkUpdates) => update({ checkUpdates })}
/>
</Row>
- <SubRow icon={<SettingIcon name="updates" />} label={t.autoUpdate} hint={t.autoUpdateHint} open={config.checkUpdates}>
+ <SubRow label={t.autoUpdate} hint={t.autoUpdateHint} open={config.checkUpdates}>
<Toggle
label={t.autoUpdate}
checked={config.autoUpdate}
diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.ts
index e1f2e28..7729647 100644
--- a/apps/settings/src/config.ts
+++ b/apps/settings/src/config.ts
@@ -65,4 +65,8 @@ export const checkUpdate = () => invoke<UpdateInfo | null>("check_update");
export const openReleaseNotes = (url: string) => invoke<void>("open_release_notes", { url });
/** Fixed project URL, opened only when the user asks. */
export const openRepository = () => invoke<void>("open_repository");
+let wallpaperRequest: Promise<string | null> | undefined;
+/** One bounded native read per Settings process, including React StrictMode. */
+export const loadWallpaperPreview = () =>
+ wallpaperRequest ??= invoke<string | null>("wallpaper_preview").catch(() => null);
export const installUpdate = () => invoke<void>("install_update");
diff --git a/apps/settings/src/controls.tsx b/apps/settings/src/controls.tsx
index 0ff15df..5a06023 100644
--- a/apps/settings/src/controls.tsx
+++ b/apps/settings/src/controls.tsx
@@ -37,7 +37,7 @@ export function Row({ label, hint, icon, stacked, children }: RowProps) {
);
}
-interface SubRowProps extends RowProps {
+interface SubRowProps extends Omit<RowProps, "icon"> {
/** Whether the option it depends on is on; the row folds away while it is off. */
open: boolean;
}
@@ -83,17 +83,14 @@ interface SliderProps {
min: number;
max: number;
label: string;
- before?: ReactNode;
- after?: ReactNode;
disabled?: boolean;
onChange: (value: number) => void;
}
-export function Slider({ value, min, max, label, before, after, disabled, onChange }: SliderProps) {
+export function Slider({ value, min, max, label, disabled, onChange }: SliderProps) {
const filled = ((value - min) / (max - min)) * 100;
return (
<div className="slider">
- {before ? <span className="slider-edge">{before}</span> : null}
<input
type="range"
aria-label={label}
@@ -105,7 +102,6 @@ export function Slider({ value, min, max, label, before, after, disabled, onChan
style={{ "--filled": `${filled}%` } as React.CSSProperties}
onChange={(event) => onChange(Number(event.target.value))}
/>
- {after ? <span className="slider-edge">{after}</span> : null}
<output className="slider-value" aria-hidden="true">{value} px</output>
</div>
);
@@ -132,11 +128,12 @@ export function VisualChoices<T extends string>({ label, value, hideLabel, optio
onChange={() => onChange(option.value)} />
<span className="visual-choice-body">
<span className="visual-preview" aria-hidden="true">{option.preview}</span>
- <span className="visual-choice-label">{option.label}</span>
- {option.detail ? <span className="visual-choice-detail">{option.detail}</span> : null}
- <span className="visual-check" aria-hidden="true">
+ <span className="visual-choice-label">{option.label}
+ <span className="visual-check" aria-hidden="true">
<svg viewBox="0 0 16 16" width="12" height="12"><path d="m4 8 2.5 2.5L12 5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
+ </span>
</span>
+ {option.detail ? <span className="visual-choice-detail">{option.detail}</span> : null}
</span>
</label>
))}
diff --git a/apps/settings/src/styles.css b/apps/settings/src/styles.css
index e077981..ad9ad97 100644
--- a/apps/settings/src/styles.css
+++ b/apps/settings/src/styles.css
@@ -363,14 +363,14 @@ input:focus-visible {
.row-sub .row {
position: relative;
- padding-left: 30px;
+ padding-left: 56px;
}
.row-sub .row::before {
position: absolute;
top: 0;
right: 0;
- left: 30px;
+ left: 56px;
height: 1px;
content: "";
background: var(--line);
@@ -430,13 +430,6 @@ input:focus-visible {
max-width: 100%;
}
-.slider-edge {
- display: flex;
- flex: none;
- color: var(--text-dim);
- font-size: 11px;
-}
-
.slider input {
appearance: none;
width: 100%;
@@ -483,13 +476,14 @@ input:focus-visible {
.visual-choice:hover .visual-choice-body { background: var(--hover); }
.visual-choice input:checked + .visual-choice-body { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, var(--card)); box-shadow: 0 0 0 1px var(--accent); }
.visual-choice input:focus-visible + .visual-choice-body { outline: 2px solid var(--accent); outline-offset: 4px; }
-.visual-choice-label { font-size: 12px; font-weight: 500; text-align: center; overflow-wrap: anywhere; }
+.visual-choice-label { position: relative; width: 100%; padding: 0 18px; font-size: 12px; font-weight: 500; text-align: center; overflow-wrap: anywhere; }
.visual-choice-detail { margin-top: -4px; font-size: 11px; color: var(--text-dim); font-variant-numeric: tabular-nums; }
.visual-preview { display: flex; justify-content: center; width: 100%; pointer-events: none; }
-.visual-check { position: absolute; top: 5px; right: 5px; display: grid; place-items: center; width: 16px; height: 16px; border-radius: 50%; background: var(--accent); color: white; opacity: 0; }
+.visual-check { position: absolute; top: 50%; right: 0; transform: translateY(-50%); display: grid; place-items: center; width: 14px; height: 14px; border-radius: 50%; background: var(--accent); color: white; opacity: 0; }
.visual-choice input:checked + .visual-choice-body .visual-check { opacity: 1; }
.preview-screen { display: block; position: relative; width: 100%; height: 72px; overflow: hidden; border: 1px solid var(--line); border-radius: 5px; background: linear-gradient(155deg, var(--preview-sky) 20%, var(--preview-land)); }
+.preview-wallpaper { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.preview-topbar { position: absolute; inset: 0 0 auto; height: 8px; display: flex; align-items: center; gap: 3px; padding: 0 5px; background: var(--sidebar); }
.preview-topbar i { width: 7px; height: 2px; border-radius: 2px; background: var(--text-dim); opacity: .5; }
.preview-window { position: absolute; left: 28%; top: 24%; width: 48%; height: 43%; border-radius: 3px; background: var(--content); box-shadow: 0 2px 5px #0001; padding: 4px; display: flex; gap: 2px; align-items: start; }
@@ -503,16 +497,22 @@ input:focus-visible {
.preview-dock i:nth-child(3) { background: #a488d5; }
.preview-dock i:nth-child(4) { background: #70bfa4; }
.preview-dock i:nth-child(5) { background: #d68093; }
-.preview-screen-island { height: 66px; }
-.preview-screen-island .preview-window { top: 40%; height: 44%; }
-.preview-island { position: absolute; top: 0; color: var(--text); }
-.preview-island[data-style="notch"] { left: 50%; transform: translateX(-50%); width: 62px; height: 17px; }
+.preview-screen-island { height: 82px; }
+.preview-screen-island .preview-window { left: 29%; top: 43%; width: 42%; height: 39%; opacity: .72; }
+.preview-island { position: absolute; top: 0; color: #15171b; filter: drop-shadow(0 1px 1px #0002); }
+.preview-island[data-style="notch"] { left: 50%; transform: translateX(-50%); width: 88px; height: 22px; }
.preview-island > svg { width: 100%; height: 100%; }
-.preview-island[data-style="bubble"] { right: 8px; top: 2px; width: 35px; height: 12px; background: currentColor; border-radius: 10px; }
-.preview-island-content { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 3px; }
-.preview-island-content i { width: 3px; height: 5px; border-radius: 2px; background: var(--content); }
-.preview-island-content i:nth-child(2) { width: 10px; height: 2px; }
-.preview-island-content i:nth-child(3) { height: 7px; }
+.preview-island[data-style="bubble"] { right: 18px; top: 4px; width: 72px; height: 18px; background: currentColor; border-radius: 12px; }
+.preview-island-content { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 5px; }
+.preview-album { display: grid; place-items: center; width: 11px; height: 11px; border-radius: 50%; background: linear-gradient(145deg, #d58761, #80649a); }
+.preview-album svg { width: 8px; height: 8px; fill: none; stroke: #fff; stroke-width: 1.5; }
+.preview-song { display: flex; flex-direction: column; gap: 3px; width: 24px; }
+.preview-song i { height: 2px; border-radius: 1px; background: #eef0f4; }
+.preview-song i + i { width: 65%; opacity: .45; }
+.preview-wave { display: flex; align-items: center; gap: 1px; height: 9px; }
+.preview-wave i { width: 2px; height: 4px; border-radius: 1px; background: #e8a47b; }
+.preview-wave i:nth-child(2) { height: 8px; }
+.preview-wave i:nth-child(3) { height: 6px; }
.preview-speed { width: 100%; max-width: 120px; height: 48px; color: var(--text-dim); }
.slider input:disabled {
diff --git a/apps/settings/src/visuals.tsx b/apps/settings/src/visuals.tsx
index 95ffb58..5e107e9 100644
--- a/apps/settings/src/visuals.tsx
+++ b/apps/settings/src/visuals.tsx
@@ -29,14 +29,15 @@ const PATHS = {
} satisfies Record<string, ReactNode>;
export function SettingIcon({ name, size = 18 }: { name: keyof typeof PATHS; size?: number }) {
- return <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{PATHS[name]}</svg>;
+ return <svg viewBox="0 0 24 24" width={size} height={size} fill={name === "star" ? "#f5c344" : "none"} stroke={name === "star" ? "#d69b16" : "currentColor"} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{PATHS[name]}</svg>;
}
const MINI_ICONS = <><i /><i /><i /><i /><i /></>;
/** Illustrations only: no window capture, network, timers or animation loop. */
-export function DockPreview({ position, iconSize }: { position: DockPosition; iconSize: number }) {
+export function DockPreview({ position, iconSize, wallpaper }: { position: DockPosition; iconSize: number; wallpaper: string | null }) {
return <span className="preview-screen">
+ {wallpaper ? <img className="preview-wallpaper" src={wallpaper} alt="" /> : null}
<span className="preview-topbar"><i /><i /><i /></span>
<span className="preview-window"><i /><i /><i /></span>
<span className="preview-dock" data-position={position}
@@ -44,12 +45,17 @@ export function DockPreview({ position, iconSize }: { position: DockPosition; ic
</span>;
}
-export function IslandPreview({ style }: { style: IslandStyle }) {
+export function IslandPreview({ style, wallpaper }: { style: IslandStyle; wallpaper: string | null }) {
return <span className="preview-screen preview-screen-island">
+ {wallpaper ? <img className="preview-wallpaper" src={wallpaper} alt="" /> : null}
<span className="preview-topbar"><i /><i /><i /></span>
<span className="preview-island" data-style={style}>
- {style === "notch" ? <svg viewBox="0 0 72 18"><path d="M0 0h72c-12 0-6 18-20 18H20C6 18 12 0 0 0" fill="currentColor" /></svg> : null}
- <span className="preview-island-content"><i /><i /><i /></span>
+ {style === "notch" ? <svg viewBox="0 0 100 24"><path d="M0 0h100c-12 0-8 24-24 24H24C8 24 12 0 0 0" fill="currentColor" /></svg> : null}
+ <span className="preview-island-content">
+ <span className="preview-album"><svg viewBox="0 0 16 16"><path d="M6 11V4l6-1v7M6 6l6-1" /><ellipse cx="4" cy="12" rx="2" ry="1.5" /><ellipse cx="10" cy="11" rx="2" ry="1.5" /></svg></span>
+ <span className="preview-song"><i /><i /></span>
+ <span className="preview-wave"><i /><i /><i /></span>
+ </span>
</span>
<span className="preview-window"><i /><i /><i /></span>
</span>;
diff --git a/assets/media-fallback.png b/assets/media-fallback.png
new file mode 100644
index 0000000..5a46215
Binary files /dev/null and b/assets/media-fallback.png differ
diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.toml
index ea3ad85..87e5568 100644
--- a/crates/muelle-shell/Cargo.toml
+++ b/crates/muelle-shell/Cargo.toml
@@ -19,6 +19,7 @@ windows = { workspace = true, features = [
"Win32_Globalization",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
+ "Win32_Graphics_Imaging",
"Win32_Media_Audio",
"Win32_Media_Audio_Endpoints",
"Win32_Storage_EnhancedStorage",
diff --git a/crates/muelle-shell/src/imagery.rs b/crates/muelle-shell/src/imagery.rs
new file mode 100644
index 0000000..98e4a79
--- /dev/null
+++ b/crates/muelle-shell/src/imagery.rs
@@ -0,0 +1,266 @@
+//! Bounded Windows image decoding for small UI previews, off the UI thread.
+use crate::icons::IconImage;
+use windows::Win32::{
+ Graphics::Imaging::{
+ CLSID_WICImagingFactory, GUID_WICPixelFormat32bppPBGRA, IWICImagingFactory,
+ WICBitmapDitherTypeNone, WICBitmapInterpolationModeFant, WICBitmapPaletteTypeCustom,
+ WICDecodeMetadataCacheOnDemand,
+ },
+ System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},
+ UI::Shell::SHCreateMemStream,
+};
+
+/// Caller initializes COM. Limits are checked before decoding pixels; only a
+/// downscaled BGRA buffer is retained. No URI fetching or shell extensions.
+#[must_use]
+pub fn decode(bytes: &[u8], side: u32, max_pixels: u64) -> Option<IconImage> {
+ if bytes.is_empty() || bytes.len() > 32 * 1024 * 1024 || !(1..=512).contains(&side) {
+ return None;
+ }
+ // SAFETY: Input bytes and all WIC objects remain alive until CopyPixels
+ // completes. The destination is checked and sized for its exact stride.
+ unsafe {
+ let factory: IWICImagingFactory =
+ CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
+ let stream = SHCreateMemStream(Some(bytes))?;
+ let decoder = factory
+ .CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand)
+ .ok()?;
+ let frame = decoder.GetFrame(0).ok()?;
+ let (mut width, mut height) = (0, 0);
+ frame.GetSize(&mut width, &mut height).ok()?;
+ if width == 0 || height == 0 || u64::from(width) * u64::from(height) > max_pixels {
+ return None;
+ }
+ let divisor = width.max(height).max(side);
+ width = ((u64::from(width) * u64::from(side)) / u64::from(divisor)).max(1) as u32;
+ height = ((u64::from(height) * u64::from(side)) / u64::from(divisor)).max(1) as u32;
+ let scaler = factory.CreateBitmapScaler().ok()?;
+ scaler
+ .Initialize(&frame, width, height, WICBitmapInterpolationModeFant)
+ .ok()?;
+ let converter = factory.CreateFormatConverter().ok()?;
+ converter
+ .Initialize(
+ &scaler,
+ &GUID_WICPixelFormat32bppPBGRA,
+ WICBitmapDitherTypeNone,
+ None,
+ 0.0,
+ WICBitmapPaletteTypeCustom,
+ )
+ .ok()?;
+ let mut bgra = vec![0; (width * height * 4) as usize];
+ converter
+ .CopyPixels(std::ptr::null(), width * 4, &mut bgra)
+ .ok()?;
+ Some(IconImage {
+ width,
+ height,
+ bgra,
+ })
+ }
+}
+
+/// Center crop and antialias the edge once, before sharing the image with UI.
+#[must_use]
+pub fn circular(image: IconImage) -> IconImage {
+ let side = image.width.min(image.height);
+ let (left, top) = ((image.width - side) / 2, (image.height - side) / 2);
+ let mut bgra = Vec::with_capacity((side * side * 4) as usize);
+ let radius = side as f32 / 2.0;
+ for y in 0..side {
+ for x in 0..side {
+ let offset = (((y + top) * image.width + x + left) * 4) as usize;
+ let distance = (x as f32 + 0.5 - radius).hypot(y as f32 + 0.5 - radius);
+ let coverage = (radius - distance + 0.5).clamp(0.0, 1.0);
+ for channel in &image.bgra[offset..offset + 4] {
+ bgra.push((f32::from(*channel) * coverage).round() as u8);
+ }
+ }
+ }
+ IconImage {
+ width: side,
+ height: side,
+ bgra,
+ }
+}
+
+/// Read the current monitor's wallpaper once on a blocking worker. Only the
+/// small decoded preview leaves this function; its local path is not exposed.
+#[must_use]
+pub fn wallpaper_preview(window: isize) -> Option<IconImage> {
+ use std::{fs::File, io::Read};
+ use windows::{
+ Win32::{
+ Foundation::{HWND, RPC_E_CHANGED_MODE},
+ Graphics::Gdi::{
+ GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromWindow,
+ },
+ System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoTaskMemFree, CoUninitialize},
+ UI::HiDpi::{
+ DPI_AWARENESS_CONTEXT, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
+ SetThreadDpiAwarenessContext,
+ },
+ UI::Shell::{DesktopWallpaper, IDesktopWallpaper},
+ },
+ core::{PCWSTR, PWSTR},
+ };
+ struct Apartment(bool);
+ impl Drop for Apartment {
+ fn drop(&mut self) {
+ if self.0 {
+ // SAFETY: Balances this thread's successful initialization.
+ unsafe { CoUninitialize() };
+ }
+ }
+ }
+ struct Text(PWSTR);
+ struct DpiContext(DPI_AWARENESS_CONTEXT);
+ impl Drop for DpiContext {
+ fn drop(&mut self) {
+ if !self.0.0.is_null() {
+ // SAFETY: Restore this worker thread's previous DPI context.
+ unsafe {
+ SetThreadDpiAwarenessContext(self.0);
+ }
+ }
+ }
+ }
+ impl Drop for Text {
+ fn drop(&mut self) {
+ // SAFETY: GetWallpaper/GetMonitorDevicePathAt allocate with COM.
+ unsafe { CoTaskMemFree(Some(self.0.0.cast())) };
+ }
+ }
+ // SAFETY: Read-only monitor/desktop queries; allocated strings and COM
+ // objects are scoped inside the apartment. No shell thumbnail handlers.
+ unsafe {
+ let initialized = CoInitializeEx(None, COINIT_MULTITHREADED);
+ if initialized.is_err() && initialized != RPC_E_CHANGED_MODE {
+ return None;
+ }
+ let _apartment = Apartment(initialized.is_ok());
+ // DesktopWallpaper always returns physical rectangles; GetMonitorInfo
+ // otherwise virtualizes them on pool/test threads at e.g. 125% DPI.
+ let _dpi = DpiContext(SetThreadDpiAwarenessContext(
+ DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
+ ));
+ let desktop: IDesktopWallpaper = CoCreateInstance(
+ &DesktopWallpaper,
+ None,
+ windows::Win32::System::Com::CLSCTX_ALL,
+ )
+ .ok()?;
+ let monitor = MonitorFromWindow(HWND(window as *mut _), MONITOR_DEFAULTTONEAREST);
+ let mut info = MONITORINFO {
+ cbSize: size_of::<MONITORINFO>() as u32,
+ ..Default::default()
+ };
+ if !GetMonitorInfoW(monitor, &mut info).as_bool() {
+ return None;
+ }
+ let mut path = None;
+ for index in 0..desktop.GetMonitorDevicePathCount().ok()?.min(64) {
+ let id = Text(desktop.GetMonitorDevicePathAt(index).ok()?);
+ if id.0.is_null() {
+ continue;
+ }
+ if desktop.GetMonitorRECT(PCWSTR(id.0.0)).ok()? == info.rcMonitor {
+ let wallpaper = Text(desktop.GetWallpaper(PCWSTR(id.0.0)).ok()?);
+ if !wallpaper.0.is_null() {
+ path = wallpaper.0.to_string().ok();
+ }
+ break;
+ }
+ }
+ let path = path.filter(|path| !path.is_empty() && !path.starts_with(r"\\"))?;
+ let file = File::open(path).ok()?;
+ if file.metadata().ok()?.len() > 32 * 1024 * 1024 {
+ return None;
+ }
+ let mut bytes = Vec::new();
+ file.take(32 * 1024 * 1024 + 1)
+ .read_to_end(&mut bytes)
+ .ok()?;
+ decode(&bytes, 384, 40_000_000)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn circular_crop_preserves_the_center_and_premultiplied_alpha() {
+ let image = IconImage {
+ width: 12,
+ height: 8,
+ bgra: (0..96)
+ .flat_map(|i| [(i % 12) as u8, 20, 40, 128])
+ .collect(),
+ };
+ let circle = circular(image);
+ assert_eq!((circle.width, circle.height), (8, 8));
+ assert_eq!(
+ &circle.bgra[(4 * 8 + 4) * 4..(4 * 8 + 4) * 4 + 4],
+ &[6, 20, 40, 128]
+ );
+ assert_eq!(&circle.bgra[..4], &[0, 0, 0, 0]);
+ assert!(
+ circle
+ .bgra
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .all(|pixel| pixel[..3].iter().all(|channel| *channel <= pixel[3]))
+ );
+ }
+
+ #[test]
+ fn native_decoder_limits_images_and_rejects_corrupt_inputs() -> windows::core::Result<()> {
+ use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
+ // SAFETY: This test owns and balances this thread's COM initialization.
+ unsafe {
+ CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
+ }
+ let bytes = include_bytes!("../../../assets/media-fallback.png");
+ let image = decode(bytes, 32, 1_000_000);
+ let too_many_pixels = decode(bytes, 32, 1);
+ let corrupt = decode(b"not an encoded image", 32, 1_000_000);
+ unsafe {
+ CoUninitialize();
+ }
+ let image = image.ok_or_else(|| {
+ windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)
+ })?;
+ assert!(image.width <= 32 && image.height <= 32);
+ assert_eq!(image.bgra.len(), (image.width * image.height * 4) as usize);
+ assert!(too_many_pixels.is_none() && corrupt.is_none());
+ assert!(decode(bytes, 0, 1_000_000).is_none());
+ assert!(decode(bytes, 513, 1_000_000).is_none());
+ Ok(())
+ }
+
+ #[test]
+ #[ignore = "Read-only probe of the connected Windows desktop wallpaper"]
+ fn native_wallpaper_preview_is_bounded() {
+ let started = std::time::Instant::now();
+ let desktop = unsafe { windows::Win32::UI::WindowsAndMessaging::GetDesktopWindow() };
+ if let Some(image) = wallpaper_preview(desktop.0 as isize) {
+ assert!(image.width <= 384 && image.height <= 384);
+ assert_eq!(image.bgra.len(), (image.width * image.height * 4) as usize);
+ eprintln!(
+ "wallpaper preview: {}x{}, {:?}",
+ image.width,
+ image.height,
+ started.elapsed()
+ );
+ } else {
+ eprintln!(
+ "No readable image wallpaper (a supported fallback), {:?}",
+ started.elapsed()
+ );
+ }
+ }
+}
diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rs
index 52476ec..01fb400 100644
--- a/crates/muelle-shell/src/lib.rs
+++ b/crates/muelle-shell/src/lib.rs
@@ -7,6 +7,7 @@ pub mod files;
pub mod folder;
pub mod icon_cache;
pub mod icons;
+pub mod imagery;
pub mod keyboard;
pub mod launcher;
pub mod log;
diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rs
index 66176de..b47ef59 100644
--- a/crates/muelle-shell/src/status.rs
+++ b/crates/muelle-shell/src/status.rs
@@ -110,6 +110,8 @@ pub struct Volume {
pub muted: bool,
/// 0 (silent) to 3 (loud): the steps the speaker glyph has.
pub level: u8,
+ /// Precise endpoint reading, retained for the music popup slider.
+ pub percent: u8,
}
#[implement(IAudioEndpointVolumeCallback)]
@@ -215,13 +217,47 @@ impl AudioWatch {
endpoint.GetMute().ok()?.as_bool(),
)
};
+ let percent = (level.clamp(0.0, 1.0) * 100.0).round() as u8;
let level = match level {
l if l < 0.01 => 0,
l if l < 0.34 => 1,
l if l < 0.67 => 2,
_ => 3,
};
- Some(Volume { muted, level })
+ Some(Volume {
+ muted,
+ level,
+ percent,
+ })
+ }
+
+ /// Uses the watched default output; the existing callback updates all UI.
+ pub fn set_percent(&mut self, percent: u8) -> Result<()> {
+ self.follow_default();
+ let (_, endpoint, _) = self.endpoint.as_ref().ok_or_else(|| {
+ windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)
+ })?;
+ // SAFETY: The endpoint belongs to this COM-initialized thread. The
+ // event context is optional. No waits, enumeration or new watcher.
+ unsafe {
+ endpoint.SetMasterVolumeLevelScalar(
+ f32::from(percent.min(100)) / 100.0,
+ std::ptr::null(),
+ )?;
+ if percent > 0 && endpoint.GetMute()?.as_bool() {
+ endpoint.SetMute(false, std::ptr::null())?;
+ }
+ }
+ Ok(())
+ }
+
+ pub fn toggle_mute(&mut self) -> Result<()> {
+ self.follow_default();
+ let (_, endpoint, _) = self.endpoint.as_ref().ok_or_else(|| {
+ windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)
+ })?;
+ // SAFETY: Read and update our current, live endpoint on its apartment.
+ unsafe { endpoint.SetMute(!endpoint.GetMute()?.as_bool(), std::ptr::null()) }
}
/// Moves the volume callback to the default device if it changed.
diff --git a/spikes/src/bin/spike_menu.rs b/spikes/src/bin/spike_menu.rs
index 0b1dea0..97f14ba 100644
--- a/spikes/src/bin/spike_menu.rs
+++ b/spikes/src/bin/spike_menu.rs
@@ -158,7 +158,14 @@ fn main() -> anyhow::Result<()> {
std::thread::sleep(Duration::from_millis(1500));
post(WM_CANCELMODE, 0, LPARAM(0));
});
- let chosen = menu::show(&gfx, owner, &items, POINT { x: 960, y: 980 }, dark);
+ let chosen = menu::show(
+ &gfx,
+ owner,
+ &items,
+ POINT { x: 960, y: 980 },
+ dark,
+ menu::Placement::Above,
+ );
println!("chosen: {chosen:?}");
}
Ok(())