A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat: implement automatic updates and energy saver integration
CristianOlivera199e60a4e71b5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74e8cfc..4428f72 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,39 @@ copia la sección de la versión que se publica a la release de GitHub.## [Unreleased]+### English++- Fixed: after choosing an item in the dock's menu (Muelle Settings, for+ one), the dock could stay magnified and stop reacting to the pointer.+- Alt+Tab: moving the mouse or clicking an empty spot no longer stops the+ 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+ updates automatically". The dock itself still never uses the network.+- 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.++### Español++- Corregido: tras elegir una opción del menú del dock (por ejemplo, Ajustes+ de Muelle), el dock podía quedarse ampliado y dejar de responder al puntero.+- Alt+Tab: mover el ratón o hacer clic en un hueco ya no impide que la lupa+ 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 →+ Sistema → «Instalar actualizaciones automáticamente». El dock en sí sigue+ sin usar la red.+- 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.+## [0.1.8]### Englishdiff --git a/README.es.md b/README.es.mdindex c38530d..dcf7cb9 100644--- a/README.es.md+++ b/README.es.md@@ -50,17 +50,13 @@ dibujar su animación; las devuelve al cerrarse.administrador, sin asistente, en unos dos segundos.2. Muelle es nuevo, así que SmartScreen puede no reconocerlo todavía y decir queprotegió tu PC. Elige **Más información → Ejecutar de todas formas**. Ver la- [política de firma de código](#política-de-firma-de-código).+ [política de firma de código](https://muellee.vercel.app/code-signing-policy).3. Aparece el dock y se oculta la barra de tareas de Windows. Desde entonces Muellese abre al iniciar Windows; puedes desactivarlo en Ajustes → Sistema.Abre **Muelle** desde el menú Inicio (o clic derecho en el dock → *Ajustes deMuelle…*) 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 → Aplicacionesinstaladas → Muelle → Desinstalar; la barra vuelve y no queda nada en marcha.@@ -131,43 +127,6 @@ pnpm build| `crates/muelle-config` | Ajustes compartidos y su guardado || `muelle/` | La web (Astro) |-## Compilar el instalador--```powershell-cd apps\settings-pnpm install-cd ..\..-.\scripts\build-installer.ps1-```--El script compila las dos apps y genera `Muelle_<versión>_x64-setup.exe` en-`target\release\bundle\nsis`. El instalador es por usuario, no pide permisos de-administrador ni muestra asistente: instala en `%LOCALAPPDATA%\Programs\Muelle`,-activa el inicio con Windows y abre el dock. Al desinstalar (Configuración →-Aplicaciones) se cierra el dock y vuelve la barra de tareas de Windows.--Al subir una etiqueta que coincida con la versión (por ejemplo `v0.1.1`), GitHub-Actions compila el instalador y lo adjunta a un borrador de release, junto con-`Muelle-Setup.exe` (el enlace de descarga de la web), `latest.json` (lo lee el-actualizador de Ajustes) y las notas de esa versión sacadas de `CHANGELOG.md`.-El repositorio necesita los secretos `TAURI_SIGNING_PRIVATE_KEY` y-`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Publica el borrador para que pase a ser la-descarga y la actualización.--## Estado--El dock, Ajustes y el instalador funcionan en Windows 11. El soporte de Windows 10-es nuevo; avisa si algo se ve mal ahí. Algunas funciones e-interacciones aún se están verificando.--## Política de firma de código--Free code signing provided by [SignPath.io](https://about.signpath.io),-certificate by [SignPath Foundation](https://signpath.org). Las versiones se-compilan desde este repositorio con `.github/workflows/release.yml` en máquinas-de GitHub, y cada firma se aprueba a mano. Política completa y roles del equipo:-[muellee.vercel.app/code-signing-policy](https://muellee.vercel.app/code-signing-policy).-## PrivacidadMuelle no recoge datos, no tiene telemetría y nunca envía nada al proyecto. Hacediff --git a/README.md b/README.mdindex 4db1b68..1b6b353 100644--- a/README.md+++ b/README.md@@ -50,24 +50,17 @@ restored when Muelle exits.## Install**[Download Muelle-Setup.exe](https://github.com/crafter-station/Muelle/releases/latest/download/Muelle-Setup.exe)**-(Windows 10, or Windows 11; 64-bit) or pick a version from+(Windows 10 version 1903 or later, or Windows 11; 64-bit) or pick a version from[Releases](https://github.com/crafter-station/Muelle/releases).1. Run `Muelle-Setup.exe`. It installs for your user only: no administratorrights, 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**.+ protected your PC. Choose **More info → Run anyway**. See the+ [code-signing policy](https://muellee.vercel.app/code-signing-policy).3. Open **Muelle** from the Start menu, then choose **Dock** topersonalize the dock and top menu bar.-## Resource usage--In one idle snapshot, Windows Task Manager showed **3.1 MB** for the grouped-`muelle (2)` processes. This point-in-time reading can vary by machine and-session; it excludes Settings and its WebView2 runtime.--<img width="1000" height="209" alt="706924247-a00b8242-be33-466a-a9f5-9390fdd8ccee" src="https://github.com/user-attachments/assets/2446de33-9ad9-4fc2-8645-4a264d90b3f4" />-## Try it on Windows### Prerequisites@@ -133,43 +126,7 @@ pnpm build| `crates/muelle-core` | Platform-independent layout and animation logic || `crates/muelle-shell` | Windows shell integration || `crates/muelle-config` | Shared settings and persistence |-| `plan.md` | Development plan and implementation notes (Spanish) |--## Build the installer--```powershell-cd apps\settings-pnpm install-cd ..\..-.\scripts\build-installer.ps1-```--The script builds both apps and produces `Muelle_<version>_x64-setup.exe` in-`target\release\bundle\nsis`. The installer runs per user, needs no-administrator rights and shows no wizard: it installs to-`%LOCALAPPDATA%\Programs\Muelle`, turns on start with Windows and opens the dock.-Uninstalling (Settings → Apps) quits the dock and gives the Windows taskbar back.--Pushing a tag that matches the version (for example `v0.1.1`) builds the-installer on GitHub Actions and attaches it to a draft release, together with-`Muelle-Setup.exe` (the website's download link), `latest.json` (read by the-updater in Settings) and that version's notes from `CHANGELOG.md`. The repository needs the secrets-`TAURI_SIGNING_PRIVATE_KEY` and `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Publish the-draft to make it the download and the update.--## Current status--The dock, Settings app and installer work on Windows 11. Windows 10 support is-new; please report anything that looks wrong there. Some features and-interactions are still being verified.--## Code signing policy--Free code signing provided by [SignPath.io](https://about.signpath.io),-certificate by [SignPath Foundation](https://signpath.org). Releases are built-from this repository by `.github/workflows/release.yml` on GitHub-hosted runners-and each signing request is approved by hand. Full policy and team roles:-[muellee.vercel.app/code-signing-policy](https://muellee.vercel.app/code-signing-policy).+| `muelle` | Astro website |## Privacydiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 04291f7..aad9bd8 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -63,9 +63,8 @@ use windows::{Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},Input::KeyboardAndMouse::{GetAsyncKeyState, GetKeyState, ReleaseCapture, SetCapture, TME_LEAVE,- TRACKMOUSEEVENT, TrackMouseEvent, VIRTUAL_KEY, VK_CONTROL, VK_DELETE, VK_DOWN,- VK_END, VK_HOME, VK_LEFT, VK_LWIN, VK_MENU, VK_RIGHT, VK_RWIN, VK_SHIFT, VK_TAB,- VK_UP,+ TRACKMOUSEEVENT, TrackMouseEvent, VIRTUAL_KEY, VK_CONTROL, VK_DOWN, VK_END,+ VK_HOME, VK_LEFT, VK_LWIN, VK_MENU, VK_RIGHT, VK_RWIN, VK_SHIFT, VK_TAB, VK_UP,},WindowsAndMessaging::{CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_OBJECT_CLOAKED,@@ -117,6 +116,7 @@ const PBT_APMRESUMEAUTOMATIC: usize = 0x0012;/// Sent when the charger is plugged in or out, and when energy saver turns/// on or off.const PBT_APMPOWERSTATUSCHANGE: usize = 0x000A;+const PBT_POWERSETTINGCHANGE: usize = 0x8013;const WINDOW_CLASS: PCWSTR = muelle_shell::dock_link::DOCK_WINDOW_CLASS;const APPBAR_CALLBACK: u32 = WM_APP + 1;@@ -183,6 +183,12 @@ 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.+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);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;@@ -416,8 +422,6 @@ struct SwitcherFollow {order: Vec<isize>,index: usize,tab_down: bool,- /// Where the pointer was; hovering an item also selects it.- pointer: POINT,}struct Stage {@@ -458,6 +462,8 @@ struct App {downloads: Option<String>,bin_full: bool,_bin_watch: Option<BinWatch>,+ /// Energy saver on or off: glass follows (see `system::transparency_enabled`).+ _saver_watch: power::SaverWatch,/// Hears pins and unpins on the Windows taskbar.pin_watch: Option<muelle_shell::watch::RegistryWatch>,assets: HashMap<String, Asset>,@@ -476,6 +482,8 @@ 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,@@ -1252,18 +1260,42 @@ impl App {let _ = KillTimer(Some(self.input), HIDE_TIMER);}self.place_windows()?;- let mut track = TRACKMOUSEEVENT {- cbSize: size_of::<TRACKMOUSEEVENT>() as u32,- dwFlags: TME_LEAVE,- hwndTrack: self.input,- dwHoverTime: 0,- };- // SAFETY: `track` is a valid structure with its size initialized.- unsafe { TrackMouseEvent(&mut track)? };}+ // Every move, not only on entering: a menu or a drag that captures+ // the mouse cancels the request, and without it the dock would+ // never hear the pointer leave and stay magnified.+ self.track_leave()?;self.render()}+ fn track_leave(&self) -> Result<()> {+ let mut track = TRACKMOUSEEVENT {+ cbSize: size_of::<TRACKMOUSEEVENT>() as u32,+ dwFlags: TME_LEAVE,+ hwndTrack: self.input,+ dwHoverTime: 0,+ };+ // SAFETY: `track` is a valid structure with its size initialized.+ unsafe { TrackMouseEvent(&mut track)? };+ Ok(())+ }++ /// A menu closed: it held the mouse, so the dock heard nothing of where+ /// the pointer went meanwhile. Settle the magnifier on where it is now.+ fn after_menu(&mut self) -> Result<()> {+ let mut point = POINT::default();+ // SAFETY: Read-only queries.+ let over = unsafe {+ GetCursorPos(&mut point).is_ok()+ && windows::Win32::UI::WindowsAndMessaging::WindowFromPoint(point) == self.input+ };+ if over {+ self.track_leave()+ } else {+ self.on_mouse_leave()+ }+ }+fn on_mouse_leave(&mut self) -> Result<()> {if !self.hovering || self.drag.is_some() {return Ok(());@@ -1357,11 +1389,6 @@ impl App {if order.len() < 2 || status::alt_tab_lists_more_than_windows(edge_open) {return Ok(());}- let mut pointer = POINT::default();- // SAFETY: A valid output for the pointer position.- unsafe {- let _ = GetCursorPos(&mut pointer);- }// Opened from the desktop or another unlisted window, the switcher// starts on the first window rather than the second.let from_listed = order.first() == Some(&LAST_FRONT.load(Ordering::Relaxed));@@ -1375,13 +1402,11 @@ impl App {index,// The Tab that opened the switcher is still down: not a new press.tab_down: true,- pointer,});self.point_at_selection()}- /// Moves the selection with each Tab press. Arrow keys, Delete (which- /// closes the selected window) or the pointer moving can change it in+ /// Moves the selection with each Tab press. Arrow keys can change it in/// ways that cannot be followed: the highlight then goes away rather/// than point at the wrong app.fn follow_selection(&mut self) -> Result<()> {@@ -1392,25 +1417,54 @@ impl App {// SAFETY: Read-only keyboard state query.unsafe { GetAsyncKeyState(i32::from(key.0)) < 0 }};- let mut pointer = POINT::default();- // SAFETY: A valid output for the pointer position.- unsafe {- let _ = GetCursorPos(&mut pointer);- }- let lost = [- VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN, VK_HOME, VK_END, VK_DELETE,- ]- .into_iter()- .any(down)- || pointer != follow.pointer;+ // Only these move the selection in ways that cannot be followed. A+ // click on an item switches to it and closes the switcher; a click+ // anywhere else, or moving the pointer, leaves the selection alone.+ let lost = [VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN, VK_HOME, VK_END]+ .into_iter()+ .any(down);if lost {return self.stop_following();}+ // A window closed from the switcher (its "x", or Delete) leaves the+ // list, and the switcher keeps the selection on the same place.+ let before = follow.order.len();+ let index = follow.index;+ let alive: Vec<bool> = follow+ .order+ .iter()+ .map(|&hwnd| {+ let window = HWND(hwnd as *mut _);+ // SAFETY: Read-only queries; a closed window simply fails them.+ unsafe {+ windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(window)).as_bool()+ && windows::Win32::UI::WindowsAndMessaging::IsWindowVisible(window)+ .as_bool()+ }+ })+ .collect();+ let removed_before = alive[..index.min(before)].iter().filter(|&&on| !on).count();+ let mut position = 0;+ follow.order.retain(|_| {+ position += 1;+ alive[position - 1]+ });+ let closed = follow.order.len() != before;+ if follow.order.is_empty() {+ return self.stop_following();+ }+ if closed {+ follow.index = (index - removed_before).min(follow.order.len() - 1);+ }let tab = down(VK_TAB);let pressed = tab && !follow.tab_down;follow.tab_down = tab;if !pressed {- return Ok(());+ return if closed {+ self.point_at_selection()+ } else {+ Ok(())+ };}let count = follow.order.len();follow.index = if down(VK_SHIFT) {@@ -1473,6 +1527,34 @@ 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+ {+ return;+ }+ let Some(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() {+ eprintln!("muelle: actualización: {error}");+ }+ }+fn hide_if_unused(&mut self) -> Result<()> {if !self.config.auto_hide || self.hovering || self.drag.is_some() || self.switching {return Ok(());@@ -2747,6 +2829,7 @@ fn run_outside(outside: Outside) {request.anchor,request.dark,);+ with_app("menú cerrado", App::after_menu);if let Some(command) = chosen {with_app_then("orden del menú", |app| {app.on_command(request.target, command)@@ -2793,7 +2876,9 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->// SAFETY: `hwnd` is our window; scheduling the same timer resets it.unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };}- WM_POWERBROADCAST if w.0 == PBT_APMPOWERSTATUSCHANGE => {+ // On battery or charging, or energy saver turned on or off: glass may+ // have to become solid, or the other way round.+ WM_POWERBROADCAST if w.0 == PBT_APMPOWERSTATUSCHANGE || w.0 == PBT_POWERSETTINGCHANGE => {// SAFETY: `hwnd` is our window; scheduling the same timer resets it.unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };}@@ -2821,6 +2906,12 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->}with_app("apps fijadas", App::sync_taskbar_pins);}+ WM_TIMER if w.0 == UPDATE_TIMER => {+ with_app("actualización", |app| {+ app.maybe_update();+ Ok(())+ });+ }WM_TIMER if w.0 == SWITCHER_TIMER => {with_app("Alt+Tab", App::check_task_switcher);}@@ -3036,6 +3127,7 @@ pub fn run() -> Result<()> {downloads: downloads_folder(),bin_full: false,_bin_watch: BinWatch::register(input, BIN_CHANGED),+ _saver_watch: power::SaverWatch::new(input.0 as isize),pin_watch: muelle_shell::pins::watch(visual.0 as isize, PINS_CHANGED),assets: HashMap::new(),assets_for: (0.0, false, 0),@@ -3049,6 +3141,7 @@ pub fn run() -> Result<()> {drag_over: false,spring: None,switching: false,+ last_update: None,switch_started: Instant::now(),follow: None,pointed: false,@@ -3140,6 +3233,8 @@ 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);diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 8e22fc8..32b0b35 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -210,6 +210,8 @@ pub struct MenuBar {_network: Option<NetworkWatch>,/// Hears when apps start or stop using the microphone or camera.privacy_watch: Option<RegistryWatch>,+ /// Energy saver on or off arrives as `WM_POWERBROADCAST`; glass follows.+ _saver_watch: muelle_shell::power::SaverWatch,audio: Option<AudioWatch>,}@@ -925,6 +927,7 @@ impl MenuBar {edge_watch: None,_network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),privacy_watch: status::watch_privacy(hwnd.0 as isize, PRIVACY_CHANGED),+ _saver_watch: muelle_shell::power::SaverWatch::new(hwnd.0 as isize),audio: AudioWatch::new(hwnd.0 as isize, STATUS_CHANGED),};bar.update_status();diff --git a/apps/settings/src-tauri/icons/icon.ico b/apps/settings/src-tauri/icons/icon.icoindex 2500890..5849f2d 100644Binary files a/apps/settings/src-tauri/icons/icon.ico and b/apps/settings/src-tauri/icons/icon.ico differdiff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsindex e992dd6..248e93d 100644--- a/apps/settings/src-tauri/src/main.rs+++ b/apps/settings/src-tauri/src/main.rs@@ -1,14 +1,18 @@//! Muelle settings: a separate process that exists only while its window is//! open. It edits the configuration file and tells the dock to reload it.+//!+//! With `--update` it opens no window: the dock starts it that way once a+//! day, while the user is away, to install a newer version if there is one.+//! It exits as soon as it knows there is none.#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]-use std::{env, io, path::PathBuf, process::Command, sync::Mutex};+use std::{env, io, path::PathBuf, process::Command, sync::Mutex, time::Duration};use muelle_config::Config;use muelle_shell::{autostart, dock_link, launcher};use serde::Serialize;-use tauri::{Emitter, Manager, State};+use tauri::{AppHandle, Emitter, Manager, State, WebviewWindowBuilder};use tauri_plugin_updater::{Update, UpdaterExt};/// The dock owns the pinned and recent apps; this app never overwrites them@@ -148,25 +152,78 @@ async fn install_update(.map_err(|error| error.to_string())}+/// The argument the dock starts this app with for a background update.+const UPDATE_ARG: &str = "--update";++/// Checks for a newer version and installs it without asking, as the user+/// chose in Settings; the installer stops and restarts the dock. Exits when+/// there is nothing to do or anything fails: the next try is tomorrow.+async fn update_in_background(app: AppHandle) {+ let config = get_config();+ let allowed = config.check_updates && config.auto_update;+ let found = match app.updater_builder().timeout(Duration::from_secs(60)) {+ // The installer starts the dock again; this app need not come back.+ builder if allowed => match builder.restart_after_install(false).build() {+ Ok(updater) => updater.check().await.ok().flatten(),+ Err(_) => None,+ },+ _ => None,+ };+ if let Some(update) = found+ && let Err(error) = update.download_and_install(|_, _| {}, || {}).await+ {+ eprintln!("muelle-settings: actualización: {error}");+ }+ app.exit(0);+}++/// Opens the Settings window, or brings it forward if it is open.+fn show_window(app: &AppHandle) {+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.unminimize();+ let _ = window.show();+ let _ = window.set_focus();+ return;+ }+ let Some(config) = app.config().app.windows.first() else {+ return;+ };+ if let Err(error) =+ WebviewWindowBuilder::from_config(app, config).and_then(|window| window.build())+ {+ eprintln!("muelle-settings: {error}");+ }+}+fn main() {muelle_config::migrate_legacy_folder();+ let background = env::args().any(|arg| arg == UPDATE_ARG);// The Start menu entry opens this app: it also brings back a dock the user quit.- if !dock_link::is_running()+ if !background+ && !dock_link::is_running()&& let Err(error) = dock_exe().and_then(|dock| Command::new(dock).spawn()){eprintln!("muelle-settings: no se pudo abrir el dock: {error}");}let result = tauri::Builder::default()// First, so a second launch exits before doing anything else.- .plugin(tauri_plugin_single_instance::init(|app, _, _| {- if let Some(window) = app.get_webview_window("main") {- let _ = window.unminimize();- let _ = window.show();- let _ = window.set_focus();+ .plugin(tauri_plugin_single_instance::init(|app, args, _| {+ // The open window checks for updates itself; a background update+ // started meanwhile has nothing to do.+ if !args.iter().any(|arg| arg == UPDATE_ARG) {+ show_window(app);}})).plugin(tauri_plugin_updater::Builder::new().build()).manage(PendingUpdate::default())+ .setup(move |app| {+ if background {+ tauri::async_runtime::spawn(update_in_background(app.handle().clone()));+ } else {+ show_window(app.handle());+ }+ Ok(())+ }).invoke_handler(tauri::generate_handler![get_config,default_config,diff --git a/apps/settings/src-tauri/tauri.conf.json b/apps/settings/src-tauri/tauri.conf.jsonindex f8be729..a105b7f 100644--- a/apps/settings/src-tauri/tauri.conf.json+++ b/apps/settings/src-tauri/tauri.conf.json@@ -12,6 +12,7 @@"windows": [{"label": "main",+ "create": false,"title": "Muelle","width": 780,"height": 560,diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex dcc1d58..7bfc3f1 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -362,6 +362,13 @@ export function App() {onChange={(checkUpdates) => update({ checkUpdates })}/></Row>+ <SubRow label={t.autoUpdate} hint={t.autoUpdateHint} open={config.checkUpdates}>+ <Toggle+ label={t.autoUpdate}+ checked={config.autoUpdate}+ onChange={(autoUpdate) => update({ autoUpdate })}+ />+ </SubRow><Row label={t.updatesNow} hint={updateHint(t, updateState, version)}>{waiting && updateState.kind !== "installing" ? (<button type="button" className="push push-primary" onClick={() => install(waiting)}>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex 96807c7..48a8f9a 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -20,6 +20,7 @@ export interface Config {showRecents: boolean;bounceOnOpen: boolean;checkUpdates: boolean;+ autoUpdate: boolean;language: Language;}diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex 974034c..3327ead 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -26,7 +26,9 @@"minimize": "Minimize","saveError": "The settings could not be saved.","checkUpdates": "Check for updates automatically",- "checkUpdatesHint": "When Settings opens, it asks GitHub whether there is a newer version.",+ "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.","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.jsonindex f614a95..35dfa14 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -26,7 +26,9 @@"minimize": "Minimizar","saveError": "No se pudieron guardar los ajustes.","checkUpdates": "Buscar actualizaciones automáticamente",- "checkUpdatesHint": "Al abrir Ajustes, pregunta a GitHub si hay una versión nueva.",+ "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.","updatesOff": "La búsqueda automática está desactivada.","updates": "Actualizaciones","updatesChecking": "Buscando actualizaciones…",diff --git a/assets/brand/muelle.ico b/assets/brand/muelle.icoindex 2500890..5849f2d 100644Binary files a/assets/brand/muelle.ico and b/assets/brand/muelle.ico differdiff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex f6d7b65..2060e44 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -70,6 +70,9 @@ pub struct Config {/// Settings asks GitHub Releases for a newer version when it opens. The/// only network access in Muelle, so it can be turned off.pub check_updates: bool,+ /// With `check_updates`: once a day, while the user is away from the+ /// computer, new versions are downloaded and installed without asking.+ pub auto_update: bool,pub language: Language,}@@ -128,6 +131,7 @@ impl Default for Config {show_recents: true,bounce_on_open: true,check_updates: true,+ auto_update: true,language: Language::Auto,}}@@ -227,6 +231,8 @@ mod tests {assert_eq!(config.icon_size, 56);assert!(config.show_indicators && config.show_recents && config.bounce_on_open);assert!(config.check_updates);+ // Files from before automatic updates get them, like new installs.+ assert!(config.auto_update);assert!(config.ai_usage);assert!(!config.show_minimized);}diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.tomlindex 0b3473e..84062cd 100644--- a/crates/muelle-shell/Cargo.toml+++ b/crates/muelle-shell/Cargo.toml@@ -32,6 +32,7 @@ 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/power.rs b/crates/muelle-shell/src/power.rsindex fea614c..eb805de 100644--- a/crates/muelle-shell/src/power.rs+++ b/crates/muelle-shell/src/power.rs@@ -83,3 +83,60 @@ pub fn run_as_background_process() {}trim_memory();}++/// Tells a window, with `WM_POWERBROADCAST` / `PBT_POWERSETTINGCHANGE`, when+/// energy saver (battery saver on Windows 10) turns on or off: Windows then+/// stops or resumes see-through effects, and glass must follow. Plugging the+/// charger in or out already arrives as `PBT_APMPOWERSTATUSCHANGE`, but+/// turning the saver on by hand does not always.+///+/// Event-driven: nothing runs until Windows sends the change. The+/// subscription ends when this is dropped.+pub struct SaverWatch(Vec<windows::Win32::System::Power::HPOWERNOTIFY>);++impl SaverWatch {+ #[must_use]+ pub fn new(hwnd: isize) -> Self {+ use windows::{+ Win32::{+ Foundation::HANDLE,+ System::{+ Power::RegisterPowerSettingNotification,+ SystemServices::GUID_POWER_SAVING_STATUS,+ },+ UI::WindowsAndMessaging::DEVICE_NOTIFY_WINDOW_HANDLE,+ },+ core::GUID,+ };+ /// Energy saver, Windows 11 22H2 and later.+ const GUID_ENERGY_SAVER_STATUS: GUID =+ GUID::from_u128(0x550e8400_e29b_41d4_a716_446655440000);+ let handles = [GUID_ENERGY_SAVER_STATUS, GUID_POWER_SAVING_STATUS]+ .iter()+ .filter_map(|setting| {+ // SAFETY: `hwnd` is the caller's live window; an unknown+ // setting on an older Windows just fails.+ unsafe {+ RegisterPowerSettingNotification(+ HANDLE(hwnd as *mut c_void),+ setting,+ DEVICE_NOTIFY_WINDOW_HANDLE,+ )+ }+ .ok()+ })+ .collect();+ Self(handles)+ }+}++impl Drop for SaverWatch {+ fn drop(&mut self) {+ for handle in self.0.drain(..) {+ // SAFETY: Registered in `new` and released once.+ unsafe {+ let _ = windows::Win32::System::Power::UnregisterPowerSettingNotification(handle);+ }+ }+ }+}diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rsindex 8aeafb3..fb0f5a7 100644--- a/crates/muelle-shell/src/system.rs+++ b/crates/muelle-shell/src/system.rs@@ -76,6 +76,26 @@ 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/muelle/src/pages/privacy.astro b/muelle/src/pages/privacy.astroindex 353bacd..dd0e1d8 100644--- a/muelle/src/pages/privacy.astro+++ b/muelle/src/pages/privacy.astro@@ -16,13 +16,15 @@ import { site } from "@/data/site";<h2>1. Update check</h2><p>- When you open Settings, it asks GitHub whether a newer version exists by downloading{" "}+ When you open Settings, and once a day while you are away from 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, seesyour IP address and handles it under the{" "}<a href="https://docs.github.com/site-policy/privacy-policies/github-general-privacy-statement" target="_blank" rel="noopener noreferrer">GitHub privacy statement</a>.- If you choose to update, the installer is downloaded from the same GitHub releases page.+ When there is one, its signed installer is downloaded from the same GitHub releases page and+ installed: by itself if <b>Install updates automatically</b> is on, otherwise when you choose to.</p>- <p>To turn it off: Settings → System → <b>Check for updates automatically</b>. You can still check by hand.</p>+ <p>To turn it off: Settings → System → <b>Check for updates automatically</b> (or only <b>Install updates automatically</b>, to keep the notice in Settings). You can still check by hand.</p><h2>2. AI provider usage</h2><p>