A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat: add network and audio status monitoring to menu bar; implement search, task view, and widgets functionality feat: create CHANGELOG.md for version history in English and Spanish feat: update README with Spanish version and installation instructions feat: enhance release workflow to include changelog notes in draft releases refactor: improve graphics rendering for system icons in the dock refactor: clean up and organize dependencies in Cargo.toml files
CristianOlivera1fdbfab61f6b0
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 64f1ea9..be6b4d4 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -73,10 +73,20 @@ jobs:Copy-Item "$nsis/$setup.sig" upload/Copy-Item "$nsis/$setup" upload/Muelle-Setup.exe+ # The release text is this version's section of CHANGELOG.md (English+ # and Spanish), between its heading and the next one.+ $lines = Get-Content CHANGELOG.md+ $start = [array]::IndexOf($lines, "## [$env:VERSION]")+ if ($start -lt 0) { throw "CHANGELOG.md has no section for $env:VERSION" }+ $rest = $lines[($start + 1)..($lines.Count - 1)]+ $end = ($rest | Select-String -Pattern '^## \[' | Select-Object -First 1).LineNumber+ $section = if ($end) { $rest[0..($end - 2)] } else { $rest }+ $section | Set-Content -Encoding utf8NoBOM notes.md+- name: Create draft releaseshell: pwshenv:GH_TOKEN: ${{ github.token }}run: |gh release create $env:GITHUB_REF_NAME (Get-ChildItem upload).FullName `- --draft --generate-notes --title "Muelle $env:GITHUB_REF_NAME"+ --draft --notes-file notes.md --title "Muelle $env:GITHUB_REF_NAME"diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..cec0c42--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,52 @@+# Changelog / Cambios++Each release lists its changes in English and in Spanish. The release workflow+copies the section of the version being published into the GitHub release.++Cada versión lista sus cambios en inglés y en español. El flujo de publicación+copia la sección de la versión que se publica a la release de GitHub.++## [0.1.1]++### English++- Menu bar: network (Wi-Fi strength, Ethernet or offline) and volume, updated+ as they change. Search, Task View and Widgets buttons appear when they are on+ in your Windows taskbar settings.+- Clicking the app that is already in front minimizes it, as the Windows+ taskbar does; click again to bring it back. Settings can switch this to+ "do nothing", as on a Mac.+- Apps opened from the dock come to the front reliably instead of sometimes+ opening behind other windows.+- Minimized apps that run as administrator, such as Task Manager, can be brought+ back from the dock.+- Settings: restore defaults, and options to show open-app indicators, show+ recent apps and animate opening apps.++### Español++- Barra superior: red (intensidad del Wi-Fi, Ethernet o sin conexión) y volumen,+ actualizados al momento. Los botones de búsqueda, Vista de tareas y Widgets+ aparecen si los tienes activados en la barra de tareas de Windows.+- Clic en la app que ya está delante la minimiza, como la barra de Windows; otro+ clic la vuelve a traer. En Ajustes se puede cambiar a «no hacer nada», como en Mac.+- Las apps abiertas desde el dock aparecen delante siempre, en vez de abrirse a+ veces detrás de otras ventanas.+- Las apps minimizadas que se ejecutan como administrador, como el Administrador+ de tareas, se pueden recuperar desde el dock.+- Ajustes: restablecer valores y opciones para mostrar los indicadores de apps+ abiertas, mostrar las apps recientes y animar al abrir apps.++## [0.1.0]++### English++- First release: glass dock with magnification, live minimized-window+ thumbnails, optional Genie effect, menu bar, Settings app in English and+ Spanish, one-step installer and in-app updates.++### Español++- Primera versión: dock de cristal con ampliación, miniaturas en vivo de las+ ventanas minimizadas, efecto genio opcional, barra superior, app de Ajustes en+ español e inglés, instalador de un paso y actualizaciones desde la app.diff --git a/Cargo.lock b/Cargo.lockindex b788b07..b79b3f4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1998,6 +1998,7 @@ version = "0.1.1"dependencies = ["thiserror 2.0.21","windows",+ "windows-core",][[package]]diff --git a/README.es.md b/README.es.mdnew file mode 100644index 0000000..3757ab4--- /dev/null+++ b/README.es.md@@ -0,0 +1,147 @@+<div align="center">++<img width="50%" alt="Muelle" src="https://github.com/user-attachments/assets/8c715a53-a0df-4780-9dd4-09ce3ccd9043" />++ **Un dock ligero, inspirado en macOS, para Windows 11.**++ Ampliación suave, miniaturas de ventanas en vivo y un efecto genio opcional al minimizar.++ [English](README.md) · **Español**+</div>++Muelle sustituye la barra de tareas de Windows por un dock personalizable y una+barra superior opcional al estilo de macOS. Está hecho para Windows 11 y sigue+en desarrollo activo.++<img width="1919" height="1008" alt="Muelle en Windows 11" src="https://github.com/user-attachments/assets/b6c44203-c425-43fb-adf5-e2edd2f02257" />++## Funciones++- Dock de cristal con ampliación suave de los iconos bajo el cursor.+- Abrir, fijar, reordenar y gestionar apps, incluidas las recientes y las ventanas abiertas.+- Miniaturas en vivo de las ventanas minimizadas.+- Clic en la app que ya está delante para minimizarla, como en la barra de Windows.+- Arrastrar y soltar archivos sobre apps, Descargas o la Papelera.+- Ocultación automática opcional.+- Barra superior con la app en primer plano, hora, red, volumen y batería, además de+ los botones de búsqueda, Vista de tareas y Widgets si los tienes en la barra de Windows.+- 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.++El efecto genio está **desactivado por defecto**. Mientras está activo, Muelle+desactiva las transiciones de Windows en las ventanas que sigue, para poder+dibujar su animación; las devuelve al cerrarse.++## Instalar++**[Descargar Muelle-Setup.exe](https://github.com/crafter-station/Muelle/releases/latest/download/Muelle-Setup.exe)**+(Windows 11, 64 bits) o elige una versión en+[Releases](https://github.com/crafter-station/Muelle/releases).++1. Ejecuta `Muelle-Setup.exe`. Se instala solo para tu usuario: sin permisos de+ administrador, sin asistente, en unos dos segundos.+2. El instalador aún no está firmado, así que SmartScreen puede decir que protegió+ tu PC. Elige **Más información → Ejecutar de todas formas**.+3. Aparece el dock y se oculta la barra de tareas de Windows. Desde entonces Muelle+ se abre al iniciar Windows; puedes desactivarlo en Ajustes → Sistema.++Abre **Muelle** desde el menú Inicio (o clic derecho en el dock → *Ajustes de+Muelle…*) para cambiar el dock. Ajustes también busca actualizaciones y las instala.++**Recuperar la barra de tareas:** clic derecho en el dock → *Salir de Muelle*.+Para quitarlo del todo: Configuración de Windows → Aplicaciones → Aplicaciones+instaladas → Muelle → Desinstalar; la barra vuelve y no queda nada en marcha.++## Probarlo desde el código++### Requisitos++- Windows 11+- Rust con la toolchain MSVC y las Build Tools de C++ de Visual Studio+- Node.js y pnpm++### Ejecutar el dock++Desde la raíz del repositorio:++```powershell+cargo run -p muelle+```++El dock oculta la barra de tareas mientras está en marcha. Pulsa **Ctrl+C** en la+terminal para salir; Muelle debería devolver la barra solo. Para devolverla a mano:++```powershell+cargo run -p muelle -- --restore+```++### Ejecutar Ajustes++Con el dock en marcha, abre otra terminal y ejecuta:++```powershell+cd apps\settings+pnpm install+pnpm tauri dev+```++Se abre la ventana de Ajustes. Los cambios de la interfaz se recargan solos; tras+cambiar el backend en Rust, reinicia `tauri dev`. Los cambios de Ajustes se+aplican al dock en marcha.++## Compilar y probar++Desde la raíz del repositorio:++```powershell+cargo fmt --all -- --check+cargo test --workspace --locked+```++Para compilar la interfaz de Ajustes:++```powershell+cd apps\settings+pnpm build+```++## Estructura++| Ruta | Para qué |+|---|---|+| `apps/dock` | El dock nativo de Windows |+| `apps/settings` | La app de Ajustes (Tauri) |+| `crates/muelle-core` | Lógica de disposición y animación, independiente de la plataforma |+| `crates/muelle-shell` | Integración con el shell de Windows |+| `crates/muelle-config` | Ajustes compartidos y su guardado |+| `muelle/` | La web (Astro) |++## Compilar el instalador++```powershell+cd apps\settings+pnpm install+cd ..\..+.\scripts\build-installer.ps1+```++El script compila las dos apps y genera `Muelle_<versión>_x64-setup.exe` en+`target\release\bundle\nsis`. El instalador es por usuario, no pide permisos de+administrador ni muestra asistente: instala en `%LOCALAPPDATA%\Programs\Muelle`,+activa el inicio con Windows y abre el dock. Al desinstalar (Configuración →+Aplicaciones) se cierra el dock y vuelve la barra de tareas de Windows.++Al subir una etiqueta que coincida con la versión (por ejemplo `v0.1.1`), GitHub+Actions compila el instalador y lo adjunta a un borrador de release, junto con+`Muelle-Setup.exe` (el enlace de descarga de la web), `latest.json` (lo lee el+actualizador de Ajustes) y las notas de esa versión sacadas de `CHANGELOG.md`.+El repositorio necesita los secretos `TAURI_SIGNING_PRIVATE_KEY` y+`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Publica el borrador para que pase a ser la+descarga y la actualización.++## Estado++El dock, Ajustes y el instalador funcionan en Windows 11. Algunas funciones e+interacciones aún se están verificando. El instalador todavía no está firmado,+así que SmartScreen avisa antes de ejecutarlo (Más información → Ejecutar de+todas formas).diff --git a/README.md b/README.mdindex 8bb3edb..b5027c9 100644--- a/README.md+++ b/README.md@@ -5,6 +5,8 @@**A lightweight, macOS-inspired dock for Windows 11.**Smooth magnification, live window previews, and an optional Genie-style minimize effect.++ **English** · [Español](README.es.md)</div>Muelle replaces the Windows taskbar with a customizable dock and an optional@@ -18,8 +20,11 @@ development.- Glass-style dock with smooth, cursor-based icon magnification.- Launch, pin, reorder, and manage apps, including recent apps and open windows.- Live minimized-window previews.+- Click the app already in front to minimize it, as on the Windows taskbar.- Drag and drop files onto apps, Downloads, or the Recycle Bin.-- Optional auto-hide and a top menu bar with the clock and system shortcuts.+- Optional auto-hide.+- A top menu bar with the app in front, clock, network, volume and battery, plus+ the Search, Task View and Widgets buttons if you have them on the Windows taskbar.- Separate Settings app with live changes, Spanish and English, and aconfigurable Genie-style minimize animation.- A watchdog restores the Windows taskbar if the dock exits unexpectedly.@@ -129,10 +134,10 @@ administrator rights and shows no wizard: it installs to`%LOCALAPPDATA%\Programs\Muelle`, turns on start with Windows and opens the dock.Uninstalling (Settings → Apps) quits the dock and gives the Windows taskbar back.-Pushing a tag that matches the version (for example `v0.1.0`) builds the+Pushing a tag that matches the version (for example `v0.1.1`) builds theinstaller on GitHub Actions and attaches it to a draft release, together with-`Muelle-Setup.exe` (the website's download link) and `latest.json` (read by the-updater in Settings). The repository needs the secrets+`Muelle-Setup.exe` (the website's download link), `latest.json` (read by the+updater in Settings) and that version's notes from `CHANGELOG.md`. The repository needs the secrets`TAURI_SIGNING_PRIVATE_KEY` and `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Publish thedraft to make it the download and the update.diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsindex 5dd133f..422761c 100644--- a/apps/dock/src/gfx.rs+++ b/apps/dock/src/gfx.rs@@ -34,7 +34,9 @@ use windows::{DirectWrite::{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_TEXT_METRICS, DWriteCreateFactory, IDWriteFactory,+ DWRITE_MEASURING_MODE_NATURAL, DWRITE_PARAGRAPH_ALIGNMENT_CENTER,+ DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_METRICS, DWriteCreateFactory,+ IDWriteFactory,},Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},},@@ -420,6 +422,59 @@ impl Gfx {})}+ /// Symbols from Segoe Fluent Icons, the Windows 11 system icon font, centered+ /// in a square. Layers are drawn in order with their opacity, so a dim full+ /// Wi-Fi fan can sit behind the bars actually received.+ pub fn glyph_brush(&self, layers: &[(char, f32)], scale: f32, ink: Ink) -> Result<LabelBrush> {+ let side = (18.0 * scale).round();+ // SAFETY: The format lives for the drawing below.+ let format = unsafe {+ let format = self.dwrite.CreateTextFormat(+ w!("Segoe Fluent Icons"),+ None,+ DWRITE_FONT_WEIGHT_NORMAL,+ DWRITE_FONT_STYLE_NORMAL,+ DWRITE_FONT_STRETCH_NORMAL,+ 15.0 * scale,+ w!(""),+ )?;+ format.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)?;+ format.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)?;+ format+ };+ let brush = self.draw(side as u32, side as u32, |dc| {+ let area = D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: side,+ bottom: side,+ };+ // SAFETY: The brush, format and text live for each drawing call.+ unsafe {+ let ink = dc.CreateSolidColorBrush(&ink.color(), None)?;+ for &(glyph, opacity) in layers {+ let mut units = [0u16; 2];+ let text = glyph.encode_utf16(&mut units);+ ink.SetOpacity(opacity);+ dc.DrawText(+ text,+ &format,+ &area,+ &ink,+ D2D1_DRAW_TEXT_OPTIONS_NONE,+ DWRITE_MEASURING_MODE_NATURAL,+ );+ }+ }+ Ok(())+ })?;+ Ok(LabelBrush {+ brush,+ width: side,+ height: side,+ })+ }+/// Two switches, one on and one off: the control center glyph.pub fn control_center_brush(&self, scale: f32, ink: Ink) -> Result<LabelBrush> {let (width, height) = ((19.0 * scale).round(), (16.0 * scale).round());diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 3545c52..4e91737 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -10,11 +10,17 @@//!//! With auto-hide on, the bar reserves no space and stays off screen; a thin//! strip along the top edge reveals it while the pointer is there.+//!+//! Status items, right to left as on a Mac: clock, control center, search,+//! network, volume, battery, then Task View and Widgets. Search, Task View and+//! Widgets appear only if the user has them on the Windows taskbar. Network+//! and volume changes arrive as `STATUS_CHANGED`; nothing polls.use anyhow::Result;use muelle_shell::{appbar::{AppBar, Edge},launcher,+ status::{self, AudioWatch, Network, NetworkWatch, TaskbarButtons, Volume},system::{self, Battery, Monitor},};use windows::{@@ -33,8 +39,8 @@ use windows::{UI::WindowsAndMessaging::{CreateWindowExW, DefWindowProcW, DestroyWindow, HWND_TOPMOST, IDC_ARROW, LoadCursorW,RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,- WM_APP, WM_LBUTTONUP, WM_MOUSEMOVE, WM_TIMER, WNDCLASSW, WS_EX_NOACTIVATE,- WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,+ WM_APP, WM_LBUTTONUP, WM_MOUSEMOVE, WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW,+ WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,},},core::{BOOL, Interface, w},@@ -61,11 +67,38 @@ const WM_POWERBROADCAST: u32 = 0x0218;const WM_MOUSELEAVE: u32 = 0x02A3;/// AppBar notifications need a message id; the bar ignores them.const APPBAR_CALLBACK: u32 = WM_APP + 20;+/// Posted by the network and audio watches.+const STATUS_CHANGED: u32 = WM_APP + 21;++/// Segoe Fluent Icons code points.+mod glyph {+ pub const WIFI: [char; 4] = ['\u{E872}', '\u{E873}', '\u{E874}', '\u{E701}'];+ pub const WIFI_FULL: char = '\u{E701}';+ pub const ETHERNET: char = '\u{E839}';+ pub const OFFLINE: char = '\u{F384}';+ pub const VOLUME: [char; 4] = ['\u{E992}', '\u{E993}', '\u{E994}', '\u{E995}'];+ pub const MUTE: char = '\u{E74F}';+ pub const SEARCH: char = '\u{E721}';+ pub const TASK_VIEW: char = '\u{E7C4}';+ pub const WIDGETS: char = '\u{F246}';+}#[derive(Clone, Copy, PartialEq, Eq)]enum Action {QuickSettings,Notifications,+ Sound,+ Search,+ TaskView,+ Widgets,+}++/// Network, volume and taskbar buttons, read only when Windows reports a change.+#[derive(Clone, Copy, PartialEq, Eq)]+struct Status {+ network: Network,+ volume: Option<Volume>,+ buttons: TaskbarButtons,}/// What the bar was last drawn for.@@ -77,6 +110,7 @@ struct Look {app_name: String,clock: String,battery: Option<Battery>,+ status: Status,}pub struct MenuBar {@@ -94,6 +128,10 @@ pub struct MenuBar {/// Current visual tree and where the full bar goes on screen.root: Option<ContainerVisual>,bounds: RECT,+ status: Status,+ /// Held for their callbacks; dropping them unsubscribes.+ _network: Option<NetworkWatch>,+ audio: Option<AudioWatch>,}unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {@@ -104,8 +142,9 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -}WM_MOUSEMOVE => app::menu_bar_hover(true),WM_MOUSELEAVE => app::menu_bar_hover(false),- // The minute changed, or the charger was plugged or unplugged.- WM_TIMER | WM_POWERBROADCAST => app::menu_bar_tick(),+ // The minute changed, the charger was plugged or unplugged, the+ // network or volume changed, or a Windows setting (taskbar buttons).+ WM_TIMER | WM_POWERBROADCAST | STATUS_CHANGED | WM_SETTINGCHANGE => app::menu_bar_tick(),// SAFETY: Standard forwarding of unhandled messages._ => return unsafe { DefWindowProcW(hwnd, msg, w, l) },}@@ -178,7 +217,15 @@ impl MenuBar {revealed: false,root: None,bounds: RECT::default(),+ status: Status {+ network: Network::Offline,+ volume: None,+ buttons: TaskbarButtons::default(),+ },+ _network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),+ audio: AudioWatch::new(hwnd.0 as isize, STATUS_CHANGED),};+ bar.update_status();bar.refresh(gfx)?;bar.schedule_next_minute();Ok(bar)@@ -273,12 +320,21 @@ impl MenuBar {Ok(())}- /// The minute changed or the power state did: redraw what differs.+ /// The minute changed, or something the bar shows did: redraw what differs.pub fn tick(&mut self, gfx: &Gfx) -> Result<()> {+ self.update_status();self.schedule_next_minute();self.refresh(gfx)}+ fn update_status(&mut self) {+ self.status = Status {+ network: status::network(),+ volume: self.audio.as_mut().and_then(AudioWatch::volume),+ buttons: status::taskbar_buttons(),+ };+ }+/// One wake-up per minute, aligned to the minute, instead of polling.fn schedule_next_minute(&self) {// SAFETY: Read-only query, then a timer on our own window (setting an@@ -303,6 +359,10 @@ impl MenuBar {match hit.map(|(_, _, action)| *action) {Some(Action::QuickSettings) => launcher::open_quick_settings(),Some(Action::Notifications) => launcher::open_notifications(),+ Some(Action::Sound) => launcher::open_sound(),+ Some(Action::Search) => launcher::open_search(),+ Some(Action::TaskView) => launcher::open_task_view(),+ Some(Action::Widgets) => launcher::open_widgets(),None => {}}}@@ -319,6 +379,7 @@ impl MenuBar {app_name: self.app_name.clone(),clock: system::clock_text(),battery: system::battery(),+ status: self.status,};if self.look.as_ref() == Some(&look) {return Ok(());@@ -384,9 +445,11 @@ impl MenuBar {place(&layers, &name, px(SIDE_MARGIN))?;}- // Right side, from the edge inward: clock, control center, battery.+ // Right side, from the edge inward.let slop = px(HIT_SLOP);let mut right = width - px(SIDE_MARGIN);+ let status = look.status;+ let symbol = |layers: &[(char, f32)]| gfx.glyph_brush(layers, scale, ink);let mut items: Vec<(LabelBrush, Action)> = vec![(gfx.text_brush(&look.clock, scale, false, ink)?,@@ -394,12 +457,39 @@ impl MenuBar {),(gfx.control_center_brush(scale, ink)?, Action::QuickSettings),];+ if status.buttons.search {+ items.push((symbol(&[(glyph::SEARCH, 1.0)])?, Action::Search));+ }+ let network = match status.network {+ // The full fan stays faint behind the bars received, as on a Mac.+ Network::Wifi { bars } => vec![+ (glyph::WIFI_FULL, 0.3),+ (glyph::WIFI[usize::from(bars.clamp(1, 4)) - 1], 1.0),+ ],+ Network::Ethernet => vec![(glyph::ETHERNET, 1.0)],+ Network::Offline => vec![(glyph::OFFLINE, 1.0)],+ };+ items.push((symbol(&network)?, Action::QuickSettings));+ if let Some(volume) = status.volume {+ let speaker = if volume.muted {+ glyph::MUTE+ } else {+ glyph::VOLUME[usize::from(volume.level.min(3))]+ };+ items.push((symbol(&[(speaker, 1.0)])?, Action::Sound));+ }if let Some(battery) = look.battery {items.push((gfx.battery_brush(battery.percent, battery.charging, scale, ink)?,Action::QuickSettings,));}+ if status.buttons.task_view {+ items.push((symbol(&[(glyph::TASK_VIEW, 1.0)])?, Action::TaskView));+ }+ if status.buttons.widgets {+ items.push((symbol(&[(glyph::WIDGETS, 1.0)])?, Action::Widgets));+ }for (item, action) in &items {let left = right - item.width;place(&layers, item, left)?;diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.tomlindex 31a50ec..dc6c2b8 100644--- a/crates/muelle-shell/Cargo.toml+++ b/crates/muelle-shell/Cargo.toml@@ -9,11 +9,17 @@ workspace = true[dependencies]thiserror.workspace = true+# `#[implement]` (COM callbacks in `status`) expands to paths in windows-core.+windows-core.workspace = truewindows = { workspace = true, features = [+ "Foundation",+ "Networking_Connectivity","Win32_Foundation","Win32_Globalization","Win32_Graphics_Dwm","Win32_Graphics_Gdi",+ "Win32_Media_Audio",+ "Win32_Media_Audio_Endpoints","Win32_Storage_EnhancedStorage","Win32_Storage_FileSystem","Win32_Storage_Packaging_Appx",diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rsindex 67a4e2e..094abc6 100644--- a/crates/muelle-shell/src/launcher.rs+++ b/crates/muelle-shell/src/launcher.rs@@ -5,7 +5,8 @@ use windows::{UI::{Input::KeyboardAndMouse::{INPUT, INPUT_0, INPUT_KEYBOARD, INPUT_MOUSE, KEYBD_EVENT_FLAGS, KEYBDINPUT,- KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_LWIN, VK_N,+ KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_LCONTROL, VK_LWIN, VK_N, VK_S,+ VK_TAB, VK_V, VK_W,},Shell::ShellExecuteW,WindowsAndMessaging::{@@ -125,6 +126,26 @@ pub fn open_notifications() {tap(&[VK_LWIN, VK_N]);}+/// Windows Search, as the taskbar's search button: Win+S.+pub fn open_search() {+ tap(&[VK_LWIN, VK_S]);+}++/// Task View (open windows and virtual desktops): Win+Tab.+pub fn open_task_view() {+ tap(&[VK_LWIN, VK_TAB]);+}++/// The Widgets board: Win+W.+pub fn open_widgets() {+ tap(&[VK_LWIN, VK_W]);+}++/// The sound output page of quick settings (Windows 11 22H2+): Win+Ctrl+V.+pub fn open_sound() {+ tap(&[VK_LWIN, VK_LCONTROL, VK_V]);+}+pub fn reveal(path: &str) -> Result<(), LaunchError> {let arguments = HSTRING::from(format!("/select,\"{path}\""));allow_foreground();diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsindex e0634d1..43766d9 100644--- a/crates/muelle-shell/src/lib.rs+++ b/crates/muelle-shell/src/lib.rs@@ -10,6 +10,7 @@ pub mod pins;pub mod power;pub mod recycle_bin;pub mod screen;+pub mod status;pub mod system;pub mod taskbar;pub mod tracker;diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rsnew file mode 100644index 0000000..73bfba2--- /dev/null+++ b/crates/muelle-shell/src/status.rs@@ -0,0 +1,308 @@+//! System status for the menu bar: the network, the output volume, and the+//! buttons the user has turned on for the Windows taskbar.+//!+//! Nothing here polls. Windows reports network and volume changes through+//! callbacks on its own threads; they only post `message` to the bar's window,+//! which then reads the new state on its UI thread.++use windows::{+ Networking::Connectivity::{+ NetworkConnectivityLevel, NetworkInformation, NetworkStatusChangedEventHandler,+ },+ Win32::{+ Foundation::{HWND, LPARAM, PROPERTYKEY, WPARAM},+ Media::Audio::{+ AUDIO_VOLUME_NOTIFICATION_DATA, DEVICE_STATE, EDataFlow, ERole,+ Endpoints::{+ IAudioEndpointVolume, IAudioEndpointVolumeCallback,+ IAudioEndpointVolumeCallback_Impl,+ },+ IMMDeviceEnumerator, IMMNotificationClient, IMMNotificationClient_Impl,+ MMDeviceEnumerator, eConsole, eRender,+ },+ System::{+ Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree},+ Registry::{HKEY_CURRENT_USER, RRF_RT_REG_DWORD, RegGetValueW},+ },+ UI::WindowsAndMessaging::PostMessageW,+ },+ core::{HSTRING, PCWSTR, Result, implement, w},+};++fn notify(window: isize, message: u32) {+ // SAFETY: Only posts a message; a window that no longer exists ignores it.+ unsafe {+ let _ = PostMessageW(Some(HWND(window as *mut _)), message, WPARAM(0), LPARAM(0));+ }+}++/* ---------------------------------------------------------------- Network */++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Network {+ Offline,+ Ethernet,+ /// Signal strength from 1 to 4 bars.+ Wifi {+ bars: u8,+ },+}++/// The connection Windows uses to reach the internet.+#[must_use]+pub fn network() -> Network {+ let Ok(profile) = NetworkInformation::GetInternetConnectionProfile() else {+ return Network::Offline;+ };+ let connected = profile+ .GetNetworkConnectivityLevel()+ .is_ok_and(|level| level != NetworkConnectivityLevel::None);+ if !connected {+ return Network::Offline;+ }+ if profile.IsWlanConnectionProfile().unwrap_or(false) {+ // Windows reports 0 to 5 bars; the glyphs have 4 steps.+ let reported = profile+ .GetSignalBars()+ .and_then(|bars| bars.Value())+ .unwrap_or(5);+ let bars = (u32::from(reported.min(5)) * 4).div_ceil(5).max(1) as u8;+ Network::Wifi { bars }+ } else {+ Network::Ethernet+ }+}++/// Posts `message` to `window` whenever the network changes.+pub struct NetworkWatch {+ token: i64,+}++impl NetworkWatch {+ #[must_use]+ pub fn new(window: isize, message: u32) -> Option<Self> {+ let handler = NetworkStatusChangedEventHandler::new(move |_| {+ notify(window, message);+ Ok(())+ });+ NetworkInformation::NetworkStatusChanged(&handler)+ .ok()+ .map(|token| Self { token })+ }+}++impl Drop for NetworkWatch {+ fn drop(&mut self) {+ let _ = NetworkInformation::RemoveNetworkStatusChanged(self.token);+ }+}++/* ----------------------------------------------------------------- Volume */++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Volume {+ pub muted: bool,+ /// 0 (silent) to 3 (loud): the steps the speaker glyph has.+ pub level: u8,+}++#[implement(IAudioEndpointVolumeCallback)]+struct VolumeChanged {+ window: isize,+ message: u32,+}++impl IAudioEndpointVolumeCallback_Impl for VolumeChanged_Impl {+ fn OnNotify(&self, _data: *mut AUDIO_VOLUME_NOTIFICATION_DATA) -> Result<()> {+ notify(self.window, self.message);+ Ok(())+ }+}++#[implement(IMMNotificationClient)]+struct DeviceChanged {+ window: isize,+ message: u32,+}++impl IMMNotificationClient_Impl for DeviceChanged_Impl {+ fn OnDeviceStateChanged(&self, _id: &PCWSTR, _state: DEVICE_STATE) -> Result<()> {+ Ok(())+ }++ fn OnDeviceAdded(&self, _id: &PCWSTR) -> Result<()> {+ Ok(())+ }++ fn OnDeviceRemoved(&self, _id: &PCWSTR) -> Result<()> {+ Ok(())+ }++ fn OnDefaultDeviceChanged(&self, flow: EDataFlow, role: ERole, _id: &PCWSTR) -> Result<()> {+ if flow == eRender && role == eConsole {+ notify(self.window, self.message);+ }+ Ok(())+ }++ fn OnPropertyValueChanged(&self, _id: &PCWSTR, _key: &PROPERTYKEY) -> Result<()> {+ Ok(())+ }+}++/// The default speakers' volume, followed across device changes.+pub struct AudioWatch {+ enumerator: IMMDeviceEnumerator,+ devices: IMMNotificationClient,+ /// Current default device, its volume control and our callback on it.+ endpoint: Option<(String, IAudioEndpointVolume, IAudioEndpointVolumeCallback)>,+ window: isize,+ message: u32,+}++impl AudioWatch {+ /// Must be created on a thread with COM initialized (the UI thread).+ #[must_use]+ pub fn new(window: isize, message: u32) -> Option<Self> {+ // SAFETY: COM is initialized on this thread; the enumerator and the+ // registered client are released in `Drop`.+ let (enumerator, devices) = unsafe {+ let enumerator: IMMDeviceEnumerator =+ CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;+ let devices: IMMNotificationClient = DeviceChanged { window, message }.into();+ enumerator+ .RegisterEndpointNotificationCallback(&devices)+ .ok()?;+ (enumerator, devices)+ };+ Some(Self {+ enumerator,+ devices,+ endpoint: None,+ window,+ message,+ })+ }++ /// Current volume of the default speakers, or `None` without any.+ pub fn volume(&mut self) -> Option<Volume> {+ self.follow_default();+ let (_, endpoint, _) = self.endpoint.as_ref()?;+ // SAFETY: Plain queries on a live COM object.+ let (level, muted) = unsafe {+ (+ endpoint.GetMasterVolumeLevelScalar().ok()?,+ endpoint.GetMute().ok()?.as_bool(),+ )+ };+ let level = match level {+ l if l < 0.01 => 0,+ l if l < 0.34 => 1,+ l if l < 0.67 => 2,+ _ => 3,+ };+ Some(Volume { muted, level })+ }++ /// Moves the volume callback to the default device if it changed.+ fn follow_default(&mut self) {+ // SAFETY: COM calls on live objects; the id string is freed with+ // CoTaskMemFree as the API requires.+ unsafe {+ let Ok(device) = self.enumerator.GetDefaultAudioEndpoint(eRender, eConsole) else {+ self.unbind();+ return;+ };+ let Ok(raw) = device.GetId() else {+ return;+ };+ let id = raw.to_string().unwrap_or_default();+ CoTaskMemFree(Some(raw.0.cast()));+ if self+ .endpoint+ .as_ref()+ .is_some_and(|(current, ..)| *current == id)+ {+ return;+ }+ self.unbind();+ let Ok(endpoint) = device.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None) else {+ return;+ };+ let callback: IAudioEndpointVolumeCallback = VolumeChanged {+ window: self.window,+ message: self.message,+ }+ .into();+ if endpoint.RegisterControlChangeNotify(&callback).is_ok() {+ self.endpoint = Some((id, endpoint, callback));+ }+ }+ }++ fn unbind(&mut self) {+ if let Some((_, endpoint, callback)) = self.endpoint.take() {+ // SAFETY: Unregisters the callback registered on this endpoint.+ unsafe {+ let _ = endpoint.UnregisterControlChangeNotify(&callback);+ }+ }+ }+}++impl Drop for AudioWatch {+ fn drop(&mut self) {+ self.unbind();+ // SAFETY: Unregisters the client registered in `new`.+ unsafe {+ let _ = self+ .enumerator+ .UnregisterEndpointNotificationCallback(&self.devices);+ }+ }+}++/* ------------------------------------------------------ Taskbar buttons */++/// The optional buttons the user has turned on in Windows Settings →+/// Personalization → Taskbar, so the menu bar offers the same ones.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct TaskbarButtons {+ pub search: bool,+ pub task_view: bool,+ pub widgets: bool,+}++const ADVANCED: PCWSTR = w!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced");+const SEARCH: PCWSTR = w!(r"Software\Microsoft\Windows\CurrentVersion\Search");++fn dword(key: PCWSTR, value: &str) -> Option<u32> {+ let mut data = 0u32;+ let mut size = size_of::<u32>() as u32;+ // SAFETY: `data` and `size` live for the call and match the requested type.+ unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ key,+ &HSTRING::from(value),+ RRF_RT_REG_DWORD,+ None,+ Some((&raw mut data).cast()),+ Some(&mut size),+ )+ .ok()+ .ok()?;+ }+ Some(data)+}++/// Read when the bar redraws: three registry values, no watch needed. A value+/// Windows has never written means the button is at its default, shown.+#[must_use]+pub fn taskbar_buttons() -> TaskbarButtons {+ TaskbarButtons {+ search: dword(SEARCH, "SearchboxTaskbarMode").unwrap_or(1) != 0,+ task_view: dword(ADVANCED, "ShowTaskViewButton").unwrap_or(1) != 0,+ widgets: dword(ADVANCED, "TaskbarDa").unwrap_or(1) != 0,+ }+}diff --git a/spikes/Cargo.toml b/spikes/Cargo.tomlindex 89a4a8e..9a30455 100644--- a/spikes/Cargo.toml+++ b/spikes/Cargo.toml@@ -25,6 +25,7 @@ windows = { workspace = true, features = ["Win32_Graphics_Dxgi","Win32_Graphics_Gdi","Win32_System_LibraryLoader",+ "Win32_System_Com","Win32_System_ProcessStatus","Win32_System_Threading","Win32_System_WinRT",diff --git a/spikes/src/bin/spike_status.rs b/spikes/src/bin/spike_status.rsnew file mode 100644index 0000000..0e50026--- /dev/null+++ b/spikes/src/bin/spike_status.rs@@ -0,0 +1,69 @@+//! Counts how often the menu bar's status watches fire while nothing changes.+//! Usage: spike_status [seconds]++use std::{+ env,+ time::{Duration, Instant},+};++use muelle_shell::status::{self, AudioWatch, NetworkWatch};+use windows::{+ Win32::{+ Foundation::HWND,+ System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx},+ UI::WindowsAndMessaging::{+ CreateWindowExW, HWND_MESSAGE, MSG, PM_REMOVE, PeekMessageW, WINDOW_EX_STYLE, WM_APP,+ WS_OVERLAPPED,+ },+ },+ core::w,+};++fn main() {+ let seconds: u64 = env::args()+ .nth(1)+ .and_then(|s| s.parse().ok())+ .unwrap_or(30);+ // SAFETY: COM for this thread; a message-only window owned by this thread.+ let hwnd = unsafe {+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ CreateWindowExW(+ WINDOW_EX_STYLE(0),+ w!("STATIC"),+ w!(""),+ WS_OVERLAPPED,+ 0,+ 0,+ 0,+ 0,+ Some(HWND_MESSAGE),+ None,+ None,+ None,+ )+ .unwrap_or_default()+ };+ let message = WM_APP + 21;+ let _network = NetworkWatch::new(hwnd.0 as isize, message);+ let mut audio = AudioWatch::new(hwnd.0 as isize, message);+ println!(+ "start: network={:?} volume={:?} buttons={:?}",+ status::network(),+ audio.as_mut().and_then(AudioWatch::volume),+ status::taskbar_buttons()+ );++ let mut events = 0;+ let started = Instant::now();+ while started.elapsed() < Duration::from_secs(seconds) {+ let mut msg = MSG::default();+ // SAFETY: Reads this thread's queue into `msg`.+ while unsafe { PeekMessageW(&mut msg, Some(HWND(hwnd.0)), 0, 0, PM_REMOVE) }.as_bool() {+ if msg.message == message {+ events += 1;+ }+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ println!("status events in {seconds} s: {events}");+}