Skip to content

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

feat: add media title strings for playback notifications in multiple languages

CristianOlivera160275efee29f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4423091..5dfdcf3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,18 @@ copia la sección de la versión que se publica a la release de GitHub.
## [Unreleased]
+## [0.1.9]
+
### English
+- Fixed: bringing back a minimized app from the dock could leave its window
+ behind the one in front, as if it had closed again (Warp, for one). Since
+ 0.1.8 the dock restored the window without taking the focus first, and
+ Windows then places it behind the active window.
+- GitHub Copilot usage was removed from the menu bar island. Its sign-in is
+ only stored encrypted, and decrypting another app's secrets is what made
+ antivirus programs flag Muelle; Muelle no longer reads the Windows
+ Credential Manager either.
- Fixed: some antivirus programs flagged Muelle 0.1.6–0.1.8 as a trojan and
deleted it, often right after updating. Two things looked like malware: to
show GitHub Copilot and Cursor usage, Muelle decrypted VS Code's stored
@@ -40,6 +50,14 @@ copia la sección de la versión que se publica a la release de GitHub.
### Español
+- Corregido: al recuperar una app minimizada desde el dock, su ventana podía
+ quedar detrás de la que estaba delante, como si se hubiera cerrado otra vez
+ (Warp, por ejemplo). Desde la 0.1.8 el dock restauraba la ventana sin tomar
+ antes el foco, y Windows la coloca entonces detrás de la ventana activa.
+- Se quitó el uso de GitHub Copilot de la isla de la barra superior. Su sesión
+ solo se guarda cifrada, y descifrar los secretos de otra app es lo que hacía
+ que los antivirus marcaran Muelle; Muelle tampoco lee ya el Administrador de
+ credenciales de Windows.
- Corregido: algunos antivirus marcaban Muelle 0.1.6–0.1.8 como troyano y lo
borraban, a menudo justo al actualizar. Dos cosas parecían malware: para
mostrar el uso de GitHub Copilot y Cursor, Muelle descifraba los secretos
diff --git a/Cargo.lock b/Cargo.lock
index dc14b5c..775cbbc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2259,7 +2259,7 @@ dependencies = [
[[package]]
name = "muelle"
-version = "0.1.8"
+version = "0.1.9"
dependencies = [
"anyhow",
"base64 0.22.1",
@@ -2273,13 +2273,14 @@ dependencies = [
"serde_json",
"windows",
"windows-core",
+ "windows-future",
"windows-numerics",
"winresource",
]
[[package]]
name = "muelle-config"
-version = "0.1.8"
+version = "0.1.9"
dependencies = [
"serde",
"serde_json",
@@ -2288,11 +2289,11 @@ dependencies = [
[[package]]
name = "muelle-core"
-version = "0.1.8"
+version = "0.1.9"
[[package]]
name = "muelle-settings"
-version = "0.1.8"
+version = "0.1.9"
dependencies = [
"muelle-config",
"muelle-shell",
@@ -2306,7 +2307,7 @@ dependencies = [
[[package]]
name = "muelle-shell"
-version = "0.1.8"
+version = "0.1.9"
dependencies = [
"thiserror 2.0.21",
"windows",
diff --git a/Cargo.toml b/Cargo.toml
index 131c575..06bae0f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "apps/dock", "apps/settings/src-tauri", "spikes"]
[workspace.package]
-version = "0.1.8"
+version = "0.1.9"
edition = "2024"
license = "MIT"
diff --git a/README.es.md b/README.es.md
index 4cfa791..0b6d207 100644
--- a/README.es.md
+++ b/README.es.md
@@ -30,7 +30,7 @@ en desarrollo activo.
además de los botones de búsqueda, Vista de tareas y Widgets si los tienes en la barra
de Windows.
- Una isla curva en la barra superior con los límites de Claude Code, Codex,
- GitHub Copilot, OpenCode Go, Gemini CLI y Antigravity. Las cuotas de
+ OpenCode Go, Gemini CLI y Antigravity. Las cuotas de
Gemini Pro y Flash aparecen por separado cuando están disponibles.
- App de Ajustes aparte, con cambios en vivo, en español e inglés, y efecto genio configurable.
- Un proceso guardián devuelve la barra de tareas de Windows si el dock se cierra de forma inesperada.
diff --git a/README.md b/README.md
index a04cb5b..f4fb386 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@ Smooth magnification, live window previews, and an optional Genie-style minimize
input language, microphone/camera in use, the hidden tray icons, plus
the Search, Task View and Widgets buttons if you have them on the Windows taskbar.
- A curved island in the menu bar for usage limits from Claude Code, Codex,
- GitHub Copilot, OpenCode Go, Gemini CLI, and Antigravity. Gemini Pro
+ OpenCode Go, Gemini CLI, and Antigravity. Gemini Pro
and Flash quotas appear separately when available.
- Separate Settings app with live changes, Spanish and English, and a
configurable Genie-style minimize animation.
diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.toml
index 2e7e51b..03f46ed 100644
--- a/apps/dock/Cargo.toml
+++ b/apps/dock/Cargo.toml
@@ -22,11 +22,13 @@ reqwest = { version = "0.13", default-features = false, features = ["blocking",
serde.workspace = true
serde_json = "1"
windows-core.workspace = true
+windows-future = "0.3"
windows-numerics.workspace = true
windows = { workspace = true, features = [
"Foundation",
"Graphics",
"Graphics_DirectX",
+ "Media_Control",
"System",
"UI",
"UI_Composition",
@@ -42,7 +44,6 @@ windows = { workspace = true, features = [
"Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Gdi",
"Win32_Security",
- "Win32_Security_Credentials",
"Win32_System_Com",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Console",
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 918c87e..8ff5d15 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -93,6 +93,7 @@ use crate::{
gfx::{Gfx, LabelBrush},
menu::{self, MenuItem},
menubar::MenuBar,
+ previews::{Choice as PreviewChoice, Picker},
scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},
shell_work::{self, Action as ShellAction},
strings::{self, text},
@@ -191,6 +192,9 @@ fn millis(duration: std::time::Duration) -> u32 {
/// The background update runs once a day: a single timer, aimed at the
/// moment the next look is due (see `schedule_update`).
const UPDATE_TIMER: usize = 12;
+const PREVIEW_TIMER: usize = 13;
+const PREVIEW_DWELL_MS: u32 = 420;
+const PREVIEW_LEAVE_MS: u32 = 75;
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.
const UPDATE_AFTER_START: std::time::Duration = std::time::Duration::from_secs(2 * 60);
@@ -538,6 +542,8 @@ struct App {
stage: Option<Stage>,
hovering: bool,
hovered: Option<usize>,
+ preview_candidate: Option<String>,
+ preview: Option<Picker>,
/// Horizontal cursor position relative to the resting dock.
cursor: f32,
/// 0 = resting, 1 = full magnification.
@@ -818,6 +824,7 @@ impl App {
if self.stage.as_ref().is_some_and(|stage| stage.key == key) {
return Ok(());
}
+ self.close_preview();
let scale = monitor.scale;
let max_scale = key.max_scale;
@@ -1293,7 +1300,131 @@ impl App {
// the mouse cancels the request, and without it the dock would
// never hear the pointer leave and stay magnified.
self.track_leave()?;
- self.render()
+ self.render()?;
+ self.aim_preview();
+ Ok(())
+ }
+
+ fn preview_target(&self) -> Option<(&str, usize)> {
+ if !self.hovering
+ || self.press.is_some()
+ || self.drag.is_some()
+ || self.drag_over
+ || self.fullscreen
+ || self.switching
+ {
+ return None;
+ }
+ let index = self.hovered?;
+ let entry = self.entries.get(index)?;
+ let id = entry.id.as_deref()?;
+ (entry.role == Role::App
+ && entry.running
+ && self
+ .windows
+ .iter()
+ .filter(|window| window.app_id == id)
+ .nth(1)
+ .is_some())
+ .then_some((id, index))
+ }
+
+ fn aim_preview(&mut self) {
+ let target = self.preview_target().map(|(id, _)| id);
+ if self
+ .preview
+ .as_ref()
+ .is_some_and(|picker| target.is_none_or(|id| id == picker.app_id))
+ || target == self.preview_candidate.as_deref() && self.preview.is_none()
+ {
+ return;
+ }
+ let candidate = target.map(str::to_owned);
+ self.close_preview();
+ if candidate.is_some() {
+ // SAFETY: The timer belongs to our UI window.
+ unsafe { SetTimer(Some(self.input), PREVIEW_TIMER, PREVIEW_DWELL_MS, None) };
+ self.preview_candidate = candidate;
+ }
+ }
+
+ fn close_preview(&mut self) {
+ if self.preview_candidate.take().is_none() && self.preview.is_none() {
+ return;
+ }
+ // SAFETY: Both timers belong to our UI window.
+ unsafe {
+ let _ = KillTimer(Some(self.input), PREVIEW_TIMER);
+ }
+ if self.preview.take().is_some() && self.config.auto_hide && !self.hovering {
+ unsafe { SetTimer(Some(self.input), HIDE_TIMER, HIDE_DELAY_MS, None) };
+ }
+ }
+
+ fn preview_tick(&mut self) -> Result<()> {
+ let mut point = POINT::default();
+ // SAFETY: Read-only pointer and window queries on the UI thread.
+ if unsafe { GetCursorPos(&mut point) }.is_err() {
+ self.close_preview();
+ return Ok(());
+ }
+ if let Some(picker) = &self.preview {
+ if !picker.contains(point) {
+ self.close_preview();
+ }
+ return Ok(());
+ }
+ // SAFETY: End the one-shot dwell before creating the preview.
+ unsafe {
+ let _ = KillTimer(Some(self.input), PREVIEW_TIMER);
+ }
+ let Some(candidate) = self.preview_candidate.take() else {
+ return Ok(());
+ };
+ let Some((id, index)) = self.preview_target() else {
+ return Ok(());
+ };
+ if id != candidate
+ || unsafe { windows::Win32::UI::WindowsAndMessaging::WindowFromPoint(point) }
+ != self.input
+ {
+ return Ok(());
+ }
+ let Some(stage) = &self.stage else {
+ return Ok(());
+ };
+ let state = magnify(
+ &stage.layout,
+ self.cursor,
+ self.amount.value,
+ &stage.magnifier,
+ );
+ let rect = &state.rects[index];
+ let anchor = RECT {
+ left: stage.dock_origin.x + rect.x.round() as i32,
+ top: stage.dock_origin.y + rect.y.round() as i32,
+ right: stage.dock_origin.x + (rect.x + rect.width).round() as i32,
+ bottom: stage.dock_origin.y + (rect.y + rect.height).round() as i32,
+ };
+ let Some(monitor) = primary_monitor() else {
+ return Ok(());
+ };
+ let windows = self.windows_of(&candidate);
+ let name = self
+ .icons
+ .get(&candidate, "")
+ .map_or_else(|| fallback_name(&candidate), |visual| visual.name.clone());
+ self.preview = Some(Picker::open(
+ &self.gfx,
+ (candidate, name),
+ windows,
+ anchor,
+ monitor,
+ (stage.key.light, stage.key.glass),
+ )?);
+ // Run only while the picker is open, including the gap above the icon.
+ unsafe { SetTimer(Some(self.input), PREVIEW_TIMER, PREVIEW_LEAVE_MS, None) };
+ Ok(())
}
fn track_leave(&self) -> Result<()> {
@@ -1329,6 +1460,9 @@ impl App {
return Ok(());
}
self.hovering = false;
+ if self.preview.is_none() {
+ self.close_preview();
+ }
self.amount.target = 0.0;
self.last_frame = Instant::now();
if self.config.auto_hide {
@@ -1359,6 +1493,7 @@ impl App {
return Ok(());
}
self.switching = true;
+ self.close_preview();
self.switch_started = Instant::now();
// SAFETY: Timers on our own window.
unsafe {
@@ -1622,7 +1757,12 @@ impl App {
}
fn hide_if_unused(&mut self) -> Result<()> {
- if !self.config.auto_hide || self.hovering || self.drag.is_some() || self.switching {
+ if !self.config.auto_hide
+ || self.hovering
+ || self.drag.is_some()
+ || self.switching
+ || self.preview.is_some()
+ {
return Ok(());
}
self.slide.target = 1.0;
@@ -1640,6 +1780,7 @@ impl App {
}
fn on_press(&mut self) -> Result<()> {
+ self.close_preview();
let Some(entry) = self.hovered.and_then(|index| self.entries.get(index)) else {
return Ok(());
};
@@ -1818,6 +1959,7 @@ impl App {
}
fn on_drag_enter(&mut self, incoming: Vec<String>, x: i32) -> Result<DROPEFFECT> {
+ self.close_preview();
self.incoming = incoming;
self.drag_over = true;
self.on_drag_over(x)
@@ -2044,6 +2186,7 @@ impl App {
/// Middle click on an app opens another window of it, as on the Windows
/// taskbar.
fn on_middle_click(&mut self) -> Result<Option<Outside>> {
+ self.close_preview();
let Some(entry) = self.hovered.and_then(|index| self.entries.get(index)) else {
return Ok(None);
};
@@ -2057,6 +2200,7 @@ impl App {
/// Right-click prepares the menu for the item under the cursor, or the dock
/// menu when over empty space or a divider.
fn on_right_click(&mut self) -> Result<Option<Outside>> {
+ self.close_preview();
let Some(stage) = &self.stage else {
return Ok(None);
};
@@ -2399,6 +2543,15 @@ impl App {
/// Refreshes open windows and recomposes the dock if anything changed.
fn sync(&mut self) -> Result<()> {
self.windows = self.tracker.list();
+ if self.preview.as_ref().is_some_and(|picker| {
+ let current = self.windows_of(&picker.app_id);
+ current.len() != picker.windows.len()
+ || current
+ .iter()
+ .any(|window| !picker.windows.contains(window))
+ }) {
+ self.close_preview();
+ }
let windows = &self.windows;
self.last_rects
.retain(|hwnd, _| windows.iter().any(|window| window.hwnd == *hwnd));
@@ -2591,6 +2744,7 @@ impl App {
// SAFETY: `self.input` is a live window on this UI thread.
unsafe {
if fullscreen {
+ self.close_preview();
SetTimer(
Some(self.input),
FULLSCREEN_TIMER,
@@ -2734,6 +2888,85 @@ pub fn menu_bar_clicked(x: f32, y: f32) {
});
}
+pub fn menu_bar_has_action(point: POINT) -> bool {
+ APP.with(|cell| {
+ cell.try_borrow().ok().is_some_and(|app| {
+ app.as_ref()
+ .and_then(|app| app.menubar.as_ref())
+ .is_some_and(|bar| bar.has_island_action(point))
+ })
+ })
+}
+
+pub fn menu_bar_media_changed() {
+ with_app("reproducción", |app| match &mut app.menubar {
+ Some(bar) => bar.media_changed(&app.gfx),
+ None => Ok(()),
+ });
+}
+
+pub fn preview_hover(point: POINT) {
+ with_app("selector de ventanas", |app| {
+ if let Some(picker) = &mut app.preview {
+ picker.hover(point)?;
+ }
+ Ok(())
+ });
+}
+
+pub fn preview_has_hit(hwnd: HWND) -> bool {
+ let mut point = POINT::default();
+ // SAFETY: The cursor coordinates are written into our local structure.
+ if unsafe {
+ GetCursorPos(&mut point).is_err()
+ || !windows::Win32::Graphics::Gdi::ScreenToClient(hwnd, &mut point).as_bool()
+ } {
+ return false;
+ }
+ APP.with(|cell| {
+ cell.try_borrow().ok().is_some_and(|app| {
+ app.as_ref()
+ .and_then(|app| app.preview.as_ref())
+ .is_some_and(|picker| picker.choice_at(point).is_some())
+ })
+ })
+}
+
+pub fn preview_click(point: POINT) {
+ with_app_then("selector de ventanas", |app| {
+ let Some(picker) = &mut app.preview else {
+ return Ok(None);
+ };
+ match picker.choice_at(point) {
+ Some(PreviewChoice::Page(page)) => picker.draw(&app.gfx, page)?,
+ Some(PreviewChoice::Window(hwnd)) => {
+ app.close_preview();
+ // SAFETY: Ignore a window that closed while the pointer moved.
+ if unsafe {
+ windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(HWND(hwnd as *mut _)))
+ }
+ .as_bool()
+ {
+ return Ok(app.activating(vec![hwnd]));
+ }
+ }
+ None => {}
+ }
+ Ok(None)
+ });
+}
+
+pub fn preview_scroll(delta: i16) {
+ with_app("selector de ventanas", |app| {
+ if let Some(picker) = &mut app.preview
+ && let Some(page) = picker.next_page(delta)
+ {
+ picker.draw(&app.gfx, page)?;
+ }
+ Ok(())
+ });
+}
+
/// The pointer rested on the top edge with the menu bar hidden.
pub fn menu_bar_edge_rested() {
with_app("barra superior", |app| match &mut app.menubar {
@@ -2749,16 +2982,16 @@ pub fn menu_bar_hover(inside: bool) {
});
}
-pub fn menu_bar_pointer_moved(x: f32) {
+pub fn menu_bar_pointer_moved(x: f32, y: f32) {
with_app("barra superior", |app| match &mut app.menubar {
- Some(bar) => bar.pointer_moved(&app.gfx, x),
+ Some(bar) => bar.pointer_moved(&app.gfx, x, y),
None => Ok(()),
});
}
-pub fn menu_bar_dismiss_usage() {
+pub fn menu_bar_dismiss_island() {
with_app("barra superior", |app| match &mut app.menubar {
- Some(bar) => bar.dismiss_usage(&app.gfx),
+ Some(bar) => bar.dismiss_island(&app.gfx),
None => Ok(()),
});
}
@@ -2989,6 +3222,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 == PREVIEW_TIMER => with_app("selector de ventanas", App::preview_tick),
WM_TIMER if w.0 == HIDE_TIMER => {
// SAFETY: Same as above.
unsafe {
@@ -3233,6 +3467,8 @@ pub fn run() -> Result<()> {
stage: None,
hovering: false,
hovered: None,
+ preview_candidate: None,
+ preview: None,
cursor: 0.0,
amount: Spring::at(0.0, HOVER_OMEGA),
last_frame: Instant::now(),
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index d6a69a6..248215b 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -40,8 +40,9 @@ use windows::{
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_SEMI_BOLD,
DWRITE_MEASURING_MODE_NATURAL, DWRITE_PARAGRAPH_ALIGNMENT_CENTER,
- DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_METRICS, DWriteCreateFactory,
- IDWriteFactory,
+ DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_METRICS, DWRITE_TRIMMING,
+ DWRITE_TRIMMING_GRANULARITY_CHARACTER, DWRITE_WORD_WRAPPING_NO_WRAP,
+ DWriteCreateFactory, IDWriteFactory,
},
Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},
},
@@ -202,18 +203,40 @@ impl Gfx {
})
}
- /// Opaque island silhouette with curved shoulders at the screen edge.
+ /// Opaque island silhouette. The compact controls meet the screen edge
+ /// with curved shoulders, while the popovers have rounded corners.
pub fn island_mask(
&self,
width: f32,
height: f32,
scale: f32,
+ attached: bool,
) -> Result<CompositionSurfaceBrush> {
self.draw(width.ceil() as u32, height.ceil() as u32, |dc| {
- let shoulder = 12.0 * scale;
- let corner = 22.0 * scale;
- // SAFETY: The geometry, sink and brush stay alive through the drawing calls.
+ let shoulder = (12.0 * scale).min(width / 5.0).min(height / 2.0);
+ let corner = (22.0 * scale)
+ .min(width / 2.0 - shoulder)
+ .min(height - shoulder);
+ // SAFETY: The geometries, sink and brush stay alive through the drawing calls.
unsafe {
+ let white = dc.CreateSolidColorBrush(&WHITE, None)?;
+ if !attached {
+ let radius = (18.0 * scale).min(width / 2.0).min(height / 2.0);
+ dc.FillRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: 0.0,
+ top: 0.0,
+ right: width,
+ bottom: height,
+ },
+ radiusX: radius,
+ radiusY: radius,
+ },
+ &white,
+ );
+ return Ok(());
+ }
let shape = dc.GetFactory()?.CreatePathGeometry()?;
let sink = shape.Open()?;
sink.BeginFigure(Vector2 { X: 0.0, Y: 0.0 }, D2D1_FIGURE_BEGIN_FILLED);
@@ -285,7 +308,6 @@ impl Gfx {
});
sink.EndFigure(D2D1_FIGURE_END_CLOSED);
sink.Close()?;
- let white = dc.CreateSolidColorBrush(&WHITE, None)?;
dc.FillGeometry(&shape, &white, None);
}
Ok(())
@@ -584,7 +606,40 @@ impl Gfx {
bold: bool,
ink: Ink,
) -> Result<LabelBrush> {
- let utf16: Vec<u16> = text.encode_utf16().collect();
+ self.draw_text_brush(text, scale, font_size, bold, ink, None)
+ }
+
+ /// Single line, elided to the available physical width.
+ pub fn text_brush_fitted(
+ &self,
+ text: &str,
+ scale: f32,
+ font_size: f32,
+ bold: bool,
+ ink: Ink,
+ max_width: f32,
+ ) -> Result<LabelBrush> {
+ self.draw_text_brush(text, scale, font_size, bold, ink, Some(max_width))
+ }
+
+ fn draw_text_brush(
+ &self,
+ text: &str,
+ scale: f32,
+ font_size: f32,
+ bold: bool,
+ ink: Ink,
+ fitted: Option<f32>,
+ ) -> Result<LabelBrush> {
+ let mut utf16: Vec<u16> = text.encode_utf16().collect();
+ if fitted.is_some() {
+ for unit in &mut utf16 {
+ if matches!(*unit, 9..=13 | 0x85 | 0x2028 | 0x2029) {
+ *unit = u16::from(b' ');
+ }
+ }
+ }
+ let max_width = fitted.map_or(4096.0, |width| width.floor().max(1.0));
let weight = if bold {
DWRITE_FONT_WEIGHT_SEMI_BOLD
} else {
@@ -603,13 +658,27 @@ impl Gfx {
)?;
let layout = self
.dwrite
- .CreateTextLayout(&utf16, &format, 4096.0, 256.0)?;
+ .CreateTextLayout(&utf16, &format, max_width, 256.0)?;
+ if fitted.is_some() {
+ layout.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP)?;
+ let ellipsis = self.dwrite.CreateEllipsisTrimmingSign(&format)?;
+ layout.SetTrimming(
+ &DWRITE_TRIMMING {
+ granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER,
+ ..Default::default()
+ },
+ &ellipsis,
+ )?;
+ }
let mut metrics = DWRITE_TEXT_METRICS::default();
layout.GetMetrics(&mut metrics)?;
(layout, metrics)
};
let (width, height) = (
- metrics.width.ceil().max(1.0),
+ fitted.map_or_else(
+ || metrics.width.ceil().max(1.0),
+ |_| metrics.width.ceil().clamp(1.0, max_width),
+ ),
metrics.height.ceil().max(1.0),
);
let brush = self.draw(width as u32, height as u32, |dc| {
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index f4061a1..7755453 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -17,8 +17,10 @@ mod drop;
mod flight;
mod gfx;
mod guard;
+mod media;
mod menu;
mod menubar;
+mod previews;
mod scene;
mod shell_work;
mod strings;
diff --git a/apps/dock/src/media.rs b/apps/dock/src/media.rs
new file mode 100644
index 0000000..0c22aca
--- /dev/null
+++ b/apps/dock/src/media.rs
@@ -0,0 +1,364 @@
+//! 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 std::{
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicIsize, AtomicU8, Ordering},
+ mpsc::{self, Receiver, SyncSender},
+ },
+ thread,
+ time::Duration,
+};
+use windows::{
+ Foundation::TypedEventHandler,
+ Media::Control::{
+ GlobalSystemMediaTransportControlsSession as Session,
+ GlobalSystemMediaTransportControlsSessionManager as Manager,
+ GlobalSystemMediaTransportControlsSessionPlaybackStatus as Status,
+ },
+ Win32::{
+ Foundation::{HWND, LPARAM, WPARAM},
+ System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize},
+ UI::WindowsAndMessaging::PostMessageW,
+ },
+ core::RuntimeType,
+};
+use windows_future::IAsyncOperation;
+
+const SESSION: u8 = 1;
+const TRACK: u8 = 2;
+const PLAYBACK: u8 = 4;
+const TIMEOUT: Duration = Duration::from_secs(3);
+
+#[derive(Clone, Copy)]
+pub enum Control {
+ Previous,
+ PlayPause,
+ Next,
+}
+
+#[derive(Clone, PartialEq)]
+pub struct Track {
+ generation: u64,
+ pub title: String,
+ pub artist: String,
+ pub playing: bool,
+ pub previous: bool,
+ pub toggle: bool,
+ pub next: bool,
+}
+
+#[derive(Clone)]
+struct Events {
+ wake: SyncSender<()>,
+ dirty: Arc<AtomicU8>,
+}
+
+impl Events {
+ fn mark(&self, flags: u8) {
+ self.dirty.fetch_or(flags, Ordering::Release);
+ let _ = self.wake.try_send(());
+ }
+}
+
+pub struct Watch {
+ window: Arc<AtomicIsize>,
+ state: Arc<Mutex<Option<Track>>>,
+ events: Events,
+ commands: SyncSender<(u64, Control)>,
+}
+
+impl Watch {
+ pub fn start(hwnd: HWND, message: u32) -> Option<Self> {
+ let window = Arc::new(AtomicIsize::new(hwnd.0 as isize));
+ let state = Arc::new(Mutex::new(None));
+ let (wake, inbox) = mpsc::sync_channel(1);
+ let (commands, requests) = mpsc::sync_channel(4);
+ let events = Events {
+ wake,
+ dirty: Arc::new(AtomicU8::new(0)),
+ };
+ {
+ let (window, state, events) = (window.clone(), state.clone(), events.clone());
+ thread::Builder::new()
+ .name("muelle-media".into())
+ .spawn(move || {
+ // SAFETY: This is a new thread. The apartment is kept alive
+ // until all of the worker's WinRT objects have been dropped.
+ if unsafe { RoInitialize(RO_INIT_MULTITHREADED) }.is_ok() {
+ run(&window, message, &state, &events, &inbox, &requests);
+ unsafe { RoUninitialize() };
+ }
+ })
+ .ok()?;
+ }
+ Some(Self {
+ window,
+ state,
+ events,
+ commands,
+ })
+ }
+
+ pub fn snapshot(&self) -> Option<Track> {
+ self.state.lock().ok().and_then(|state| state.clone())
+ }
+
+ pub fn send(&self, track: &Track, control: Control) {
+ if self.commands.try_send((track.generation, control)).is_ok() {
+ self.events.mark(0);
+ }
+ }
+}
+
+impl Drop for Watch {
+ fn drop(&mut self) {
+ // The worker can be inside a media app's asynchronous operation.
+ self.window.store(0, Ordering::Release);
+ self.events.mark(0);
+ }
+}
+
+fn complete<T: RuntimeType + Send>(operation: IAsyncOperation<T>) -> Option<T> {
+ let (send, receive) = mpsc::channel();
+ operation
+ .when(move |result| {
+ let _ = send.send(result);
+ })
+ .ok()?;
+ match receive.recv_timeout(TIMEOUT) {
+ Ok(result) => result.ok(),
+ Err(_) => {
+ let _ = operation.Cancel();
+ None
+ }
+ }
+}
+
+struct Current {
+ session: Session,
+ track_event: Option<i64>,
+ playback_event: Option<i64>,
+ title: String,
+ artist: String,
+}
+
+impl Current {
+ fn new(session: Session, events: &Events) -> Self {
+ let track = events.clone();
+ let playback = events.clone();
+ let track_event = session
+ .MediaPropertiesChanged(&TypedEventHandler::new(move |_, _| {
+ track.mark(TRACK);
+ Ok(())
+ }))
+ .ok();
+ let playback_event = session
+ .PlaybackInfoChanged(&TypedEventHandler::new(move |_, _| {
+ playback.mark(PLAYBACK);
+ Ok(())
+ }))
+ .ok();
+ Self {
+ session,
+ track_event,
+ playback_event,
+ title: String::new(),
+ artist: String::new(),
+ }
+ }
+
+ fn update_track(&mut self) {
+ if let Some(properties) = self
+ .session
+ .TryGetMediaPropertiesAsync()
+ .ok()
+ .and_then(complete)
+ {
+ self.title = properties
+ .Title()
+ .map(|value| value.to_string_lossy())
+ .unwrap_or_default();
+ self.artist = properties
+ .Artist()
+ .map(|value| value.to_string_lossy())
+ .unwrap_or_default();
+ }
+ }
+
+ fn snapshot(&self, generation: u64) -> Option<Track> {
+ let info = self.session.GetPlaybackInfo().ok()?;
+ let status = info.PlaybackStatus().ok()?;
+ if !matches!(status, Status::Playing | Status::Paused | Status::Changing) {
+ return None;
+ }
+ let playing = matches!(status, Status::Playing | Status::Changing);
+ let controls = info.Controls().ok()?;
+ Some(Track {
+ generation,
+ title: self.title.clone(),
+ artist: self.artist.clone(),
+ playing,
+ previous: controls.IsPreviousEnabled().unwrap_or(false),
+ next: controls.IsNextEnabled().unwrap_or(false),
+ toggle: controls.IsPlayPauseToggleEnabled().unwrap_or(false)
+ || if playing {
+ controls.IsPauseEnabled()
+ } else {
+ controls.IsPlayEnabled()
+ }
+ .unwrap_or(false),
+ })
+ }
+
+ fn command(&self, control: Control) {
+ let operation = match control {
+ Control::Previous => self.session.TrySkipPreviousAsync(),
+ Control::Next => self.session.TrySkipNextAsync(),
+ Control::PlayPause => {
+ let Ok(info) = self.session.GetPlaybackInfo() else {
+ return;
+ };
+ if info
+ .Controls()
+ .and_then(|c| c.IsPlayPauseToggleEnabled())
+ .unwrap_or(false)
+ {
+ self.session.TryTogglePlayPauseAsync()
+ } else if info
+ .PlaybackStatus()
+ .is_ok_and(|status| matches!(status, Status::Playing | Status::Changing))
+ {
+ self.session.TryPauseAsync()
+ } else {
+ self.session.TryPlayAsync()
+ }
+ }
+ };
+ if let Ok(operation) = operation {
+ // Keep commands ordered even if the player acknowledges one slowly.
+ let _ = complete(operation);
+ }
+ }
+}
+
+impl Drop for Current {
+ fn drop(&mut self) {
+ if let Some(token) = self.track_event {
+ let _ = self.session.RemoveMediaPropertiesChanged(token);
+ }
+ if let Some(token) = self.playback_event {
+ let _ = self.session.RemovePlaybackInfoChanged(token);
+ }
+ }
+}
+
+fn run(
+ window: &AtomicIsize,
+ message: u32,
+ state: &Mutex<Option<Track>>,
+ events: &Events,
+ inbox: &Receiver<()>,
+ requests: &Receiver<(u64, Control)>,
+) {
+ let Some(manager) = Manager::RequestAsync().ok().and_then(complete) else {
+ return;
+ };
+ let sessions = events.clone();
+ let current_session = events.clone();
+ let sessions_event = manager
+ .SessionsChanged(&TypedEventHandler::new(move |_, _| {
+ sessions.mark(SESSION);
+ Ok(())
+ }))
+ .ok();
+ let current_event = manager
+ .CurrentSessionChanged(&TypedEventHandler::new(move |_, _| {
+ current_session.mark(SESSION);
+ Ok(())
+ }))
+ .ok();
+ let mut current: Option<Current> = None;
+ let mut generation: u64 = 0;
+ events.mark(SESSION);
+ while inbox.recv().is_ok() && window.load(Ordering::Acquire) != 0 {
+ let mut dirty = events.dirty.swap(0, Ordering::AcqRel);
+ if dirty & SESSION != 0 {
+ let session = manager.GetCurrentSession().ok();
+ if session.as_ref() != current.as_ref().map(|active| &active.session) {
+ generation = generation.wrapping_add(1);
+ current = session.map(|session| Current::new(session, events));
+ dirty |= TRACK;
+ }
+ }
+ if dirty != 0 {
+ if dirty & TRACK != 0
+ && let Some(current) = &mut current
+ {
+ current.update_track();
+ }
+ let latest = current
+ .as_ref()
+ .and_then(|current| current.snapshot(generation));
+ if let Ok(mut snapshot) = state.lock()
+ && *snapshot != latest
+ {
+ *snapshot = latest;
+ drop(snapshot);
+ let hwnd = window.load(Ordering::Acquire);
+ if hwnd != 0 {
+ // SAFETY: Posts a notification by value to the bar. The
+ // message holds no reference to the worker or its data.
+ unsafe {
+ let _ =
+ PostMessageW(Some(HWND(hwnd as *mut _)), message, WPARAM(0), LPARAM(0));
+ }
+ }
+ }
+ }
+ for (target, control) in requests.try_iter().take(4) {
+ if window.load(Ordering::Acquire) == 0 {
+ break;
+ }
+ if target == generation
+ && let Some(active) = &current
+ && manager.GetCurrentSession().ok().as_ref() == Some(&active.session)
+ {
+ active.command(control);
+ }
+ }
+ }
+ if let Some(token) = sessions_event {
+ let _ = manager.RemoveSessionsChanged(token);
+ }
+ if let Some(token) = current_event {
+ let _ = manager.RemoveCurrentSessionChanged(token);
+ }
+}
+
+#[cfg(test)]
+mod native_probe {
+ use super::*;
+
+ #[test]
+ #[ignore = "Requires the Windows media session service"]
+ fn windows_media_manager_responds_in_mta() -> windows::core::Result<()> {
+ // SAFETY: Initialize this test thread's apartment and release it
+ // after the manager has been dropped.
+ unsafe {
+ RoInitialize(RO_INIT_MULTITHREADED)?;
+ }
+ let manager = Manager::RequestAsync().ok().and_then(complete);
+ let connected = manager
+ .as_ref()
+ .is_some_and(|manager| manager.GetSessions().is_ok());
+ drop(manager);
+ // SAFETY: Balances this thread's successful initialization.
+ unsafe {
+ RoUninitialize();
+ }
+ assert!(connected);
+ Ok(())
+ }
+}
diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rs
index 70437b9..f3e140f 100644
--- a/apps/dock/src/menu.rs
+++ b/apps/dock/src/menu.rs
@@ -19,7 +19,9 @@ use anyhow::Result;
use windows::{
UI::{
Color,
- Composition::{ContainerVisual, Desktop::DesktopWindowTarget, ShapeVisual, Visual},
+ Composition::{
+ ContainerVisual, Desktop::DesktopWindowTarget, ShapeVisual, Visual, VisualCollection,
+ },
},
Win32::{
Foundation::{COLORREF, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
@@ -222,32 +224,7 @@ impl Popup {
let root = c.CreateContainerVisual()?;
root.SetSize(Vector2::new(width, height))?;
let layers = root.Children()?;
- // As the dock and the menu bar: frosted where Windows allows it,
- // solid otherwise.
- let tint = match (dark, glass) {
- (true, true) => rgba(38, 38, 40, 175),
- (false, true) => rgba(246, 246, 248, 215),
- (true, false) => rgba(44, 44, 46, 255),
- (false, false) => rgba(240, 240, 242, 255),
- };
- if glass {
- add_sprite(
- &layers,
- c.CreateHostBackdropBrush()?.cast()?,
- 0.0,
- 0.0,
- width,
- height,
- )?;
- }
- add_sprite(
- &layers,
- c.CreateColorBrushWithColor(tint)?.cast()?,
- 0.0,
- 0.0,
- width,
- height,
- )?;
+ draw_popup_background(&layers, dark, glass, width, height)?;
let selection = c.CreateShapeVisual()?;
let selection_shape = c.CreateRoundedRectangleGeometry()?;
@@ -659,35 +636,79 @@ fn create_window(dark: bool) -> Result<HWND> {
Some(instance.into()),
None,
)?;
- // Without this, the system backdrop brush appears black.
- let enable = BOOL::from(true);
+ apply_popup_frame(hwnd, dark);
+ Ok(hwnd)
+ }
+}
+
+/// Applies the native frame used by dock popups. Returns whether DWM
+/// accepted the corner preference so callers can provide a fallback.
+pub(crate) fn apply_popup_frame(hwnd: HWND, dark: bool) -> bool {
+ let enable = BOOL::from(true);
+ let round = DWMWCP_ROUND;
+ let border = if dark {
+ COLORREF(0x0058_5654)
+ } else {
+ COLORREF(0x00C8_C6C4)
+ };
+ // SAFETY: Attribute values have the expected type and size; hwnd is a
+ // live window owned by the caller. Older systems can reject attributes.
+ unsafe {
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_USE_HOSTBACKDROPBRUSH,
(&raw const enable).cast(),
- size_of::<BOOL>() as u32,
+ size_of_val(&enable) as u32,
);
- // Rounded with a hairline border on Windows 11; ignored on Windows 10.
- let round = DWMWCP_ROUND;
- let _ = DwmSetWindowAttribute(
+ let rounded = DwmSetWindowAttribute(
hwnd,
DWMWA_WINDOW_CORNER_PREFERENCE,
(&raw const round).cast(),
size_of_val(&round) as u32,
- );
- let border = if dark {
- COLORREF(0x0058_5654)
- } else {
- COLORREF(0x00C8_C6C4)
- };
+ )
+ .is_ok();
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_BORDER_COLOR,
(&raw const border).cast(),
- size_of::<COLORREF>() as u32,
+ size_of_val(&border) as u32,
);
- Ok(hwnd)
+ rounded
+ }
+}
+
+pub(crate) fn draw_popup_background(
+ layers: &VisualCollection,
+ dark: bool,
+ glass: bool,
+ width: f32,
+ height: f32,
+) -> Result<()> {
+ let tint = match (dark, glass) {
+ (true, true) => rgba(38, 38, 40, 175),
+ (false, true) => rgba(246, 246, 248, 215),
+ (true, false) => rgba(44, 44, 46, 255),
+ (false, false) => rgba(240, 240, 242, 255),
+ };
+ let compositor = layers.Compositor()?;
+ if glass {
+ add_sprite(
+ layers,
+ compositor.CreateHostBackdropBrush()?.cast()?,
+ 0.0,
+ 0.0,
+ width,
+ height,
+ )?;
}
+ add_sprite(
+ layers,
+ compositor.CreateColorBrushWithColor(tint)?.cast()?,
+ 0.0,
+ 0.0,
+ width,
+ height,
+ )
}
unsafe extern "system" fn menu_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index 2296906..e3510bc 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -21,7 +21,7 @@ use muelle_shell::{
appbar::{AppBar, Edge},
launcher,
status::{self, AudioWatch, Network, NetworkWatch, Privacy, TaskbarButtons, Volume},
- system::{self, Battery, Monitor},
+ system::{self, Battery},
watch::RegistryWatch,
};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering};
@@ -59,6 +59,7 @@ use windows_numerics::{Vector2, Vector3};
use crate::{
app,
gfx::{Gfx, Ink, LabelBrush},
+ media::{self, Control as MediaControl, Track},
strings,
usage::{
self, ActiveProviders, Monitor as UsageMonitor, Provider, ProviderUsage, Snapshot, State,
@@ -80,6 +81,7 @@ const REVEAL_TIMER: usize = 2;
/// Posted by the edge hook when the pointer reaches or leaves the top edge.
const EDGE_ENTER: u32 = WM_APP + 26;
const EDGE_LEAVE: u32 = WM_APP + 27;
+const MEDIA_CHANGED: u32 = WM_APP + 28;
const CLOCK_TIMER: usize = 1;
const ISLAND_SINGLE_WIDTH: f32 = 145.0;
@@ -95,7 +97,7 @@ 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;
const USAGE_CHANGED: u32 = WM_APP + 23;
-const DISMISS_USAGE: u32 = WM_APP + 24;
+const DISMISS_ISLAND: u32 = WM_APP + 24;
/// Posted when an app starts or stops using the microphone or camera.
const PRIVACY_CHANGED: u32 = WM_APP + 25;
/// `wParam` of WM_SETTINGCHANGE when the work area changes, which every
@@ -103,14 +105,15 @@ const PRIVACY_CHANGED: u32 = WM_APP + 25;
const SPI_SETWORKAREA: usize = 0x002F;
/// A `TICK` is already posted.
static TICK_PENDING: AtomicBool = AtomicBool::new(false);
-static ISLAND_LEFT: AtomicI32 = AtomicI32::new(0);
-static ISLAND_RIGHT: AtomicI32 = AtomicI32::new(0);
+static TRIGGERS_LEFT: AtomicI32 = AtomicI32::new(0);
+static TRIGGERS_RIGHT: AtomicI32 = AtomicI32::new(0);
+static PANEL_LEFT: AtomicI32 = AtomicI32::new(0);
+static PANEL_RIGHT: AtomicI32 = AtomicI32::new(0);
static BAR_TOP: AtomicI32 = AtomicI32::new(0);
static BAR_BOTTOM: AtomicI32 = AtomicI32::new(0);
-static HEADER_BOTTOM: AtomicI32 = AtomicI32::new(0);
static PANEL_BOTTOM: AtomicI32 = AtomicI32::new(0);
-/// The hook exists only while the usage panel is open.
-static USAGE_HOOK_WINDOW: AtomicIsize = AtomicIsize::new(0);
+/// The hook exists only while the island is expanded.
+static ISLAND_HOOK_WINDOW: AtomicIsize = AtomicIsize::new(0);
/// The hidden bar's window, for the edge hook; 0 while no hook is installed.
static EDGE_HOOK_WINDOW: AtomicIsize = AtomicIsize::new(0);
/// The row of the top edge and its span, in screen pixels.
@@ -177,8 +180,56 @@ struct Look {
usage: Snapshot,
usage_enabled: bool,
active_providers: ActiveProviders,
- expanded: bool,
+ panel: Option<Island>,
usage_refreshing: bool,
+ track: Option<Track>,
+}
+
+impl Look {
+ fn panel_height(&self) -> f32 {
+ match self.panel {
+ Some(Island::Music) => 148.0,
+ Some(Island::Usage) => 74.0 + self.active_providers.count() as f32 * ISLAND_ROW_HEIGHT,
+ None => 0.0,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Island {
+ Music,
+ Usage,
+}
+
+#[derive(Clone, Copy, Default)]
+struct Span {
+ left: f32,
+ right: f32,
+}
+
+impl Span {
+ fn width(self) -> f32 {
+ self.right - self.left
+ }
+}
+
+#[derive(Clone, Copy)]
+enum IslandAction {
+ Toggle(Island),
+ Media(MediaControl),
+ Refresh,
+}
+
+struct IslandHit {
+ bounds: (f32, f32, f32, f32),
+ action: IslandAction,
+}
+
+impl IslandHit {
+ fn at(&self, x: f32, y: f32) -> bool {
+ let (left, top, right, bottom) = self.bounds;
+ x >= left && x < right && y >= top && y < bottom
+ }
}
pub struct MenuBar {
@@ -198,11 +249,12 @@ pub struct MenuBar {
bounds: RECT,
status: Status,
usage: Option<UsageMonitor>,
- expanded: bool,
+ media: Option<media::Watch>,
+ panel: Option<Island>,
visual_height: i32,
- island_left: f32,
- island_right: f32,
- refresh_button: Option<(f32, f32, f32, f32)>,
+ triggers_span: Span,
+ panel_span: Span,
+ island_hits: Vec<IslandHit>,
outside_click_hook: Option<HHOOK>,
/// Watches the top edge while the bar auto-hides.
edge_watch: Option<EdgeWatch>,
@@ -225,20 +277,17 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
}
WM_MOUSEMOVE => {
let x = (l.0 & 0xFFFF) as i16;
- app::menu_bar_pointer_moved(f32::from(x));
+ let y = (l.0 >> 16) as i16;
+ app::menu_bar_pointer_moved(f32::from(x), f32::from(y));
}
WM_MOUSELEAVE => app::menu_bar_hover(false),
- DISMISS_USAGE => app::menu_bar_dismiss_usage(),
+ DISMISS_ISLAND => app::menu_bar_dismiss_island(),
PRIVACY_CHANGED => app::menu_bar_privacy_changed(),
+ MEDIA_CHANGED => app::menu_bar_media_changed(),
WM_SETCURSOR => {
let mut point = POINT::default();
// SAFETY: The point is a valid output for the current pointer location.
- if unsafe { GetCursorPos(&mut point) }.is_ok()
- && point.x >= ISLAND_LEFT.load(Ordering::Relaxed)
- && point.x < ISLAND_RIGHT.load(Ordering::Relaxed)
- && point.y >= BAR_TOP.load(Ordering::Relaxed)
- && point.y < HEADER_BOTTOM.load(Ordering::Relaxed)
- {
+ if unsafe { GetCursorPos(&mut point) }.is_ok() && app::menu_bar_has_action(point) {
// SAFETY: The stock hand cursor is owned by Windows.
if let Ok(hand) = unsafe { LoadCursorW(None, IDC_HAND) } {
unsafe { SetCursor(Some(hand)) };
@@ -252,8 +301,8 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
let y = (l.0 >> 16) as i16 as i32;
if y >= BAR_BOTTOM.load(Ordering::Relaxed)
&& y < PANEL_BOTTOM.load(Ordering::Relaxed)
- && (x < ISLAND_LEFT.load(Ordering::Relaxed)
- || x >= ISLAND_RIGHT.load(Ordering::Relaxed))
+ && (x < PANEL_LEFT.load(Ordering::Relaxed)
+ || x >= PANEL_RIGHT.load(Ordering::Relaxed))
{
return LRESULT(-1);
}
@@ -413,18 +462,22 @@ unsafe extern "system" fn outside_click_proc(code: i32, w: WPARAM, l: LPARAM) ->
{
// SAFETY: Windows provides an MSLLHOOKSTRUCT for mouse hook actions.
let point = unsafe { (*(l.0 as *const MSLLHOOKSTRUCT)).pt };
- if point.x < ISLAND_LEFT.load(Ordering::Relaxed)
- || point.x >= ISLAND_RIGHT.load(Ordering::Relaxed)
- || point.y < BAR_TOP.load(Ordering::Relaxed)
- || point.y >= PANEL_BOTTOM.load(Ordering::Relaxed)
- {
- let window = USAGE_HOOK_WINDOW.load(Ordering::Relaxed);
+ let in_triggers = point.y >= BAR_TOP.load(Ordering::Relaxed)
+ && point.y < BAR_BOTTOM.load(Ordering::Relaxed)
+ && point.x >= TRIGGERS_LEFT.load(Ordering::Relaxed)
+ && point.x < TRIGGERS_RIGHT.load(Ordering::Relaxed);
+ let in_panel = point.y >= BAR_BOTTOM.load(Ordering::Relaxed)
+ && point.y < PANEL_BOTTOM.load(Ordering::Relaxed)
+ && point.x >= PANEL_LEFT.load(Ordering::Relaxed)
+ && point.x < PANEL_RIGHT.load(Ordering::Relaxed);
+ if !in_triggers && !in_panel {
+ let window = ISLAND_HOOK_WINDOW.load(Ordering::Relaxed);
if window != 0 {
// SAFETY: The window remains live until the hook is removed in Drop.
unsafe {
let _ = PostMessageW(
Some(HWND(window as *mut _)),
- DISMISS_USAGE,
+ DISMISS_ISLAND,
WPARAM(0),
LPARAM(0),
);
@@ -436,7 +489,7 @@ unsafe extern "system" fn outside_click_proc(code: i32, w: WPARAM, l: LPARAM) ->
unsafe { CallNextHookEx(None, code, w, l) }
}
-fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
+pub(crate) fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
Color {
A: a,
R: r,
@@ -445,7 +498,7 @@ fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
}
}
-fn add_visual(
+pub(crate) fn add_visual(
compositor: &Compositor,
layers: &VisualCollection,
brush: &CompositionBrush,
@@ -473,7 +526,7 @@ fn add_visual(
clippy::too_many_arguments,
reason = "A rounded shape needs its rectangle, radius and two colors"
)]
-fn add_rounded_box(
+pub(crate) fn add_rounded_box(
compositor: &Compositor,
layers: &VisualCollection,
x: f32,
@@ -918,11 +971,12 @@ impl MenuBar {
privacy: Privacy::default(),
},
usage: usage_enabled.then(|| UsageMonitor::new(hwnd.0 as isize, USAGE_CHANGED)),
- expanded: false,
+ media: media::Watch::start(hwnd, MEDIA_CHANGED),
+ panel: None,
visual_height: 0,
- island_left: 0.0,
- island_right: 0.0,
- refresh_button: None,
+ triggers_span: Span::default(),
+ panel_span: Span::default(),
+ island_hits: Vec::new(),
outside_click_hook: None,
edge_watch: None,
_network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),
@@ -967,14 +1021,12 @@ impl MenuBar {
return Ok(());
}
self.usage = enabled.then(|| UsageMonitor::new(self.hwnd.0 as isize, USAGE_CHANGED));
- self.expanded = false;
self.refresh(gfx)
}
/// The pointer reached the top edge or left the bar.
pub fn hover(&mut self, gfx: &Gfx, inside: bool) -> Result<()> {
- if !inside && self.expanded {
- self.expanded = false;
+ if !inside && self.panel.take().is_some() {
self.refresh(gfx)?;
}
if !self.auto_hide || self.revealed == inside {
@@ -996,16 +1048,20 @@ impl MenuBar {
}
/// Leaving the island sideways still stays inside the full-width bar window.
- pub fn pointer_moved(&mut self, gfx: &Gfx, x: f32) -> Result<()> {
- if self.expanded && (x < self.island_left || x >= self.island_right) {
- self.dismiss_usage(gfx)?;
+ pub fn pointer_moved(&mut self, gfx: &Gfx, x: f32, y: f32) -> Result<()> {
+ let span = if y < (self.bounds.bottom - self.bounds.top) as f32 {
+ self.triggers_span
+ } else {
+ self.panel_span
+ };
+ if self.panel.is_some() && (x < span.left || x >= span.right) {
+ self.dismiss_island(gfx)?;
}
self.hover(gfx, true)
}
- pub fn dismiss_usage(&mut self, gfx: &Gfx) -> Result<()> {
- if self.expanded {
- self.expanded = false;
+ pub fn dismiss_island(&mut self, gfx: &Gfx) -> Result<()> {
+ if self.panel.take().is_some() {
self.refresh(gfx)?;
}
Ok(())
@@ -1124,7 +1180,8 @@ impl MenuBar {
}
fn sync_outside_click_hook(&mut self) -> Result<()> {
- let needed = self.expanded && self.visible && (!self.auto_hide || self.revealed);
+ let needed =
+ self.panel_span.width() > 0.0 && self.visible && (!self.auto_hide || self.revealed);
if needed && self.outside_click_hook.is_none() {
// SAFETY: This process owns the hook procedure and installs the hook
// only while the panel is visible.
@@ -1137,13 +1194,13 @@ impl MenuBar {
0,
)?
};
- USAGE_HOOK_WINDOW.store(self.hwnd.0 as isize, Ordering::Relaxed);
+ ISLAND_HOOK_WINDOW.store(self.hwnd.0 as isize, Ordering::Relaxed);
self.outside_click_hook = Some(hook);
} else if !needed && let Some(hook) = self.outside_click_hook {
// SAFETY: This hook was installed by this MenuBar.
unsafe { UnhookWindowsHookEx(hook)? };
self.outside_click_hook = None;
- USAGE_HOOK_WINDOW.store(0, Ordering::Relaxed);
+ ISLAND_HOOK_WINDOW.store(0, Ordering::Relaxed);
}
Ok(())
}
@@ -1189,48 +1246,41 @@ impl MenuBar {
}
pub fn click(&mut self, gfx: &Gfx, x: f32, y: f32) -> Result<()> {
- if x >= self.island_left && x < self.island_right {
- let bar_height = self.bounds.bottom as f32 - self.bounds.top as f32;
- if self.expanded
- && self
- .refresh_button
- .is_some_and(|(left, top, right, bottom)| {
- x >= left && x < right && y >= top && y < bottom
- })
- {
- if let Some(usage) = &mut self.usage {
- usage.refresh(true);
+ if let Some(hit) = self.island_hits.iter().find(|hit| hit.at(x, y)) {
+ match hit.action {
+ IslandAction::Toggle(island) => {
+ self.panel = toggle_panel(self.panel, island);
+ if self.panel.is_some() {
+ let mut track = TRACKMOUSEEVENT {
+ cbSize: size_of::<TRACKMOUSEEVENT>() as u32,
+ dwFlags: TME_LEAVE,
+ hwndTrack: self.hwnd,
+ dwHoverTime: 0,
+ };
+ // SAFETY: `track` describes our live window.
+ unsafe { TrackMouseEvent(&mut track)? };
+ }
}
- return self.refresh(gfx);
- }
- let header_bottom = if self.expanded {
- 49.0 * self.look.as_ref().map_or(1.0, |look| look.scale)
- } else {
- bar_height
- };
- if y < header_bottom {
- self.expanded = !self.expanded;
- if self.expanded {
+ IslandAction::Refresh => {
if let Some(usage) = &mut self.usage {
- usage.refresh(false);
+ usage.refresh(true);
}
- let mut track = TRACKMOUSEEVENT {
- cbSize: size_of::<TRACKMOUSEEVENT>() as u32,
- dwFlags: TME_LEAVE,
- hwndTrack: self.hwnd,
- dwHoverTime: 0,
- };
- // SAFETY: `track` describes our live window.
- unsafe { TrackMouseEvent(&mut track)? };
}
- return self.refresh(gfx);
+ IslandAction::Media(control) => {
+ if let Some(media) = &self.media
+ && let Some(track) = self.look.as_ref().and_then(|look| look.track.as_ref())
+ {
+ media.send(track, control);
+ }
+ return Ok(());
+ }
}
- return Ok(());
+ return self.refresh(gfx);
}
- if self.expanded {
- self.expanded = false;
- self.refresh(gfx)?;
+ if y >= (self.bounds.bottom - self.bounds.top) as f32 {
+ return Ok(());
}
+ self.dismiss_island(gfx)?;
let hit = self
.zones
.iter()
@@ -1263,6 +1313,12 @@ impl MenuBar {
Ok(())
}
+ pub fn has_island_action(&self, point: POINT) -> bool {
+ let x = (point.x - self.bounds.left) as f32;
+ let y = (point.y - self.bounds.top) as f32;
+ self.island_hits.iter().any(|hit| hit.at(x, y))
+ }
+
/// Redraws the bar if anything it shows has changed.
pub fn refresh(&mut self, gfx: &Gfx) -> Result<()> {
let Some(monitor) = system::primary_monitor() else {
@@ -1273,8 +1329,9 @@ impl MenuBar {
} else {
ActiveProviders::default()
};
+ let track = self.media.as_ref().and_then(media::Watch::snapshot);
+ self.panel = available_panel(self.panel, track.is_some(), active_providers.any());
if !active_providers.any() {
- self.expanded = false;
if let Some(usage) = &mut self.usage {
usage.mark_inactive();
}
@@ -1300,28 +1357,40 @@ impl MenuBar {
.map_or_else(Snapshot::default, UsageMonitor::snapshot),
usage_enabled: self.usage.is_some() && active_providers.any(),
active_providers,
- expanded: self.expanded,
+ panel: self.panel,
usage_refreshing: self.usage.as_ref().is_some_and(UsageMonitor::is_refreshing),
+ track,
+ };
+ self.apply_look(gfx, look)
+ }
+
+ /// Track changes only need to update the contents of the island.
+ pub fn media_changed(&mut self, gfx: &Gfx) -> Result<()> {
+ let Some(mut look) = self.look.clone() else {
+ return self.refresh(gfx);
};
+ look.track = self.media.as_ref().and_then(media::Watch::snapshot);
+ self.panel = available_panel(self.panel, look.track.is_some(), look.usage_enabled);
+ look.panel = self.panel;
+ self.apply_look(gfx, look)
+ }
+
+ fn apply_look(&mut self, gfx: &Gfx, look: Look) -> Result<()> {
if self.look.as_ref() == Some(&look) {
return Ok(());
}
- self.build(gfx, &monitor, &look)?;
+ self.build(gfx, &look)?;
self.look = Some(look);
Ok(())
}
- fn build(&mut self, gfx: &Gfx, monitor: &Monitor, look: &Look) -> Result<()> {
+ fn build(&mut self, gfx: &Gfx, look: &Look) -> Result<()> {
let c = &gfx.compositor;
let scale = look.scale;
let px = |logical: f32| (logical * scale).round();
- let screen = monitor.screen;
+ let screen = look.screen;
let (width, height) = ((screen.right - screen.left) as f32, px(HEIGHT));
- let visual_height = if look.expanded {
- px(74.0 + look.active_providers.count() as f32 * ISLAND_ROW_HEIGHT)
- } else {
- height
- };
+ let visual_height = height + px(look.panel_height());
let ink = if look.light { Ink::Dark } else { Ink::Light };
let root = c.CreateContainerVisual()?;
@@ -1377,7 +1446,14 @@ impl MenuBar {
self.zones.clear();
let mut left_end = px(SIDE_MARGIN);
if !look.app_name.is_empty() {
- let name = gfx.text_brush(&look.app_name, scale, true, ink)?;
+ let name = gfx.text_brush_fitted(
+ &look.app_name,
+ scale,
+ 13.0,
+ true,
+ ink,
+ px(220.0).min(width * 0.22),
+ )?;
place(&layers, &name, px(SIDE_MARGIN))?;
left_end += name.width;
}
@@ -1454,41 +1530,44 @@ impl MenuBar {
right = left - px(ITEM_GAP);
}
- if look.usage_enabled {
- self.draw_island(gfx, look, &layers, width, height, left_end, right)?;
- } else {
- self.island_left = 0.0;
- self.island_right = 0.0;
- self.refresh_button = None;
- }
+ self.island_hits.clear();
+ self.triggers_span = Span::default();
+ self.panel_span = Span::default();
+ self.draw_island(gfx, look, &layers, width, height, left_end, right)?;
self.target.SetRoot(&root)?;
self.root = Some(root);
- self.visual_height = visual_height as i32;
+ self.visual_height = if self.panel_span.width() > 0.0 {
+ visual_height
+ } else {
+ height
+ } as i32;
self.bounds = RECT {
bottom: screen.top + height as i32,
..screen
};
- ISLAND_LEFT.store(screen.left + self.island_left as i32, Ordering::Relaxed);
- ISLAND_RIGHT.store(screen.left + self.island_right as i32, Ordering::Relaxed);
- BAR_TOP.store(screen.top, Ordering::Relaxed);
- BAR_BOTTOM.store(screen.top + height as i32, Ordering::Relaxed);
- HEADER_BOTTOM.store(
- screen.top
- + if look.expanded {
- px(49.0) as i32
- } else {
- height as i32
- },
+ TRIGGERS_LEFT.store(
+ screen.left + self.triggers_span.left as i32,
+ Ordering::Relaxed,
+ );
+ TRIGGERS_RIGHT.store(
+ screen.left + self.triggers_span.right as i32,
Ordering::Relaxed,
);
+ PANEL_LEFT.store(screen.left + self.panel_span.left as i32, Ordering::Relaxed);
+ PANEL_RIGHT.store(
+ screen.left + self.panel_span.right as i32,
+ Ordering::Relaxed,
+ );
+ BAR_TOP.store(screen.top, Ordering::Relaxed);
+ BAR_BOTTOM.store(screen.top + height as i32, Ordering::Relaxed);
PANEL_BOTTOM.store(screen.top + self.visual_height, Ordering::Relaxed);
self.place()
}
#[expect(
clippy::too_many_arguments,
- reason = "The island receives the measured bar bounds from the current layout"
+ reason = "The island is laid out between the measured bar items"
)]
fn draw_island(
&mut self,
@@ -1500,296 +1579,794 @@ impl MenuBar {
left_end: f32,
right_start: f32,
) -> Result<()> {
+ let px = |logical: f32| (logical * look.scale).round();
+ let triggers = trigger_layout(
+ Span {
+ left: left_end + px(8.0),
+ right: right_start - px(8.0),
+ },
+ width / 2.0,
+ look.scale,
+ look.track.is_some(),
+ look.active_providers.count(),
+ );
+ let [(_, music), (_, usage)] = triggers;
+ let (Some(first), Some(last)) = (music.or(usage), usage.or(music)) else {
+ return Ok(());
+ };
+ self.triggers_span = Span {
+ left: first.left,
+ right: last.right,
+ };
+ let geometry = IslandGeometry::new(self.triggers_span, 0.0, look);
+ let compact = island_surface(gfx, look, layers, geometry, bar_height)?;
+ let divider = music
+ .zip(usage)
+ .map(|(music, usage)| ((music.right + usage.left) / 2.0).round());
let c = &gfx.compositor;
- let scale = look.scale;
- let px = |logical: f32| (logical * scale).round();
- let requested = px(if look.expanded {
- ISLAND_EXPANDED_WIDTH
- } else if look.active_providers.count() == 1 {
- ISLAND_SINGLE_WIDTH
+ if let Some(x) = divider {
+ add_visual(
+ c,
+ &compact,
+ &c.CreateColorBrushWithColor(geometry.border())?.cast()?,
+ x - self.triggers_span.left,
+ px(7.0),
+ px(1.0).max(1.0),
+ bar_height - 2.0 * px(7.0),
+ )?;
+ }
+ let providers = island_providers(look);
+ for (kind, span) in triggers {
+ let Some(span) = span else {
+ continue;
+ };
+ let geometry = IslandGeometry::new(span, 0.0, look);
+ let segment = c.CreateContainerVisual()?;
+ segment.SetSize(Vector2::new(geometry.width, bar_height))?;
+ segment.SetOffset(Vector3::new(span.left - self.triggers_span.left, 0.0, 0.0))?;
+ let content = segment.Children()?;
+ compact.InsertAtTop(&segment)?;
+ match kind {
+ Island::Music => {
+ if let Some(track) = &look.track {
+ draw_compact_player(
+ gfx,
+ &content,
+ geometry,
+ geometry.width,
+ bar_height,
+ track,
+ )?;
+ }
+ }
+ Island::Usage => {
+ draw_compact_usage(gfx, &content, geometry, bar_height, &providers)?
+ }
+ }
+ let (left, right) = match kind {
+ Island::Music => (span.left, divider.unwrap_or(span.right)),
+ Island::Usage => (divider.unwrap_or(span.left), span.right),
+ };
+ self.island_hits.push(IslandHit {
+ bounds: (left, 0.0, right, bar_height),
+ action: IslandAction::Toggle(kind),
+ });
+ if look.panel != Some(kind) {
+ continue;
+ }
+ self.panel_span = panel_span(
+ span,
+ width,
+ px(match kind {
+ Island::Music => 360.0,
+ Island::Usage => ISLAND_EXPANDED_WIDTH,
+ }),
+ );
+ let geometry = IslandGeometry::new(self.panel_span, bar_height, look);
+ let height = px(look.panel_height());
+ let content = island_surface(gfx, look, layers, geometry, height)?;
+ match kind {
+ Island::Music => {
+ if let Some(track) = &look.track {
+ self.draw_player(gfx, &content, geometry, track)?;
+ }
+ }
+ Island::Usage => {
+ self.draw_usage_panel(gfx, &content, geometry, height, look, &providers)?
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn draw_usage_panel(
+ &mut self,
+ gfx: &Gfx,
+ content: &VisualCollection,
+ geometry: IslandGeometry,
+ island_height: f32,
+ look: &Look,
+ providers: &[IslandProvider<'_>],
+ ) -> Result<()> {
+ let c = &gfx.compositor;
+ let scale = geometry.scale;
+ let px = |v| geometry.px(v);
+ let island_width = geometry.width;
+ let ink = geometry.ink();
+ let title = strings::text();
+ add_panel_text(
+ gfx,
+ content,
+ title.usage_title,
+ px(28.0),
+ px(15.0),
+ scale,
+ 13.0,
+ true,
+ ink,
+ 0.94,
+ )?;
+ let button_text = if look.usage_refreshing {
+ title.usage_refreshing
} else {
- 134.0 * look.active_providers.count() as f32
- });
- let left_limit = left_end + px(8.0);
- let usable = (right_start - left_limit - px(8.0)).max(px(145.0));
- let island_width = requested.min(usable);
- let island_left = ((width - island_width) / 2.0)
- .max(left_limit)
- .min((right_start - island_width - px(8.0)).max(left_limit));
- let island_height = if look.expanded {
- px(74.0 + look.active_providers.count() as f32 * ISLAND_ROW_HEIGHT)
+ title.usage_refresh
+ };
+ let button_label = gfx.text_brush_sized(button_text, scale, 11.5, true, ink)?;
+ let button_width = button_label.width + px(20.0);
+ let button_height = px(27.0);
+ let button_left = island_width - px(23.0) - button_width;
+ let button_top = px(8.0);
+ add_rounded_box(
+ c,
+ content,
+ button_left,
+ button_top,
+ button_width,
+ button_height,
+ px(13.5),
+ if look.light {
+ rgba(28, 51, 79, 18)
+ } else {
+ rgba(235, 242, 252, 26)
+ },
+ Some(if look.light {
+ rgba(41, 62, 86, 36)
+ } else {
+ rgba(226, 237, 251, 43)
+ }),
+ )?;
+ add_visual(
+ c,
+ content,
+ &button_label.brush.cast()?,
+ button_left + px(10.0),
+ button_top + (button_height - button_label.height) / 2.0,
+ button_label.width,
+ button_label.height,
+ )?;
+ self.island_hits.push(geometry.hit(
+ button_left,
+ button_top,
+ button_width,
+ button_height,
+ IslandAction::Refresh,
+ ));
+ for (index, (provider, usage, accent)) in providers.iter().enumerate() {
+ draw_usage_card(
+ gfx,
+ content,
+ *provider,
+ usage,
+ *accent,
+ scale,
+ look.light,
+ island_width,
+ px(53.0 + index as f32 * ISLAND_ROW_HEIGHT),
+ )?;
+ }
+ let newest_age = providers
+ .iter()
+ .filter_map(|provider| provider.1.age_minutes())
+ .min();
+ if let Some(minutes) = newest_age {
+ let status = format!("{} {minutes} min", title.usage_updated);
+ let label = gfx.text_brush_sized(&status, scale, 11.0, false, ink)?;
+ add_visual(
+ c,
+ content,
+ &label.brush.cast()?,
+ (island_width - label.width) / 2.0,
+ island_height - px(21.0),
+ label.width,
+ label.height,
+ )?
+ .SetOpacity(0.53)?;
+ }
+ Ok(())
+ }
+
+ fn draw_player(
+ &mut self,
+ gfx: &Gfx,
+ layers: &VisualCollection,
+ geometry: IslandGeometry,
+ track: &Track,
+ ) -> Result<()> {
+ let px = |v| geometry.px(v);
+ let c = &gfx.compositor;
+ let ink = geometry.ink();
+ add_panel_text(
+ gfx,
+ layers,
+ strings::text().media_title,
+ px(26.0),
+ px(15.0),
+ geometry.scale,
+ 12.5,
+ true,
+ ink,
+ 0.88,
+ )?;
+ let chevron = gfx.glyph_brush(&[('', 0.72)], geometry.scale, ink)?;
+ let x = geometry.width - px(22.0) - chevron.width;
+ add_visual(
+ c,
+ layers,
+ &chevron.brush.cast()?,
+ x,
+ (px(46.0) - chevron.height) / 2.0,
+ chevron.width,
+ chevron.height,
+ )?;
+ self.island_hits.push(geometry.hit(
+ x - px(6.0),
+ px(7.0),
+ chevron.width + px(12.0),
+ px(32.0),
+ IslandAction::Toggle(Island::Music),
+ ));
+ add_rounded_box(
+ c,
+ layers,
+ px(14.0),
+ px(45.0),
+ geometry.width - px(28.0),
+ px(91.0),
+ px(16.0),
+ geometry.fill(),
+ Some(geometry.border()),
+ )?;
+ let tile = px(34.0);
+ add_rounded_box(
+ c,
+ layers,
+ px(25.0),
+ px(54.0),
+ tile,
+ tile,
+ px(10.0),
+ geometry.selection(),
+ 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(54.0) + (tile - note.height) / 2.0,
+ note.width,
+ note.height,
+ )?;
+ let available = geometry.width - px(91.0);
+ let title = gfx.text_brush_fitted(
+ track_title(track),
+ geometry.scale,
+ 13.0,
+ true,
+ ink,
+ available,
+ )?;
+ let title_y = if track.artist.trim().is_empty() {
+ px(71.0) - title.height / 2.0
} else {
- bar_height
+ px(55.0)
};
- self.island_left = island_left;
- self.island_right = island_left + island_width;
+ add_visual(
+ c,
+ layers,
+ &title.brush.cast()?,
+ px(69.0),
+ title_y,
+ title.width,
+ title.height,
+ )?;
+ if !track.artist.trim().is_empty() {
+ let artist =
+ gfx.text_brush_fitted(&track.artist, geometry.scale, 11.0, false, ink, available)?;
+ add_visual(
+ c,
+ layers,
+ &artist.brush.cast()?,
+ px(69.0),
+ px(73.0),
+ artist.width,
+ artist.height,
+ )?
+ .SetOpacity(0.69)?;
+ }
+ let center = geometry.width / 2.0;
+ for (control, glyph, enabled, offset) in [
+ (MediaControl::Previous, '\u{E892}', track.previous, -44.0),
+ (
+ MediaControl::PlayPause,
+ if track.playing {
+ '\u{E769}'
+ } else {
+ '\u{E768}'
+ },
+ track.toggle,
+ 0.0,
+ ),
+ (MediaControl::Next, '\u{E893}', track.next, 44.0),
+ ] {
+ let size = px(34.0);
+ let x = center + px(offset) - size / 2.0;
+ let y = px(96.0);
+ let main = matches!(control, MediaControl::PlayPause);
+ if main {
+ add_rounded_box(
+ c,
+ layers,
+ x,
+ y,
+ size,
+ size,
+ size / 2.0,
+ geometry.selection(),
+ Some(geometry.border()),
+ )?;
+ }
+ let symbol = gfx.glyph_brush(&[(glyph, 1.0)], geometry.scale, ink)?;
+ add_visual(
+ c,
+ layers,
+ &symbol.brush.cast()?,
+ x + (size - symbol.width) / 2.0,
+ y + (size - symbol.height) / 2.0,
+ symbol.width,
+ symbol.height,
+ )?
+ .SetOpacity(if enabled { 1.0 } else { 0.30 })?;
+ if enabled {
+ self.island_hits
+ .push(geometry.hit(x, y, size, size, IslandAction::Media(control)));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Copy)]
+struct IslandGeometry {
+ left: f32,
+ top: f32,
+ width: f32,
+ scale: f32,
+ light: bool,
+}
+
+impl IslandGeometry {
+ fn new(span: Span, top: f32, look: &Look) -> Self {
+ Self {
+ left: span.left,
+ top,
+ width: span.width(),
+ scale: look.scale,
+ light: look.light,
+ }
+ }
+
+ fn hit(self, x: f32, y: f32, width: f32, height: f32, action: IslandAction) -> IslandHit {
+ let left = self.left + x;
+ let top = self.top + y;
+ IslandHit {
+ bounds: (left, top, left + width, top + height),
+ action,
+ }
+ }
+
+ fn px(self, logical: f32) -> f32 {
+ (logical * self.scale).round()
+ }
+ fn ink(self) -> Ink {
+ if self.light { Ink::Dark } else { Ink::Light }
+ }
+ fn fill(self) -> Color {
+ if self.light {
+ rgba(35, 63, 96, 15)
+ } else {
+ rgba(223, 237, 255, 17)
+ }
+ }
+ fn border(self) -> Color {
+ if self.light {
+ rgba(35, 57, 83, 31)
+ } else {
+ rgba(223, 237, 255, 37)
+ }
+ }
+ fn selection(self) -> Color {
+ if self.light {
+ rgba(198, 221, 250, 255)
+ } else {
+ rgba(70, 98, 136, 180)
+ }
+ }
+}
+
+fn toggle_panel(open: Option<Island>, clicked: Island) -> Option<Island> {
+ (open != Some(clicked)).then_some(clicked)
+}
+
+fn available_panel(open: Option<Island>, music: bool, usage: bool) -> Option<Island> {
+ open.filter(|island| match island {
+ Island::Music => music,
+ Island::Usage => usage,
+ })
+}
+
+fn trigger_layout(
+ bounds: Span,
+ center: f32,
+ scale: f32,
+ music: bool,
+ providers: usize,
+) -> [(Island, Option<Span>); 2] {
+ let px = |v: f32| (v * scale).round();
+ let mut result = [(Island::Music, None), (Island::Usage, None)];
+ let gap = if music && providers > 0 { px(8.0) } else { 0.0 };
+ let music_width = if music { px(214.0) } else { 0.0 };
+ let usage_width = match providers {
+ 0 => 0.0,
+ 1 => px(ISLAND_SINGLE_WIDTH),
+ count => px(134.0 * count as f32),
+ };
+ let total = music_width + usage_width;
+ let available = (bounds.width() - gap).min(total);
+ if total == 0.0 || available < px(if gap > 0.0 { 85.0 } else { 42.0 }) {
+ return result;
+ }
+ let music_width = if gap > 0.0 {
+ (available * music_width / total)
+ .round()
+ .clamp(px(42.0), available - px(42.0))
+ } else if music {
+ available
+ } else {
+ 0.0
+ };
+ let left = (center - (available + gap) / 2.0)
+ .clamp(
+ bounds.left,
+ (bounds.right - available - gap).max(bounds.left),
+ )
+ .round();
+ if music {
+ result[0].1 = Some(Span {
+ left,
+ right: left + music_width,
+ });
+ }
+ if providers > 0 {
+ result[1].1 = Some(Span {
+ left: left + music_width + gap,
+ right: left + available + gap,
+ });
+ }
+ result
+}
+
+fn panel_span(trigger: Span, screen_width: f32, desired: f32) -> Span {
+ let width = desired.max(trigger.width()).min(screen_width);
+ let left = ((trigger.left + trigger.right - width) / 2.0)
+ .clamp(0.0, screen_width - width)
+ .round();
+ Span {
+ left,
+ right: left + width,
+ }
+}
- let island = c.CreateContainerVisual()?;
- island.SetSize(Vector2 {
- X: island_width,
+type IslandProvider<'a> = (Provider, &'a ProviderUsage, Color);
+
+fn island_providers(look: &Look) -> Vec<IslandProvider<'_>> {
+ Provider::ALL
+ .into_iter()
+ .filter(|provider| look.active_providers.has(*provider))
+ .map(|provider| {
+ let accent = match provider {
+ Provider::Claude => rgba(217, 119, 87, 255),
+ Provider::Codex => rgba(135, 190, 245, 255),
+ Provider::OpenCode => rgba(132, 196, 166, 255),
+ Provider::Gemini => rgba(111, 146, 255, 255),
+ };
+ (provider, look.usage.get(provider), accent)
+ })
+ .collect()
+}
+
+fn island_surface(
+ gfx: &Gfx,
+ look: &Look,
+ layers: &VisualCollection,
+ geometry: IslandGeometry,
+ island_height: f32,
+) -> Result<VisualCollection> {
+ let c = &gfx.compositor;
+ let px = |v| geometry.px(v);
+ let island_left = geometry.left;
+ let island_width = geometry.width;
+ let scale = geometry.scale;
+ let island = c.CreateContainerVisual()?;
+ island.SetSize(Vector2 {
+ X: island_width,
+ Y: island_height,
+ })?;
+ island.SetOffset(Vector3 {
+ X: island_left.round(),
+ Y: geometry.top,
+ Z: 0.0,
+ })?;
+ let content = island.Children()?;
+ let attached = geometry.top == 0.0;
+ let silhouette = gfx.island_mask(island_width, island_height, scale, attached)?;
+ let shadow = c.CreateDropShadow()?;
+ shadow.SetMask(&silhouette)?;
+ shadow.SetBlurRadius(px(12.0))?;
+ shadow.SetOffset(Vector3 {
+ X: 0.0,
+ Y: px(5.0),
+ Z: 0.0,
+ })?;
+ shadow.SetColor(rgba(0, 0, 0, 92))?;
+ let shadow_host = c.CreateSpriteVisual()?;
+ shadow_host.SetSize(Vector2 {
+ X: island_width,
+ Y: island_height,
+ })?;
+ shadow_host.SetShadow(&shadow)?;
+ content.InsertAtTop(&shadow_host)?;
+
+ let tint = match (look.light, look.glass) {
+ (true, true) => rgba(247, 249, 252, 243),
+ (false, true) => rgba(7, 9, 13, 242),
+ (true, false) => rgba(247, 249, 252, 255),
+ (false, false) => rgba(10, 12, 17, 255),
+ };
+ if look.glass {
+ // The backdrop cannot be used as a mask-brush source. Inset its
+ // rounded clip so it stays entirely inside the curved silhouette.
+ let inset = if attached {
+ (12.0 * scale)
+ .min(island_width / 5.0)
+ .min(island_height / 2.0)
+ } else {
+ 0.0
+ };
+ let glass_width = island_width - inset * 2.0;
+ let glass = c.CreateContainerVisual()?;
+ glass.SetSize(Vector2 {
+ X: glass_width,
Y: island_height,
})?;
- island.SetOffset(Vector3 {
- X: island_left.round(),
+ glass.SetOffset(Vector3 {
+ X: inset,
Y: 0.0,
Z: 0.0,
})?;
- let content = island.Children()?;
- let silhouette = gfx.island_mask(island_width, island_height, scale)?;
- let shadow = c.CreateDropShadow()?;
- shadow.SetMask(&silhouette)?;
- shadow.SetBlurRadius(px(12.0))?;
- shadow.SetOffset(Vector3 {
- X: 0.0,
- Y: px(5.0),
- Z: 0.0,
+ let outline = c.CreateRoundedRectangleGeometry()?;
+ let lift = if attached { px(22.0) } else { 0.0 };
+ let radius = if attached { px(22.0) } else { px(18.0) };
+ outline.SetSize(Vector2 {
+ X: glass_width,
+ Y: island_height + lift,
})?;
- shadow.SetColor(rgba(0, 0, 0, 92))?;
- let shadow_host = c.CreateSpriteVisual()?;
- shadow_host.SetSize(Vector2 {
- X: island_width,
- Y: island_height,
+ outline.SetOffset(Vector2 { X: 0.0, Y: -lift })?;
+ outline.SetCornerRadius(Vector2 {
+ X: radius,
+ Y: radius,
})?;
- shadow_host.SetShadow(&shadow)?;
- content.InsertAtTop(&shadow_host)?;
-
- let tint = match (look.light, look.glass) {
- (true, true) => rgba(247, 249, 252, 243),
- (false, true) => rgba(7, 9, 13, 242),
- (true, false) => rgba(247, 249, 252, 255),
- (false, false) => rgba(10, 12, 17, 255),
- };
- if look.glass {
- // The backdrop cannot be used as a mask-brush source. Inset its
- // rounded clip so it stays entirely inside the curved silhouette.
- let inset = px(12.0);
- let glass_width = island_width - inset * 2.0;
- let glass = c.CreateContainerVisual()?;
- glass.SetSize(Vector2 {
- X: glass_width,
- Y: island_height,
- })?;
- glass.SetOffset(Vector3 {
- X: inset,
- Y: 0.0,
- Z: 0.0,
- })?;
- let outline = c.CreateRoundedRectangleGeometry()?;
- outline.SetSize(Vector2 {
- X: glass_width,
- Y: island_height + px(22.0),
- })?;
- outline.SetOffset(Vector2 {
- X: 0.0,
- Y: -px(22.0),
- })?;
- outline.SetCornerRadius(Vector2 {
- X: px(22.0),
- Y: px(22.0),
- })?;
- glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;
- add_visual(
- c,
- &glass.Children()?,
- &c.CreateHostBackdropBrush()?.cast()?,
- 0.0,
- 0.0,
- glass_width,
- island_height,
- )?;
- content.InsertAtTop(&glass)?;
- }
- let masked = c.CreateMaskBrush()?;
- masked.SetSource(&c.CreateColorBrushWithColor(tint)?)?;
- masked.SetMask(&silhouette)?;
+ glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;
add_visual(
c,
- &content,
- &masked.cast()?,
+ &glass.Children()?,
+ &c.CreateHostBackdropBrush()?.cast()?,
0.0,
0.0,
- island_width,
+ glass_width,
island_height,
)?;
+ content.InsertAtTop(&glass)?;
+ }
+ let masked = c.CreateMaskBrush()?;
+ masked.SetSource(&c.CreateColorBrushWithColor(tint)?)?;
+ masked.SetMask(&silhouette)?;
+ add_visual(
+ c,
+ &content,
+ &masked.cast()?,
+ 0.0,
+ 0.0,
+ island_width,
+ island_height,
+ )?;
- let ink = if look.light { Ink::Dark } else { Ink::Light };
- let providers = Provider::ALL
- .into_iter()
- .filter(|provider| look.active_providers.has(*provider))
- .map(|provider| {
- let accent = match provider {
- Provider::Claude => rgba(217, 119, 87, 255),
- Provider::Codex => rgba(135, 190, 245, 255),
- Provider::Copilot => rgba(147, 164, 186, 255),
- Provider::OpenCode => rgba(132, 196, 166, 255),
- Provider::Gemini => rgba(111, 146, 255, 255),
+ layers.InsertAtTop(&island)?;
+ Ok(content)
+}
+
+fn draw_compact_usage(
+ gfx: &Gfx,
+ content: &VisualCollection,
+ geometry: IslandGeometry,
+ bar_height: f32,
+ providers: &[IslandProvider<'_>],
+) -> Result<()> {
+ let c = &gfx.compositor;
+ let px = |v| geometry.px(v);
+ let ink = geometry.ink();
+ let scale = geometry.scale;
+ let inset = px(13.0);
+ let half = (geometry.width - 2.0 * inset) / providers.len().max(1) as f32;
+ if half < px(20.0) {
+ let icon = gfx.glyph_brush(&[('\u{E9D9}', 1.0)], scale, ink)?;
+ add_visual(
+ c,
+ content,
+ &icon.brush.cast()?,
+ (geometry.width - icon.width) / 2.0,
+ (bar_height - icon.height) / 2.0,
+ icon.width,
+ icon.height,
+ )?;
+ return Ok(());
+ }
+ for (index, (provider, usage, accent)) in providers.iter().enumerate() {
+ // When space is tight the full list is still available in the panel.
+ if half < px(20.0) {
+ break;
+ }
+ let icon_size = px(18.0) as u32;
+ let start = inset
+ + index as f32 * half
+ + if half < px(84.0) {
+ (half - icon_size as f32) / 2.0
+ } else {
+ px(21.0)
+ };
+ if let Some(image) = usage::logo(*provider) {
+ let image_brush = gfx.icon_brush(image, icon_size)?;
+ let brush: CompositionBrush =
+ if !matches!(provider, Provider::Claude | Provider::Gemini) && geometry.light {
+ let tinted = c.CreateMaskBrush()?;
+ tinted.SetMask(&image_brush)?;
+ tinted.SetSource(&c.CreateColorBrushWithColor(rgba(27, 34, 45, 255))?)?;
+ tinted.cast()?
+ } else {
+ image_brush.cast()?
};
- (provider, provider.name(), look.usage.get(provider), accent)
- })
- .collect::<Vec<_>>();
- if look.expanded {
- let title = strings::text();
- add_panel_text(
+ add_visual(
+ c,
+ content,
+ &brush,
+ start,
+ (bar_height - icon_size as f32) / 2.0,
+ icon_size as f32,
+ icon_size as f32,
+ )?;
+ }
+ let percent = usage.main_window().map_or("—".to_owned(), |window| {
+ format!("{}%", window.used_percent)
+ });
+ if half > px(106.0) {
+ add_text(
gfx,
- &content,
- title.usage_title,
- px(28.0),
- px(15.0),
+ content,
+ &percent,
+ start + px(25.0),
+ px(6.0),
scale,
- 13.0,
true,
ink,
- 0.94,
)?;
- let button_text = if look.usage_refreshing {
- title.usage_refreshing
- } else {
- title.usage_refresh
- };
- let button_label = gfx.text_brush_sized(button_text, scale, 11.5, true, ink)?;
- let button_width = button_label.width + px(20.0);
- let button_height = px(27.0);
- let button_left = island_width - px(23.0) - button_width;
- let button_top = px(8.0);
- add_rounded_box(
- c,
- &content,
- button_left,
- button_top,
- button_width,
- button_height,
- px(13.5),
- if look.light {
- rgba(28, 51, 79, 18)
- } else {
- rgba(235, 242, 252, 26)
- },
- Some(if look.light {
- rgba(41, 62, 86, 36)
- } else {
- rgba(226, 237, 251, 43)
- }),
+ }
+ if half >= px(84.0) {
+ let ring = gfx.usage_ring(
+ usage.main_window().map(|window| window.used_percent),
+ scale,
+ *accent,
)?;
add_visual(
c,
- &content,
- &button_label.brush.cast()?,
- button_left + px(10.0),
- button_top + (button_height - button_label.height) / 2.0,
- button_label.width,
- button_label.height,
+ content,
+ &ring.brush.cast()?,
+ inset + (index + 1) as f32 * half - px(16.0) - ring.width,
+ (bar_height - ring.height) / 2.0,
+ ring.width,
+ ring.height,
)?;
- self.refresh_button = Some((
- island_left + button_left,
- button_top,
- island_left + button_left + button_width,
- button_top + button_height,
- ));
- for (index, (provider, _name, usage, accent)) in providers.iter().enumerate() {
- draw_usage_card(
- gfx,
- &content,
- *provider,
- usage,
- *accent,
- scale,
- look.light,
- island_width,
- px(53.0 + index as f32 * ISLAND_ROW_HEIGHT),
- )?;
- }
- let newest_age = providers
- .iter()
- .filter_map(|provider| provider.2.age_minutes())
- .min();
- if let Some(minutes) = newest_age {
- let status = format!("{} {minutes} min", title.usage_updated);
- let label = gfx.text_brush_sized(&status, scale, 11.0, false, ink)?;
- add_visual(
- c,
- &content,
- &label.brush.cast()?,
- (island_width - label.width) / 2.0,
- island_height - px(21.0),
- label.width,
- label.height,
- )?
- .SetOpacity(0.53)?;
- }
- } else {
- self.refresh_button = None;
- let half = island_width / providers.len() as f32;
- for (index, (provider, _name, usage, accent)) in providers.iter().enumerate() {
- let icon_size = px(18.0) as u32;
- let start = index as f32 * half
- + if half < px(84.0) {
- (half - icon_size as f32) / 2.0
- } else {
- px(21.0)
- };
- if let Some(image) = usage::logo(*provider) {
- let image_brush = gfx.icon_brush(image, icon_size)?;
- let brush: CompositionBrush =
- if !matches!(provider, Provider::Claude | Provider::Gemini) && look.light {
- let tinted = c.CreateMaskBrush()?;
- tinted.SetMask(&image_brush)?;
- tinted
- .SetSource(&c.CreateColorBrushWithColor(rgba(27, 34, 45, 255))?)?;
- tinted.cast()?
- } else {
- image_brush.cast()?
- };
- add_visual(
- c,
- &content,
- &brush,
- start,
- (bar_height - icon_size as f32) / 2.0,
- icon_size as f32,
- icon_size as f32,
- )?;
- }
- let percent = usage.main_window().map_or("—".to_owned(), |window| {
- format!("{}%", window.used_percent)
- });
- if half > px(106.0) {
- add_text(
- gfx,
- &content,
- &percent,
- start + px(25.0),
- px(6.0),
- scale,
- true,
- ink,
- )?;
- }
- if half >= px(84.0) {
- let ring = gfx.usage_ring(
- usage.main_window().map(|window| window.used_percent),
- scale,
- *accent,
- )?;
- add_visual(
- c,
- &content,
- &ring.brush.cast()?,
- (index + 1) as f32 * half - px(16.0) - ring.width,
- (bar_height - ring.height) / 2.0,
- ring.width,
- ring.height,
- )?;
- }
- }
}
- layers.InsertAtTop(&island)?;
- Ok(())
}
+ Ok(())
+}
+
+fn track_title(track: &Track) -> &str {
+ if track.title.trim().is_empty() {
+ strings::text().media_title
+ } else {
+ &track.title
+ }
+}
+
+fn draw_compact_player(
+ gfx: &Gfx,
+ layers: &VisualCollection,
+ geometry: IslandGeometry,
+ width: f32,
+ height: f32,
+ track: &Track,
+) -> 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 show_title = width > x + px(18.0);
+ let note_x = if show_title {
+ px(18.0)
+ } else {
+ (width - note.width) / 2.0
+ };
+ add_visual(
+ c,
+ layers,
+ &note.brush.cast()?,
+ note_x,
+ (height - note.height) / 2.0,
+ note.width,
+ note.height,
+ )?;
+ if show_title {
+ let label = gfx.text_brush_fitted(
+ track_title(track),
+ geometry.scale,
+ 11.5,
+ true,
+ ink,
+ width - x - px(13.0),
+ )?;
+ add_visual(
+ c,
+ layers,
+ &label.brush.cast()?,
+ x,
+ (height - label.height) / 2.0,
+ label.width,
+ label.height,
+ )?;
+ }
+ Ok(())
}
impl Drop for MenuBar {
fn drop(&mut self) {
- USAGE_HOOK_WINDOW.store(0, Ordering::Relaxed);
+ self.media = None;
+ ISLAND_HOOK_WINDOW.store(0, Ordering::Relaxed);
EDGE_HOOK_WINDOW.store(0, Ordering::Relaxed);
self.edge_watch = None;
if let Some(hook) = self.outside_click_hook.take() {
@@ -1806,3 +2383,56 @@ impl Drop for MenuBar {
}
}
}
+
+#[cfg(test)]
+mod island_tests {
+ use super::*;
+
+ #[test]
+ fn clicking_usage_replaces_music_and_clicking_again_closes_it() {
+ let open = toggle_panel(Some(Island::Music), Island::Usage);
+ assert_eq!(open, Some(Island::Usage));
+ assert_eq!(toggle_panel(open, Island::Usage), None);
+ }
+
+ #[test]
+ fn usage_panel_covers_the_last_provider_even_when_the_trigger_is_wide() {
+ let screen = 1920.0;
+ let triggers = trigger_layout(
+ Span {
+ left: 210.0,
+ right: 1540.0,
+ },
+ screen / 2.0,
+ 1.25,
+ true,
+ 5,
+ );
+ let Some(usage) = triggers[1].1 else {
+ panic!("Usage trigger should fit");
+ };
+ let panel = panel_span(usage, screen, 550.0);
+ assert!(panel.left <= usage.left && panel.right >= usage.right);
+ }
+
+ #[test]
+ fn narrow_bar_still_gives_each_trigger_its_own_clickable_span() {
+ let bounds = Span {
+ left: 200.0,
+ right: 390.0,
+ };
+ let [(_, Some(music)), (_, Some(usage))] = trigger_layout(bounds, 300.0, 1.5, true, 3)
+ else {
+ panic!("Both triggers should fit");
+ };
+ assert!(
+ music.left >= bounds.left && music.right < usage.left && usage.right <= bounds.right
+ );
+ }
+
+ #[test]
+ fn losing_a_session_closes_its_panel_without_opening_the_other() {
+ assert_eq!(available_panel(Some(Island::Music), false, true), None);
+ assert_eq!(available_panel(Some(Island::Usage), true, false), None);
+ }
+}
diff --git a/apps/dock/src/previews.rs b/apps/dock/src/previews.rs
new file mode 100644
index 0000000..89979dd
--- /dev/null
+++ b/apps/dock/src/previews.rs
@@ -0,0 +1,495 @@
+//! A non-activating, on-demand window picker. DWM composites the cards'
+//! thumbnails directly and releases them as soon as the picker closes.
+
+use anyhow::Result;
+use muelle_shell::{system::Monitor, tracker};
+use windows::{
+ UI::Composition::{ContainerVisual, Desktop::DesktopWindowTarget},
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ Graphics::Gdi::{CreateRoundRectRgn, DeleteObject, SetWindowRgn},
+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
+ UI::WindowsAndMessaging::{
+ CS_DROPSHADOW, CreateWindowExW, DefWindowProcW, DestroyWindow, GetForegroundWindow,
+ HWND_TOPMOST, IDC_ARROW, IDC_HAND, LoadCursorW, RegisterClassW, SW_SHOWNA,
+ SWP_NOACTIVATE, SetCursor, SetWindowPos, ShowWindow, WM_LBUTTONUP, WM_MOUSEMOVE,
+ WM_MOUSEWHEEL, WM_SETCURSOR, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
+ },
+ },
+ core::{Interface, w},
+};
+use windows_numerics::Vector2;
+
+use crate::{
+ app,
+ gfx::{Gfx, Ink},
+ menu::{apply_popup_frame, draw_popup_background},
+ menubar::{add_rounded_box, add_visual, rgba},
+ thumbnails::Thumbnails,
+};
+
+const PREVIEW_WIDTH: f32 = 176.0;
+const PREVIEW_GAP: f32 = 12.0;
+const PANEL_PADDING: f32 = 12.0;
+
+#[derive(Clone, Copy)]
+pub enum Choice {
+ Window(isize),
+ Page(usize),
+}
+
+struct Hit {
+ bounds: RECT,
+ choice: Choice,
+ highlight: ContainerVisual,
+}
+
+struct Window(HWND);
+
+impl Drop for Window {
+ fn drop(&mut self) {
+ // SAFETY: Created and destroyed on the dock thread.
+ unsafe {
+ let _ = DestroyWindow(self.0);
+ }
+ }
+}
+
+pub struct Picker {
+ thumbnails: Thumbnails,
+ target: DesktopWindowTarget,
+ window: Window,
+ pub app_id: String,
+ pub windows: Vec<isize>,
+ app_name: String,
+ foreground: HWND,
+ anchor: RECT,
+ bounds: RECT,
+ hits: Vec<Hit>,
+ hot: Option<usize>,
+ page: usize,
+ per_page: usize,
+ monitor: Monitor,
+ light: bool,
+ glass: bool,
+ native_corners: bool,
+}
+
+impl Picker {
+ pub fn open(
+ gfx: &Gfx,
+ app: (String, String),
+ windows: Vec<isize>,
+ anchor: RECT,
+ monitor: Monitor,
+ theme: (bool, bool),
+ ) -> Result<Self> {
+ let class = w!("MuelleWindowPreviews");
+ // SAFETY: The class and window belong to the dock UI thread.
+ let window = Window(unsafe {
+ let module = GetModuleHandleW(None)?;
+ RegisterClassW(&WNDCLASSW {
+ style: CS_DROPSHADOW,
+ lpfnWndProc: Some(proc),
+ hInstance: module.into(),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ lpszClassName: class,
+ ..Default::default()
+ });
+ CreateWindowExW(
+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_NOACTIVATE | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
+ class,
+ w!("Muelle"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(module.into()),
+ None,
+ )?
+ });
+ let hwnd = window.0;
+ let native_corners = apply_popup_frame(hwnd, !theme.0);
+ // SAFETY: hwnd is a live, top-level window owned by this process.
+ let (target, foreground) = unsafe {
+ (
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?,
+ GetForegroundWindow(),
+ )
+ };
+ let available = (monitor.screen.right - monitor.screen.left) as f32 / monitor.scale;
+ let per_page = ((available - 2.0 * PANEL_PADDING + PREVIEW_GAP)
+ / (PREVIEW_WIDTH + PREVIEW_GAP))
+ .floor()
+ .clamp(1.0, 4.0) as usize;
+ let mut picker = Self {
+ thumbnails: Thumbnails::new(hwnd),
+ target,
+ window,
+ app_id: app.0,
+ app_name: app.1,
+ windows,
+ foreground,
+ anchor,
+ bounds: RECT::default(),
+ hits: Vec::new(),
+ hot: None,
+ page: 0,
+ per_page,
+ monitor,
+ light: theme.0,
+ glass: theme.1,
+ native_corners,
+ };
+ picker.draw(gfx, 0)?;
+ Ok(picker)
+ }
+
+ pub fn draw(&mut self, gfx: &Gfx, page: usize) -> Result<()> {
+ let px = |logical: f32| (logical * self.monitor.scale).round();
+ let total = self.windows.len().div_ceil(self.per_page);
+ let page = page.min(total - 1);
+ let count = self.windows.len().min(self.per_page);
+ let start = page * self.per_page;
+ let visible = &self.windows[start..(start + count).min(self.windows.len())];
+ let screen = self.monitor.screen;
+ let gap = px(PREVIEW_GAP);
+ let inset = px(PANEL_PADDING);
+ let card = px(PREVIEW_WIDTH).min(
+ (((screen.right - screen.left) as f32 - 2.0 * inset - gap * (count - 1) as f32)
+ / count as f32)
+ .floor()
+ .max(1.0),
+ );
+ let width = inset * 2.0 + card * count as f32 + gap * (count - 1) as f32;
+ let first_card = inset + (card + gap) * (count - visible.len()) as f32 / 2.0;
+ let height = px(168.0);
+ let top = (self.anchor.top - height as i32 - px(7.0) as i32).max(screen.top);
+ let left = ((self.anchor.left + self.anchor.right - width as i32) / 2)
+ .clamp(screen.left, (screen.right - width as i32).max(screen.left));
+ let c = &gfx.compositor;
+ let root = c.CreateContainerVisual()?;
+ root.SetSize(Vector2::new(width, height))?;
+ let layers = root.Children()?;
+ draw_popup_background(&layers, !self.light, self.glass, width, height)?;
+ let hwnd = self.window.0;
+ // SAFETY: This window belongs to the UI thread. A region is used when
+ // DWM doesn't accept the native corner preference and owned by Windows
+ // only if SetWindowRgn succeeds.
+ unsafe {
+ if !self.native_corners {
+ let diameter = px(16.0) as i32;
+ let region = CreateRoundRectRgn(
+ 0,
+ 0,
+ width as i32 + 1,
+ height as i32 + 1,
+ diameter,
+ diameter,
+ );
+ if !region.is_invalid() && SetWindowRgn(hwnd, Some(region), true) == 0 {
+ let _ = DeleteObject(region.into());
+ }
+ }
+ SetWindowPos(
+ hwnd,
+ Some(HWND_TOPMOST),
+ left,
+ top,
+ width as i32,
+ height as i32,
+ SWP_NOACTIVATE,
+ )?;
+ }
+ let ink = if self.light { Ink::Dark } else { Ink::Light };
+ let label = gfx.text_brush_fitted(
+ &self.app_name,
+ self.monitor.scale,
+ 12.0,
+ true,
+ ink,
+ width - px(if total > 1 { 110.0 } else { 30.0 }),
+ )?;
+ add_visual(
+ c,
+ &layers,
+ &label.brush.cast()?,
+ px(16.0),
+ (px(35.0) - label.height) / 2.0,
+ label.width,
+ label.height,
+ )?;
+
+ let mut hits = Vec::with_capacity(visible.len() + 2);
+ let outline = if self.light {
+ rgba(29, 34, 42, 90)
+ } else {
+ rgba(249, 250, 252, 112)
+ };
+ self.thumbnails.sync(visible);
+ for (index, &hwnd) in visible.iter().enumerate() {
+ let x = (first_card + (card + gap) * index as f32).round();
+ let slot = rect(x, px(32.0), card, px(106.0));
+ let image = self.thumbnails.place_preview(hwnd, slot).unwrap_or(slot);
+ let hot = c.CreateContainerVisual()?;
+ hot.SetSize(Vector2::new(width, height))?;
+ let halo = px(2.0);
+ add_rounded_box(
+ c,
+ &hot.Children()?,
+ image.left as f32 - halo,
+ image.top as f32 - halo,
+ (image.right - image.left) as f32 + halo * 2.0,
+ (image.bottom - image.top) as f32 + halo * 2.0,
+ px(4.0),
+ rgba(0, 0, 0, 0),
+ Some(outline),
+ )?;
+ hot.SetIsVisible(false)?;
+ layers.InsertAtTop(&hot)?;
+ let title = tracker::title(hwnd);
+ let name = if title.is_empty() {
+ &self.app_name
+ } else {
+ &title
+ };
+ let name = gfx.text_brush_fitted(name, self.monitor.scale, 11.5, false, ink, card)?;
+ add_visual(
+ c,
+ &layers,
+ &name.brush.cast()?,
+ x,
+ slot.bottom as f32 + px(7.0),
+ name.width,
+ name.height,
+ )?;
+ hits.push(Hit {
+ bounds: rect(x - gap / 2.0, px(29.0), card + gap, height - px(34.0)),
+ choice: Choice::Window(hwnd),
+ highlight: hot,
+ });
+ }
+ if total > 1 {
+ let number = format!("{}/{}", page + 1, total);
+ let label = gfx.text_brush_sized(&number, self.monitor.scale, 10.5, false, ink)?;
+ add_visual(
+ c,
+ &layers,
+ &label.brush.cast()?,
+ width - px(40.0) - label.width / 2.0,
+ (px(35.0) - label.height) / 2.0,
+ label.width,
+ label.height,
+ )?
+ .SetOpacity(0.65)?;
+ for (glyph, x, destination) in [
+ ('‹', width - px(76.0), page.checked_sub(1)),
+ (
+ '›',
+ width - px(25.0),
+ (page + 1 < total).then_some(page + 1),
+ ),
+ ] {
+ let label =
+ gfx.text_brush_sized(&glyph.to_string(), self.monitor.scale, 17.0, true, ink)?;
+ let y = px(6.0);
+ let side = px(21.0);
+ let hot = c.CreateContainerVisual()?;
+ hot.SetSize(Vector2::new(width, height))?;
+ let fill = if self.light {
+ rgba(0, 0, 0, 21)
+ } else {
+ rgba(255, 255, 255, 24)
+ };
+ add_rounded_box(c, &hot.Children()?, x, y, side, side, px(5.0), fill, None)?;
+ hot.SetIsVisible(false)?;
+ layers.InsertAtTop(&hot)?;
+ let button = add_visual(
+ c,
+ &layers,
+ &label.brush.cast()?,
+ x + (side - label.width) / 2.0,
+ y + (side - label.height) / 2.0,
+ label.width,
+ label.height,
+ )?;
+ if let Some(destination) = destination {
+ hits.push(Hit {
+ bounds: rect(x, y, side, side),
+ choice: Choice::Page(destination),
+ highlight: hot,
+ });
+ } else {
+ button.SetOpacity(0.27)?;
+ }
+ }
+ }
+ self.target.SetRoot(&root)?;
+ // SAFETY: Show the picker without taking focus from the active app.
+ unsafe {
+ let _ = ShowWindow(hwnd, SW_SHOWNA);
+ }
+ self.bounds = rect(left as f32, top as f32, width, height);
+ self.hits = hits;
+ self.hot = None;
+ self.page = page;
+ Ok(())
+ }
+
+ pub fn contains(&self, point: POINT) -> bool {
+ // SAFETY: Reading the foreground does not activate the picker.
+ if unsafe { GetForegroundWindow() } != self.foreground {
+ return false;
+ }
+ let near_anchor = point.y >= self.anchor.top
+ && point.y < self.anchor.bottom
+ && point.x >= self.anchor.left - 4
+ && point.x < self.anchor.right + 4;
+ let bridge = point.y >= self.bounds.bottom
+ && point.y < self.anchor.top
+ && point.x >= self.bounds.left.min(self.anchor.left)
+ && point.x < self.bounds.right.max(self.anchor.right);
+ inside(self.bounds, point) || near_anchor || bridge
+ }
+
+ pub fn choice_at(&self, point: POINT) -> Option<Choice> {
+ self.hits
+ .iter()
+ .find(|hit| inside(hit.bounds, point))
+ .map(|hit| hit.choice)
+ }
+
+ pub fn hover(&mut self, point: POINT) -> Result<()> {
+ let hit = self.hits.iter().position(|hit| inside(hit.bounds, point));
+ if hit != self.hot {
+ if let Some(index) = self.hot {
+ self.hits[index].highlight.SetIsVisible(false)?;
+ }
+ if let Some(index) = hit {
+ self.hits[index].highlight.SetIsVisible(true)?;
+ }
+ self.hot = hit;
+ }
+ Ok(())
+ }
+
+ pub fn next_page(&self, delta: i16) -> Option<usize> {
+ let next = if delta > 0 {
+ self.page.checked_sub(1)?
+ } else {
+ self.page + 1
+ };
+ (next < self.windows.len().div_ceil(self.per_page)).then_some(next)
+ }
+}
+
+fn rect(x: f32, y: f32, w: f32, h: f32) -> RECT {
+ RECT {
+ left: x as i32,
+ top: y as i32,
+ right: (x + w) as i32,
+ bottom: (y + h) as i32,
+ }
+}
+
+fn inside(rect: RECT, point: POINT) -> bool {
+ point.x >= rect.left && point.x < rect.right && point.y >= rect.top && point.y < rect.bottom
+}
+
+unsafe extern "system" fn proc(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ let point = POINT {
+ x: (l.0 as i16).into(),
+ y: ((l.0 >> 16) as i16).into(),
+ };
+ match message {
+ WM_MOUSEMOVE => app::preview_hover(point),
+ WM_LBUTTONUP => app::preview_click(point),
+ WM_MOUSEWHEEL => app::preview_scroll((w.0 >> 16) as i16),
+ WM_SETCURSOR if app::preview_has_hit(hwnd) => {
+ // SAFETY: The stock hand cursor is owned by Windows.
+ if let Ok(hand) = unsafe { LoadCursorW(None, IDC_HAND) } {
+ unsafe { SetCursor(Some(hand)) };
+ return LRESULT(1);
+ }
+ }
+ // SAFETY: Default handling for the preview's own window.
+ _ => return unsafe { DefWindowProcW(hwnd, message, w, l) },
+ }
+ LRESULT(0)
+}
+
+#[cfg(test)]
+mod native_probe {
+ use super::*;
+ use windows::Win32::System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ };
+
+ #[test]
+ #[ignore = "Requires an interactive Windows desktop with DWM"]
+ fn picker_places_live_thumbnails_on_the_shared_caption_line() -> Result<()> {
+ // SAFETY: The controller initializes and owns the test thread's queue.
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let gfx = Gfx::new()?;
+ // SAFETY: These hidden source windows belong to this thread and are
+ // destroyed by their Window wrappers.
+ let fixture = || unsafe {
+ CreateWindowExW(
+ WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ w!("STATIC"),
+ w!("Muelle preview test"),
+ WS_POPUP,
+ 0,
+ 0,
+ 160,
+ 120,
+ None,
+ None,
+ None,
+ None,
+ )
+ .map(Window)
+ };
+ let sources = [fixture()?, fixture()?];
+ let handles = sources.iter().map(|source| source.0.0 as isize).collect();
+ let monitor =
+ muelle_shell::system::primary_monitor().ok_or_else(|| anyhow::anyhow!("no display"))?;
+ let center = (monitor.screen.right + monitor.screen.left) / 2;
+ let picker = Picker::open(
+ &gfx,
+ ("probe".into(), "Muelle".into()),
+ handles,
+ RECT {
+ left: center - 20,
+ right: center + 20,
+ top: monitor.screen.bottom - 130,
+ bottom: monitor.screen.bottom - 90,
+ },
+ monitor,
+ (false, false),
+ )?;
+ assert_eq!(picker.hits.len(), 2);
+ for source in &sources {
+ let image = picker
+ .thumbnails
+ .placed_bounds(source.0.0 as isize)
+ .ok_or_else(|| anyhow::anyhow!("DWM did not place the preview"))?;
+ let caption_line = (32.0 * monitor.scale).round() + (106.0 * monitor.scale).round();
+ assert_eq!(image.bottom, caption_line as i32);
+ }
+ Ok(())
+ }
+}
diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rs
index 4d1c95a..b7d778c 100644
--- a/apps/dock/src/strings.rs
+++ b/apps/dock/src/strings.rs
@@ -34,6 +34,7 @@ pub struct Strings {
pub usage_resets: &'static str,
pub usage_updated: &'static str,
pub usage_used: &'static str,
+ pub media_title: &'static str,
pub shell_operation_failed: &'static str,
}
@@ -65,6 +66,7 @@ const ES: Strings = Strings {
usage_resets: "Reinicia",
usage_updated: "Actualizado hace",
usage_used: "usado",
+ media_title: "Reproducción",
};
const EN: Strings = Strings {
@@ -95,6 +97,7 @@ const EN: Strings = Strings {
usage_resets: "Resets",
usage_updated: "Updated",
usage_used: "used",
+ media_title: "Now playing",
};
/// 0 = not chosen yet (follow Windows), 1 = Spanish, 2 = English.
diff --git a/apps/dock/src/thumbnails.rs b/apps/dock/src/thumbnails.rs
index e7211f3..41b60d9 100644
--- a/apps/dock/src/thumbnails.rs
+++ b/apps/dock/src/thumbnails.rs
@@ -82,19 +82,7 @@ impl Thumbnails {
return;
};
let (x, y, width, height) = slot;
- let source = thumbnail.source;
- let ratio = if source.cx > 0 && source.cy > 0 {
- source.cx as f32 / source.cy as f32
- } else {
- 1.0
- };
- let fit = |box_width: f32, box_height: f32| {
- if ratio >= box_width / box_height {
- (box_width, box_width / ratio)
- } else {
- (box_height * ratio, box_height)
- }
- };
+ let fit = |width, height| thumbnail.fit(width, height);
let (inner_width, inner_height) =
(width * (1.0 - 2.0 * INSET), height * (1.0 - 2.0 * INSET));
// Either the band above the badge or the band to its left, whichever
@@ -122,8 +110,51 @@ impl Thumbnails {
right: (left + fit_width).round() as i32,
bottom: (top + fit_height).round() as i32,
};
- if thumbnail.placed == Some((destination, opacity)) {
- return;
+ thumbnail.update(destination, opacity);
+ }
+
+ /// Fits the preview with its bottom edge on the caption's common baseline.
+ /// Returns the actual DWM bounds so the hover outline can follow the image.
+ pub fn place_preview(&mut self, hwnd: isize, slot: RECT) -> Option<RECT> {
+ let thumbnail = self.live.get_mut(&hwnd)?;
+ let width = (slot.right - slot.left) as f32;
+ let (w, h) = thumbnail.fit(width, (slot.bottom - slot.top) as f32);
+ let w = w.round().max(1.0) as i32;
+ let h = h.round().max(1.0) as i32;
+ let left = slot.left + ((slot.right - slot.left) - w) / 2;
+ let destination = RECT {
+ left,
+ top: slot.bottom - h,
+ right: left + w,
+ bottom: slot.bottom,
+ };
+ thumbnail.update(destination, 255).then_some(destination)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn placed_bounds(&self, hwnd: isize) -> Option<RECT> {
+ self.live.get(&hwnd)?.placed.map(|(bounds, _)| bounds)
+ }
+}
+
+impl Thumbnail {
+ fn fit(&self, width: f32, height: f32) -> (f32, f32) {
+ let source = self.source;
+ let ratio = if source.cx > 0 && source.cy > 0 {
+ source.cx as f32 / source.cy as f32
+ } else {
+ 1.0
+ };
+ if ratio >= width / height {
+ (width, width / ratio)
+ } else {
+ (height * ratio, height)
+ }
+ }
+
+ fn update(&mut self, destination: RECT, opacity: u8) -> bool {
+ if self.placed == Some((destination, opacity)) {
+ return true;
}
let properties = DWM_THUMBNAIL_PROPERTIES {
@@ -138,10 +169,10 @@ impl Thumbnails {
..Default::default()
};
// SAFETY: Valid handle and properties structure.
- unsafe {
- if DwmUpdateThumbnailProperties(thumbnail.handle, &properties).is_ok() {
- thumbnail.placed = Some((destination, opacity));
- }
+ if unsafe { DwmUpdateThumbnailProperties(self.handle, &properties) }.is_err() {
+ return false;
}
+ self.placed = Some((destination, opacity));
+ true
}
}
diff --git a/apps/dock/src/usage.rs b/apps/dock/src/usage.rs
index d52d21b..21b5cca 100644
--- a/apps/dock/src/usage.rs
+++ b/apps/dock/src/usage.rs
@@ -14,25 +14,19 @@ use std::{
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
-use chrono::{DateTime, Local, NaiveDate, Utc};
+use chrono::{DateTime, Local, Utc};
use muelle_shell::icons::IconImage;
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use windows::Win32::{
Foundation::{CloseHandle, HWND, LPARAM, WPARAM},
- Security::Credentials::{CRED_TYPE_GENERIC, CREDENTIALW, CredFree, CredReadW},
System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
TH32CS_SNAPPROCESS,
},
- System::Threading::{
- OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
- QueryFullProcessImageNameW,
- },
UI::WindowsAndMessaging::PostMessageW,
};
-use windows::core::{PWSTR, w};
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
@@ -117,26 +111,18 @@ impl Snapshot {
pub enum Provider {
Claude,
Codex,
- Copilot,
OpenCode,
Gemini,
}
impl Provider {
- pub const COUNT: usize = 5;
- pub const ALL: [Self; Self::COUNT] = [
- Self::Claude,
- Self::Codex,
- Self::Copilot,
- Self::OpenCode,
- Self::Gemini,
- ];
+ pub const COUNT: usize = 4;
+ pub const ALL: [Self; Self::COUNT] = [Self::Claude, Self::Codex, Self::OpenCode, Self::Gemini];
pub fn name(self) -> &'static str {
match self {
Self::Claude => "Claude",
Self::Codex => "Codex",
- Self::Copilot => "Copilot",
Self::OpenCode => "OpenCode",
Self::Gemini => "Gemini",
}
@@ -184,10 +170,6 @@ pub fn active_providers() -> ActiveProviders {
if let Some(provider) = match name.to_ascii_lowercase().as_str() {
"claude.exe" => Some(Provider::Claude),
"codex.exe" => Some(Provider::Codex),
- "copilot.exe" if github_copilot_process(entry.th32ProcessID) => {
- Some(Provider::Copilot)
- }
- "copilot-runtime.exe" => Some(Provider::Copilot),
"opencode.exe" => Some(Provider::OpenCode),
"gemini.exe" | "antigravity.exe" | "agy.exe" => Some(Provider::Gemini),
_ => None,
@@ -210,39 +192,9 @@ pub fn active_providers() -> ActiveProviders {
active
}
-fn github_copilot_process(pid: u32) -> bool {
- // Microsoft Copilot also runs as copilot.exe; it has no GitHub quota.
- // SAFETY: The process handle is closed on every successful open.
- let Ok(process) = (unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) })
- else {
- return false;
- };
- let mut buffer = [0u16; 1024];
- let mut length = buffer.len() as u32;
- // SAFETY: `buffer` remains live and `length` states its capacity.
- let found = unsafe {
- QueryFullProcessImageNameW(
- process,
- PROCESS_NAME_WIN32,
- PWSTR(buffer.as_mut_ptr()),
- &mut length,
- )
- }
- .is_ok();
- // SAFETY: OpenProcess returned this handle.
- unsafe {
- let _ = CloseHandle(process);
- }
- found
- && String::from_utf16_lossy(&buffer[..length as usize])
- .to_ascii_lowercase()
- .contains("github")
-}
-
pub fn logo(provider: Provider) -> Option<&'static IconImage> {
static CLAUDE: std::sync::OnceLock<Option<IconImage>> = std::sync::OnceLock::new();
static CODEX: std::sync::OnceLock<Option<IconImage>> = std::sync::OnceLock::new();
- static COPILOT: std::sync::OnceLock<Option<IconImage>> = std::sync::OnceLock::new();
static OPENCODE: std::sync::OnceLock<Option<IconImage>> = std::sync::OnceLock::new();
static GEMINI: std::sync::OnceLock<Option<IconImage>> = std::sync::OnceLock::new();
match provider {
@@ -252,9 +204,6 @@ pub fn logo(provider: Provider) -> Option<&'static IconImage> {
Provider::Codex => CODEX
.get_or_init(|| decode_logo(include_bytes!("../../../assets/usage/codex.png")))
.as_ref(),
- Provider::Copilot => COPILOT
- .get_or_init(|| decode_logo(include_bytes!("../../../assets/usage/copilot.png")))
- .as_ref(),
Provider::OpenCode => OPENCODE
.get_or_init(|| decode_logo(include_bytes!("../../../assets/usage/opencode.png")))
.as_ref(),
@@ -420,7 +369,6 @@ fn fetch_all() -> Snapshot {
match provider {
Provider::Claude => fetch_claude(&client),
Provider::Codex => fetch_codex(&client),
- Provider::Copilot => fetch_copilot(&client),
Provider::OpenCode => fetch_opencode(&client),
Provider::Gemini => fetch_gemini(&client),
}
@@ -460,29 +408,6 @@ fn home() -> Option<PathBuf> {
env::var_os("USERPROFILE").map(PathBuf::from)
}
-fn credential_text(target: windows::core::PCWSTR) -> Option<String> {
- let mut credential: *mut CREDENTIALW = std::ptr::null_mut();
- // SAFETY: Windows allocates `credential` on success; it is freed below.
- unsafe { CredReadW(target, CRED_TYPE_GENERIC, None, &mut credential).ok()? };
- if credential.is_null() {
- return None;
- }
- // SAFETY: CredReadW returned a valid blob of CredentialBlobSize bytes.
- let token = unsafe {
- let item = &*credential;
- if item.CredentialBlob.is_null() || item.CredentialBlobSize == 0 {
- None
- } else {
- let bytes =
- std::slice::from_raw_parts(item.CredentialBlob, item.CredentialBlobSize as usize);
- String::from_utf8(bytes.to_vec()).ok()
- }
- };
- // SAFETY: `credential` belongs to this successful CredReadW call.
- unsafe { CredFree(credential.cast()) };
- token.map(|value| value.trim_matches('\0').trim().to_owned())
-}
-
fn fetch_claude(client: &Client) -> ProviderUsage {
let Some(root) = env::var_os("CLAUDE_CONFIG_DIR")
.map(PathBuf::from)
@@ -573,97 +498,6 @@ fn fetch_codex(client: &Client) -> ProviderUsage {
}
}
-fn fetch_copilot(client: &Client) -> ProviderUsage {
- let tokens = [
- env::var("COPILOT_GITHUB_TOKEN").ok(),
- env::var("GH_TOKEN").ok(),
- env::var("GITHUB_TOKEN").ok(),
- credential_text(w!("copilot-cli")),
- credential_text(w!("copilot-language-server/oauth-token-key")),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>();
- for token in tokens.into_iter().filter(|value| !value.is_empty()) {
- let response = client
- .get("https://api.github.com/copilot_internal/user")
- .header("Authorization", format!("token {token}"))
- .header("Accept", "application/json")
- .header("Editor-Version", "vscode/1.96.2")
- .header("Editor-Plugin-Version", "copilot-chat/0.26.7")
- .header("User-Agent", "GitHubCopilotChat/0.26.7")
- .header("X-Github-Api-Version", "2025-04-01")
- .send();
- let Ok(response) = response else {
- return unavailable();
- };
- if matches!(response.status().as_u16(), 401 | 403) {
- continue;
- }
- let Ok(body) = response
- .error_for_status()
- .and_then(|response| response.text())
- else {
- return unavailable();
- };
- let Ok(value) = serde_json::from_str::<Value>(&body) else {
- return unavailable();
- };
- let windows = parse_copilot(&value);
- return if windows.is_empty() {
- unavailable()
- } else {
- ready(windows)
- };
- }
- sign_in()
-}
-
-fn parse_copilot(value: &Value) -> Vec<Window> {
- let quotas = value
- .get("quota_snapshots")
- .or_else(|| value.get("quotaSnapshots"));
- let reset = value
- .get("quota_reset_date_utc")
- .or_else(|| value.get("quota_reset_date"))
- .and_then(Value::as_str)
- .and_then(|text| {
- DateTime::parse_from_rfc3339(text)
- .ok()
- .map(|date| date.with_timezone(&Utc))
- .or_else(|| {
- NaiveDate::parse_from_str(text, "%Y-%m-%d")
- .ok()?
- .and_hms_opt(0, 0, 0)
- .map(|date| date.and_utc())
- })
- });
- [
- ("premium_interactions", "premiumInteractions"),
- ("chat", "chat"),
- ]
- .into_iter()
- .filter_map(|(snake, camel)| {
- let quotas = quotas?;
- let quota = quotas.get(snake).or_else(|| quotas.get(camel))?;
- if quota.get("unlimited").and_then(Value::as_bool) == Some(true) {
- return None;
- }
- let remaining = percent(
- quota
- .get("percent_remaining")
- .or_else(|| quota.get("percentRemaining"))?,
- )?;
- Some(Window {
- label: Some(if snake == "chat" { "Chat" } else { "Premium" }.to_owned()),
- minutes: 30 * 24 * 60,
- used_percent: 100 - remaining,
- resets_at: reset,
- })
- })
- .collect()
-}
-
fn fetch_opencode(client: &Client) -> ProviderUsage {
let Some(path) = home().map(|path| path.join(".local/share/opencode/auth.json")) else {
return sign_in();
@@ -1216,25 +1050,6 @@ mod tests {
assert_eq!(windows[0].title(), "7 d");
}
- #[test]
- fn copilot_uses_remaining_quota_and_monthly_reset() {
- let windows = parse_copilot(&json!({
- "quota_reset_date": "2026-12-01",
- "quota_snapshots": {
- "premium_interactions": {"percent_remaining": 73},
- "chat": {"unlimited": true}
- }
- }));
- assert_eq!(windows.len(), 1);
- assert_eq!(windows[0].used_percent, 27);
- assert_eq!(windows[0].title(), "Premium");
- assert!(windows[0].resets_at.is_some());
- let camel = parse_copilot(&json!({"quotaSnapshots": {
- "premiumInteractions": {"percentRemaining": 62}
- }}));
- assert_eq!(camel[0].used_percent, 38);
- }
-
#[test]
fn opencode_ignores_unmeasured_lanes() {
let windows = parse_opencode(&json!({"usage": {
diff --git a/assets/usage/copilot.png b/assets/usage/copilot.png
deleted file mode 100644
index c7ff5db..0000000
Binary files a/assets/usage/copilot.png and /dev/null differ
diff --git a/assets/usage/copilot.svg b/assets/usage/copilot.svg
deleted file mode 100644
index d369efe..0000000
--- a/assets/usage/copilot.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 16 16">
- <path fill="#f5f7fa" fill-rule="evenodd" d="M7.06 9.66v1.41c0 .39-.31.7-.7.7s-.7-.31-.7-.7V9.66c0-.39.31-.7.7-.7s.7.31.7.7m2.58-.7c-.39 0-.7.31-.7.7v1.41c0 .39.31.7.7.7s.7-.31.7-.7V9.66c0-.39-.31-.7-.7-.7m5.86.31v1.76c0 .72-3.14 3.56-7.5 3.56S.62 11.85.5 11.06V9.23c.08-.59.63-1.58 1.49-1.94c.01-.07.02-.13.03-.21c.03-.17.06-.36.12-.57c-.19-.48-.24-1.02-.24-1.55c0-.82.12-1.66.65-2.33c.54-.69 1.4-1.05 2.55-1.18c1.13-.13 2.12.03 2.76.72c.05.05.09.1.13.15c.04-.05.09-.11.13-.15c.64-.69 1.63-.84 2.76-.72c1.15.13 2.01.5 2.55 1.18c.53.67.65 1.51.65 2.33c0 .54-.05 1.08-.24 1.55c.06.21.09.4.12.57l.03.21c.87.36 1.43 1.38 1.49 1.96zM3.31 4.97c0 .74.12 1.1.29 1.29c.15.17.49.36 1.35.36c.8 0 1.26-.22 1.54-.51c.3-.3.49-.78.58-1.46c.11-.88-.03-1.31-.23-1.51c-.18-.19-.6-.39-1.58-.28c-.96.11-1.39.38-1.61.66c-.23.29-.35.74-.35 1.46zm9.38 2.88l-.02-.11c-.46.2-1.01.27-1.62.27c-1.07 0-1.93-.31-2.54-.93c-.2-.21-.37-.44-.51-.7c-.14.25-.31.49-.51.7c-.61.62-1.47.93-2.54.93c-.61 0-1.16-.08-1.62-.27l-.02.11v3.99c.39.3 2.55 1.34 4.69 1.34s4.3-1.04 4.69-1.34zm0-2.88c0-.72-.12-1.16-.35-1.46c-.22-.28-.65-.55-1.61-.66c-.98-.11-1.39.09-1.58.28c-.19.21-.34.64-.23 1.51c.09.68.28 1.15.58 1.46c.28.29.73.51 1.54.51c.86 0 1.2-.19 1.35-.36c.17-.19.29-.54.29-1.29z" clip-rule="evenodd"/>
-</svg>
diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.toml
index 9ac5600..0fa997b 100644
--- a/crates/muelle-shell/Cargo.toml
+++ b/crates/muelle-shell/Cargo.toml
@@ -30,6 +30,8 @@ windows = { workspace = true, features = [
"Win32_System_Registry",
"Win32_Security",
"Win32_System_Threading",
+ "Win32_System_Ole",
+ "Win32_System_SystemServices",
"Win32_System_TaskScheduler",
"Win32_System_Variant",
"Win32_UI_HiDpi",
diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rs
index ba050cf..1b1fcd2 100644
--- a/crates/muelle-shell/src/launcher.rs
+++ b/crates/muelle-shell/src/launcher.rs
@@ -387,11 +387,28 @@ pub fn activate(windows: &[isize]) {
else {
return;
};
- if IsIconic(front).as_bool() {
- let _ = ShowWindowAsync(front, SW_RESTORE);
- return;
- }
+ // The focus first, then the restore. When the dock is not allowed to
+ // take the foreground (the genie ends a moment after the click),
+ // Windows places a window it restores behind the active one: it
+ // showed for an instant and was covered again.
bring_to_front(front);
+ if IsIconic(front).as_bool() && !ShowWindowAsync(front, SW_RESTORE).as_bool() {
+ // Windows refuses it for an app running as administrator (Task
+ // Manager, for one); what Alt+Tab uses restores it anyway.
+ windows::Win32::UI::WindowsAndMessaging::SwitchToThisWindow(front, true);
+ }
+ // Asked for outright as well, after the restore: the focus alone
+ // does not always raise the window. Posted, so a busy app cannot
+ // block the dock.
+ let _ = SetWindowPos(
+ front,
+ Some(HWND_TOP),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS,
+ );
}
}
diff --git a/muelle/src/assets/usage/copilot.svg b/muelle/src/assets/usage/copilot.svg
deleted file mode 100644
index d369efe..0000000
--- a/muelle/src/assets/usage/copilot.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 16 16">
- <path fill="#f5f7fa" fill-rule="evenodd" d="M7.06 9.66v1.41c0 .39-.31.7-.7.7s-.7-.31-.7-.7V9.66c0-.39.31-.7.7-.7s.7.31.7.7m2.58-.7c-.39 0-.7.31-.7.7v1.41c0 .39.31.7.7.7s.7-.31.7-.7V9.66c0-.39-.31-.7-.7-.7m5.86.31v1.76c0 .72-3.14 3.56-7.5 3.56S.62 11.85.5 11.06V9.23c.08-.59.63-1.58 1.49-1.94c.01-.07.02-.13.03-.21c.03-.17.06-.36.12-.57c-.19-.48-.24-1.02-.24-1.55c0-.82.12-1.66.65-2.33c.54-.69 1.4-1.05 2.55-1.18c1.13-.13 2.12.03 2.76.72c.05.05.09.1.13.15c.04-.05.09-.11.13-.15c.64-.69 1.63-.84 2.76-.72c1.15.13 2.01.5 2.55 1.18c.53.67.65 1.51.65 2.33c0 .54-.05 1.08-.24 1.55c.06.21.09.4.12.57l.03.21c.87.36 1.43 1.38 1.49 1.96zM3.31 4.97c0 .74.12 1.1.29 1.29c.15.17.49.36 1.35.36c.8 0 1.26-.22 1.54-.51c.3-.3.49-.78.58-1.46c.11-.88-.03-1.31-.23-1.51c-.18-.19-.6-.39-1.58-.28c-.96.11-1.39.38-1.61.66c-.23.29-.35.74-.35 1.46zm9.38 2.88l-.02-.11c-.46.2-1.01.27-1.62.27c-1.07 0-1.93-.31-2.54-.93c-.2-.21-.37-.44-.51-.7c-.14.25-.31.49-.51.7c-.61.62-1.47.93-2.54.93c-.61 0-1.16-.08-1.62-.27l-.02.11v3.99c.39.3 2.55 1.34 4.69 1.34s4.3-1.04 4.69-1.34zm0-2.88c0-.72-.12-1.16-.35-1.46c-.22-.28-.65-.55-1.61-.66c-.98-.11-1.39.09-1.58.28c-.19.21-.34.64-.23 1.51c.09.68.28 1.15.58 1.46c.28.29.73.51 1.54.51c.86 0 1.2-.19 1.35-.36c.17-.19.29-.54.29-1.29z" clip-rule="evenodd"/>
-</svg>
diff --git a/muelle/src/data/usage.ts b/muelle/src/data/usage.ts
index 2ad8cc0..22ef70c 100644
--- a/muelle/src/data/usage.ts
+++ b/muelle/src/data/usage.ts
@@ -1,6 +1,5 @@
import claude from "@/assets/usage/claude.svg";
import codex from "@/assets/usage/codex.svg";
-import copilot from "@/assets/usage/copilot.svg";
import gemini from "@/assets/usage/gemini.svg";
import opencode from "@/assets/usage/opencode.svg";
@@ -34,13 +33,6 @@ export const usageProviders: UsageProvider[] = [
primary: { label: "5 h", used: 28, resets: "Resets 4:30 PM" },
secondary: { label: "7 d", used: 41, resets: "Resets Nov 21" },
},
- {
- name: "GitHub Copilot",
- logo: copilot,
- color: "#93a4ba",
- primary: { label: "Premium", used: 32, resets: "Resets Nov 30" },
- secondary: { label: "Chat", used: 74, resets: "Resets Nov 30" },
- },
{
name: "OpenCode Go",
logo: opencode,
@@ -60,13 +52,13 @@ export const usageProviders: UsageProvider[] = [
export const usageIntro = {
eyebrow: "AI usage",
title: "AI plan usage, at a glance.",
- lead: "Muelle shows available limits for Claude Code, Codex, GitHub Copilot, OpenCode Go, and Gemini CLI or Antigravity. Gemini Pro and Flash quotas appear separately when available.",
+ lead: "Muelle shows available limits for Claude Code, Codex, OpenCode Go, and Gemini CLI or Antigravity. Gemini Pro and Flash quotas appear separately when available.",
} as const;
export const usageFacts = [
{
title: "Only while you use them",
- body: "The island recognizes five clients: Claude Code, Codex, GitHub Copilot, OpenCode Go, and Gemini CLI or Antigravity.",
+ body: "The island recognizes four clients: Claude Code, Codex, OpenCode Go, and Gemini CLI or Antigravity.",
},
{
title: "Your existing session",
diff --git a/muelle/src/pages/privacy.astro b/muelle/src/pages/privacy.astro
index 44226ca..833b3d0 100644
--- a/muelle/src/pages/privacy.astro
+++ b/muelle/src/pages/privacy.astro
@@ -28,7 +28,7 @@ import { site } from "@/data/site";
<h2>2. AI provider usage</h2>
<p>
- The menu bar can show available plan limits for Claude Code, Codex, GitHub Copilot,
+ The menu bar can show available plan limits for Claude Code, Codex,
OpenCode Go, Gemini CLI, or Antigravity. It checks usage only while a supported client is
running. Gemini Pro and Flash quotas are shown as separate model families when the provider
supplies them.
@@ -36,13 +36,12 @@ import { site } from "@/data/site";
<ul>
<li>
It reads the sign-in that each command-line client already stores on your computer: Claude Code,
- Codex, OpenCode, Gemini CLI or Antigravity, and for GitHub Copilot the sign-in of the Copilot CLI or
- the <code>GH_TOKEN</code> / <code>GITHUB_TOKEN</code> variables. Muelle never decrypts other
+ Codex, OpenCode, Gemini CLI or Antigravity. Muelle never decrypts other
apps' stored secrets or reads their databases, and does not save or change these credentials.
</li>
<li>
With that sign-in it asks the corresponding provider for available limits every five minutes while the indicator is visible, or when you press Refresh:
- Anthropic, OpenAI, GitHub, OpenCode, or Google. The sign-in only goes to its own provider.
+ Anthropic, OpenAI, OpenCode, or Google. The sign-in only goes to its own provider.
Antigravity usage is read from its authenticated local service on <code>127.0.0.1</code>.
Percentages and reset times stay in memory and are shown in the menu bar.
</li>
diff --git a/spikes/src/bin/spike_restore.rs b/spikes/src/bin/spike_restore.rs
index 79cf562..ba738a4 100644
--- a/spikes/src/bin/spike_restore.rs
+++ b/spikes/src/bin/spike_restore.rs
@@ -2,13 +2,22 @@
//! long it takes to be restored, in the foreground and on top of the other
//! app windows. Usage: `spike_restore <exe name> <method A..F> [calm]`.
-use std::{thread::sleep, time::{Duration, Instant}};
+use std::{
+ thread::sleep,
+ time::{Duration, Instant},
+};
use windows::{
Win32::{
Foundation::{CloseHandle, HWND, LPARAM, RECT, WPARAM},
- Graphics::Dwm::{DWMWA_CLOAKED, DWMWA_TRANSITIONS_FORCEDISABLED, DwmGetWindowAttribute, DwmSetWindowAttribute},
- System::Threading::{OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW},
+ Graphics::Dwm::{
+ DWMWA_CLOAKED, DWMWA_TRANSITIONS_FORCEDISABLED, DwmGetWindowAttribute,
+ DwmSetWindowAttribute,
+ },
+ System::Threading::{
+ OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
+ QueryFullProcessImageNameW,
+ },
UI::WindowsAndMessaging::*,
},
core::{BOOL, PWSTR},
@@ -18,24 +27,45 @@ fn exe(hwnd: HWND) -> String {
unsafe {
let mut pid = 0;
GetWindowThreadProcessId(hwnd, Some(&mut pid));
- let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return String::new() };
+ let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else {
+ return String::new();
+ };
let mut buffer = [0u16; 512];
let mut len = buffer.len() as u32;
- let ok = QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, PWSTR(buffer.as_mut_ptr()), &mut len).is_ok();
+ let ok = QueryFullProcessImageNameW(
+ process,
+ PROCESS_NAME_WIN32,
+ PWSTR(buffer.as_mut_ptr()),
+ &mut len,
+ )
+ .is_ok();
let _ = CloseHandle(process);
- if !ok { return String::new() }
- String::from_utf16_lossy(&buffer[..len as usize]).rsplit(char::from(92)).next().unwrap_or_default().to_lowercase()
+ if !ok {
+ return String::new();
+ }
+ String::from_utf16_lossy(&buffer[..len as usize])
+ .rsplit(char::from(92))
+ .next()
+ .unwrap_or_default()
+ .to_lowercase()
}
}
-struct Find { name: String, found: HWND }
+struct Find {
+ name: String,
+ found: HWND,
+}
unsafe extern "system" fn find(hwnd: HWND, l: LPARAM) -> BOOL {
unsafe {
let f = &mut *(l.0 as *mut Find);
let ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
let mut r = RECT::default();
let _ = GetWindowRect(hwnd, &mut r);
- if (IsWindowVisible(hwnd).as_bool()) && ex & WS_EX_TOOLWINDOW.0 == 0 && GetWindowTextLengthW(hwnd) > 0 && exe(hwnd) == f.name {
+ if (IsWindowVisible(hwnd).as_bool())
+ && ex & WS_EX_TOOLWINDOW.0 == 0
+ && GetWindowTextLengthW(hwnd) > 0
+ && exe(hwnd) == f.name
+ {
f.found = hwnd;
return false.into();
}
@@ -46,16 +76,28 @@ unsafe extern "system" fn find(hwnd: HWND, l: LPARAM) -> BOOL {
fn on_top(target: HWND) -> bool {
unsafe {
let mut frame = RECT::default();
- if IsIconic(target).as_bool() || GetWindowRect(target, &mut frame).is_err() { return false; }
+ if IsIconic(target).as_bool() || GetWindowRect(target, &mut frame).is_err() {
+ return false;
+ }
let mut current = GetTopWindow(None).ok();
while let Some(w) = current {
- if w == target { return true; }
+ if w == target {
+ return true;
+ }
let ex = GetWindowLongW(w, GWL_EXSTYLE) as u32;
let mut r = RECT::default();
let mut cloaked = 0u32;
let _ = DwmGetWindowAttribute(w, DWMWA_CLOAKED, (&raw mut cloaked).cast(), 4);
- if IsWindowVisible(w).as_bool() && !IsIconic(w).as_bool() && cloaked == 0 && ex & (WS_EX_TOPMOST.0 | WS_EX_TOOLWINDOW.0) == 0
- && GetWindowRect(w, &mut r).is_ok() && r.left < frame.right && frame.left < r.right && r.top < frame.bottom && frame.top < r.bottom {
+ if IsWindowVisible(w).as_bool()
+ && !IsIconic(w).as_bool()
+ && cloaked == 0
+ && ex & (WS_EX_TOPMOST.0 | WS_EX_TOOLWINDOW.0) == 0
+ && GetWindowRect(w, &mut r).is_ok()
+ && r.left < frame.right
+ && frame.left < r.right
+ && r.top < frame.bottom
+ && frame.top < r.bottom
+ {
return false;
}
current = GetWindow(w, GW_HWNDNEXT).ok();
@@ -69,37 +111,91 @@ fn main() {
let method = std::env::args().nth(2).unwrap_or_else(|| "A".into());
let calm = std::env::args().nth(3).as_deref() == Some("calm");
unsafe {
- let mut f = Find { name, found: HWND::default() };
+ let mut f = Find {
+ name,
+ found: HWND::default(),
+ };
let _ = EnumWindows(Some(find), LPARAM(&raw mut f as isize));
let hwnd = f.found;
- if hwnd.is_invalid() { println!("window not found"); return; }
+ if hwnd.is_invalid() {
+ println!("window not found");
+ return;
+ }
let off = BOOL::from(calm);
- let _ = DwmSetWindowAttribute(hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, (&raw const off).cast(), 4);
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_TRANSITIONS_FORCEDISABLED,
+ (&raw const off).cast(),
+ 4,
+ );
let _ = ShowWindow(hwnd, SW_MINIMIZE);
sleep(Duration::from_millis(1500));
let start = Instant::now();
match method.as_str() {
- "A" => { let _ = ShowWindow(hwnd, SW_RESTORE); let _ = SetForegroundWindow(hwnd); }
- "B" => { let _ = PostMessageW(Some(hwnd), WM_SYSCOMMAND, WPARAM(SC_RESTORE as usize), LPARAM(0)); let _ = SetForegroundWindow(hwnd); }
+ "A" => {
+ let _ = ShowWindow(hwnd, SW_RESTORE);
+ let _ = SetForegroundWindow(hwnd);
+ }
+ "B" => {
+ let _ = PostMessageW(
+ Some(hwnd),
+ WM_SYSCOMMAND,
+ WPARAM(SC_RESTORE as usize),
+ LPARAM(0),
+ );
+ let _ = SetForegroundWindow(hwnd);
+ }
"C" => SwitchToThisWindow(hwnd, true),
- "D" => { let _ = SetForegroundWindow(hwnd); let _ = ShowWindow(hwnd, SW_RESTORE); }
- "E" => { let _ = ShowWindowAsync(hwnd, SW_RESTORE); let _ = SetForegroundWindow(hwnd); }
- "F" => { let _ = ShowWindow(hwnd, SW_RESTORE); let _ = SetForegroundWindow(hwnd);
- let _ = SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS); }
+ "D" => {
+ let _ = SetForegroundWindow(hwnd);
+ let _ = ShowWindow(hwnd, SW_RESTORE);
+ }
+ "E" => {
+ let _ = ShowWindowAsync(hwnd, SW_RESTORE);
+ let _ = SetForegroundWindow(hwnd);
+ }
+ "F" => {
+ let _ = ShowWindow(hwnd, SW_RESTORE);
+ let _ = SetForegroundWindow(hwnd);
+ let _ = SetWindowPos(
+ hwnd,
+ Some(HWND_TOP),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS,
+ );
+ }
_ => {}
}
let call_ms = start.elapsed().as_millis();
let (mut restored, mut front, mut top) = (None, None, None);
while start.elapsed() < Duration::from_millis(4000) {
let t = start.elapsed().as_millis();
- if restored.is_none() && !IsIconic(hwnd).as_bool() { restored = Some(t); }
- if front.is_none() && GetForegroundWindow() == hwnd { front = Some(t); }
- if top.is_none() && on_top(hwnd) { top = Some(t); }
- if restored.is_some() && front.is_some() && top.is_some() { break; }
+ if restored.is_none() && !IsIconic(hwnd).as_bool() {
+ restored = Some(t);
+ }
+ if front.is_none() && GetForegroundWindow() == hwnd {
+ front = Some(t);
+ }
+ if top.is_none() && on_top(hwnd) {
+ top = Some(t);
+ }
+ if restored.is_some() && front.is_some() && top.is_some() {
+ break;
+ }
sleep(Duration::from_millis(5));
}
- println!("method {method} calm={calm}: call returned {call_ms} ms, restored {restored:?}, foreground {front:?}, on top {top:?}");
+ println!(
+ "method {method} calm={calm}: call returned {call_ms} ms, restored {restored:?}, foreground {front:?}, on top {top:?}"
+ );
let on = BOOL::from(false);
- let _ = DwmSetWindowAttribute(hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, (&raw const on).cast(), 4);
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_TRANSITIONS_FORCEDISABLED,
+ (&raw const on).cast(),
+ 4,
+ );
}
}