A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(settings): retire menu bar status item overrides and streamline preferences
CristianOlivera1e3611b732040
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 256c5ce..997c724 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,9 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Battery percentage, Search, Task View and Widgets now follow Windows settings+ directly. Removed their duplicate Settings switches and retired saved overrides.+ Search changes also update through registry notifications; no new polling.- Bluetooth now follows Windows automatically: its menu-bar icon appears onlywhile a Bluetooth radio is on. Removed the duplicate Settings toggle andretired saved overrides. State/hotplug events update the icon without polling.@@ -28,6 +31,9 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Porcentaje de batería, Búsqueda, Vista de tareas y Widgets siguen directamente+ los ajustes de Windows. Retirados sus interruptores duplicados y preferencias+ antiguas. Búsqueda también se actualiza por eventos del registro, sin sondeo.- Bluetooth sigue automáticamente a Windows: su icono aparece solo cuando hayuna radio Bluetooth encendida. Retirados el interruptor duplicado de Ajustesy las preferencias antiguas. Los eventos de estado/hardware actualizan eldiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex c59ab39..c391170 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -4484,10 +4484,6 @@ impl App {/// Creates or removes the menu bar to match the settings.fn apply_menu_bar_setting(&mut self) {let widgets = MenuBarWidgets {- search: self.config.menu_bar_search,- task_view: self.config.menu_bar_task_view,- widgets: self.config.menu_bar_widgets,- battery_percent: self.config.menu_bar_battery_percent,island_style: self.config.menu_bar_island_style,};if !self.config.menu_bar {diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 1e0d403..c4b3b4b 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -179,20 +179,12 @@ enum Action {#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct MenuBarWidgets {- pub search: Option<bool>,- pub task_view: Option<bool>,- pub widgets: Option<bool>,- pub battery_percent: Option<bool>,pub island_style: IslandStyle,}impl Default for MenuBarWidgets {fn default() -> Self {Self {- search: None,- task_view: None,- widgets: None,- battery_percent: None,island_style: IslandStyle::Notch,}}@@ -520,6 +512,8 @@ pub struct MenuBar {privacy_watch: Option<RegistryWatch>,/// Windows' taskbar preferences, including the battery percentage.settings_watch: Option<RegistryWatch>,+ /// Search uses its own Windows preference key.+ search_watch: Option<RegistryWatch>,/// Energy saver on or off arrives as `WM_POWERBROADCAST`; glass follows._saver_watch: muelle_shell::power::SaverWatch,audio: Option<AudioWatch>,@@ -1188,6 +1182,7 @@ impl MenuBar {_network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),privacy_watch: status::watch_privacy(hwnd.0 as isize, REGISTRY_CHANGED),settings_watch: status::watch_taskbar_settings(hwnd.0 as isize, REGISTRY_CHANGED),+ search_watch: status::watch_search_settings(hwnd.0 as isize, REGISTRY_CHANGED),_saver_watch: muelle_shell::power::SaverWatch::new(hwnd.0 as isize),audio: AudioWatch::new(hwnd.0 as isize, AUDIO_CHANGED),};@@ -1652,7 +1647,6 @@ impl MenuBar {Ok(())}- /// The minute changed, or something the bar shows did: redraw what differs./// Privacy activity or the user's taskbar preferences changed.pub fn registry_changed(&mut self, gfx: &Gfx) -> Result<()> {if let Some(watch) = &mut self.privacy_watch {@@ -1661,7 +1655,19 @@ impl MenuBar {if let Some(watch) = &mut self.settings_watch {watch.arm();}- self.tick(gfx)+ if let Some(watch) = &mut self.search_watch {+ watch.arm();+ }+ // Only reread registry-backed indicators. This event must not trigger+ // network/audio queries, provider scans or accessory discovery.+ self.status.buttons = status::taskbar_buttons();+ self.status.battery_percentage = status::battery_percentage_enabled();+ self.status.privacy = status::privacy();+ let Some(mut look) = self.look.clone() else {+ return self.refresh(gfx);+ };+ look.status = self.status;+ self.apply_look(gfx, look)}pub fn tick(&mut self, gfx: &Gfx) -> Result<()> {@@ -2111,15 +2117,7 @@ impl MenuBar {items.push((symbol(&[(glyph, 1.0)])?, action));}}- let show_search = look.widgets.search.unwrap_or(status.buttons.search);- let show_task_view = look.widgets.task_view.unwrap_or(status.buttons.task_view);- let show_widgets = look.widgets.widgets.unwrap_or(status.buttons.widgets);- let show_battery_percentage = look- .widgets- .battery_percent- .unwrap_or(status.battery_percentage);-- if show_search {+ if status.buttons.search {items.push((symbol(&[(glyph::SEARCH, 1.0)])?, Action::Search));}if status.bluetooth_on {@@ -2149,7 +2147,7 @@ impl MenuBar {}let mut battery_label = None;if let Some(battery) = look.battery {- if show_battery_percentage {+ if status.battery_percentage {battery_label = Some((items.len(),gfx.text_brush(&format!("{}%", battery.percent), scale, false, ink)?,@@ -2181,10 +2179,10 @@ impl MenuBar {// 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));- if show_task_view {+ if status.buttons.task_view {items.push((symbol(&[(glyph::TASK_VIEW, 1.0)])?, Action::TaskView));}- if show_widgets {+ if status.buttons.widgets {items.push((symbol(&[(glyph::WIDGETS, 1.0)])?, Action::Widgets));}for (index, (item, action)) in items.iter().enumerate() {@@ -4049,6 +4047,9 @@ fn draw_bubble_player(impl Drop for MenuBar {fn drop(&mut self) {+ self.search_watch = None;+ self.settings_watch = None;+ self.privacy_watch = None;self.bluetooth = None;self.accessories = None;self.exit_animation = None;@@ -4074,6 +4075,91 @@ impl Drop for MenuBar {mod island_tests {use super::*;+ #[test]+ #[ignore = "Hidden compositor fixture; synthetic preferences, no Windows settings writes"]+ fn native_status_items_follow_windows_preferences_without_overrides() -> Result<()> {+ use anyhow::Context;+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ let mut bar = MenuBar::create(&gfx, false, false, true, MenuBarWidgets::default())?;+ bar.set_visible(false)?;+ let mut look = bar.look.clone().context("initial look")?;+ look.screen = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };+ look.battery = Some(Battery {+ percent: 75,+ charging: false,+ saver: false,+ });+ look.accessories = [None, None];+ look.status.bluetooth_on = false;+ let mut battery_width = [0.0; 2];+ for mask in 0..16 {+ look.status.buttons = TaskbarButtons {+ search: mask & 1 != 0,+ task_view: mask & 2 != 0,+ widgets: mask & 4 != 0,+ };+ look.status.battery_percentage = mask & 8 != 0;+ bar.apply_look(&gfx, look.clone())?;+ for (action, on) in [+ (Action::Search, look.status.buttons.search),+ (Action::TaskView, look.status.buttons.task_view),+ (Action::Widgets, look.status.buttons.widgets),+ ] {+ assert_eq!(+ bar.zones.iter().filter(|(_, _, a)| *a == action).count(),+ usize::from(on)+ );+ }+ // The battery is the last QuickSettings zone. Its percentage must+ // add label width, without introducing another clickable control.+ let battery = bar+ .zones+ .iter()+ .rev()+ .find(|(_, _, a)| *a == Action::QuickSettings)+ .context("battery zone")?;+ battery_width[usize::from(look.status.battery_percentage)] = battery.1 - battery.0;+ }+ assert!(battery_width[1] > battery_width[0]);+ // No phantom battery or percentage on a desktop without a battery.+ look.battery = None;+ bar.apply_look(&gfx, look)?;+ assert_eq!(+ bar.zones+ .iter()+ .filter(|(_, _, a)| *a == Action::QuickSettings)+ .count(),+ 2+ );++ // The native registry handler reads the real Windows values without+ // replacing the media/provider snapshot or resetting the clock timer.+ bar.registry_changed(&gfx)?;+ let current = bar.look.as_ref().context("updated look")?;+ assert!(current.status.buttons == status::taskbar_buttons());+ assert_eq!(+ current.status.battery_percentage,+ status::battery_percentage_enabled()+ );+ Ok(())+ }+#[test]#[ignore = "Hidden compositor fixture; synthetic Bluetooth states, no hardware changes"]fn native_bluetooth_indicator_appears_only_for_an_enabled_system_radio() -> Result<()> {diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsindex d4532ee..035597f 100644--- a/apps/settings/src-tauri/src/main.rs+++ b/apps/settings/src-tauri/src/main.rs@@ -46,27 +46,18 @@ async fn set_config(patch: serde_json::Map<String, serde_json::Value>) -> Result.map_err(|error| error.to_string())?}-/// Read-only system defaults for the Settings view, separate from saved-/// overrides. Reuse the menu bar's readers so both agree on absent values.+/// Read-only animation preference for the Settings view. Windows remains+/// the source of truth; the dock owns status-item preference notifications.#[derive(Serialize)]#[serde(rename_all = "camelCase")]struct WindowsPreferences {animations: bool,- menu_bar_search: bool,- menu_bar_task_view: bool,- menu_bar_widgets: bool,- menu_bar_battery_percent: bool,}#[tauri::command]fn windows_preferences() -> WindowsPreferences {- let buttons = muelle_shell::status::taskbar_buttons();WindowsPreferences {animations: muelle_shell::system::animations_enabled(),- menu_bar_search: buttons.search,- menu_bar_task_view: buttons.task_view,- menu_bar_widgets: buttons.widgets,- menu_bar_battery_percent: muelle_shell::status::battery_percentage_enabled(),}}diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex ac4ae9f..6469053 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -611,38 +611,6 @@ export function App() {/></SubRow></Card>- {config.menuBar && (- <Card title={t.menuBarItems}>- <Row icon={<SettingIcon name="battery" />} label={t.menuBarBatteryPercent} hint={t.menuBarBatteryPercentHint}>- <Toggle- label={t.menuBarBatteryPercent}- checked={config.menuBarBatteryPercent ?? windowsPreferences?.menuBarBatteryPercent}- onChange={(menuBarBatteryPercent) => update({ menuBarBatteryPercent })}- />- </Row>- <Row icon={<SettingIcon name="search" />} label={t.menuBarSearch} hint={t.menuBarSearchHint}>- <Toggle- label={t.menuBarSearch}- checked={config.menuBarSearch ?? windowsPreferences?.menuBarSearch}- onChange={(menuBarSearch) => update({ menuBarSearch })}- />- </Row>- <Row icon={<SettingIcon name="windows" />} label={t.menuBarTaskView} hint={t.menuBarTaskViewHint}>- <Toggle- label={t.menuBarTaskView}- checked={config.menuBarTaskView ?? windowsPreferences?.menuBarTaskView}- onChange={(menuBarTaskView) => update({ menuBarTaskView })}- />- </Row>- <Row icon={<SettingIcon name="widgets" />} label={t.menuBarWidgets} hint={t.menuBarWidgetsHint}>- <Toggle- label={t.menuBarWidgets}- checked={config.menuBarWidgets ?? windowsPreferences?.menuBarWidgets}- onChange={(menuBarWidgets) => update({ menuBarWidgets })}- />- </Row>- </Card>- )}</>) : (<>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex 19c857e..6e9f017 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -36,10 +36,6 @@ export interface Config {menuBarMusic: boolean;menuBarIslandStyle: IslandStyle;accessoryBattery: boolean;- menuBarSearch: boolean | null;- menuBarTaskView: boolean | null;- menuBarWidgets: boolean | null;- menuBarBatteryPercent: boolean | null;showIndicators: boolean;showRecents: boolean;bounceOnOpen: boolean;@@ -63,10 +59,6 @@ export const getAutostart = () => invoke<boolean>("get_autostart");/** Current Windows values for display only; never merge these into Config. */export interface WindowsPreferences {animations: boolean;- menuBarSearch: boolean;- menuBarTaskView: boolean;- menuBarWidgets: boolean;- menuBarBatteryPercent: boolean;}let windowsPreferencesRequest: Promise<WindowsPreferences> | undefined;diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex f8b8df5..84946b2 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -55,15 +55,6 @@"accessoryBattery": "Show accessory battery","accessoryBatteryHint": "Supported mice and headsets. No device queries while off.","aiUsageHint": "Uses your existing sessions; checks every 5 min. Never saves credentials.",- "menuBarItems": "Status items",- "menuBarBatteryPercent": "Show battery percentage",- "menuBarBatteryPercentHint": "Display the charge percentage next to the battery icon.",- "menuBarSearch": "Search button",- "menuBarSearchHint": "Show the Windows search button.",- "menuBarTaskView": "Task View button",- "menuBarTaskViewHint": "Show Task View to manage open windows and virtual desktops.",- "menuBarWidgets": "Widgets button",- "menuBarWidgetsHint": "Show the Widgets board button.","autostart": "Open Muelle at login","language": "Language","languageAuto": "Automatic",diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonindex 72a2238..0b30e66 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -55,15 +55,6 @@"accessoryBattery": "Mostrar batería de accesorios","accessoryBatteryHint": "Ratones y auriculares compatibles. Apagado, no los consulta.","aiUsageHint": "Usa tus sesiones abiertas; consulta cada 5 min. No guarda credenciales.",- "menuBarItems": "Elementos de estado",- "menuBarBatteryPercent": "Mostrar porcentaje de batería",- "menuBarBatteryPercentHint": "Muestra el nivel de carga junto al icono de la batería.",- "menuBarSearch": "Botón de búsqueda",- "menuBarSearchHint": "Muestra el botón de búsqueda de Windows.",- "menuBarTaskView": "Botón de Vista de tareas",- "menuBarTaskViewHint": "Muestra la Vista de tareas para ver ventanas y escritorios virtuales.",- "menuBarWidgets": "Botón de Widgets",- "menuBarWidgetsHint": "Muestra el botón del panel de widgets.","autostart": "Abrir Muelle al iniciar sesión","language": "Idioma","languageAuto": "Automático",diff --git a/apps/settings/src/i18n/fr.json b/apps/settings/src/i18n/fr.jsonindex cc4b91e..41cea42 100644--- a/apps/settings/src/i18n/fr.json+++ b/apps/settings/src/i18n/fr.json@@ -55,15 +55,6 @@"accessoryBattery": "Afficher la batterie des accessoires","accessoryBatteryHint": "Souris et casques compatibles. Aucune interrogation si désactivé.","aiUsageHint": "Utilise vos sessions existantes ; vérifie toutes les 5 min. Aucun identifiant enregistré.",- "menuBarItems": "Éléments d'état",- "menuBarBatteryPercent": "Afficher le pourcentage de batterie",- "menuBarBatteryPercentHint": "Affiche le pourcentage à côté de l'icône de batterie.",- "menuBarSearch": "Bouton de recherche",- "menuBarSearchHint": "Affiche le bouton de recherche Windows.",- "menuBarTaskView": "Bouton Vue des tâches",- "menuBarTaskViewHint": "Affiche la Vue des tâches pour gérer les fenêtres et bureaux virtuels.",- "menuBarWidgets": "Bouton Widgets",- "menuBarWidgetsHint": "Affiche le bouton du panneau des widgets.","autostart": "Ouvrir Muelle à l'ouverture de session","language": "Langue","languageAuto": "Automatique",diff --git a/apps/settings/src/visuals.tsx b/apps/settings/src/visuals.tsxindex 774ad20..0e0610b 100644--- a/apps/settings/src/visuals.tsx+++ b/apps/settings/src/visuals.tsx@@ -17,9 +17,6 @@ const PATHS = {music: <><path d="M9 17V5l12-2v12M9 9l12-2" /><ellipse cx="6" cy="18" rx="3" ry="2" /><ellipse cx="18" cy="16" rx="3" ry="2" /></>,ai: <><path d="m12 2 2.6 7.4L22 12l-7.4 2.6L12 22l-2.6-7.4L2 12l7.4-2.6z" /></>,headphones: <><path d="M4 14v-3a8 8 0 0 1 16 0v3" /><rect x="3" y="12" width="4" height="8" rx="2" /><rect x="17" y="12" width="4" height="8" rx="2" /></>,- battery: <><rect x="2" y="6" width="18" height="12" rx="2" /><path d="M23 10v4M6 10v4m4-4v4m4-4v4" /></>,- search: <><circle cx="10" cy="10" r="7" /><path d="m15 15 6 6" /></>,- widgets: <><rect x="3" y="3" width="7" height="18" rx="2" /><rect x="14" y="3" width="7" height="7" rx="2" /><rect x="14" y="14" width="7" height="7" rx="2" /></>,start: <><path d="M12 3v9M6 5a9 9 0 1 0 12 0" /></>,language: <><circle cx="12" cy="12" r="10" /><ellipse cx="12" cy="12" rx="4" ry="10" /><path d="M2 12h20" /></>,updates: <><path d="M20 8a8 8 0 0 0-14-3L3 8m0-5v5h5m-4 8a8 8 0 0 0 14 3l3-3m-5 0h5v5" /></>,diff --git a/apps/settings/tests/app.test.mjs b/apps/settings/tests/app.test.mjsindex 88479b2..1547307 100644--- a/apps/settings/tests/app.test.mjs+++ b/apps/settings/tests/app.test.mjs@@ -32,8 +32,7 @@ const base = {showTrash: true, pinExplorer: true,showDownloads: true,showOtherWorkspaces: false,- menuBarIslandStyle: "notch", menuBarSearch: null, menuBarTaskView: null,- menuBarWidgets: null, menuBarBatteryPercent: null, checkUpdates: false,+ menuBarIslandStyle: "notch", checkUpdates: false,pinned: [], recent: [], shortcutsFolder: null,};const settle = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };@@ -73,7 +72,7 @@ function fixture(section = "menubar", config = {}, save = async () => {}) {switch (command) {case "get_config": return { ...loaded };case "get_autostart": return false;- case "windows_preferences": return { animations: true, menuBarSearch: false };+ case "windows_preferences": return { animations: true };case "wallpaper_preview": return null;case "default_config": return base;case "set_config": calls.push({ ...args.patch }); return save(args.patch);@@ -133,7 +132,24 @@ test("Bluetooth has no duplicate setting even with an old saved visibility overrfor (const language of Object.keys(texts)) for (const menuBarBluetooth of [false, true]) {const view = fixture("menubar", { language, menuBar: true, menuBarBluetooth });assert.doesNotMatch(renderToStaticMarkup(view.body()), /Bluetooth/i);- assert.ok([...elements(view.body())].some((node) => node.props.title === texts[language].menuBarItems));+ }+});++test("retired Windows status-item overrides expose no controls and create no save", async () => {+ for (const language of Object.keys(texts)) for (const old of [null, false, true]) {+ const view = fixture("menubar", { language, menuBarSearch: old, menuBarTaskView: old,+ menuBarWidgets: old, menuBarBatteryPercent: old });+ const unmount = await view.mount();+ try {+ const controls = [...elements(view.body())].filter((node) => "checked" in node.props);+ assert.deepEqual(controls.map((node) => node.props.label), [texts[language].menuBarShow,+ texts[language].menuBarAutoHide, texts[language].menuBarMusic, texts[language].aiUsage,+ texts[language].accessoryBattery]);+ view.fire(60);+ await settle();+ assert.deepEqual(view.calls, []);+ assert.equal(await view.close(), false);+ } finally { unmount(); }}});@@ -162,7 +178,7 @@ test("failed writes remain retryable and prevent closing until saved", async ()const view = fixture("menubar", {}, async () => { if (fail) throw new Error("disk busy"); });const unmount = await view.mount();try {- view.change(texts.en.menuBarSearch, false);+ view.change(texts.en.menuBarAutoHide, false);view.fire(60);await settle();assert.equal(await view.close(), true);@@ -170,7 +186,7 @@ test("failed writes remain retryable and prevent closing until saved", async ()assert.ok(renderToStaticMarkup(view.body()).includes(texts.en.saveError));fail = false;assert.equal(await view.close(), false);- assert.deepEqual(view.calls, Array(3).fill({ menuBarSearch: false }));+ assert.deepEqual(view.calls, Array(3).fill({ menuBarAutoHide: false }));assert.ok(!renderToStaticMarkup(view.body()).includes(texts.en.saveError));} finally { unmount(); }});@@ -181,15 +197,15 @@ test("a queued newer choice wins over an earlier failed write", async () => {? new Promise((_, reject) => { rejectFirst = reject; }) : Promise.resolve());const unmount = await view.mount();try {- view.change(texts.en.menuBarSearch, false);+ view.change(texts.en.menuBarAutoHide, false);view.fire(60);await settle();- view.change(texts.en.menuBarSearch, true);- view.change(texts.en.menuBarWidgets, false);+ view.change(texts.en.menuBarAutoHide, true);+ view.change(texts.en.menuBarMusic, false);view.fire(60);rejectFirst(new Error("disk busy"));await settle();- assert.deepEqual(view.calls, [{ menuBarSearch: false }, { menuBarSearch: true, menuBarWidgets: false }]);+ assert.deepEqual(view.calls, [{ menuBarAutoHide: false }, { menuBarAutoHide: true, menuBarMusic: false }]);assert.equal(await view.close(), false);assert.equal(view.calls.length, 2, "the obsolete value must not be replayed on close");} finally { unmount(); }diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex 703a482..856581c 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -96,14 +96,6 @@ pub struct Config {pub menu_bar_island_style: IslandStyle,/// Opt-in peripheral monitoring. Off means no accessory reader or queries.pub accessory_battery: bool,- /// Show search button in the menu bar (`None` follows Windows taskbar setting).- pub menu_bar_search: Option<bool>,- /// Show Task View button in the menu bar (`None` follows Windows taskbar setting).- pub menu_bar_task_view: Option<bool>,- /// Show Widgets button in the menu bar (`None` follows Windows taskbar setting).- pub menu_bar_widgets: Option<bool>,- /// Show battery percentage in the menu bar (`None` follows Windows setting).- pub menu_bar_battery_percent: Option<bool>,/// The dot under apps that have windows open.pub show_indicators: bool,/// The section of recently used apps that are not pinned.@@ -315,10 +307,6 @@ impl Default for Config {menu_bar_music: true,menu_bar_island_style: IslandStyle::Notch,accessory_battery: false,- menu_bar_search: None,- menu_bar_task_view: None,- menu_bar_widgets: Some(false),- menu_bar_battery_percent: None,show_indicators: true,show_recents: true,bounce_on_open: true,@@ -618,16 +606,40 @@ mod tests {}#[test]- fn widgets_button_is_off_by_default_and_can_be_enabled() -> Result<(), ConfigError> {- let path = scratch("widgets-button");- assert_eq!(Config::default().menu_bar_widgets, Some(false));-- let saved = update_preferences(- &path,- serde_json::Map::from_iter([("menuBarWidgets".into(), true.into())]),- )?;- assert_eq!(saved.menu_bar_widgets, Some(true));-+ fn retired_status_overrides_are_ignored_without_changing_other_preferences()+ -> Result<(), ConfigError> {+ let path = scratch("retired-status-overrides");+ save(&path, &Config::default())?;+ for old in [serde_json::Value::Null, false.into(), true.into()] {+ let mut patch = serde_json::Map::from_iter([+ ("menuBarSearch".into(), old.clone()),+ ("menuBarTaskView".into(), old.clone()),+ ("menuBarWidgets".into(), old.clone()),+ ("menuBarBatteryPercent".into(), old),+ ("showStart".into(), false.into()),+ ("accessoryBattery".into(), true.into()),+ ]);+ // Exercise loading an existing file, then saving a Settings patch.+ fs::write(&path, serde_json::to_vec(&patch)?).map_err(|source| ConfigError::Io {+ path: path.clone(),+ source,+ })?;+ let loaded = load(&path)?.unwrap_or_default();+ assert!(!loaded.show_start && loaded.accessory_battery);+ patch.insert("iconSize".into(), 64.into());+ let saved = update_preferences(&path, patch)?;+ assert!(!saved.show_start && saved.accessory_battery);+ assert_eq!(saved.icon_size, 64);+ let json = serde_json::to_value(load(&path)?.unwrap_or_default())?;+ for key in [+ "menuBarSearch",+ "menuBarTaskView",+ "menuBarWidgets",+ "menuBarBatteryPercent",+ ] {+ assert!(json.get(key).is_none(), "retired override {key}");+ }+ }Ok(())}diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rsindex b47ef59..a25c240 100644--- a/crates/muelle-shell/src/status.rs+++ b/crates/muelle-shell/src/status.rs@@ -395,7 +395,7 @@ pub fn alt_tab_lists_more_than_windows(edge_open: bool) -> bool {(tabs && edge_open) || all_desktops}-/// Read when the bar redraws: three registry values, no watch needed. A value+/// Read at startup and when Windows reports a preference change. A value/// Windows has never written means the button is at its default, shown.#[must_use]pub fn taskbar_buttons() -> TaskbarButtons {@@ -430,6 +430,13 @@ pub fn watch_taskbar_settings(hwnd: isize, message: u32) -> Option<crate::watch:crate::watch::RegistryWatch::new(ADVANCED, false, hwnd, message)}+/// Search visibility lives outside Explorer's Advanced key. Listen separately+/// so changes are reflected without waiting for a clock tick or a broadcast.+#[must_use]+pub fn watch_search_settings(hwnd: isize, message: u32) -> Option<crate::watch::RegistryWatch> {+ crate::watch::RegistryWatch::new(SEARCH, false, hwnd, message)+}+/* ---------------------------------------------------------------- Privacy *//// Where Windows records which apps use the microphone and camera, anddiff --git a/crates/muelle-shell/src/watch.rs b/crates/muelle-shell/src/watch.rsindex b2755a5..167c036 100644--- a/crates/muelle-shell/src/watch.rs+++ b/crates/muelle-shell/src/watch.rs@@ -1,6 +1,8 @@//! Telling a window when a registry key changes, without polling and without//! a thread of its own.+use std::sync::atomic::{AtomicBool, Ordering};+use windows::{Win32::{Foundation::{CloseHandle, HANDLE, HWND, INVALID_HANDLE_VALUE, LPARAM, WPARAM},@@ -35,7 +37,13 @@ pub struct RegistryWatch {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)>,+ target: Box<Target>,+}++struct Target {+ window: isize,+ message: u32,+ notified: AtomicBool,}impl RegistryWatch {@@ -61,19 +69,29 @@ impl RegistryWatch {subtree,event,wait: HANDLE::default(),- target: Box::new((hwnd, message)),+ target: Box::new(Target {+ window: hwnd,+ message,+ notified: AtomicBool::new(false),+ }),};watch.arm().then_some(watch)}/// Listens for the next change.pub fn arm(&mut self) -> bool {+ // Several watches can share one UI notification. Do not register a+ // second notification on a key whose existing wait has not fired.+ if !self.wait.is_invalid() && !self.target.notified.swap(false, Ordering::AcqRel) {+ return true;+ }// 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);+ // The callback only posts a message. Finish it before replacing+ // the wait so Drop can account for every use of the target.+ let _ = UnregisterWaitEx(self.wait, Some(INVALID_HANDLE_VALUE));self.wait = HANDLE::default();}// Thread-agnostic, so the registration survives whichever thread made it.@@ -100,10 +118,16 @@ impl RegistryWatch {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)>() };+ let target = unsafe { &*context.cast::<Target>() };+ target.notified.store(true, Ordering::Release);// SAFETY: Posting is asynchronous; a closed window just drops it.unsafe {- let _ = PostMessageW(Some(HWND(hwnd as *mut _)), message, WPARAM(0), LPARAM(0));+ let _ = PostMessageW(+ Some(HWND(target.window as *mut _)),+ target.message,+ WPARAM(0),+ LPARAM(0),+ );}}@@ -120,3 +144,136 @@ impl Drop for RegistryWatch {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};+ use windows::{+ Win32::{+ System::Registry::{+ KEY_SET_VALUE, REG_DWORD, REG_OPTION_VOLATILE, RegCreateKeyExW, RegDeleteKeyW,+ RegSetValueExW,+ },+ UI::WindowsAndMessaging::{+ CreateWindowExW, DestroyWindow, MSG, PM_REMOVE, PeekMessageW, WM_APP, WS_POPUP,+ },+ },+ core::{HSTRING, Result, w},+ };++ #[test]+ #[ignore = "Native registry notification test; writes only a temporary test key"]+ fn native_shared_notifications_do_not_duplicate_waits_and_can_rearm() -> Result<()> {+ let path = HSTRING::from(format!(+ r"Software\MuelleRegistryWatchTest-{}-{}",+ std::process::id(),+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos()+ ));+ let mut key = HKEY::default();+ unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ &path,+ None,+ None,+ REG_OPTION_VOLATILE,+ KEY_SET_VALUE,+ None,+ &mut key,+ None,+ )+ .ok()?;+ }+ struct Key(HKEY, HSTRING);+ impl Drop for Key {+ fn drop(&mut self) {+ unsafe {+ let _ = RegCloseKey(self.0);+ let _ = RegDeleteKeyW(HKEY_CURRENT_USER, &self.1);+ }+ }+ }+ let _key = Key(key, path.clone());+ let window = unsafe {+ CreateWindowExW(+ Default::default(),+ w!("STATIC"),+ w!("Muelle watch test"),+ WS_POPUP,+ -32000,+ -32000,+ 1,+ 1,+ None,+ None,+ None,+ None,+ )?+ };+ struct Window(HWND);+ impl Drop for Window {+ fn drop(&mut self) {+ unsafe {+ let _ = DestroyWindow(self.0);+ }+ }+ }+ let _window = Window(window);+ let mut watch = RegistryWatch::new(+ PCWSTR(path.as_ptr()),+ false,+ window.0 as isize,+ WM_APP + 300,+ )+ .ok_or_else(windows::core::Error::from_thread)?;+ let initial_wait = watch.wait;+ for _ in 0..10 {+ assert!(watch.arm());+ assert_eq!(+ watch.wait, initial_wait,+ "unrelated notifications must keep the existing wait"+ );+ }+ for value in [0u32, 1, 0] {+ unsafe {+ RegSetValueExW(+ key,+ w!("visibility"),+ None,+ REG_DWORD,+ Some(&value.to_le_bytes()),+ )+ .ok()?;+ }+ let deadline = Instant::now() + Duration::from_secs(2);+ let mut message = MSG::default();+ loop {+ if unsafe {+ PeekMessageW(+ &mut message,+ Some(window),+ WM_APP + 300,+ WM_APP + 300,+ PM_REMOVE,+ )+ .as_bool()+ } {+ break;+ }+ assert!(+ Instant::now() < deadline,+ "registry notification deadline exceeded"+ );+ std::thread::sleep(Duration::from_millis(2));+ }+ assert!(watch.target.notified.load(Ordering::Acquire));+ assert!(watch.arm());+ assert!(!watch.target.notified.load(Ordering::Acquire));+ }+ Ok(())+ }+}