Skip to content

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

feat: enhance launcher with new shell_execute functions and keyboard shortcuts

CristianOlivera1db38ac23f7a1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7286404..6c482e7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,31 @@ copia la sección de la versión que se publica a la release de GitHub.
### English
+- Faster start with Windows: Muelle now starts from a task that runs at
+ sign-in instead of the Run key, which Windows launches seconds after the
+ desktop at low priority. Existing installs switch over on their own.
+- The Windows taskbar no longer shows in full at every start: when Windows
+ shuts down or restarts with Muelle set to start again, the taskbar stays
+ hidden instead of being given back.
+- Pinned apps imported from the Windows taskbar now keep its order and include
+ Store apps (Media Player, WhatsApp...). The dock menu has "Add Apps Pinned to
+ the Windows Taskbar" to bring in any that are missing.
+- Uninstalling now also removes the start-with-Windows entry.
+- Pinning or unpinning an app on the Windows taskbar (from Start, Explorer or
+ the app's menu) now pins or unpins it in the dock too, right away, and also
+ when it happened while Muelle was closed.
+- Unchecking "Keep in Dock" also unpins the app from the Windows taskbar.
+- Uninstalled apps leave the dock instead of staying as a broken icon.
+- As on the Windows taskbar: middle click or Shift+click opens another window,
+ Ctrl+Shift+click and a new menu item open the app as administrator, and the
+ right edge of the menu bar (and the dock menu) shows the desktop.
+- Menu bar: an input language indicator (ES, EN...) when more than one is
+ installed; click it to switch. The clock follows time and time zone changes
+ at once.
+- Menu bar: microphone, camera and location icons while an app is using them,
+ as in the Windows tray; click one to see which apps in Windows Settings.
+- Switching virtual desktops updates the dock at once: it shows the apps of the
+ desktop in front, as the Windows taskbar does.
- Windows 10 support (version 1903 or later). The dock used to close right
after starting there. On Windows 10 the dock and menu bar are solid instead
of glass, since it has no backdrop blur for desktop apps.
@@ -32,6 +57,32 @@ copia la sección de la versión que se publica a la release de GitHub.
### Español
+- Arranque más rápido con Windows: Muelle ahora se inicia con una tarea al
+ iniciar sesión en lugar de la clave Run, que Windows lanza segundos después del
+ escritorio y con prioridad baja. Las instalaciones existentes cambian solas.
+- La barra de tareas de Windows ya no aparece entera en cada arranque: al apagar
+ o reiniciar con Muelle configurado para iniciarse, la barra se queda oculta en
+ lugar de devolverse.
+- Las apps fijadas que se importan de la barra de Windows conservan su orden e
+ incluyen las de la Store (Reproductor multimedia, WhatsApp...). El menú del dock
+ tiene «Añadir apps fijadas en la barra de Windows» para traer las que falten.
+- Al desinstalar también se quita el inicio con Windows.
+- Anclar o desanclar una app de la barra de tareas de Windows (desde Inicio, el
+ Explorador o el menú de la app) ahora la ancla o desancla también en el dock, al
+ momento, e incluso si pasó con Muelle cerrado.
+- Quitar la marca de «Mantener en el Dock» también desancla la app de la barra de
+ tareas de Windows.
+- Las apps desinstaladas salen del dock en lugar de quedarse como icono roto.
+- Como en la barra de Windows: clic central o Mayús+clic abre otra ventana,
+ Ctrl+Mayús+clic y una opción nueva del menú abren la app como administrador, y
+ el borde derecho de la barra superior (y el menú del dock) muestra el escritorio.
+- Barra superior: indicador del idioma del teclado (ES, EN...) cuando hay más de
+ uno instalado; con un clic se cambia. El reloj sigue al momento los cambios de
+ hora y de zona horaria.
+- Barra superior: iconos de micrófono, cámara y ubicación mientras una app los
+ usa, como en la bandeja de Windows; con un clic se ve qué apps en Configuración.
+- Cambiar de escritorio virtual actualiza el dock al momento: muestra las apps del
+ escritorio que está delante, como la barra de Windows.
- Soporte para Windows 10 (versión 1903 o posterior). Antes el dock se cerraba
nada más arrancar ahí. En Windows 10 el dock y la barra superior son sólidos
en lugar de cristal, porque no ofrece desenfoque de fondo a las apps de
diff --git a/README.es.md b/README.es.md
index a5c23ff..545eb90 100644
--- a/README.es.md
+++ b/README.es.md
@@ -25,8 +25,10 @@ en desarrollo activo.
- 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.
+- Barra superior con la app en primer plano, hora, red, volumen y batería, el idioma
+ del teclado, el micrófono/cámara/ubicación en uso y los iconos ocultos de la bandeja,
+ 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, Cursor, OpenCode Go, Gemini CLI y Antigravity. Las cuotas de
Gemini Pro y Flash aparecen por separado cuando están disponibles.
@@ -55,6 +57,10 @@ dibujar su animación; las devuelve al cerrarse.
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.
+**Inicio con Windows:** Muelle se inicia con una tarea que se ejecuta al iniciar
+sesión, llamada *Muelle (tu usuario)* en el Programador de tareas. Se desactiva en
+Ajustes → Sistema.
+
**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.
diff --git a/README.md b/README.md
index a819f7c..7b4d74d 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,8 @@ Smooth magnification, live window previews, and an optional Genie-style minimize
- 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.
-- A top menu bar with the app in front, clock, network, volume and battery, plus
+- A top menu bar with the app in front, clock, network, volume and battery, the
+ input language, microphone/camera/location 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, Cursor, OpenCode Go, Gemini CLI, and Antigravity. Gemini Pro
@@ -54,14 +55,17 @@ restored when Muelle exits.
1. Run `Muelle-Setup.exe`. It installs for your user only: no administrator
rights, no wizard, about two seconds.
2. Muelle is new, so Windows SmartScreen may not recognize it yet and say it
- protected your PC. Choose **More info → Run anyway**. See the
- [code signing policy](#code-signing-policy).
+ protected your PC. Choose **More info → Run anyway**.
3. Open **Muelle** from the Start menu, then choose **Dock** to
personalize the dock and top menu bar.
You can also open Settings by right-clicking the dock and choosing *Muelle
Settings…*. It checks for updates and installs them for you.
+**Start with Windows:** Muelle starts from a task that runs when you sign in,
+named *Muelle (your user name)* in Task Scheduler. Turn it off in Settings →
+System.
+
**Get the taskbar back:** right-click the dock and choose *Quit Muelle*. To
remove it completely, go to Windows Settings → Apps → Installed apps → Muelle →
Uninstall; the taskbar comes back and nothing is left running.
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index ef567d5..69728e9 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -36,7 +36,7 @@ use muelle_shell::{
icon_cache::IconCache,
launcher,
names::display_name,
- pins::{link_target, taskbar_pins},
+ pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable, unpin_from_taskbar},
power,
recycle_bin::{self, BinWatch},
system::{
@@ -64,18 +64,19 @@ use windows::{
UI::{
Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},
Input::KeyboardAndMouse::{
- ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent,
+ GetKeyState, ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT,
+ TrackMouseEvent, VK_CONTROL, VK_SHIFT,
},
WindowsAndMessaging::{
- CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_SYSTEM_MINIMIZEEND,
- EVENT_SYSTEM_MINIMIZESTART, FindWindowW, GetCursorPos, GetMessageW,
- GetSystemMetrics, HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MSG,
- OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW, PostQuitMessage,
- RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW, SM_CXDRAG,
- SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
+ CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_OBJECT_CLOAKED,
+ EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
+ FindWindowW, GetCursorPos, GetMessageW, GetSystemMetrics, HWND_TOPMOST, IDC_ARROW,
+ KillTimer, LoadCursorW, MSG, OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW,
+ PostQuitMessage, RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW,
+ SM_CXDRAG, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS, WM_APP,
WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED,
- WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_QUIT, WM_RBUTTONUP,
+ WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONUP, WM_MOUSEMOVE, WM_QUIT, WM_RBUTTONUP,
WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE,
WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT,
WS_POPUP,
@@ -103,6 +104,8 @@ const HSHELL_RUDEAPPACTIVATED: usize = 0x8004;
const HSHELL_FLASH: usize = 0x8006;
/// A window's title or icon changed.
const HSHELL_REDRAW: usize = 6;
+/// The keyboard language changed.
+const HSHELL_LANGUAGE: usize = 8;
/// `wParam` of WM_SETTINGCHANGE when the work area changes. The dock's own
/// reservation causes this, so handling it would create a loop.
const SPI_SETWORKAREA: usize = 0x002F;
@@ -124,6 +127,8 @@ const DRAG_CANCELLED: u32 = WM_APP + 5;
/// Runs a file drop after OLE's `Drop` returns, so the drag source is not
/// blocked while files are copied or an app starts.
const DROP_RUN: u32 = WM_APP + 6;
+/// Posted when apps are pinned to or unpinned from the Windows taskbar.
+const PINS_CHANGED: u32 = WM_APP + 7;
const ICON_SOURCE_SIZE: u32 = 256;
/// Magnification range, in icons on either side of the cursor.
@@ -165,6 +170,9 @@ const BIN_TIMER: usize = 5;
const BIN_DELAY_MS: u32 = 300;
const HIDE_TIMER: usize = 6;
const HIDE_DELAY_MS: u32 = 300;
+/// Explorer writes a pin change in a few steps; read it once they settle.
+const PINS_TIMER: usize = 7;
+const PINS_DELAY_MS: u32 = 400;
/// Auto-hide slide speed (about 250 ms).
const SLIDE_OMEGA: f32 = 24.0;
@@ -189,6 +197,9 @@ const CMD_QUIT_APP: u32 = 4;
const CMD_EMPTY_BIN: u32 = 5;
const CMD_QUIT_DOCK: u32 = 6;
const CMD_TOGGLE_HIDING: u32 = 7;
+const CMD_IMPORT_PINS: u32 = 10;
+const CMD_RUN_AS_ADMIN: u32 = 11;
+const CMD_SHOW_DESKTOP: u32 = 12;
const CMD_WINDOW: u32 = 100;
const MENU_WINDOWS: usize = 12;
const MENU_TITLE_CHARS: usize = 60;
@@ -202,6 +213,7 @@ static CONFIG_CHANGED: OnceLock<u32> = OnceLock::new();
static MAIN_WINDOW: AtomicIsize = AtomicIsize::new(0);
static DROP_WINDOW: AtomicIsize = AtomicIsize::new(0);
static MINIMIZE_HOOK: AtomicIsize = AtomicIsize::new(0);
+static CLOAK_HOOK: AtomicIsize = AtomicIsize::new(0);
#[derive(Clone, PartialEq)]
struct Entry {
@@ -249,6 +261,10 @@ enum Outside {
Menu(MenuRequest),
QuitDock,
OpenSettings,
+ OpenAsAdmin(String),
+ /// Unpin from the Windows taskbar too (see `pins::unpin_from_taskbar`).
+ UnpinFromTaskbar(String),
+ ShowDesktop,
}
struct MenuRequest {
@@ -366,6 +382,8 @@ struct App {
downloads: Option<String>,
bin_full: bool,
_bin_watch: Option<BinWatch>,
+ /// Hears pins and unpins on the Windows taskbar.
+ pin_watch: Option<muelle_shell::watch::RegistryWatch>,
assets: HashMap<String, Asset>,
/// Scale, theme and icon pixel size the cached assets were drawn for.
assets_for: (f32, bool, u32),
@@ -421,8 +439,10 @@ fn load_config() -> Config {
match muelle_config::load(&path) {
Ok(Some(config)) => config,
Ok(None) => {
+ let pins = taskbar_pins();
let config = Config {
- pinned: taskbar_pins(),
+ pinned: pins.clone(),
+ taskbar_pins: Some(pins),
..Config::default()
};
if let Err(error) = muelle_config::save(&path, &config) {
@@ -1458,6 +1478,26 @@ impl App {
};
let windows = self.windows_of(&id);
+ // As on the Windows taskbar: Shift+click opens another window of the
+ // app, Ctrl+Shift+click opens it as administrator.
+ if role == Role::App {
+ // SAFETY: Read-only keyboard state queries.
+ let (shift, ctrl) = unsafe {
+ (
+ GetKeyState(i32::from(VK_SHIFT.0)) < 0,
+ GetKeyState(i32::from(VK_CONTROL.0)) < 0,
+ )
+ };
+ if shift {
+ self.start_bounce(id.clone(), None);
+ return Ok(Some(if ctrl {
+ Outside::OpenAsAdmin(id)
+ } else {
+ Outside::Open(id)
+ }));
+ }
+ }
+
Ok(match role {
Role::App if windows.is_empty() => {
self.start_bounce(id.clone(), None);
@@ -1473,6 +1513,19 @@ 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>> {
+ let Some(entry) = self.hovered.and_then(|index| self.entries.get(index)) else {
+ return Ok(None);
+ };
+ let (Some(id), Role::App) = (entry.id.clone(), entry.role) else {
+ return Ok(None);
+ };
+ self.start_bounce(id.clone(), None);
+ Ok(Some(Outside::Open(id)))
+ }
+
/// 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>> {
@@ -1513,6 +1566,8 @@ impl App {
};
let items = vec![
MenuItem::action(CMD_TOGGLE_HIDING, hiding),
+ MenuItem::action(CMD_SHOW_DESKTOP, text().show_desktop),
+ MenuItem::action(CMD_IMPORT_PINS, text().import_pins),
MenuItem::action(CMD_SETTINGS, text().settings),
MenuItem::Separator,
MenuItem::action(CMD_QUIT_DOCK, text().quit_dock),
@@ -1566,6 +1621,7 @@ impl App {
});
}
if is_file {
+ items.push(MenuItem::action(CMD_RUN_AS_ADMIN, t.run_as_admin));
items.push(MenuItem::action(CMD_REVEAL, t.show_in_explorer));
}
if !windows.is_empty() {
@@ -1602,6 +1658,8 @@ impl App {
return match command {
CMD_QUIT_DOCK => Ok(Some(Outside::QuitDock)),
CMD_TOGGLE_HIDING => self.toggle_hiding().map(|()| None),
+ CMD_IMPORT_PINS => self.import_taskbar_pins().map(|()| None),
+ CMD_SHOW_DESKTOP => Ok(Some(Outside::ShowDesktop)),
CMD_SETTINGS => Ok(Some(Outside::OpenSettings)),
_ => Ok(None),
};
@@ -1622,15 +1680,24 @@ impl App {
Some(Outside::Open(id))
}
CMD_TOGGLE_PIN => {
- if self.roster.is_pinned(&id) {
+ // Unpinning here also unpins on the Windows taskbar, as there is
+ // only one taskbar for the user. Pinning cannot go the other way.
+ let on_taskbar = self
+ .config
+ .taskbar_pins
+ .as_ref()
+ .is_some_and(|pins| pins.contains(&id));
+ let unpinning = self.roster.is_pinned(&id);
+ if unpinning {
self.roster.unpin(&id);
} else {
self.roster.pin(&id);
}
save_settings(&self.roster, &self.config);
self.refresh()?;
- None
+ (unpinning && on_taskbar).then_some(Outside::UnpinFromTaskbar(id))
}
+ CMD_RUN_AS_ADMIN => Some(Outside::OpenAsAdmin(id)),
CMD_REVEAL => Some(Outside::Reveal(id)),
CMD_QUIT_APP => {
launcher::close(&windows);
@@ -1656,6 +1723,7 @@ impl App {
let config = Config {
pinned: self.config.pinned.clone(),
recent: self.config.recent.clone(),
+ taskbar_pins: self.config.taskbar_pins.clone(),
..saved
};
if config == self.config {
@@ -1682,6 +1750,70 @@ impl App {
self.refresh()
}
+ /// Adds the apps pinned to the Windows taskbar that the dock does not
+ /// have yet, in the taskbar's order, after the dock's own pins. Nothing is
+ /// removed or reordered: the dock imports them by itself only the first
+ /// time it runs, and pins the user removed since then stay removed until
+ /// they ask for this.
+ /// Brings pins and unpins made on the Windows taskbar to the dock, as if
+ /// it were the taskbar: what was pinned there is pinned here, what was
+ /// unpinned there is unpinned here. Apps pinned only in the dock stay.
+ /// Windows offers no way to do the reverse (pin to the taskbar).
+ fn sync_taskbar_pins(&mut self) -> Result<()> {
+ let pruned = self.prune_missing_pins();
+ let Some(current) = taskbar_pins_if_readable() else {
+ if pruned {
+ save_settings(&self.roster, &self.config);
+ return self.refresh();
+ }
+ return Ok(());
+ };
+ let Some(previous) = self.config.taskbar_pins.replace(current.clone()) else {
+ // First look since this feature: remember, change nothing.
+ save_settings(&self.roster, &self.config);
+ return Ok(());
+ };
+ if previous == current {
+ if pruned {
+ save_settings(&self.roster, &self.config);
+ return self.refresh();
+ }
+ return Ok(());
+ }
+ for id in current.iter().filter(|id| !previous.contains(id)) {
+ self.roster.pin(id);
+ }
+ for id in previous.iter().filter(|id| !current.contains(id)) {
+ self.roster.unpin(id);
+ }
+ save_settings(&self.roster, &self.config);
+ self.refresh()
+ }
+
+ /// Unpins apps that were uninstalled, so no broken icon stays behind, as
+ /// the Windows taskbar drops them. Returns whether anything changed.
+ fn prune_missing_pins(&mut self) -> bool {
+ let missing: Vec<String> = self
+ .roster
+ .pinned()
+ .iter()
+ .filter(|id| !app_exists(id))
+ .cloned()
+ .collect();
+ for id in &missing {
+ self.roster.unpin(id);
+ }
+ !missing.is_empty()
+ }
+
+ fn import_taskbar_pins(&mut self) -> Result<()> {
+ for id in taskbar_pins() {
+ self.roster.pin(&id);
+ }
+ save_settings(&self.roster, &self.config);
+ self.refresh()
+ }
+
fn toggle_hiding(&mut self) -> Result<()> {
self.config.auto_hide = !self.config.auto_hide;
save_settings(&self.roster, &self.config);
@@ -1972,6 +2104,14 @@ unsafe extern "system" fn on_win_event(
// hook reports it, and a window the dock still thought minimized kept
// its thumbnail and skipped the genie on its next minimize.
with_app("restaurar", App::sync);
+ } else if event == EVENT_OBJECT_CLOAKED || event == EVENT_OBJECT_UNCLOAKED {
+ // Shows the windows of the virtual desktop in front, as the Windows
+ // taskbar does. A desktop switch cloaks many windows at once; the
+ // timer turns the burst into one re-read.
+ // SAFETY: A timer on our own window.
+ unsafe {
+ SetTimer(Some(main_window()), SYNC_TIMER, SYNC_DELAY_MS, None);
+ }
}
}
@@ -2015,6 +2155,22 @@ pub fn menu_bar_dismiss_usage() {
});
}
+/// Redraws the menu bar from what it reads on each draw (input language,
+/// clock), without asking the network or audio again.
+pub fn menu_bar_refresh() {
+ with_app("barra superior", |app| match &mut app.menubar {
+ Some(bar) => bar.refresh(&app.gfx),
+ None => Ok(()),
+ });
+}
+
+pub fn menu_bar_privacy_changed() {
+ with_app("barra superior", |app| match &mut app.menubar {
+ Some(bar) => bar.privacy_changed(&app.gfx),
+ None => Ok(()),
+ });
+}
+
pub fn menu_bar_tick() {
with_app("barra superior", |app| match &mut app.menubar {
Some(bar) => bar.tick(&app.gfx),
@@ -2090,6 +2246,16 @@ fn run_outside(outside: Outside) {
recycle_bin::empty(owner);
}
Outside::QuitDock => request_quit(),
+ Outside::OpenAsAdmin(id) => report(launcher::open_as_admin(&id)),
+ Outside::ShowDesktop => launcher::show_desktop(),
+ Outside::UnpinFromTaskbar(id) => {
+ // The shell command may load extensions: keep it off the UI thread.
+ thread::spawn(move || {
+ // SAFETY: COM for this short-lived thread only.
+ let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
+ let _ = unpin_from_taskbar(&id);
+ });
+ }
Outside::OpenSettings => {
// The settings app is installed next to the dock.
let settings = env::current_exe()
@@ -2118,6 +2284,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
WM_MOUSELEAVE => with_app("salida del ratón", App::on_mouse_leave),
WM_LBUTTONDOWN => with_app("pulsación", App::on_press),
WM_LBUTTONUP => with_app_then("clic", App::on_release),
+ WM_MBUTTONUP => with_app_then("clic central", App::on_middle_click),
WM_CAPTURECHANGED => {
// SAFETY: Posting a message to our own window.
unsafe {
@@ -2148,6 +2315,23 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
}
query_bin_in_background();
}
+ PINS_CHANGED => {
+ with_app("apps fijadas", |app| {
+ if let Some(watch) = &mut app.pin_watch {
+ watch.arm();
+ }
+ Ok(())
+ });
+ // SAFETY: `hwnd` is our window; scheduling the same timer resets it.
+ unsafe { SetTimer(Some(hwnd), PINS_TIMER, PINS_DELAY_MS, None) };
+ }
+ WM_TIMER if w.0 == PINS_TIMER => {
+ // SAFETY: `hwnd` is this live window on its owning UI thread.
+ unsafe {
+ let _ = KillTimer(Some(hwnd), w.0);
+ }
+ with_app("apps fijadas", App::sync_taskbar_pins);
+ }
WM_TIMER if w.0 == HIDE_TIMER => {
// SAFETY: Same as above.
unsafe {
@@ -2203,6 +2387,8 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
// The dock shows no titles, so only a window it does not list yet
// (an app that declares its identity late) needs a new look.
HSHELL_REDRAW if is_tracked(l.0) => {}
+ // The input language indicator of the menu bar.
+ HSHELL_LANGUAGE => menu_bar_refresh(),
code => {
if code == HSHELL_FLASH {
with_app("aviso de atención", |app| {
@@ -2347,6 +2533,7 @@ pub fn run() -> Result<()> {
downloads: downloads_folder(),
bin_full: false,
_bin_watch: BinWatch::register(input, BIN_CHANGED),
+ pin_watch: muelle_shell::pins::watch(visual.0 as isize, PINS_CHANGED),
assets: HashMap::new(),
assets_for: (0.0, false, 0),
remove_label: None,
@@ -2382,6 +2569,14 @@ pub fn run() -> Result<()> {
let _ = SetConsoleCtrlHandler(None, false);
let _ = SetConsoleCtrlHandler(Some(on_console_ctrl), true);
+ // Apps uninstalled while Muelle was closed leave the dock.
+ if app.prune_missing_pins() {
+ save_settings(&app.roster, &app.config);
+ }
+ // Pins and unpins made on the Windows taskbar while Muelle was closed.
+ if let Err(error) = app.sync_taskbar_pins() {
+ eprintln!("muelle: apps fijadas de la barra de Windows: {error:#}");
+ }
app.sync()?;
// `sync` recomposes only when the list changes; run it unconditionally at startup.
if app.stage.is_none() {
@@ -2410,6 +2605,18 @@ pub fn run() -> Result<()> {
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
);
MINIMIZE_HOOK.store(minimize_hook.0 as isize, Ordering::Relaxed);
+ // Switching virtual desktops hides (cloaks) the windows of the one
+ // left and shows those of the one entered, and no shell hook says so.
+ let cloak_hook = SetWinEventHook(
+ EVENT_OBJECT_CLOAKED,
+ EVENT_OBJECT_UNCLOAKED,
+ None,
+ Some(on_win_event),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ );
+ CLOAK_HOOK.store(cloak_hook.0 as isize, Ordering::Relaxed);
let target: IDropTarget = DropTarget.into();
RegisterDragDrop(input, &target)?;
DROP_WINDOW.store(input.0 as isize, Ordering::Relaxed);
@@ -2438,9 +2645,9 @@ pub fn run() -> Result<()> {
// SAFETY: The drop target was registered on this window in this thread.
unsafe {
let _ = RevokeDragDrop(HWND(DROP_WINDOW.load(Ordering::Relaxed) as *mut _));
- let _ = UnhookWinEvent(HWINEVENTHOOK(
- MINIMIZE_HOOK.load(Ordering::Relaxed) as *mut _
- ));
+ for hook in [&MINIMIZE_HOOK, &CLOAK_HOOK] {
+ let _ = UnhookWinEvent(HWINEVENTHOOK(hook.load(Ordering::Relaxed) as *mut _));
+ }
}
APP.with_borrow_mut(|app| {
if let Some(app) = app {
diff --git a/apps/dock/src/guard.rs b/apps/dock/src/guard.rs
index 6379338..475a985 100644
--- a/apps/dock/src/guard.rs
+++ b/apps/dock/src/guard.rs
@@ -40,7 +40,7 @@ pub fn run(pid: u32) -> Result<()> {
let _ = CloseHandle(process);
}
// If the dock exited cleanly, it already restored the taskbar; repeating this is harmless.
- taskbar::give_back();
+ taskbar::give_back_on_exit();
// The dock turns off window transitions while it runs (genie effect); if
// it died without restoring them, do it here.
for window in WindowTracker::default().list() {
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index fe2ff9d..a904738 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -93,7 +93,9 @@ fn run_dock() -> Result<()> {
// Start the watchdog first so it can restore the taskbar if anything fails later.
guard::spawn()?;
+ // Moves an older `Run` autostart to the faster logon task, off the UI thread.
+ std::thread::spawn(autostart::migrate_legacy);
let result = app::run();
- taskbar::give_back();
+ taskbar::give_back_on_exit();
result
}
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index aa26071..c1005fc 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -20,8 +20,9 @@ use anyhow::Result;
use muelle_shell::{
appbar::{AppBar, Edge},
launcher,
- status::{self, AudioWatch, Network, NetworkWatch, TaskbarButtons, Volume},
+ status::{self, AudioWatch, Network, NetworkWatch, Privacy, TaskbarButtons, Volume},
system::{self, Battery, Monitor},
+ watch::RegistryWatch,
};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering};
use windows::{
@@ -46,8 +47,9 @@ use windows::{
RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetCursor, SetTimer,
SetWindowPos, SetWindowsHookExW, UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP,
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NCHITTEST,
- WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE, WM_TIMER, WM_XBUTTONDOWN, WNDCLASSW,
- WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
+ WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE, WM_TIMECHANGE, WM_TIMER,
+ WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
},
},
core::{BOOL, Interface, w},
@@ -88,6 +90,8 @@ const STATUS_CHANGED: u32 = WM_APP + 21;
const TICK: u32 = WM_APP + 22;
const USAGE_CHANGED: u32 = WM_APP + 23;
const DISMISS_USAGE: u32 = WM_APP + 24;
+/// Posted when an app starts or stops using the microphone, camera or location.
+const PRIVACY_CHANGED: u32 = WM_APP + 25;
/// `wParam` of WM_SETTINGCHANGE when the work area changes, which every
/// AppBar reservation (the dock's, this bar's) causes.
const SPI_SETWORKAREA: usize = 0x002F;
@@ -102,6 +106,9 @@ 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);
+/// Width of the show-desktop strip at the right edge, in logical pixels.
+const SHOW_DESKTOP_EDGE: f32 = 5.0;
+
/// Segoe Fluent Icons code points.
mod glyph {
pub const WIFI: [char; 4] = ['\u{E872}', '\u{E873}', '\u{E874}', '\u{E701}'];
@@ -115,6 +122,9 @@ mod glyph {
pub const WIDGETS: char = '\u{F246}';
/// The taskbar's "show hidden icons" arrow.
pub const HIDDEN_ICONS: char = '\u{E70E}';
+ pub const MICROPHONE: char = '\u{E720}';
+ pub const CAMERA: char = '\u{E722}';
+ pub const LOCATION: char = '\u{E81D}';
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -126,6 +136,11 @@ enum Action {
TaskView,
Widgets,
HiddenIcons,
+ InputLanguage,
+ ShowDesktop,
+ Microphone,
+ Camera,
+ Location,
}
/// Network, volume and taskbar buttons, read only when Windows reports a change.
@@ -134,6 +149,7 @@ struct Status {
network: Network,
volume: Option<Volume>,
buttons: TaskbarButtons,
+ privacy: Privacy,
}
/// What the bar was last drawn for.
@@ -146,6 +162,8 @@ struct Look {
glass: bool,
app_name: String,
clock: String,
+ /// The input language indicator, when more than one is installed.
+ input: Option<String>,
battery: Option<Battery>,
status: Status,
usage: Snapshot,
@@ -180,6 +198,8 @@ pub struct MenuBar {
outside_click_hook: Option<HHOOK>,
/// Held for their callbacks; dropping them unsubscribes.
_network: Option<NetworkWatch>,
+ /// Hears when apps start or stop using the microphone, camera or location.
+ privacy_watch: Option<RegistryWatch>,
audio: Option<AudioWatch>,
}
@@ -196,6 +216,7 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
}
WM_MOUSELEAVE => app::menu_bar_hover(false),
DISMISS_USAGE => app::menu_bar_dismiss_usage(),
+ PRIVACY_CHANGED => app::menu_bar_privacy_changed(),
WM_SETCURSOR => {
let mut point = POINT::default();
// SAFETY: The point is a valid output for the current pointer location.
@@ -233,7 +254,9 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
// Some of these are sent while the dock is busy reserving space, and
// updating then was dropped. From the message loop the dock is never
// busy, and a burst of them makes a single update.
- WM_TIMER | WM_POWERBROADCAST | STATUS_CHANGED | USAGE_CHANGED | WM_SETTINGCHANGE => {
+ // WM_TIMECHANGE: the clock or time zone was changed.
+ WM_TIMER | WM_POWERBROADCAST | WM_TIMECHANGE | STATUS_CHANGED | USAGE_CHANGED
+ | WM_SETTINGCHANGE => {
if !TICK_PENDING.swap(true, Ordering::Relaxed) {
// SAFETY: Posting to our own live window.
unsafe {
@@ -762,6 +785,7 @@ impl MenuBar {
network: Network::Offline,
volume: None,
buttons: TaskbarButtons::default(),
+ privacy: Privacy::default(),
},
usage: usage_enabled.then(|| UsageMonitor::new(hwnd.0 as isize, USAGE_CHANGED)),
expanded: false,
@@ -771,6 +795,7 @@ impl MenuBar {
refresh_button: None,
outside_click_hook: None,
_network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),
+ privacy_watch: status::watch_privacy(hwnd.0 as isize, PRIVACY_CHANGED),
audio: AudioWatch::new(hwnd.0 as isize, STATUS_CHANGED),
};
bar.update_status();
@@ -931,6 +956,14 @@ impl MenuBar {
}
/// The minute changed, or something the bar shows did: redraw what differs.
+ /// An app started or stopped using the microphone, camera or location.
+ pub fn privacy_changed(&mut self, gfx: &Gfx) -> Result<()> {
+ if let Some(watch) = &mut self.privacy_watch {
+ watch.arm();
+ }
+ self.tick(gfx)
+ }
+
pub fn tick(&mut self, gfx: &Gfx) -> Result<()> {
self.update_status();
self.schedule_next_minute();
@@ -942,6 +975,7 @@ impl MenuBar {
network: status::network(),
volume: self.audio.as_mut().and_then(AudioWatch::volume),
buttons: status::taskbar_buttons(),
+ privacy: status::privacy(),
};
}
@@ -1023,6 +1057,18 @@ impl MenuBar {
Some(Action::TaskView) => launcher::open_task_view(),
Some(Action::Widgets) => launcher::open_widgets(),
Some(Action::HiddenIcons) => launcher::open_hidden_icons(anchor),
+ Some(Action::InputLanguage) => launcher::open_input_switcher(),
+ Some(Action::ShowDesktop) => launcher::show_desktop(),
+ // Windows' own pages list which apps use each device.
+ Some(Action::Microphone) => {
+ let _ = launcher::open("ms-settings:privacy-microphone");
+ }
+ Some(Action::Camera) => {
+ let _ = launcher::open("ms-settings:privacy-webcam");
+ }
+ Some(Action::Location) => {
+ let _ = launcher::open("ms-settings:privacy-location");
+ }
None => {}
}
Ok(())
@@ -1056,6 +1102,7 @@ impl MenuBar {
glass: system::transparency_enabled(),
app_name: self.app_name.clone(),
clock: system::clock_text(),
+ input: system::input_language(),
battery: system::battery(),
status: self.status,
usage: self
@@ -1158,6 +1205,18 @@ impl MenuBar {
),
(gfx.control_center_brush(scale, ink)?, Action::QuickSettings),
];
+ // Privacy indicators, as the Windows tray shows them: something is
+ // using the microphone, camera or location right now.
+ let privacy = status.privacy;
+ for (on, glyph, action) in [
+ (privacy.microphone, glyph::MICROPHONE, Action::Microphone),
+ (privacy.camera, glyph::CAMERA, Action::Camera),
+ (privacy.location, glyph::LOCATION, Action::Location),
+ ] {
+ if on {
+ items.push((symbol(&[(glyph, 1.0)])?, action));
+ }
+ }
if status.buttons.search {
items.push((symbol(&[(glyph::SEARCH, 1.0)])?, Action::Search));
}
@@ -1185,6 +1244,12 @@ impl MenuBar {
Action::QuickSettings,
));
}
+ if let Some(language) = &look.input {
+ items.push((
+ gfx.text_brush(language, scale, false, ink)?,
+ Action::InputLanguage,
+ ));
+ }
// The notification area (antivirus, OneDrive, apps in the background)
// lives only in the hidden taskbar; this arrow opens its flyout.
items.push((symbol(&[(glyph::HIDDEN_ICONS, 1.0)])?, Action::HiddenIcons));
@@ -1194,6 +1259,14 @@ impl MenuBar {
if status.buttons.widgets {
items.push((symbol(&[(glyph::WIDGETS, 1.0)])?, Action::Widgets));
}
+ // The last pixels of the right edge show the desktop, like the
+ // corner of the Windows taskbar: easy to hit by throwing the pointer
+ // there. First in the list, so it wins over the clock next to it.
+ self.zones.push((
+ width - px(SHOW_DESKTOP_EDGE),
+ width + 1.0,
+ Action::ShowDesktop,
+ ));
for (item, action) in &items {
let left = right - item.width;
place(&layers, item, left)?;
diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rs
index 6c64905..92034a9 100644
--- a/apps/dock/src/strings.rs
+++ b/apps/dock/src/strings.rs
@@ -21,6 +21,9 @@ pub struct Strings {
pub remove: &'static str,
pub close_window: &'static str,
pub settings: &'static str,
+ pub import_pins: &'static str,
+ pub run_as_admin: &'static str,
+ pub show_desktop: &'static str,
pub usage_title: &'static str,
pub usage_refresh: &'static str,
pub usage_refreshing: &'static str,
@@ -47,6 +50,9 @@ const ES: Strings = Strings {
remove: "Quitar",
close_window: "&Cerrar",
settings: "&Ajustes de Muelle…",
+ import_pins: "Añadir apps &fijadas en la barra de Windows",
+ run_as_admin: "Ejecutar como a&dministrador",
+ show_desktop: "Mostrar &escritorio",
usage_title: "Uso de IA",
usage_refresh: "Actualizar",
usage_refreshing: "Actualizando…",
@@ -73,6 +79,9 @@ const EN: Strings = Strings {
remove: "Remove",
close_window: "&Close",
settings: "Muelle &Settings…",
+ import_pins: "Add Apps &Pinned to the Windows Taskbar",
+ run_as_admin: "Run as a&dministrator",
+ show_desktop: "Show &Desktop",
usage_title: "AI usage",
usage_refresh: "Refresh",
usage_refreshing: "Refreshing…",
diff --git a/apps/settings/src-tauri/installer/hooks.nsh b/apps/settings/src-tauri/installer/hooks.nsh
index 5067ff2..1928145 100644
--- a/apps/settings/src-tauri/installer/hooks.nsh
+++ b/apps/settings/src-tauri/installer/hooks.nsh
@@ -43,6 +43,12 @@
!macro NSIS_HOOK_PREUNINSTALL
!insertmacro MUELLE_STOP_DOCK
+ ; Removes the logon task (and an older Run entry), which would otherwise
+ ; keep pointing at the deleted muelle.exe. Updates keep it.
+ ${If} $UpdateMode <> 1
+ ${AndIf} ${FileExists} "$INSTDIR\muelle.exe"
+ ExecWait '"$INSTDIR\muelle.exe" --autostart off'
+ ${EndIf}
!macroend
!macro NSIS_HOOK_POSTUNINSTALL
@@ -50,6 +56,8 @@
SetShellVarContext current
; The icon cache is always disposable.
RmDir /r "$LOCALAPPDATA\Muelle"
+ ; Where Muelle remembers that it starts with Windows.
+ DeleteRegKey HKCU "Software\Muelle"
${If} $DeleteAppDataCheckboxState = 1
RmDir /r "$APPDATA\Muelle"
${EndIf}
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index 9dffb36..e992dd6 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -18,6 +18,7 @@ fn merged_with_disk(config: Config) -> Config {
Ok(Some(disk)) => Config {
pinned: disk.pinned,
recent: disk.recent,
+ taskbar_pins: disk.taskbar_pins,
..config
},
_ => config,
diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rs
index 7dea165..f6d7b65 100644
--- a/crates/muelle-config/src/lib.rs
+++ b/crates/muelle-config/src/lib.rs
@@ -38,6 +38,10 @@ pub struct Config {
pub version: u32,
pub pinned: Vec<String>,
pub recent: Vec<String>,
+ /// The apps pinned to the Windows taskbar when the dock last looked, to
+ /// bring pins and unpins made there (even while Muelle was closed) to the
+ /// dock. `None` until it first looks.
+ pub taskbar_pins: Option<Vec<String>>,
#[serde(alias = "auto_hide")]
pub auto_hide: bool,
/// Icon side at rest, in logical pixels.
@@ -110,6 +114,7 @@ impl Default for Config {
version: CURRENT_VERSION,
pinned: Vec::new(),
recent: Vec::new(),
+ taskbar_pins: None,
auto_hide: false,
icon_size: 48,
magnification: true,
diff --git a/crates/muelle-shell/src/autostart.rs b/crates/muelle-shell/src/autostart.rs
index ce73a6c..b66151a 100644
--- a/crates/muelle-shell/src/autostart.rs
+++ b/crates/muelle-shell/src/autostart.rs
@@ -1,58 +1,222 @@
+//! Starting Muelle when the user signs in.
+//!
+//! A scheduled task with a logon trigger, not the `Run` registry key: Windows
+//! launches `Run` entries several seconds after the desktop appears, at low
+//! priority, so the full Windows taskbar showed for a long while at every
+//! sign-in. A logon task starts with the session. Creating one for yourself
+//! needs no administrator rights.
+//!
+//! Whether autostart is on is also written to `HKCU\Software\Muelle`, because
+//! task registrations cannot be read without administrator rights and the
+//! watchdog has to know it instantly while Windows shuts down.
+
+use std::{env, fs, os::windows::process::CommandExt, path::PathBuf, process::Command};
+
use windows::{
Win32::{
Foundation::WIN32_ERROR,
System::Registry::{
- HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_SZ, RegCloseKey, RegDeleteValueW,
- RegOpenKeyExW, RegSetValueExW,
+ HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ,
+ RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteValueW,
+ RegGetValueW, RegOpenKeyExW, RegSetValueExW,
},
},
- core::{HSTRING, w},
+ core::{PCWSTR, w},
};
-const VALUE_NAME: &str = "Muelle";
+/// The value Muelle used to add under `Run`, before the logon task.
+const LEGACY_RUN_VALUE: PCWSTR = w!("Muelle");
+const RUN_KEY: PCWSTR = w!(r"Software\Microsoft\Windows\CurrentVersion\Run");
+const MUELLE_KEY: PCWSTR = w!(r"Software\Muelle");
+const MARKER_VALUE: PCWSTR = w!("Autostart");
+/// `schtasks.exe` runs without a console window.
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+/// Starts `exe` at every sign-in, or stops doing so (`None`).
pub fn set(exe: Option<&str>) -> windows::core::Result<()> {
+ match exe {
+ Some(exe) => {
+ if create_task(exe) {
+ delete_legacy_run_value()?;
+ } else {
+ // Without the Task Scheduler service, the slower `Run` entry
+ // still starts the dock.
+ set_legacy_run_value(exe)?;
+ }
+ set_marker(true)
+ }
+ None => {
+ delete_task();
+ delete_legacy_run_value()?;
+ set_marker(false)
+ }
+ }
+}
+
+/// `true` if Muelle is set to start when the user signs in. Reads only the
+/// registry, so it is instant and works while Windows shuts down.
+#[must_use]
+pub fn is_enabled() -> bool {
+ marker() || legacy_run_value_exists()
+}
+
+/// Moves an autostart registered by an older Muelle (the `Run` key) to the
+/// logon task. Updates keep the user's choice and never re-register it, so
+/// the dock does it once on its own.
+pub fn migrate_legacy() {
+ if !legacy_run_value_exists() {
+ return;
+ }
+ let Ok(exe) = env::current_exe() else {
+ return;
+ };
+ let _ = set(Some(&exe.to_string_lossy()));
+}
+
+/// The task name: one per user, since task names are shared by the whole PC.
+fn task_name() -> String {
+ format!("Muelle ({})", env::var("USERNAME").unwrap_or_default())
+}
+
+fn schtasks(args: &[&str]) -> bool {
+ let system =
+ env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from);
+ Command::new(system.join(r"System32\schtasks.exe"))
+ .args(args)
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .is_ok_and(|output| output.status.success())
+}
+
+fn create_task(exe: &str) -> bool {
+ let user = match (env::var("USERDOMAIN"), env::var("USERNAME")) {
+ (Ok(domain), Ok(name)) => format!("{domain}\\{name}"),
+ (_, Ok(name)) => name,
+ _ => return false,
+ };
+ let path = env::temp_dir().join(format!("muelle-autostart-{}.xml", std::process::id()));
+ // schtasks wants the definition as UTF-16 with a byte order mark.
+ let bytes: Vec<u8> = std::iter::once(0xFEFF_u16)
+ .chain(task_xml(&user, exe).encode_utf16())
+ .flat_map(u16::to_le_bytes)
+ .collect();
+ if fs::write(&path, bytes).is_err() {
+ return false;
+ }
+ let created = schtasks(&[
+ "/Create",
+ "/TN",
+ &task_name(),
+ "/XML",
+ &path.to_string_lossy(),
+ "/F",
+ ]);
+ let _ = fs::remove_file(&path);
+ created
+}
+
+fn delete_task() {
+ // Deleting a task that does not exist fails harmlessly.
+ schtasks(&["/Delete", "/TN", &task_name(), "/F"]);
+}
+
+/// The task: at this user's sign-in, run `exe` as them, without admin rights,
+/// at normal priority (tasks default to below normal), on battery too, with
+/// no time limit.
+fn task_xml(user: &str, exe: &str) -> String {
+ let user = escape(user);
+ let exe = escape(exe);
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-16"?>
+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
+ <RegistrationInfo>
+ <Description>Starts the Muelle dock when you sign in. Turn it off in Muelle Settings.</Description>
+ </RegistrationInfo>
+ <Triggers>
+ <LogonTrigger>
+ <Enabled>true</Enabled>
+ <UserId>{user}</UserId>
+ </LogonTrigger>
+ </Triggers>
+ <Principals>
+ <Principal id="Author">
+ <UserId>{user}</UserId>
+ <LogonType>InteractiveToken</LogonType>
+ <RunLevel>LeastPrivilege</RunLevel>
+ </Principal>
+ </Principals>
+ <Settings>
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
+ <Priority>4</Priority>
+ </Settings>
+ <Actions Context="Author">
+ <Exec>
+ <Command>{exe}</Command>
+ </Exec>
+ </Actions>
+</Task>
+"#
+ )
+}
+
+fn escape(text: &str) -> String {
+ text.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
+}
+
+fn marker() -> bool {
+ let mut value = 0u32;
+ let mut size = size_of::<u32>() as u32;
+ // SAFETY: `value` and `size` describe a valid 4-byte buffer.
+ let status = unsafe {
+ RegGetValueW(
+ HKEY_CURRENT_USER,
+ MUELLE_KEY,
+ MARKER_VALUE,
+ RRF_RT_REG_DWORD,
+ None,
+ Some((&raw mut value).cast()),
+ Some(&mut size),
+ )
+ };
+ status.is_ok() && value != 0
+}
+
+fn set_marker(on: bool) -> windows::core::Result<()> {
let mut key = HKEY::default();
- // SAFETY: The key is closed before returning, and strings live through each call.
+ let value = u32::from(on).to_le_bytes();
+ // SAFETY: The key is closed before returning; `value` lives through the call.
unsafe {
- RegOpenKeyExW(
+ RegCreateKeyExW(
HKEY_CURRENT_USER,
- w!("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
+ MUELLE_KEY,
+ None,
None,
+ REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE,
+ None,
&mut key,
+ None,
)
.ok()?;
- let result = match exe {
- Some(path) => {
- let command: Vec<u16> = format!("\"{path}\"")
- .encode_utf16()
- .chain(Some(0))
- .collect();
- let bytes = std::slice::from_raw_parts(command.as_ptr().cast(), command.len() * 2);
- RegSetValueExW(key, &HSTRING::from(VALUE_NAME), None, REG_SZ, Some(bytes))
- }
- None => match RegDeleteValueW(key, &HSTRING::from(VALUE_NAME)) {
- // Removing a value that does not exist is not an error.
- WIN32_ERROR(2) => WIN32_ERROR(0),
- other => other,
- },
- };
+ let result = RegSetValueExW(key, MARKER_VALUE, None, REG_DWORD, Some(&value));
let _ = RegCloseKey(key);
result.ok()
}
}
-/// `true` if Muelle is registered to start when the user signs in.
-#[must_use]
-pub fn is_enabled() -> bool {
- use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW};
+fn legacy_run_value_exists() -> bool {
// SAFETY: Only asks whether the value exists; no buffers are passed.
unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
- w!(r"Software\Microsoft\Windows\CurrentVersion\Run"),
- &HSTRING::from(VALUE_NAME),
+ RUN_KEY,
+ LEGACY_RUN_VALUE,
RRF_RT_REG_SZ,
None,
None,
@@ -61,3 +225,49 @@ pub fn is_enabled() -> bool {
.is_ok()
}
}
+
+fn set_legacy_run_value(exe: &str) -> windows::core::Result<()> {
+ with_run_key(|key| {
+ let command: Vec<u16> = format!("\"{exe}\"").encode_utf16().chain(Some(0)).collect();
+ // SAFETY: `command` lives through the call.
+ unsafe {
+ let bytes = std::slice::from_raw_parts(command.as_ptr().cast(), command.len() * 2);
+ RegSetValueExW(key, LEGACY_RUN_VALUE, None, REG_SZ, Some(bytes))
+ }
+ })
+}
+
+fn delete_legacy_run_value() -> windows::core::Result<()> {
+ // SAFETY: Deletes a value of the open key.
+ with_run_key(
+ |key| match unsafe { RegDeleteValueW(key, LEGACY_RUN_VALUE) } {
+ // Removing a value that does not exist is not an error.
+ WIN32_ERROR(2) => WIN32_ERROR(0),
+ other => other,
+ },
+ )
+}
+
+fn with_run_key(action: impl FnOnce(HKEY) -> WIN32_ERROR) -> windows::core::Result<()> {
+ let mut key = HKEY::default();
+ // SAFETY: The key is closed before returning.
+ unsafe {
+ RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, None, KEY_SET_VALUE, &mut key).ok()?;
+ let result = action(key);
+ let _ = RegCloseKey(key);
+ result.ok()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn task_xml_should_escape_the_path_and_keep_the_user() {
+ let xml = task_xml(r"PC\ana", r"C:\Apps & Tools\muelle.exe");
+ assert!(xml.contains(r"<Command>C:\Apps &amp; Tools\muelle.exe</Command>"));
+ assert!(xml.contains(r"<UserId>PC\ana</UserId>"));
+ assert!(xml.contains("<Priority>4</Priority>"));
+ }
+}
diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rs
index 7a1eabf..041e10d 100644
--- a/crates/muelle-shell/src/launcher.rs
+++ b/crates/muelle-shell/src/launcher.rs
@@ -9,8 +9,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_B, VK_LCONTROL, VK_LWIN, VK_N,
- VK_RETURN, VK_S, VK_TAB, VK_V, VK_W,
+ KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_B, VK_D, VK_LCONTROL, VK_LWIN,
+ VK_N, VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,
},
Shell::ShellExecuteW,
WindowsAndMessaging::{
@@ -43,18 +43,20 @@ fn allow_foreground() {
}
pub fn open(id: &str) -> Result<(), LaunchError> {
+ shell_execute(w!("open"), id)
+}
+
+/// Opens `id` as administrator, with the UAC prompt, as the taskbar's
+/// "Run as administrator" and Ctrl+Shift+click do.
+pub fn open_as_admin(id: &str) -> Result<(), LaunchError> {
+ shell_execute(w!("runas"), id)
+}
+
+fn shell_execute(verb: PCWSTR, id: &str) -> Result<(), LaunchError> {
allow_foreground();
// SAFETY: The strings live for the duration of the call.
- let result = unsafe {
- ShellExecuteW(
- None,
- w!("open"),
- &HSTRING::from(id),
- None,
- None,
- SW_SHOWNORMAL,
- )
- };
+ let result =
+ unsafe { ShellExecuteW(None, verb, &HSTRING::from(id), None, None, SW_SHOWNORMAL) };
// ShellExecute returns a value greater than 32 on success.
let code = result.0 as isize;
if code > 32 {
@@ -221,6 +223,18 @@ pub fn open_sound() {
}
}
+/// Shows the desktop, or brings the windows back: what the taskbar's corner
+/// button does (Win+D).
+pub fn show_desktop() {
+ tap(&[VK_LWIN, VK_D]);
+}
+
+/// The input language switcher, as clicking the taskbar's language
+/// indicator (Win+Space).
+pub fn open_input_switcher() {
+ tap(&[VK_LWIN, VK_SPACE]);
+}
+
/// How long the taskbar takes to put the focus on its notification area.
const HIDDEN_ICONS_DELAY: Duration = Duration::from_millis(250);
/// How long the flyout is kept under the arrow while Windows finishes
diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rs
index 43766d9..43788c9 100644
--- a/crates/muelle-shell/src/lib.rs
+++ b/crates/muelle-shell/src/lib.rs
@@ -14,3 +14,4 @@ pub mod status;
pub mod system;
pub mod taskbar;
pub mod tracker;
+pub mod watch;
diff --git a/crates/muelle-shell/src/pins.rs b/crates/muelle-shell/src/pins.rs
index cb547de..9a384cc 100644
--- a/crates/muelle-shell/src/pins.rs
+++ b/crates/muelle-shell/src/pins.rs
@@ -1,48 +1,325 @@
-use std::{env, fs, path::PathBuf};
+use std::{
+ env, fs,
+ path::{Path, PathBuf},
+};
use windows::{
Win32::{
- System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, IPersistFile, STGM_READ},
- UI::Shell::{IShellLinkW, ShellLink},
+ Storage::FileSystem::GetDriveTypeW,
+ System::{
+ Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, IPersistFile, STGM_READ},
+ Registry::{HKEY_CURRENT_USER, RRF_RT_REG_BINARY, RegGetValueW},
+ },
+ UI::{
+ Shell::{
+ BHID_SFUIObject, CMF_NORMAL, CMINVOKECOMMANDINFO, GCS_VERBW, IContextMenu,
+ IShellItem, IShellLinkW, SHCreateItemFromParsingName, ShellLink,
+ },
+ WindowsAndMessaging::{
+ CreatePopupMenu, DestroyMenu, GetMenuItemCount, GetMenuItemID, SW_SHOWNORMAL,
+ },
+ },
},
- core::{HSTRING, Interface},
+ core::{HSTRING, Interface, PCSTR, PCWSTR, PSTR, w},
};
-use crate::tracker::normalize_id;
+const TASKBAND: PCWSTR = w!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband");
+
+use crate::{tracker::normalize_id, watch::RegistryWatch};
-/// Limitations: results are alphabetized by shortcut (the actual taskbar order
-/// uses an undocumented binary format), and Store apps are omitted because
-/// Windows stores them elsewhere.
+/// The apps pinned to the Windows taskbar, in the taskbar's order: desktop
+/// apps by the program their shortcut opens, Store apps (Media Player, Phone
+/// Link, WhatsApp...) as `shell:AppsFolder\<AppUserModelID>`.
+///
+/// Desktop pins are the shortcuts in `User Pinned\TaskBar`. The order, and
+/// the Store apps, which have no shortcut there, come from
+/// `Taskband\Favorites`, an undocumented binary list. It is only searched
+/// for those shortcut names and for AppUserModelIDs, so if its format
+/// changes the desktop pins still come, in alphabetical order.
///
/// Requires COM to be initialized on the calling thread.
#[must_use]
pub fn taskbar_pins() -> Vec<String> {
- let Ok(appdata) = env::var("APPDATA") else {
- return Vec::new();
- };
+ taskbar_pins_if_readable().unwrap_or_default()
+}
+
+/// Like [`taskbar_pins`], but `None` when Windows' pinned list cannot be
+/// read at all, so a failed read is never mistaken for "everything was
+/// unpinned".
+#[must_use]
+pub fn taskbar_pins_if_readable() -> Option<Vec<String>> {
+ let favorites = favorites()?;
+ let appdata = env::var("APPDATA").ok()?;
let folder = PathBuf::from(appdata)
.join("Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
- let Ok(entries) = fs::read_dir(folder) else {
- return Vec::new();
- };
-
- let mut links: Vec<PathBuf> = entries
- .filter_map(|entry| Some(entry.ok()?.path()))
- .filter(|path| {
- path.extension()
- .is_some_and(|ext| ext.eq_ignore_ascii_case("lnk"))
+ let mut links: Vec<PathBuf> = fs::read_dir(folder)
+ .map(|entries| {
+ entries
+ .filter_map(|entry| Some(entry.ok()?.path()))
+ .filter(|path| {
+ path.extension()
+ .is_some_and(|ext| ext.eq_ignore_ascii_case("lnk"))
+ })
+ .collect()
})
- .collect();
+ .unwrap_or_default();
links.sort();
- let mut pins: Vec<String> = Vec::new();
- for target in links.iter().filter_map(|link| link_target(link)) {
+ // (position in Favorites, id); shortcuts it does not mention go last.
+ let mut found: Vec<(usize, String)> = Vec::new();
+ for link in &links {
+ let Some(target) = link_target(link) else {
+ continue;
+ };
let id = normalize_id(&target);
- if id.ends_with(".exe") && PathBuf::from(&id).exists() && !pins.contains(&id) {
+ if !id.ends_with(".exe") || !Path::new(&id).exists() {
+ continue;
+ }
+ let position = link
+ .file_name()
+ .and_then(|name| name.to_str())
+ .and_then(|name| find_utf16(&favorites, name))
+ .unwrap_or(usize::MAX);
+ found.push((position, id));
+ }
+ found.extend(
+ app_user_model_ids(&favorites)
+ .into_iter()
+ .map(|(position, aumid)| (position, format!("shell:AppsFolder\\{aumid}"))),
+ );
+ // Stable: shortcuts with the same (unknown) position keep their alphabetical order.
+ found.sort_by_key(|(position, _)| *position);
+
+ let mut pins: Vec<String> = Vec::new();
+ for (_, id) in found {
+ if !pins.contains(&id) {
pins.push(id);
}
}
- pins
+ Some(pins)
+}
+
+/// Tells a window, by posting it `message`, when apps are pinned to or
+/// unpinned from the Windows taskbar (from Start, Explorer or an app's own
+/// menu): Explorer rewrites `Taskband` for every pin and unpin.
+#[must_use]
+pub fn watch(hwnd: isize, message: u32) -> Option<RegistryWatch> {
+ RegistryWatch::new(TASKBAND, false, hwnd, message)
+}
+
+/// The taskbar's pinned list as Explorer stores it.
+fn favorites() -> Option<Vec<u8>> {
+ let key = TASKBAND;
+ let mut size = 0u32;
+ // SAFETY: First call only asks for the size; the second fills a buffer of that size.
+ unsafe {
+ RegGetValueW(
+ HKEY_CURRENT_USER,
+ key,
+ w!("Favorites"),
+ RRF_RT_REG_BINARY,
+ None,
+ None,
+ Some(&mut size),
+ )
+ .ok()
+ .ok()?;
+ let mut blob = vec![0u8; size as usize];
+ RegGetValueW(
+ HKEY_CURRENT_USER,
+ key,
+ w!("Favorites"),
+ RRF_RT_REG_BINARY,
+ None,
+ Some(blob.as_mut_ptr().cast()),
+ Some(&mut size),
+ )
+ .ok()
+ .ok()?;
+ blob.truncate(size as usize);
+ Some(blob)
+ }
+}
+
+/// Byte offset of `text`, as UTF-16, inside `blob`, ignoring ASCII case.
+fn find_utf16(blob: &[u8], text: &str) -> Option<usize> {
+ let needle: Vec<u8> = text
+ .to_ascii_lowercase()
+ .encode_utf16()
+ .flat_map(u16::to_le_bytes)
+ .collect();
+ if needle.is_empty() {
+ return None;
+ }
+ let lowered: Vec<u8> = blob.iter().map(u8::to_ascii_lowercase).collect();
+ lowered
+ .windows(needle.len())
+ .position(|window| window == needle.as_slice())
+}
+
+/// AppUserModelIDs of Store apps (`Name_publisherid!App`) found in `blob`,
+/// with their byte offsets, in order. Strings may start at any byte, so
+/// both alignments are read.
+fn app_user_model_ids(blob: &[u8]) -> Vec<(usize, String)> {
+ let mut found: Vec<(usize, String)> = Vec::new();
+ for start in 0..2 {
+ let units: Vec<u16> = blob[start.min(blob.len())..]
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|&pair| u16::from_le_bytes(pair))
+ .collect();
+ let allowed = |unit: u16| {
+ char::from_u32(u32::from(unit))
+ .is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '!'))
+ };
+ let mut index = 0;
+ while index < units.len() {
+ if !allowed(units[index]) {
+ index += 1;
+ continue;
+ }
+ let begin = index;
+ while index < units.len() && allowed(units[index]) {
+ index += 1;
+ }
+ let word = String::from_utf16_lossy(&units[begin..index]);
+ if is_app_user_model_id(&word) {
+ found.push((start + begin * 2, word));
+ }
+ }
+ }
+ found.sort_by_key(|(position, _)| *position);
+ found
+}
+
+/// `Package.Name_publisherid!AppId`, where the publisher id is 13 lowercase
+/// letters and digits.
+fn is_app_user_model_id(word: &str) -> bool {
+ let Some((family, app)) = word.split_once('!') else {
+ return false;
+ };
+ let Some((name, publisher)) = family.rsplit_once('_') else {
+ return false;
+ };
+ !app.is_empty()
+ && !app.contains('!')
+ && !name.is_empty()
+ && publisher.len() == 13
+ && publisher
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
+}
+
+/// Unpins `id` from the Windows taskbar with the shell's own "Unpin from
+/// taskbar" command, so unpinning in the dock unpins there too. Windows lets
+/// programs unpin but not pin, so the reverse is not possible. `false` if it
+/// is not pinned there or the command is missing.
+///
+/// Requires COM on the calling thread; it may load shell extensions, so call
+/// it off the UI thread.
+#[must_use]
+pub fn unpin_from_taskbar(id: &str) -> bool {
+ let Some(item) = pinned_item(id) else {
+ return false;
+ };
+ invoke_verb(&item, "taskbarunpin")
+}
+
+/// What Explorer pinned for `id`: the Store app itself, or the shortcut in
+/// `User Pinned\TaskBar` that opens the program.
+fn pinned_item(id: &str) -> Option<String> {
+ if id.starts_with("shell:AppsFolder\\") {
+ return Some(id.to_owned());
+ }
+ let folder = PathBuf::from(env::var("APPDATA").ok()?)
+ .join("Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
+ fs::read_dir(folder)
+ .ok()?
+ .filter_map(|entry| Some(entry.ok()?.path()))
+ .find(|link| link_target(link).is_some_and(|target| normalize_id(&target) == id))
+ .map(|link| link.to_string_lossy().into_owned())
+}
+
+/// Runs the context menu command `verb` (canonical name) on the shell item
+/// at `path`, as clicking it in Explorer would.
+fn invoke_verb(path: &str, verb: &str) -> bool {
+ // SAFETY: COM objects and the popup menu live for the block; the menu is
+ // destroyed before returning.
+ unsafe {
+ let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(path), None)
+ else {
+ return false;
+ };
+ let Ok(menu) = item.BindToHandler::<_, IContextMenu>(None, &BHID_SFUIObject) else {
+ return false;
+ };
+ let Ok(popup) = CreatePopupMenu() else {
+ return false;
+ };
+ let mut done = false;
+ if menu
+ .QueryContextMenu(popup, 0, 1, 0x7FFF, CMF_NORMAL)
+ .is_ok()
+ {
+ for position in 0..GetMenuItemCount(Some(popup)).max(0) {
+ let command = GetMenuItemID(popup, position);
+ if command == u32::MAX || command == 0 {
+ continue;
+ }
+ let offset = (command - 1) as usize;
+ let mut name = [0u16; 64];
+ let named = menu
+ .GetCommandString(
+ offset,
+ GCS_VERBW,
+ None,
+ PSTR(name.as_mut_ptr().cast()),
+ name.len() as u32,
+ )
+ .is_ok();
+ let len = name.iter().position(|&unit| unit == 0).unwrap_or(0);
+ if !named || !String::from_utf16_lossy(&name[..len]).eq_ignore_ascii_case(verb) {
+ continue;
+ }
+ let info = CMINVOKECOMMANDINFO {
+ cbSize: size_of::<CMINVOKECOMMANDINFO>() as u32,
+ // A command offset passed where a verb name would go.
+ lpVerb: PCSTR(offset as *const u8),
+ nShow: SW_SHOWNORMAL.0,
+ ..Default::default()
+ };
+ done = menu.InvokeCommand(&info).is_ok();
+ break;
+ }
+ }
+ let _ = DestroyMenu(popup);
+ done
+ }
+}
+
+/// `false` only when `id` certainly no longer exists: a program removed from
+/// a fixed drive, or a Store app that was uninstalled. Programs on removable
+/// or network drives count as present; they may just be unplugged.
+///
+/// Requires COM on the calling thread.
+#[must_use]
+pub fn app_exists(id: &str) -> bool {
+ if id.starts_with("shell:AppsFolder\\") {
+ // SAFETY: Only asks the shell whether it can resolve the item.
+ return unsafe {
+ SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(id), None)
+ }
+ .is_ok();
+ }
+ let path = Path::new(id);
+ let Some(root) = id.get(..3).filter(|root| root.ends_with(":\\")) else {
+ return true;
+ };
+ const DRIVE_FIXED: u32 = 3;
+ // SAFETY: Read-only query on a drive root.
+ let fixed = unsafe { GetDriveTypeW(&HSTRING::from(root)) } == DRIVE_FIXED;
+ !fixed || path.exists()
}
pub fn link_target(link: &std::path::Path) -> Option<String> {
@@ -63,3 +340,48 @@ pub fn link_target(link: &std::path::Path) -> Option<String> {
(len > 0).then(|| String::from_utf16_lossy(&buffer[..len]))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn utf16(text: &str) -> Vec<u8> {
+ text.encode_utf16().flat_map(u16::to_le_bytes).collect()
+ }
+
+ #[test]
+ fn favorites_should_give_store_apps_and_shortcuts_in_taskbar_order() {
+ // Shaped like the real blob: binary noise around UTF-16 names, one of
+ // them at an odd offset.
+ let mut blob = vec![0x14, 0x00, 0x1f, 0x80];
+ blob.extend(utf16("File Explorer.lnk"));
+ blob.extend([0x00, 0x00, 0x07]);
+ blob.extend(utf16(
+ "Microsoft.ZuneMusic_8wekyb3d8bbwe!Microsoft.ZuneMusic",
+ ));
+ blob.extend([0x00, 0x00, 0x49]);
+ blob.extend(utf16("Brave.lnk"));
+
+ let explorer = find_utf16(&blob, "file explorer.lnk");
+ let brave = find_utf16(&blob, "Brave.lnk");
+ let store = app_user_model_ids(&blob);
+ assert_eq!(store.len(), 1);
+ assert_eq!(
+ store[0].1,
+ "Microsoft.ZuneMusic_8wekyb3d8bbwe!Microsoft.ZuneMusic"
+ );
+ assert!(explorer < Some(store[0].0) && Some(store[0].0) < brave);
+ }
+
+ #[test]
+ fn app_user_model_id_should_need_a_publisher_id_and_an_app() {
+ assert!(is_app_user_model_id(
+ "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"
+ ));
+ assert!(!is_app_user_model_id("Microsoft.Windows.Explorer"));
+ assert!(!is_app_user_model_id(
+ "Microsoft.ZuneMusic_11.2312.8.0_x64__8wekyb3d8bbwe"
+ ));
+ assert!(!is_app_user_model_id("Name_8wekyb3d8bbwe!"));
+ }
+}
diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rs
index 73bfba2..bce96ba 100644
--- a/crates/muelle-shell/src/status.rs
+++ b/crates/muelle-shell/src/status.rs
@@ -306,3 +306,105 @@ pub fn taskbar_buttons() -> TaskbarButtons {
widgets: dword(ADVANCED, "TaskbarDa").unwrap_or(1) != 0,
}
}
+
+/* ---------------------------------------------------------------- Privacy */
+
+/// Where Windows records which apps use the microphone, camera and
+/// location, and when: the source of its own privacy icons in the tray.
+pub const CONSENT_STORE: windows::core::PCWSTR = windows::core::w!(
+ r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore"
+);
+
+/// Which sensitive devices some app is using right now.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct Privacy {
+ pub microphone: bool,
+ pub camera: bool,
+ pub location: bool,
+}
+
+/// Reads [`CONSENT_STORE`]. Call it when [`watch_privacy`] reports a change,
+/// not on a timer.
+#[must_use]
+pub fn privacy() -> Privacy {
+ Privacy {
+ microphone: capability_in_use("microphone"),
+ camera: capability_in_use("webcam"),
+ location: capability_in_use("location"),
+ }
+}
+
+/// Tells a window, by posting it `message`, when an app starts or stops
+/// using the microphone, camera or location.
+#[must_use]
+pub fn watch_privacy(hwnd: isize, message: u32) -> Option<crate::watch::RegistryWatch> {
+ crate::watch::RegistryWatch::new(CONSENT_STORE, true, hwnd, message)
+}
+
+/// An app is using `capability` while its key has a start time and no stop
+/// time. Store apps have a key each; desktop programs sit under `NonPackaged`.
+fn capability_in_use(capability: &str) -> bool {
+ use windows::Win32::System::Registry::{
+ HKEY, HKEY_CURRENT_USER, KEY_READ, RRF_RT_REG_QWORD, RegCloseKey, RegEnumKeyExW,
+ RegGetValueW, RegOpenKeyExW,
+ };
+ use windows::core::{HSTRING, PCWSTR, PWSTR, w};
+
+ let in_use = |parent: HKEY, path: &str| -> bool {
+ let mut key = HKEY::default();
+ // SAFETY: Read-only registry walk; every opened key is closed.
+ unsafe {
+ if RegOpenKeyExW(parent, &HSTRING::from(path), None, KEY_READ, &mut key).is_err() {
+ return false;
+ }
+ let mut found = false;
+ let mut index = 0;
+ loop {
+ let mut name = [0u16; 512];
+ let mut len = name.len() as u32;
+ if RegEnumKeyExW(
+ key,
+ index,
+ Some(PWSTR(name.as_mut_ptr())),
+ &mut len,
+ None,
+ None,
+ None,
+ None,
+ )
+ .is_err()
+ {
+ break;
+ }
+ index += 1;
+ let read = |value: PCWSTR| {
+ let mut time = 0u64;
+ let mut size = size_of::<u64>() as u32;
+ RegGetValueW(
+ key,
+ PCWSTR(name.as_ptr()),
+ value,
+ RRF_RT_REG_QWORD,
+ None,
+ Some((&raw mut time).cast()),
+ Some(&mut size),
+ )
+ .is_ok()
+ .then_some(time)
+ };
+ if read(w!("LastUsedTimeStart")).is_some_and(|start| start != 0)
+ && read(w!("LastUsedTimeStop")) == Some(0)
+ {
+ found = true;
+ break;
+ }
+ }
+ let _ = RegCloseKey(key);
+ found
+ }
+ };
+ let base = format!(
+ r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\{capability}"
+ );
+ in_use(HKEY_CURRENT_USER, &base) || in_use(HKEY_CURRENT_USER, &format!(r"{base}\NonPackaged"))
+}
diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rs
index 606d8ff..ccc99d0 100644
--- a/crates/muelle-shell/src/system.rs
+++ b/crates/muelle-shell/src/system.rs
@@ -48,6 +48,34 @@ pub fn transparency_enabled() -> bool {
!saver && personalize(w!("EnableTransparency")) != Some(0)
}
+/// The input language of the window in front as two capital letters
+/// ("ES", "EN"), or `None` with a single language installed: the Windows
+/// taskbar only shows its language indicator when there is a choice.
+#[must_use]
+pub fn input_language() -> Option<String> {
+ use windows::Win32::{
+ Globalization::LCIDToLocaleName,
+ UI::{
+ Input::KeyboardAndMouse::{GetKeyboardLayout, GetKeyboardLayoutList},
+ WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId},
+ },
+ };
+ // SAFETY: Read-only queries; `name` is a valid buffer for the locale name.
+ unsafe {
+ if GetKeyboardLayoutList(None) < 2 {
+ return None;
+ }
+ // Each thread has its own layout: the one that matters is in front.
+ let thread = GetWindowThreadProcessId(GetForegroundWindow(), None);
+ let language = (GetKeyboardLayout(thread).0 as usize & 0xFFFF) as u32;
+ let mut name = [0u16; 85];
+ let len = usize::try_from(LCIDToLocaleName(language, Some(&mut name), 0)).ok()?;
+ let tag = String::from_utf16_lossy(name.get(..len.checked_sub(1)?)?);
+ let code = tag.split('-').next()?.to_uppercase();
+ (!code.is_empty()).then_some(code)
+ }
+}
+
/// `true` on Windows 11 (build 22000 or later), `false` on Windows 10.
/// Read once: the version does not change while the dock runs.
#[must_use]
diff --git a/crates/muelle-shell/src/taskbar.rs b/crates/muelle-shell/src/taskbar.rs
index 0f325d1..58ed492 100644
--- a/crates/muelle-shell/src/taskbar.rs
+++ b/crates/muelle-shell/src/taskbar.rs
@@ -56,6 +56,22 @@ pub fn take_over() {
}
}
+/// What the dock and its watchdog do when the dock stops: give the taskbar
+/// back, except while Windows shuts down, restarts or signs out with Muelle
+/// set to start again. Then the taskbar stays auto-hidden for the next
+/// sign-in; given back, Windows showed it in full at every start until the
+/// dock took it over again. Turning autostart off, quitting or uninstalling
+/// still gives it back.
+pub fn give_back_on_exit() {
+ use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SHUTTINGDOWN};
+ // SAFETY: Read-only system query.
+ let session_ending = unsafe { GetSystemMetrics(SM_SHUTTINGDOWN) } != 0;
+ if session_ending && crate::autostart::is_enabled() {
+ return;
+ }
+ give_back();
+}
+
/// Restores the taskbar to its state before `take_over`. Has no effect if the
/// dock did not take it over.
pub fn give_back() {
diff --git a/crates/muelle-shell/src/watch.rs b/crates/muelle-shell/src/watch.rs
new file mode 100644
index 0000000..b2755a5
--- /dev/null
+++ b/crates/muelle-shell/src/watch.rs
@@ -0,0 +1,122 @@
+//! Telling a window when a registry key changes, without polling and without
+//! a thread of its own.
+
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, HANDLE, HWND, INVALID_HANDLE_VALUE, LPARAM, WPARAM},
+ System::{
+ Registry::{
+ HKEY, HKEY_CURRENT_USER, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET,
+ REG_NOTIFY_CHANGE_NAME, REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey,
+ RegNotifyChangeKeyValue, RegOpenKeyExW,
+ },
+ Threading::{
+ CreateEventW, INFINITE, RegisterWaitForSingleObject, UnregisterWaitEx,
+ WT_EXECUTEONLYONCE,
+ },
+ },
+ UI::WindowsAndMessaging::PostMessageW,
+ },
+ core::PCWSTR,
+};
+
+/// Posts `message` to a window when a key under `HKEY_CURRENT_USER` changes:
+/// a value is written, or (with `subtree`) a key below it is added, removed
+/// or written.
+///
+/// The registry signals an event and the system thread pool posts the
+/// message. Each registration fires once; the receiver calls
+/// [`RegistryWatch::arm`] again when it handles the message, so a burst of
+/// changes costs one message until then.
+pub struct RegistryWatch {
+ key: HKEY,
+ subtree: bool,
+ event: HANDLE,
+ wait: HANDLE,
+ /// Where the thread pool posts: window and message. Boxed so its address,
+ /// handed to the thread pool, never moves.
+ target: Box<(isize, u32)>,
+}
+
+impl RegistryWatch {
+ #[must_use]
+ pub fn new(path: PCWSTR, subtree: bool, hwnd: isize, message: u32) -> Option<Self> {
+ let mut key = HKEY::default();
+ // SAFETY: Opens a key for notifications only; closed in `Drop`.
+ unsafe {
+ RegOpenKeyExW(HKEY_CURRENT_USER, path, None, KEY_NOTIFY, &mut key)
+ .ok()
+ .ok()?;
+ }
+ // SAFETY: An auto-reset event owned by this watch, closed in `Drop`.
+ let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
+ // SAFETY: The key opened above.
+ unsafe {
+ let _ = RegCloseKey(key);
+ }
+ return None;
+ };
+ let mut watch = Self {
+ key,
+ subtree,
+ event,
+ wait: HANDLE::default(),
+ target: Box::new((hwnd, message)),
+ };
+ watch.arm().then_some(watch)
+ }
+
+ /// Listens for the next change.
+ pub fn arm(&mut self) -> bool {
+ // SAFETY: Every handle belongs to this watch; `target` outlives the
+ // wait, which `Drop` cancels before freeing it.
+ unsafe {
+ if !self.wait.is_invalid() {
+ // Without an event to wait on: the one-shot wait has run.
+ let _ = UnregisterWaitEx(self.wait, None);
+ self.wait = HANDLE::default();
+ }
+ // Thread-agnostic, so the registration survives whichever thread made it.
+ let filter =
+ REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_THREAD_AGNOSTIC;
+ if RegNotifyChangeKeyValue(self.key, self.subtree, filter, Some(self.event), true)
+ .is_err()
+ {
+ return false;
+ }
+ RegisterWaitForSingleObject(
+ &mut self.wait,
+ self.event,
+ Some(changed),
+ Some(std::ptr::from_ref(&*self.target).cast()),
+ INFINITE,
+ WT_EXECUTEONLYONCE,
+ )
+ .is_ok()
+ }
+ }
+}
+
+unsafe extern "system" fn changed(context: *mut std::ffi::c_void, _timed_out: bool) {
+ // SAFETY: `context` points at the watch's boxed target, alive until the
+ // wait is cancelled.
+ let (hwnd, message) = unsafe { *context.cast::<(isize, u32)>() };
+ // SAFETY: Posting is asynchronous; a closed window just drops it.
+ unsafe {
+ let _ = PostMessageW(Some(HWND(hwnd as *mut _)), message, WPARAM(0), LPARAM(0));
+ }
+}
+
+impl Drop for RegistryWatch {
+ fn drop(&mut self) {
+ // SAFETY: Waits for a running callback to finish before the target
+ // is freed, then releases this watch's handles once.
+ unsafe {
+ if !self.wait.is_invalid() {
+ let _ = UnregisterWaitEx(self.wait, Some(INVALID_HANDLE_VALUE));
+ }
+ let _ = CloseHandle(self.event);
+ let _ = RegCloseKey(self.key);
+ }
+ }
+}
diff --git a/muelle/src/pages/privacy.astro b/muelle/src/pages/privacy.astro
index ed22260..353bacd 100644
--- a/muelle/src/pages/privacy.astro
+++ b/muelle/src/pages/privacy.astro
@@ -63,8 +63,8 @@ import { site } from "@/data/site";
<li><code>%LOCALAPPDATA%\Muelle</code>: a cache of app icons and names, so the dock starts fast.</li>
</ul>
<p>
- To show what is on screen (open windows, their icons, network and volume status for the menu bar), Muelle asks
- Windows itself; none of it leaves your computer. Uninstalling removes the cache, and optionally your settings.
+ To show what is on screen (open windows, their icons, network and volume status, and whether an app is using the
+ microphone, camera or location, for the menu bar), Muelle asks Windows itself; none of it leaves your computer. Uninstalling removes the cache, and optionally your settings.
</p>
<h2>This website</h2>
diff --git a/spikes/Cargo.toml b/spikes/Cargo.toml
index 9a30455..de80a8e 100644
--- a/spikes/Cargo.toml
+++ b/spikes/Cargo.toml
@@ -30,6 +30,7 @@ windows = { workspace = true, features = [
"Win32_System_Threading",
"Win32_System_WinRT",
"Win32_System_WinRT_Composition",
+ "Win32_UI_Accessibility",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_System_SystemInformation",
diff --git a/spikes/src/bin/spike_cloak.rs b/spikes/src/bin/spike_cloak.rs
new file mode 100644
index 0000000..8adbb0b
--- /dev/null
+++ b/spikes/src/bin/spike_cloak.rs
@@ -0,0 +1,67 @@
+//! Counts window cloak and uncloak events (virtual desktop switches, Start,
+//! some Store apps) for a while, to check what listening to them costs.
+//! Usage: `spike_cloak [seconds]`.
+
+use std::{
+ sync::atomic::{AtomicU32, Ordering},
+ time::{Duration, Instant},
+};
+
+use windows::Win32::{
+ Foundation::HWND,
+ UI::{
+ Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},
+ WindowsAndMessaging::{
+ DispatchMessageW, EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED, MSG, OBJID_WINDOW,
+ PM_REMOVE, PeekMessageW, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS,
+ },
+ },
+};
+
+static EVENTS: AtomicU32 = AtomicU32::new(0);
+
+unsafe extern "system" fn on_event(
+ _hook: HWINEVENTHOOK,
+ _event: u32,
+ _hwnd: HWND,
+ object: i32,
+ _child: i32,
+ _thread: u32,
+ _time: u32,
+) {
+ if object == OBJID_WINDOW.0 {
+ EVENTS.fetch_add(1, Ordering::Relaxed);
+ }
+}
+
+fn main() {
+ let seconds: u64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(20);
+ // SAFETY: An out-of-context hook delivered through this thread's message loop.
+ let hook = unsafe {
+ SetWinEventHook(
+ EVENT_OBJECT_CLOAKED,
+ EVENT_OBJECT_UNCLOAKED,
+ None,
+ Some(on_event),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ )
+ };
+ let until = Instant::now() + Duration::from_secs(seconds);
+ let mut msg = MSG::default();
+ while Instant::now() < until {
+ // SAFETY: Standard message pump on this thread.
+ unsafe {
+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
+ DispatchMessageW(&msg);
+ }
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ // SAFETY: The hook installed above.
+ unsafe {
+ let _ = UnhookWinEvent(hook);
+ }
+ println!("cloak/uncloak events in {seconds} s: {}", EVENTS.load(Ordering::Relaxed));
+}
diff --git a/spikes/src/bin/spike_pins.rs b/spikes/src/bin/spike_pins.rs
new file mode 100644
index 0000000..0416b23
--- /dev/null
+++ b/spikes/src/bin/spike_pins.rs
@@ -0,0 +1,26 @@
+//! Prints what the dock would import from the Windows taskbar's pinned apps,
+//! whether each one still exists, the input language indicator and which
+//! privacy indicators (microphone, camera, location) are on.
+
+use muelle_shell::{
+ pins::{app_exists, taskbar_pins},
+ status::privacy,
+ system::input_language,
+};
+use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
+
+fn main() {
+ // SAFETY: COM for this thread, needed to read shortcuts and shell items.
+ let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
+ for (index, id) in taskbar_pins().iter().enumerate() {
+ println!("{}. {id} (exists: {})", index + 1, app_exists(id));
+ }
+ for id in [
+ r"c:\program files\no-such-app\gone.exe",
+ r"shell:AppsFolder\Not.Installed_8wekyb3d8bbwe!App",
+ ] {
+ println!("missing check: {id} -> exists {}", app_exists(id));
+ }
+ println!("input language: {:?}", input_language());
+ println!("privacy: {:?}", privacy());
+}