Skip to content

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

feat: enhance automatic update mechanism and improve related settings

CristianOlivera142975ae0e01b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4428f72..2dbce6b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,10 +16,12 @@ copia la sección de la versión que se publica a la release de GitHub.
dock's magnifier from following the selection, and closing a window from
the switcher keeps it on the right app. Only the arrow keys, which move the
selection in ways Muelle cannot see, make it step aside.
-- Automatic updates: once a day, while you are away from the computer and
- nothing runs full screen, Muelle installs new versions by itself; the dock
- restarts in a moment. It can be turned off in Settings → System → "Install
+- Automatic updates: once a day, a couple of minutes after you turn on the
+ computer (or every 24 hours if it stays on), Muelle installs new versions by
+ itself; the dock restarts in a moment. Never while an app is full screen. It can be turned off in Settings → System → "Install
updates automatically". The dock itself still never uses the network.
+- Windows 10: the menu bar no longer shows a Widgets button, which Windows
+ 10 does not have; it opened Windows Ink instead.
- Glass follows energy saver: turning it on or off (by hand or at low battery)
switches the dock, the menu bar and the dock menu between glass and solid
at once.
@@ -32,11 +34,14 @@ copia la sección de la versión que se publica a la release de GitHub.
del dock siga la selección, y cerrar una ventana desde el selector la
mantiene en la app correcta. Solo las flechas, que mueven la selección de
formas que Muelle no ve, hacen que se aparte.
-- Actualizaciones automáticas: una vez al día, mientras no usas el ordenador y
- nada está a pantalla completa, Muelle instala las versiones nuevas por sí
- solo; el dock se reinicia en un momento. Se puede desactivar en Ajustes →
+- Actualizaciones automáticas: una vez al día, un par de minutos después de
+ encender el ordenador (o cada 24 horas si sigue encendido), Muelle instala
+ las versiones nuevas por sí solo; el dock se reinicia en un momento. Nunca
+ con una app a pantalla completa. Se puede desactivar en Ajustes →
Sistema → «Instalar actualizaciones automáticamente». El dock en sí sigue
sin usar la red.
+- Windows 10: la barra superior ya no muestra un botón de Widgets, que Windows
+ 10 no tiene; abría Windows Ink en su lugar.
- El cristal sigue al ahorro de energía: al activarlo o desactivarlo (a mano o
con batería baja), el dock, la barra superior y el menú del dock cambian
entre cristal y sólido al momento.
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index aad9bd8..851b266 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -183,12 +183,19 @@ const SPRING_TIMER: usize = 8;
const SPRING_DELAY_MS: u32 = 600;
/// While the Alt+Tab switcher is open, checks how long it stays: Windows
/// reports when it comes to the front, but not reliably when it closes.
-/// Every so often the dock looks whether it is a good moment to update:
-/// a day since the last time, and the user away from the computer.
+/// A duration as timer milliseconds; Windows caps timers at about 24 days.
+fn millis(duration: std::time::Duration) -> u32 {
+ duration.as_millis().min(0x7FFF_FFFF) as u32
+}
+
+/// The background update runs once a day: a single timer, aimed at the
+/// moment the next look is due (see `schedule_update`).
const UPDATE_TIMER: usize = 12;
-const UPDATE_POLL_MS: u32 = 10 * 60 * 1000;
const UPDATE_EVERY: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
-const UPDATE_IDLE: std::time::Duration = std::time::Duration::from_secs(5 * 60);
+/// After the dock starts, the look waits this long, so it never slows signing in.
+const UPDATE_AFTER_START: std::time::Duration = std::time::Duration::from_secs(2 * 60);
+/// While a full-screen app (a game, a presentation) is in front, try later.
+const UPDATE_RETRY: std::time::Duration = std::time::Duration::from_secs(60 * 60);
const SWITCHER_TIMER: usize = 9;
/// Short enough to see every Tab press (a key stays down 50-100 ms).
const SWITCHER_POLL_MS: u32 = 16;
@@ -482,11 +489,11 @@ struct App {
drag_over: bool,
/// The entry a drag is resting on, which springs open on `SPRING_TIMER`.
spring: Option<String>,
- /// When the last background update was started (see `UPDATE_TIMER`).
- last_update: Option<Instant>,
/// The Alt+Tab switcher is open; an auto-hidden dock shows meanwhile.
switching: bool,
switch_started: Instant,
+ /// When the dock started (the update waits a little after it).
+ launched: Instant,
/// The selection in the switcher, as far as it can be followed.
follow: Option<SwitcherFollow>,
/// The magnifier rests on the icon selected in Alt+Tab, not the pointer.
@@ -1316,7 +1323,12 @@ impl App {
/// selection: Windows 11's switcher reports it to no one (no accessible
/// focus, selection or name on its items; checked with MSAA and UIA).
fn task_switcher_opened(&mut self) -> Result<()> {
- if self.switching {
+ // Only Alt+Tab (and Ctrl+Alt+Tab). Task View shares the switcher's
+ // window, and on Windows 11 its virtual desktops sit along the
+ // bottom edge, where the dock would cover them.
+ // SAFETY: Read-only keyboard state query.
+ let alt = unsafe { GetAsyncKeyState(i32::from(VK_MENU.0)) < 0 };
+ if self.switching || !alt {
return Ok(());
}
self.switching = true;
@@ -1527,30 +1539,49 @@ impl App {
self.render()
}
- /// Starts the background update (Settings without a window, which does
- /// the network part) once a day, only while nobody is using the
- /// computer and nothing runs full screen, so restarting the dock bothers
- /// no one. The dock itself never touches the network.
- fn maybe_update(&mut self) {
- if !self.config.check_updates
- || !self.config.auto_update
- || self.fullscreen
- || self
- .last_update
- .is_some_and(|last| last.elapsed() < UPDATE_EVERY)
- || muelle_shell::system::idle_time() < UPDATE_IDLE
- {
+ /// Aims the update timer at the next look: a day after the last one,
+ /// which survives restarts, and never sooner than two minutes after the
+ /// dock starts. So the dock wakes for it once a day, not on a schedule.
+ fn schedule_update(&self) {
+ // SAFETY: Timers on our own window; setting one again replaces it.
+ unsafe {
+ if !self.config.check_updates || !self.config.auto_update {
+ let _ = KillTimer(Some(self.input), UPDATE_TIMER);
+ return;
+ }
+ let wait = muelle_shell::updates::due_in(UPDATE_EVERY)
+ .max(UPDATE_AFTER_START.saturating_sub(self.launched.elapsed()));
+ SetTimer(Some(self.input), UPDATE_TIMER, millis(wait), None);
+ }
+ }
+
+ /// Starts the background update: Settings without a window, which does
+ /// the network part and exits when there is nothing to install. The
+ /// dock itself never touches the network.
+ fn update_now(&mut self) {
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(self.input), UPDATE_TIMER);
+ }
+ if !self.config.check_updates || !self.config.auto_update {
+ return;
+ }
+ // Installing restarts the dock: not in the middle of a game.
+ if self.fullscreen {
+ // SAFETY: Our own timer.
+ unsafe { SetTimer(Some(self.input), UPDATE_TIMER, millis(UPDATE_RETRY), None) };
return;
}
- let Some(settings) = env::current_exe()
+ // Recorded first: whatever happens, the next look is tomorrow.
+ muelle_shell::updates::mark_checked();
+ self.schedule_update();
+ let settings = env::current_exe()
.ok()
.map(|exe| exe.with_file_name("muelle-settings.exe"))
- .filter(|path| path.exists())
- else {
- return;
- };
- self.last_update = Some(Instant::now());
- if let Err(error) = std::process::Command::new(settings).arg("--update").spawn() {
+ .filter(|path| path.exists());
+ if let Some(settings) = settings
+ && let Err(error) = std::process::Command::new(settings).arg("--update").spawn()
+ {
eprintln!("muelle: actualización: {error}");
}
}
@@ -2206,6 +2237,8 @@ impl App {
self.last_frame = Instant::now();
}
self.config = config;
+ // Updates may have been turned on or off.
+ self.schedule_update();
self.sync_thumbnails();
self.apply_menu_bar_setting();
self.update_menu_bar_app()?;
@@ -2908,7 +2941,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
}
WM_TIMER if w.0 == UPDATE_TIMER => {
with_app("actualización", |app| {
- app.maybe_update();
+ app.update_now();
Ok(())
});
}
@@ -2959,6 +2992,11 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
WM_POWERBROADCAST if w.0 == PBT_APMRESUMEAUTOMATIC => {
// SAFETY: `hwnd` is this live window on its owning UI thread.
unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };
+ // Timers do not count the time asleep: aim it again by the clock.
+ with_app("actualización", |app| {
+ app.schedule_update();
+ Ok(())
+ });
}
_ if CONFIG_CHANGED.get() == Some(&msg) => with_app("ajustes", App::reload_config),
_ if TASKBAR_CREATED.get() == Some(&msg) => {
@@ -3141,8 +3179,8 @@ pub fn run() -> Result<()> {
drag_over: false,
spring: None,
switching: false,
- last_update: None,
switch_started: Instant::now(),
+ launched: Instant::now(),
follow: None,
pointed: false,
pending_drop: None,
@@ -3233,12 +3271,11 @@ pub fn run() -> Result<()> {
);
FOREGROUND_HOOK.store(foreground_hook.0 as isize, Ordering::Relaxed);
LAST_FRONT.store(tracker::foreground_window(), Ordering::Relaxed);
- // The first look comes after ten minutes, never during sign-in.
- SetTimer(Some(input), UPDATE_TIMER, UPDATE_POLL_MS, None);
let target: IDropTarget = DropTarget.into();
RegisterDragDrop(input, &target)?;
DROP_WINDOW.store(input.0 as isize, Ordering::Relaxed);
+ app.schedule_update();
APP.set(Some(app));
}
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index 248e93d..765c25a 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -169,12 +169,18 @@ async fn update_in_background(app: AppHandle) {
},
_ => None,
};
- if let Some(update) = found
+ // Opening Settings meanwhile lands in this process (single instance):
+ // then it stays as the user's Settings, which shows the update itself,
+ // and installing must not close it under them.
+ let window_opened = || app.get_webview_window("main").is_some();
+ if let Some(update) = found.filter(|_| !window_opened())
&& let Err(error) = update.download_and_install(|_, _| {}, || {}).await
{
eprintln!("muelle-settings: actualización: {error}");
}
- app.exit(0);
+ if !window_opened() {
+ app.exit(0);
+ }
}
/// Opens the Settings window, or brings it forward if it is open.
diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.json
index 3327ead..88da713 100644
--- a/apps/settings/src/i18n/en.json
+++ b/apps/settings/src/i18n/en.json
@@ -28,7 +28,7 @@
"checkUpdates": "Check for updates automatically",
"checkUpdatesHint": "Settings asks GitHub whether there is a newer version when it opens.",
"autoUpdate": "Install updates automatically",
- "autoUpdateHint": "Once a day, while you are away from the computer, Muelle installs new versions by itself.",
+ "autoUpdateHint": "Once a day, a couple of minutes after you turn on the computer (or every 24 hours if it stays on), Muelle installs new versions by itself.",
"updatesOff": "Automatic checks are off.",
"updates": "Updates",
"updatesChecking": "Checking for updates…",
diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.json
index 35dfa14..8cf015b 100644
--- a/apps/settings/src/i18n/es.json
+++ b/apps/settings/src/i18n/es.json
@@ -28,7 +28,7 @@
"checkUpdates": "Buscar actualizaciones automáticamente",
"checkUpdatesHint": "Ajustes pregunta a GitHub si hay una versión nueva al abrirse.",
"autoUpdate": "Instalar actualizaciones automáticamente",
- "autoUpdateHint": "Una vez al día, mientras no usas el ordenador, Muelle instala las versiones nuevas por sí solo.",
+ "autoUpdateHint": "Una vez al día, un par de minutos después de encender el ordenador (o cada 24 horas si sigue encendido), Muelle instala las versiones nuevas por sí solo.",
"updatesOff": "La búsqueda automática está desactivada.",
"updates": "Actualizaciones",
"updatesChecking": "Buscando actualizaciones…",
diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.toml
index 84062cd..0b3473e 100644
--- a/crates/muelle-shell/Cargo.toml
+++ b/crates/muelle-shell/Cargo.toml
@@ -32,7 +32,6 @@ windows = { workspace = true, features = [
"Win32_System_Threading",
"Win32_System_Variant",
"Win32_UI_HiDpi",
- "Win32_System_SystemInformation",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rs
index 43788c9..699622a 100644
--- a/crates/muelle-shell/src/lib.rs
+++ b/crates/muelle-shell/src/lib.rs
@@ -14,4 +14,5 @@ pub mod status;
pub mod system;
pub mod taskbar;
pub mod tracker;
+pub mod updates;
pub mod watch;
diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rs
index 0c5cb38..f211b18 100644
--- a/crates/muelle-shell/src/status.rs
+++ b/crates/muelle-shell/src/status.rs
@@ -296,8 +296,6 @@ fn dword(key: PCWSTR, value: &str) -> Option<u32> {
Some(data)
}
-/// Read when the bar redraws: three registry values, no watch needed. A value
-/// Windows has never written means the button is at its default, shown.
/// Alt+Tab also lists Microsoft Edge tabs ("Show tabs from apps"), or the
/// windows of every virtual desktop: then its list is not the open windows
/// of this desktop in order.
@@ -309,12 +307,16 @@ 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
+/// Windows has never written means the button is at its default, shown.
#[must_use]
pub fn taskbar_buttons() -> TaskbarButtons {
TaskbarButtons {
search: dword(SEARCH, "SearchboxTaskbarMode").unwrap_or(1) != 0,
task_view: dword(ADVANCED, "ShowTaskViewButton").unwrap_or(1) != 0,
- widgets: dword(ADVANCED, "TaskbarDa").unwrap_or(1) != 0,
+ // Windows 10 has no Widgets (its value is never written there, so it
+ // would read as shown), and Win+W opens Windows Ink instead.
+ widgets: crate::system::is_windows_11() && dword(ADVANCED, "TaskbarDa").unwrap_or(1) != 0,
}
}
diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rs
index fb0f5a7..8aeafb3 100644
--- a/crates/muelle-shell/src/system.rs
+++ b/crates/muelle-shell/src/system.rs
@@ -76,26 +76,6 @@ pub fn input_language() -> Option<String> {
}
}
-/// How long since the user last touched the keyboard or mouse.
-#[must_use]
-pub fn idle_time() -> std::time::Duration {
- use windows::Win32::{
- System::SystemInformation::GetTickCount,
- UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO},
- };
- let mut input = LASTINPUTINFO {
- cbSize: size_of::<LASTINPUTINFO>() as u32,
- dwTime: 0,
- };
- // SAFETY: `input` is a valid structure with its size set.
- if !unsafe { GetLastInputInfo(&mut input) }.as_bool() {
- return std::time::Duration::ZERO;
- }
- // Both wrap every 49.7 days; the difference stays right.
- let ticks = unsafe { GetTickCount() }.wrapping_sub(input.dwTime);
- std::time::Duration::from_millis(u64::from(ticks))
-}
-
/// `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/updates.rs b/crates/muelle-shell/src/updates.rs
new file mode 100644
index 0000000..5808e27
--- /dev/null
+++ b/crates/muelle-shell/src/updates.rs
@@ -0,0 +1,82 @@
+//! When Muelle last looked for an update. Kept in `HKCU\Software\Muelle`
+//! (which the uninstaller removes), so it looks once a day however often the
+//! computer is restarted or the dock relaunched.
+
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use windows::{
+ Win32::System::Registry::{
+ HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_QWORD,
+ RRF_RT_REG_QWORD, RegCloseKey, RegCreateKeyExW, RegGetValueW, RegSetValueExW,
+ },
+ core::{PCWSTR, w},
+};
+
+const MUELLE_KEY: PCWSTR = w!(r"Software\Muelle");
+const LAST_CHECK: PCWSTR = w!("LastUpdateCheck");
+
+/// How long until the next look is due, `every` after the last one: zero if
+/// it is due now, or if Muelle never looked.
+#[must_use]
+pub fn due_in(every: Duration) -> Duration {
+ let Some(last) = last_check() else {
+ return Duration::ZERO;
+ };
+ let now = now_seconds();
+ // A clock set back past the last look would postpone it for that long.
+ if last > now {
+ return Duration::ZERO;
+ }
+ every.saturating_sub(Duration::from_secs(now - last))
+}
+
+/// Records that Muelle looked for an update now.
+pub fn mark_checked() {
+ let value = now_seconds().to_le_bytes();
+ let mut key = HKEY::default();
+ // SAFETY: The key is closed before returning; `value` lives through the call.
+ unsafe {
+ if RegCreateKeyExW(
+ HKEY_CURRENT_USER,
+ MUELLE_KEY,
+ None,
+ None,
+ REG_OPTION_NON_VOLATILE,
+ KEY_SET_VALUE,
+ None,
+ &mut key,
+ None,
+ )
+ .is_err()
+ {
+ return;
+ }
+ let _ = RegSetValueExW(key, LAST_CHECK, None, REG_QWORD, Some(&value));
+ let _ = RegCloseKey(key);
+ }
+}
+
+fn last_check() -> Option<u64> {
+ let mut value = 0u64;
+ let mut size = size_of::<u64>() as u32;
+ // SAFETY: `value` and `size` describe a valid 8-byte buffer.
+ unsafe {
+ RegGetValueW(
+ HKEY_CURRENT_USER,
+ MUELLE_KEY,
+ LAST_CHECK,
+ RRF_RT_REG_QWORD,
+ None,
+ Some((&raw mut value).cast()),
+ Some(&mut size),
+ )
+ }
+ .is_ok()
+ .then_some(value)
+}
+
+fn now_seconds() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_or(0, |since| since.as_secs())
+}
diff --git a/muelle/src/pages/privacy.astro b/muelle/src/pages/privacy.astro
index dd0e1d8..51c9474 100644
--- a/muelle/src/pages/privacy.astro
+++ b/muelle/src/pages/privacy.astro
@@ -16,7 +16,7 @@ import { site } from "@/data/site";
<h2>1. Update check</h2>
<p>
- When you open Settings, and once a day while you are away from the computer, Muelle asks GitHub
+ When you open Settings, and once a day shortly after you turn on the computer, Muelle asks GitHub
whether a newer version exists by downloading{" "}
<code>{updateManifest}</code>. Nothing about you or your computer is sent with it; GitHub, like any website, sees
your IP address and handles it under the{" "}
diff --git a/spikes/src/bin/spike_verbs.rs b/spikes/src/bin/spike_verbs.rs
new file mode 100644
index 0000000..3420f68
--- /dev/null
+++ b/spikes/src/bin/spike_verbs.rs
@@ -0,0 +1,50 @@
+//! Lists the shell context menu verbs of the items pinned to the taskbar,
+//! without invoking any: is "taskbarunpin" there for `pins::unpin_from_taskbar`?
+
+use std::{env, fs, path::PathBuf};
+
+use windows::{
+ Win32::{
+ System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx},
+ UI::{
+ Shell::{BHID_SFUIObject, CMF_NORMAL, GCS_VERBW, IContextMenu, IShellItem, SHCreateItemFromParsingName},
+ WindowsAndMessaging::{CreatePopupMenu, DestroyMenu, GetMenuItemCount, GetMenuItemID},
+ },
+ },
+ core::{HSTRING, PSTR},
+};
+
+fn verbs(path: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ unsafe {
+ let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(path), None) else { return vec!["(no item)".into()] };
+ let Ok(menu) = item.BindToHandler::<_, IContextMenu>(None, &BHID_SFUIObject) else { return vec!["(no menu)".into()] };
+ let Ok(popup) = CreatePopupMenu() else { return out };
+ 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 mut name = [0u16; 64];
+ if menu.GetCommandString((command - 1) as usize, GCS_VERBW, None, PSTR(name.as_mut_ptr().cast()), name.len() as u32).is_ok() {
+ let len = name.iter().position(|&u| u == 0).unwrap_or(0);
+ if len > 0 { out.push(String::from_utf16_lossy(&name[..len])); }
+ }
+ }
+ }
+ let _ = DestroyMenu(popup);
+ }
+ out
+}
+
+fn main() {
+ unsafe { let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); }
+ let folder = PathBuf::from(env::var("APPDATA").unwrap_or_default())
+ .join(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar");
+ for entry in fs::read_dir(folder).into_iter().flatten().flatten() {
+ let path = entry.path().to_string_lossy().into_owned();
+ println!("{} -> {:?}", entry.file_name().to_string_lossy(), verbs(&path));
+ }
+ for id in muelle_shell::pins::taskbar_pins().iter().filter(|id| id.starts_with("shell:")) {
+ println!("{id} -> {:?}", verbs(id));
+ }
+}