From 01739171a3e990c70145b1059e2d94e726ce2c89 Mon Sep 17 00:00:00 2001 From: muneer320 Date: Sat, 21 Nov 2026 03:09:03 +0530 Subject: [PATCH 1/4] feat: add channel-aware updates and tray checks --- README.md | 4 +- SECURITY.md | 4 +- docs/ARCHITECTURE.md | 4 + docs/INSTALLATION.md | 23 +++ docs/klicky.1 | 8 + packaging/apt/guide.html | 2 +- packaging/apt/index.html | 2 +- packaging/apt/privacy.html | 4 +- src/cli.rs | 10 + src/lib.rs | 2 + src/update.rs | 381 +++++++++++++++++++++++++++++++++++++ src/update/windows.ps1 | 46 +++++ src/windows/cli.rs | 10 + src/windows/desktop.rs | 149 ++++++++++++++- src/windows/mod.rs | 2 +- src/windows/package.rs | 2 +- 16 files changed, 635 insertions(+), 18 deletions(-) create mode 100644 src/update.rs create mode 100644 src/update/windows.ps1 diff --git a/README.md b/README.md index c55d986..d863a35 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ Any ordinary keyboard works; the sound is added in software. Linux reads evdev b
Does it record what I type? -Normal operation stores no typed text, logs no key names and sends no network requests. Global keyboard permission is sensitive, so grant it only to trusted software. Unix benchmark mode prints mapped key names and is for controlled tests. [Privacy and security](SECURITY.md) +Normal playback stores no typed text, logs no key names and sends no network requests. Explicit update checks contact GitHub without sending keyboard events or settings. Global keyboard permission is sensitive, so grant it only to trusted software. Unix benchmark mode prints mapped key names and is for controlled tests. [Privacy and security](SECURITY.md)
@@ -187,6 +187,8 @@ The [troubleshooting guide](docs/TROUBLESHOOTING.md) covers permissions, startup Use the method you installed with. Microsoft Store manages updates for its copy. For helper installations, rerun the install command above. For package managers, follow the [Homebrew](docs/INSTALLATION.md#homebrew) or [Scoop](docs/INSTALLATION.md#scoop) update steps, including stopping Klicky first. Settings and custom sounds are preserved during updates. +Current source also includes a [centralized update command](docs/INSTALLATION.md#centralized-update-command); it will reach packaged installations with the next app release. +
diff --git a/SECURITY.md b/SECURITY.md index 19179f3..dc2f5b5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -62,7 +62,9 @@ The daemon receives raw global key-down events, including events generated while ### Network behavior -Klicky contains no network client and makes no network requests. +Keyboard playback makes no network requests. Update checks run only when requested with `klicky update` or the Windows tray's **Check for updates** action. The check uses HTTPS to read the latest stable release from GitHub; GitHub receives the request's IP address and a Klicky update-check user agent. No keyboard events, settings or usage statistics are included. There is no background update polling. + +After confirmation, the existing installer or package manager handles downloads and installation. Store installations stay under Microsoft Store's control. Unknown, portable and source builds are not automatically overwritten. Windows standalone updates use the official HTTPS installation helper and its release checksum verification; this is not a code-signing or antivirus guarantee. ## Operational guidance diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 754d6ca..0ef77e9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -2,6 +2,10 @@ Klicky uses one resident process per user session. Linux/macOS retain their Unix daemon and service lifecycle; Windows has a native tray coordinator with separate input, audio and control adapters. Sound-pack preparation and mixer-facing types are shared. The library entrypoint selects the platform at compile time. +## Explicit updates + +`src/update.rs` supplies both CLIs and the Windows tray with stable-release checks and installation-channel detection. Checks use a bounded HTTPS curl request only after an explicit action. Windows tray network work runs on the metadata worker, away from input, audio and GUI callbacks. Confirmed updates are handed to the installation owner; source and unknown copies receive manual guidance. The update command never becomes a second package manager. + ## Data flow ```mermaid diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 4891d6c..f37a662 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -2,6 +2,29 @@ [Back to README](../README.md) · [Visual field guide](https://klicky.muneer320.tech/guide.html#installation) · [Troubleshooting](TROUBLESHOOTING.md) +## Centralized update command + +The updater is included in current source and will ship in the next app release. For v0.6.1 and earlier, use the installation-specific update steps below. + +```sh +klicky update --check +klicky update +``` + +`--check` shows the installed version, latest stable GitHub release and recognized installation method. It does not open an installer, stop playback or change files. Checks happen only when requested. GitHub receives a normal HTTPS request; no typing, settings or usage statistics are sent. + +`klicky update` explains the update route and asks for confirmation. `--yes` accepts that handoff for terminal automation; it does not accept installer terms, bypass security or confirm completion. The Windows tray's **Check for updates** action uses the same check and offers the same handoff. + +- **Microsoft Store:** opens Store's Downloads and updates page. Store controls which version is available. +- **Windows standalone installer:** opens an update terminal and the official installer wizard. Existing settings and custom packs remain. +- **Scoop:** opens a terminal, stops a running copy, refreshes Scoop and updates Klicky. A running/paused copy is restarted in its previous playback state; a stopped copy stays stopped. +- **Homebrew:** updates the tap and formula. A previously running engine is restarted; its paused state is restored. Login-startup preferences are not enabled by the updater. +- **APT:** refreshes repository metadata and upgrades the installed `klicky` package. It may request `sudo` approval. +- **pacman:** offers a full `pacman -Syu` system upgrade, rather than a partial upgrade. Review pacman's transaction before accepting it. +- **Source, portable or unknown copies:** shows manual guidance instead of guessing an installation method or replacing files. + +Package-manager versions can arrive later than the GitHub release. A successful check is not proof that your manager already offers that version, and a Windows terminal handoff is not confirmation that installation completed. Use `klicky --version` in a new terminal afterward. The standalone Windows CLI currently requires its full path unless you have added it to PATH. + ## Windows **Windows 11 x64.** [Get Klicky from Microsoft Store](https://apps.microsoft.com/detail/9NLVFX7T2X6Q), then open it from Start. Use the tray menu to choose a pack, adjust volume, pause/resume or enable **Start with Windows**. The Store installs the complete app and manages updates. diff --git a/docs/klicky.1 b/docs/klicky.1 index 77720f8..848090e 100644 --- a/docs/klicky.1 +++ b/docs/klicky.1 @@ -10,6 +10,14 @@ Klicky is a small daemon that plays mechanical keyboard sounds for global keypre On Linux it reads keyboard events through evdev and works independently of Wayland or X11. .SH COMMANDS .TP +.B update [--check] [--yes] +Explicitly check the latest stable release and identify the installation method. +With --check, do not change files or open an update tool. Otherwise ask before +handing the update to its existing installer or package manager; --yes accepts +that handoff. Source, portable and unknown builds require manual updates. +The check contacts GitHub over HTTPS, without sending input or configuration. +There is no background polling. +.TP .B start Start the daemon in the foreground. Startup is exclusive: another instance cannot take ownership while the daemon diff --git a/packaging/apt/guide.html b/packaging/apt/guide.html index d71ac9a..dedd939 100644 --- a/packaging/apt/guide.html +++ b/packaging/apt/guide.html @@ -728,7 +728,7 @@

Under the keycaps.

Local sounds. Sensitive permissions.

Normal operation does not store typed text, log key names, record - microphone audio or make network requests. Installation helpers + microphone audio or send keyboard events over the network. Explicit update checks contact GitHub without sending settings or input data. Installation helpers download files; the running app needs no cloud service.

diff --git a/packaging/apt/index.html b/packaging/apt/index.html index acd8b47..564f397 100644 --- a/packaging/apt/index.html +++ b/packaging/apt/index.html @@ -978,7 +978,7 @@

Before you move in.

Does Klicky record what I type?

- Normal operation does not store typed text, log key names or + Normal playback does not store typed text, log key names or make network requests. It reads global keyboard events locally to select sounds, so its input permission is sensitive. Unix benchmark mode does print mapped key names; use it only for diff --git a/packaging/apt/privacy.html b/packaging/apt/privacy.html index 12a8f51..5f58a7a 100644 --- a/packaging/apt/privacy.html +++ b/packaging/apt/privacy.html @@ -62,7 +62,7 @@

A little sound. A little clarity.

Your typing stays on your device.

Klicky plays keyboard sounds locally. There is no Klicky account, cloud service, advertising or analytics in the app.

-

Last updated: November 11, 2026. Maintained by Muneer Alam and the Klicky contributors.

+

Last updated: November 21, 2026. Maintained by Muneer Alam and the Klicky contributors.

@@ -74,7 +74,7 @@

Your typing stays on your device.

What happens when you press a key?

Klicky receives keyboard events so it can choose and play a sound while you use other apps. Normal playback does not record your typed text, save a history of keypresses or transmit those events. The Windows app does not access your microphone.

Global input access is sensitive: keyboard events can occur while you enter a password or other private information. Klicky does not need that text, but you should grant input access only to software you trust. On Windows, playback is paused while the desktop is locked or inactive.

-

The desktop app contains no network client and makes no network requests. It does not send your typing, sound choices or usage statistics to me or to another service.

+

Keyboard playback makes no network requests. If you request an update check, Klicky contacts GitHub over HTTPS to read its latest stable release. GitHub receives your IP address and a Klicky update-check user agent, but no typing, settings or usage statistics. There is no background polling. After confirmation, your existing installer or package manager handles downloads and installation.

Settings and custom sounds stay local.

diff --git a/src/cli.rs b/src/cli.rs index 5778187..32c50a3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -16,6 +16,15 @@ struct Cli { #[derive(Subcommand)] enum Commands { + /// Check for a stable release or open the supported update route + Update { + /// Only check; do not open an installer or package manager + #[arg(long)] + check: bool, + /// Accept the displayed update handoff without prompting + #[arg(long)] + yes: bool, + }, /// Start the klicky daemon Start { /// Print latency measurements for each keypress @@ -76,6 +85,7 @@ pub fn run() -> Result<()> { let cli = Cli::parse(); match cli.command { + Commands::Update { check, yes } => crate::update::run(check, yes)?, Commands::Start { benchmark } => engine::run(benchmark)?, Commands::Stop => service::stop()?, Commands::List => cmd_list()?, diff --git a/src/lib.rs b/src/lib.rs index 0731ad6..2ad27b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,6 +17,8 @@ mod player; #[cfg(any(target_os = "linux", target_os = "macos"))] mod service; mod soundpack; +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] +pub mod update; #[cfg(target_os = "windows")] pub mod windows; diff --git a/src/update.rs b/src/update.rs new file mode 100644 index 0000000..813c890 --- /dev/null +++ b/src/update.rs @@ -0,0 +1,381 @@ +//! Explicit update checks and handoff to the installation's existing owner. +use std::io::{self, IsTerminal, Write}; +use std::path::Path; +use std::process::Command; + +use anyhow::{bail, Context, Result}; +use serde::Deserialize; + +const RELEASE_API: &str = "https://api.github.com/repos/Muneer320/klicky/releases/latest"; +pub const GUIDE: &str = "https://klicky.muneer320.tech/guide.html#installation"; +const CURRENT: &str = env!("CARGO_PKG_VERSION"); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Route { + Store, + Standalone, + Scoop, + Homebrew, + Apt, + Pacman, + Manual, +} + +impl Route { + pub fn description(self) -> &'static str { + match self { + Self::Store => "Microsoft Store (Store manages the offered version)", + Self::Standalone => "Windows standalone installer", + Self::Scoop => "Scoop", + Self::Homebrew => "Homebrew", + Self::Apt => "APT", + Self::Pacman => "pacman", + Self::Manual => "source, portable or unrecognized installation", + } + } + + pub fn action(self) -> &'static str { + match self { + Self::Store => "Open Microsoft Store's Downloads and updates page.", + Self::Standalone => "Open a terminal and run the official standalone installer. Its wizard handles replacement and startup restoration.", + Self::Scoop => "Open a terminal, stop Klicky, run scoop update and scoop update klicky, then restore playback.", + Self::Homebrew => "Stop Klicky, run brew update and brew upgrade muneer320/tap/klicky, then restore playback.", + Self::Apt => "Stop Klicky, run sudo apt-get update and sudo apt-get install --only-upgrade klicky, then restore playback.", + Self::Pacman => "Stop Klicky, run sudo pacman -Syu (a full system upgrade), then restore playback.", + Self::Manual => "Use your original source checkout or portable download. Automatic replacement is disabled for this installation.", + } + } +} + +#[derive(Deserialize)] +struct Release { + tag_name: String, + draft: bool, + prerelease: bool, +} + +pub struct Check { + pub route: Route, + pub latest: String, + pub newer: bool, +} + +impl Check { + pub fn summary(&self) -> String { + let state = if self.newer { + "A newer stable release is available." + } else { + "This build is at or ahead of the latest stable release." + }; + format!( + "Installed: {CURRENT}\nLatest stable: {}\nInstallation: {}\n{state}\n\n{}\nPackage-manager and Store versions may arrive later than GitHub releases.", + self.latest, self.route.description(), self.route.action() + ) + } +} + +fn version(value: &str) -> Result<[u64; 3]> { + let numbers: Vec<_> = value.split('.').collect(); + if numbers.len() != 3 + || numbers + .iter() + .any(|s| s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit())) + { + bail!("expected a stable three-part version"); + } + Ok([ + numbers[0].parse()?, + numbers[1].parse()?, + numbers[2].parse()?, + ]) +} + +fn parse_release(bytes: &[u8]) -> Result<(String, bool)> { + let release: Release = serde_json::from_slice(bytes).context("read GitHub release response")?; + if release.draft || release.prerelease { + bail!("GitHub did not return a published stable release"); + } + let latest = release + .tag_name + .strip_prefix('v') + .context("release tag is missing v")?; + let newer = version(latest)? > version(CURRENT)?; + Ok((latest.to_owned(), newer)) +} + +pub fn check() -> Result { + let route = detect(&std::env::current_exe()?.canonicalize()?)?; + // Windows/macOS supply curl; Linux installations already require it for the + // download helper. No shell, credentials, configuration or input data is sent. + let mut request = Command::new(curl()); + #[cfg(target_os = "windows")] + { + use std::os::windows::process::CommandExt; + request.creation_flags(0x08000000); // CREATE_NO_WINDOW for tray checks + } + let output = request + .args([ + "--fail", + "--silent", + "--show-error", + "--proto", + "=https", + "--connect-timeout", + "5", + "--max-time", + "15", + "--max-filesize", + "1048576", + "--header", + "Accept: application/vnd.github+json", + "--user-agent", + "Klicky-update-check", + RELEASE_API, + ]) + .output() + .context("run curl for the explicit update check")?; + if !output.status.success() { + bail!( + "Update check failed; nothing was changed. {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + } + let (latest, newer) = parse_release(&output.stdout)?; + Ok(Check { + route, + latest, + newer, + }) +} + +#[cfg(target_os = "windows")] +fn curl() -> std::path::PathBuf { + system_tool("curl.exe") +} +#[cfg(not(target_os = "windows"))] +fn curl() -> std::path::PathBuf { + "curl".into() +} + +#[cfg(target_os = "windows")] +fn system_tool(name: &str) -> std::path::PathBuf { + std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into())) + .join("System32") + .join(name) +} + +pub fn run(check_only: bool, yes: bool) -> Result<()> { + let result = check()?; + println!("{}", result.summary()); + if check_only || !result.newer { + return Ok(()); + } + if result.route == Route::Manual { + bail!("Update manually using {GUIDE}; no files were changed"); + } + if !yes { + if !io::stdin().is_terminal() { + bail!("Use --check, or --yes to accept the displayed handoff"); + } + print!("Continue with this update route? [y/N] "); + io::stdout().flush()?; + let mut answer = String::new(); + io::stdin().read_line(&mut answer)?; + if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") { + println!("Cancelled; nothing was changed."); + return Ok(()); + } + } + handoff(result.route, true)?; + Ok(()) +} + +#[cfg(target_os = "windows")] +fn detect(exe: &Path) -> Result { + windows_route( + exe, + dirs::data_local_dir().as_deref(), + crate::windows::package::current()?, + ) +} + +#[cfg(target_os = "windows")] +fn windows_route(exe: &Path, local: Option<&Path>, packaged: bool) -> Result { + if packaged { + return Ok(Route::Store); + } + let parent = exe.parent().context("executable has no directory")?; + if let Some(local) = local { + let expected = local.join("Programs/Klicky"); + if expected.canonicalize().is_ok_and(|path| path == parent) + && parent.join("INSTALLER-IDENTITY.ini").is_file() + { + return Ok(Route::Standalone); + } + } + // Resolve the real keg directory, not the shim on PATH. Scoop retains both + // manifests beside the installed binary; a portable ZIP has neither. + if parent.parent().is_some_and(|p| { + p.file_name() + .is_some_and(|n| n.eq_ignore_ascii_case("klicky")) + }) && parent.parent().and_then(Path::parent).is_some_and(|p| { + p.file_name() + .is_some_and(|n| n.eq_ignore_ascii_case("apps")) + }) && parent.join("manifest.json").is_file() + && parent.join("install.json").is_file() + { + return Ok(Route::Scoop); + } + Ok(Route::Manual) +} + +#[cfg(not(target_os = "windows"))] +fn detect(exe: &Path) -> Result { + #[cfg(target_os = "macos")] + if option_env!("KLICKY_MACOS_INSTALL_BINARY") + .and_then(|p| Path::new(p).canonicalize().ok()) + .is_some_and(|p| p == exe) + { + return Ok(Route::Homebrew); + } + #[cfg(target_os = "linux")] + if exe == Path::new("/usr/bin/klicky") { + if Command::new("dpkg-query") + .args(["-S", "/usr/bin/klicky"]) + .output() + .is_ok_and(|o| { + o.status.success() + && String::from_utf8_lossy(&o.stdout) + .lines() + .any(|s| s == "klicky: /usr/bin/klicky") + }) + { + return Ok(Route::Apt); + } + if Command::new("pacman") + .args(["-Qoq", "/usr/bin/klicky"]) + .output() + .is_ok_and(|o| o.status.success() && o.stdout == b"klicky\n") + { + return Ok(Route::Pacman); + } + } + let _ = exe; + Ok(Route::Manual) +} + +#[cfg(target_os = "windows")] +pub fn handoff(route: Route, wait_for_cli: bool) -> Result<()> { + use std::os::windows::process::CommandExt; + if route == Route::Store { + return open_store(); + } + let channel = match route { + Route::Standalone => "Standalone", + Route::Scoop => "Scoop", + _ => bail!("Automatic replacement is disabled for this installation; use {GUIDE}"), + }; + let exe = std::env::current_exe()?.canonicalize()?; + let directory = exe.parent().context("no bundle directory")?; + let cli = if route == Route::Scoop { + directory + .parent() + .context("no Scoop application directory")? + .join("current/klicky.exe") + } else { + directory.join("klicky.exe") + }; + let cli = cli + .to_str() + .context("CLI path is not Unicode")? + .replace('\'', "''"); + let caller = if wait_for_cli { std::process::id() } else { 0 }; + // Run outside the bundle so the CLI can exit before replacement. A separate + // console keeps installer errors visible; the manager owns the actual update. + let script = format!( + "& {{ {} }} -Channel {channel} -Cli '{cli}' -CallerPid {caller}", + include_str!("update/windows.ps1") + ); + Command::new(system_tool("WindowsPowerShell/v1.0/powershell.exe")) + .args(["-NoProfile", "-Command", &script]) + .creation_flags(0x00000010) // CREATE_NEW_CONSOLE: interactive update handoff + .spawn() + .context("open the update terminal")?; + println!( + "Update handed to a separate terminal. This is not confirmation of a completed update." + ); + Ok(()) +} + +#[cfg(target_os = "windows")] +fn open_store() -> Result<()> { + use windows::core::{w, PCWSTR}; + use windows::Win32::UI::Shell::ShellExecuteW; + use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + let result = unsafe { + ShellExecuteW( + None, + w!("open"), + w!("ms-windows-store://downloadsandupdates"), + PCWSTR::null(), + PCWSTR::null(), + SW_SHOWNORMAL, + ) + }; + if result.0 as isize <= 32 { + bail!("Microsoft Store could not open; use Store > Library > Get updates"); + } + println!("Opened Microsoft Store; it manages this installation's updates."); + Ok(()) +} + +#[cfg(not(target_os = "windows"))] +pub fn handoff(route: Route, _wait_for_cli: bool) -> Result<()> { + let commands: &[(&str, &[&str])] = match route { + Route::Homebrew => &[ + ("brew", &["update"]), + ("brew", &["upgrade", "muneer320/tap/klicky"]), + ], + Route::Apt => &[ + ("sudo", &["apt-get", "update"]), + ("sudo", &["apt-get", "install", "--only-upgrade", "klicky"]), + ], + Route::Pacman => &[("sudo", &["pacman", "-Syu"])], + _ => bail!("Update manually using {GUIDE}; no files were changed"), + }; + let playback = match crate::ipc::playback_status() { + Ok(state) => Some(state), + Err(error) if crate::ipc::is_daemon_unavailable(&error) => None, + Err(error) => return Err(error).context("cannot preserve current playback state"), + }; + let launcher = option_env!("KLICKY_MACOS_INSTALL_BINARY") + .map(std::path::PathBuf::from) + .unwrap_or(std::env::current_exe()?); + crate::service::run(crate::cli::ServiceAction::Stop)?; + let update = (|| { + for (program, args) in commands { + let status = Command::new(program) + .args(*args) + .status() + .with_context(|| format!("run {program}"))?; + if !status.success() { + bail!("{program} did not complete the update; check its output above"); + } + } + Ok(()) + })(); + // Use the installed CLI after replacement, rather than this old executable's + // service code. Do not enable login startup or start a previously stopped app. + if let Some(state) = playback { + let status = Command::new(&launcher) + .args(["service", "start"]) + .status()?; + if !status.success() { + bail!("Klicky could not restart; update result: {update:?}"); + } + if state.paused && !Command::new(&launcher).arg("pause").status()?.success() { + bail!("Klicky restarted but could not restore Pause; update result: {update:?}"); + } + } + update +} diff --git a/src/update/windows.ps1 b/src/update/windows.ps1 new file mode 100644 index 0000000..9159006 --- /dev/null +++ b/src/update/windows.ps1 @@ -0,0 +1,46 @@ +param( + [Parameter(Mandatory)][ValidateSet('Standalone', 'Scoop')][string]$Channel, + [string]$Cli, + [int]$CallerPid = 0 +) +$ErrorActionPreference = 'Stop' +try { + if ($CallerPid) { + $caller = Get-Process -Id $CallerPid -ErrorAction SilentlyContinue + if ($caller -and -not $caller.WaitForExit(30000)) { + throw 'The Klicky update command is still running; nothing was replaced.' + } + } + if ($Channel -eq 'Standalone') { + Invoke-RestMethod 'https://klicky.muneer320.tech/install.ps1' | Invoke-Expression + } + else { + $status = (& $Cli status) + if ($LASTEXITCODE -ne 0) { throw 'Cannot read playback state' } + $running = ($status -join "`n") -notmatch 'Klicky is not running' + if ($running) { + $state = (& $Cli diagnostics | ConvertFrom-Json) + if ($LASTEXITCODE -ne 0) { throw 'Cannot preserve playback state; update with Scoop manually.' } + & $Cli service stop + if ($LASTEXITCODE -ne 0) { throw 'Klicky did not stop' } + } + try { + scoop update + if ($LASTEXITCODE -ne 0) { throw 'Scoop refresh failed' } + scoop update klicky + if ($LASTEXITCODE -ne 0) { throw 'Scoop update failed' } + } + finally { + if ($running) { + if ($state.snapshot.state -eq 'paused') { & $Cli service start --paused } + else { & $Cli service start } + if ($LASTEXITCODE -ne 0) { Write-Warning 'Klicky did not restart; use its Start shortcut.' } + } + } + } +} +catch { + Write-Error $_ -ErrorAction Continue + Read-Host 'Update failed. Press Enter to close' + exit 1 +} diff --git a/src/windows/cli.rs b/src/windows/cli.rs index 4c1324c..1f40f0a 100644 --- a/src/windows/cli.rs +++ b/src/windows/cli.rs @@ -20,6 +20,15 @@ struct Cli { } #[derive(Subcommand)] enum Commands { + /// Check for a stable release or open the supported update route + Update { + /// Only check; do not open an installer or package manager + #[arg(long)] + check: bool, + /// Accept the displayed update handoff without prompting + #[arg(long)] + yes: bool, + }, /// Run the Windows tray app in this process; Ctrl+C stops it Start { /// Collect aggregate internal dispatch diagnostics (not audible latency) @@ -86,6 +95,7 @@ enum ServiceAction { pub fn run() -> Result<()> { match Cli::parse().command { + Commands::Update { check, yes } => crate::update::run(check, yes), Commands::Start { benchmark, paused, diff --git a/src/windows/desktop.rs b/src/windows/desktop.rs index 9602734..d50291f 100644 --- a/src/windows/desktop.rs +++ b/src/windows/desktop.rs @@ -42,6 +42,8 @@ const LOGIN_ENABLE: u32 = 6; const LOGIN_DISABLE: u32 = 7; const LOGIN_CHECK: u32 = 8; const LOGIN_SETTINGS: u32 = 9; +const CHECK_UPDATES: u32 = 10; +const OPEN_UPDATE: u32 = 11; /// Run in the interactive user's process. Capture starts only after WTS verification. pub fn run(options: Options) -> Result<()> { @@ -114,9 +116,16 @@ struct Metadata { #[derive(Default)] struct Update { packs: Option, String>>, + release: Option>, + handoff: Option>, +} +enum Work { + Packs, + CheckRelease, + Handoff(crate::update::Route), } struct Worker { - work: Sender<()>, + work: Sender, results: Arc, } impl Worker { @@ -131,13 +140,26 @@ impl Worker { std::thread::Builder::new() .name("klicky-ui-work".into()) .spawn(move || { - while queue.recv().is_ok() { - let update = Update { - packs: Some( - paths - .available_sound_packs() - .map_err(|error| format!("{error:#}")), - ), + while let Ok(work) = queue.recv() { + let update = match work { + Work::Packs => Update { + packs: Some( + paths + .available_sound_packs() + .map_err(|error| format!("{error:#}")), + ), + ..Default::default() + }, + Work::CheckRelease => Update { + release: Some(crate::update::check().map_err(|e| format!("{e:#}"))), + ..Default::default() + }, + Work::Handoff(route) => Update { + handoff: Some( + crate::update::handoff(route, false).map_err(|e| format!("{e:#}")), + ), + ..Default::default() + }, }; let mut latest = mailbox .latest @@ -146,12 +168,18 @@ impl Worker { if update.packs.is_some() { latest.packs = update.packs; } + if update.release.is_some() { + latest.release = update.release; + } + if update.handoff.is_some() { + latest.handoff = update.handoff; + } unsafe { let _ = SetEvent(HANDLE(mailbox.event.as_raw_handle())); } } })?; - work.try_send(())?; + work.try_send(Work::Packs)?; Ok(Self { work, results }) } fn take(&self) -> Result { @@ -184,6 +212,8 @@ struct State { operation_error: Option, pending: Vec, refreshing: bool, + checking_updates: bool, + update_check: Option, menu_open: bool, taskbar_created: u32, icon_added: bool, @@ -267,6 +297,8 @@ fn run_ui(paths: Paths, controller: Controller) -> Result<()> { operation_error: None, pending: Vec::new(), refreshing: true, + checking_updates: false, + update_check: None, menu_open: false, taskbar_created: unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) }, icon_added: false, @@ -539,6 +571,45 @@ fn take_metadata(hwnd: HWND) -> Result<()> { Err(error) => state.packs_error = Some(error), } } + if let Some(result) = update.handoff { + state.checking_updates = false; + if let Err(error) = result { + state.operation_error = Some(error); + } + } + if let Some(result) = update.release { + state.checking_updates = false; + let text = match result { + Ok(check) => { + let text = if check.newer { + format!("Klicky {} is available (installed {}). Reopen the tray menu for the update route.", check.latest, env!("CARGO_PKG_VERSION")) + } else { + format!( + "Klicky {} is at or ahead of the latest stable release ({}).", + env!("CARGO_PKG_VERSION"), + check.latest + ) + }; + state.update_check = Some(check); + text + } + Err(error) => { + state.update_check = None; + state.operation_error = Some(error.clone()); + error + } + }; + if !state.view.finished { + let mut data = icon_data(hwnd); + data.uFlags = NIF_INFO; + data.dwInfoFlags = NIIF_INFO; + copy_utf16("Klicky updates", &mut data.szInfoTitle); + copy_utf16(&text, &mut data.szInfo); + unsafe { + let _ = Shell_NotifyIconW(NIM_MODIFY, &data); + } + } + } Ok(()) } @@ -847,6 +918,49 @@ fn show_menu(hwnd: HWND) -> Result<()> { }, )?; menu.submenu("Start with Windows", login, MF_ENABLED)?; + let checking = state_ref(hwnd).borrow().checking_updates; + menu.item( + CHECK_UPDATES, + if checking { + "Checking for updates..." + } else { + "Check for updates" + }, + if checking || view.finished { + MF_GRAYED + } else { + MF_ENABLED + }, + )?; + { + let state = state_ref(hwnd).borrow(); + if let Some(check) = &state.update_check { + menu.item( + 0, + &format!( + "Installed {}; latest {}", + env!("CARGO_PKG_VERSION"), + check.latest + ), + MF_GRAYED, + )?; + if check.newer { + if check.route == crate::update::Route::Manual { + menu.item(0, "Manual update: see the installation guide", MF_GRAYED)?; + } else { + menu.item( + OPEN_UPDATE, + &format!("Update using {}...", check.route.description()), + if checking || view.finished { + MF_GRAYED + } else { + MF_ENABLED + }, + )?; + } + } + } + } menu.item(QUIT, "Quit Klicky", MF_ENABLED)?; let mut point = POINT::default(); unsafe { @@ -875,6 +989,21 @@ fn show_menu(hwnd: HWND) -> Result<()> { let _ = PostMessageW(Some(hwnd), WM_NULL, WPARAM(0), LPARAM(0)); } state_ref(hwnd).borrow_mut().menu_open = false; + if selected == CHECK_UPDATES { + let mut state = state_ref(hwnd).borrow_mut(); + state.worker.work.try_send(Work::CheckRelease)?; + state.checking_updates = true; + return Ok(()); + } + if selected == OPEN_UPDATE { + let mut state = state_ref(hwnd).borrow_mut(); + if let Some(check) = &state.update_check { + let route = check.route; + state.worker.work.try_send(Work::Handoff(route))?; + state.checking_updates = true; + } + return Ok(()); + } let login_request = match selected { LOGIN_ENABLE => Some(StartupRequest::Set(true)), LOGIN_DISABLE => Some(StartupRequest::Set(false)), @@ -894,7 +1023,7 @@ fn show_menu(hwnd: HWND) -> Result<()> { state .worker .work - .try_send(()) + .try_send(Work::Packs) .map_err(|_| anyhow::anyhow!("Tray metadata worker is unavailable"))?; state.refreshing = true; } diff --git a/src/windows/mod.rs b/src/windows/mod.rs index f39b731..4c246c3 100644 --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -8,7 +8,7 @@ pub mod desktop; mod files; pub mod input; mod lifecycle; -mod package; +pub(crate) mod package; mod paths; pub mod pipe; mod process; diff --git a/src/windows/package.rs b/src/windows/package.rs index 24740b6..b7c8762 100644 --- a/src/windows/package.rs +++ b/src/windows/package.rs @@ -11,7 +11,7 @@ use windows_future::{AsyncStatus, IAsyncOperation}; use super::startup::Status; -pub(super) fn current() -> Result { +pub(crate) fn current() -> Result { let mut length = 0; match unsafe { GetCurrentPackageFullName(&mut length, None) } { APPMODEL_ERROR_NO_PACKAGE => Ok(false), From 9ec8ee602809811dd79524810cc7773b5002183b Mon Sep 17 00:00:00 2001 From: muneer320 Date: Sat, 21 Nov 2026 03:19:53 +0530 Subject: [PATCH 2/4] fix: preserve playback and release updater executable before replacement --- .github/workflows/ci.yml | 6 +-- docs/INSTALLATION.md | 2 +- scripts/install.ps1 | 6 +++ src/update.rs | 92 ++++++++++++++++++++++------------------ src/update/unix.sh | 47 ++++++++++++++++++++ src/update/windows.ps1 | 18 ++++---- 6 files changed, 115 insertions(+), 56 deletions(-) create mode 100644 src/update/unix.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3078ee5..0d71444 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -93,7 +93,7 @@ jobs: shell: pwsh run: | $ErrorActionPreference = 'Stop' - foreach ($file in Get-ChildItem scripts -Filter '*.ps1') { + foreach ($file in Get-ChildItem -Path scripts,src/update -Filter '*.ps1') { $tokens = $null $errors = $null $null = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$errors) @@ -141,8 +141,8 @@ jobs: - name: Check shell scripts if: matrix.os == 'ubuntu-latest' run: | - for script in scripts/*.sh packaging/omarchy-bar/*.sh; do bash -n "$script"; done - shellcheck scripts/*.sh packaging/omarchy-bar/*.sh + for script in scripts/*.sh packaging/omarchy-bar/*.sh src/update/*.sh; do bash -n "$script"; done + shellcheck scripts/*.sh packaging/omarchy-bar/*.sh src/update/*.sh - name: Check macOS menu bar helper if: matrix.os == 'macos-latest' && needs.scope.outputs.native == 'true' run: | diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index f37a662..4f82ff8 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -18,7 +18,7 @@ klicky update - **Microsoft Store:** opens Store's Downloads and updates page. Store controls which version is available. - **Windows standalone installer:** opens an update terminal and the official installer wizard. Existing settings and custom packs remain. - **Scoop:** opens a terminal, stops a running copy, refreshes Scoop and updates Klicky. A running/paused copy is restarted in its previous playback state; a stopped copy stays stopped. -- **Homebrew:** updates the tap and formula. A previously running engine is restarted; its paused state is restored. Login-startup preferences are not enabled by the updater. +- **Homebrew:** updates the tap and formula. A previously running engine and menu helper are restarted; the engine's paused state is restored. Login-startup preferences are not enabled by the updater. - **APT:** refreshes repository metadata and upgrades the installed `klicky` package. It may request `sudo` approval. - **pacman:** offers a full `pacman -Syu` system upgrade, rather than a partial upgrade. Review pacman's transaction before accepting it. - **Source, portable or unknown copies:** shows manual guidance instead of guessing an installation method or replacing files. diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 6cb459e..c81d337 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -1,4 +1,6 @@ # Downloads a published Windows installer; never uses expiring CI artifacts. +param([switch]$Update) + & { Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' @@ -75,6 +77,10 @@ if (-not (Test-Path -LiteralPath $cli -PathType Leaf)) { throw "Setup finished, but Klicky could not start because its control executable is missing: $cli. Details: $log`n$securityHelp`nIf there is no security detection, repair the installation with the official installer." } + if ($Update) { + Write-Output 'Klicky update finished. The installer restored its previous running and pause state.' + return + } $launch = Start-KlickyProcess -Stage 'Klicky startup after installation' -Options @{ FilePath = $cli; ArgumentList = @('service', 'start'); WindowStyle = 'Hidden' } diff --git a/src/update.rs b/src/update.rs index 813c890..ca25949 100644 --- a/src/update.rs +++ b/src/update.rs @@ -115,6 +115,7 @@ pub fn check() -> Result { } let output = request .args([ + "--disable", "--fail", "--silent", "--show-error", @@ -128,6 +129,8 @@ pub fn check() -> Result { "1048576", "--header", "Accept: application/vnd.github+json", + "--header", + "X-GitHub-Api-Version: 2022-11-28", "--user-agent", "Klicky-update-check", RELEASE_API, @@ -232,11 +235,23 @@ fn windows_route(exe: &Path, local: Option<&Path>, packaged: bool) -> Result Result { #[cfg(target_os = "macos")] - if option_env!("KLICKY_MACOS_INSTALL_BINARY") - .and_then(|p| Path::new(p).canonicalize().ok()) - .is_some_and(|p| p == exe) - { - return Ok(Route::Homebrew); + if let Some(launcher) = option_env!("KLICKY_MACOS_INSTALL_BINARY") { + // The tap's stable opt/bin launcher is a shell wrapper. The actual Rust + // executable is installed under the keg's libexec directory. + if let Some(keg) = Path::new(launcher) + .parent() + .and_then(Path::parent) + .and_then(|p| p.canonicalize().ok()) + { + if keg.join("INSTALL_RECEIPT.json").is_file() + && keg + .join("libexec/bin/klicky") + .canonicalize() + .is_ok_and(|p| p == exe) + { + return Ok(Route::Homebrew); + } + } } #[cfg(target_os = "linux")] if exe == Path::new("/usr/bin/klicky") { @@ -310,8 +325,12 @@ pub fn handoff(route: Route, wait_for_cli: bool) -> Result<()> { #[cfg(target_os = "windows")] fn open_store() -> Result<()> { use windows::core::{w, PCWSTR}; + use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED}; use windows::Win32::UI::Shell::ShellExecuteW; use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + unsafe { + CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()?; + } let result = unsafe { ShellExecuteW( None, @@ -322,6 +341,9 @@ fn open_store() -> Result<()> { SW_SHOWNORMAL, ) }; + unsafe { + CoUninitialize(); + } if result.0 as isize <= 32 { bail!("Microsoft Store could not open; use Store > Library > Get updates"); } @@ -331,16 +353,11 @@ fn open_store() -> Result<()> { #[cfg(not(target_os = "windows"))] pub fn handoff(route: Route, _wait_for_cli: bool) -> Result<()> { - let commands: &[(&str, &[&str])] = match route { - Route::Homebrew => &[ - ("brew", &["update"]), - ("brew", &["upgrade", "muneer320/tap/klicky"]), - ], - Route::Apt => &[ - ("sudo", &["apt-get", "update"]), - ("sudo", &["apt-get", "install", "--only-upgrade", "klicky"]), - ], - Route::Pacman => &[("sudo", &["pacman", "-Syu"])], + use std::os::unix::process::CommandExt; + let manager = match route { + Route::Homebrew => "homebrew", + Route::Apt => "apt", + Route::Pacman => "pacman", _ => bail!("Update manually using {GUIDE}; no files were changed"), }; let playback = match crate::ipc::playback_status() { @@ -351,31 +368,22 @@ pub fn handoff(route: Route, _wait_for_cli: bool) -> Result<()> { let launcher = option_env!("KLICKY_MACOS_INSTALL_BINARY") .map(std::path::PathBuf::from) .unwrap_or(std::env::current_exe()?); - crate::service::run(crate::cli::ServiceAction::Stop)?; - let update = (|| { - for (program, args) in commands { - let status = Command::new(program) - .args(*args) - .status() - .with_context(|| format!("run {program}"))?; - if !status.success() { - bail!("{program} did not complete the update; check its output above"); - } - } - Ok(()) - })(); - // Use the installed CLI after replacement, rather than this old executable's - // service code. Do not enable login startup or start a previously stopped app. - if let Some(state) = playback { - let status = Command::new(&launcher) - .args(["service", "start"]) - .status()?; - if !status.success() { - bail!("Klicky could not restart; update result: {update:?}"); - } - if state.paused && !Command::new(&launcher).arg("pause").status()?.success() { - bail!("Klicky restarted but could not restore Pause; update result: {update:?}"); - } - } - update + // exec preserves the foreground terminal while releasing the old executable. + // Debian/Arch guards must not mistake the updater CLI for a running engine. + let error = Command::new("/bin/sh") + .args([ + "-c", + include_str!("update/unix.sh"), + "klicky-update", + manager, + ]) + .arg(launcher) + .arg(if playback.is_some() { "1" } else { "0" }) + .arg(if playback.is_some_and(|state| state.paused) { + "1" + } else { + "0" + }) + .exec(); + Err(error).context("hand off to the installation owner; no update started") } diff --git a/src/update/unix.sh b/src/update/unix.sh new file mode 100644 index 0000000..950b13f --- /dev/null +++ b/src/update/unix.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Executed in place of the CLI, so package guards no longer see a Klicky process. +set -u +manager=$1 +launcher=$2 +was_running=$3 +was_paused=$4 +menu_running=0 +menu_job="gui/$(id -u)/dev.klicky.homebrew-menu" +if [ "$manager" = homebrew ] && + launchctl print "$menu_job" 2>/dev/null | grep -Eq '^[[:space:]]*pid = [0-9]+'; then + menu_running=1 +fi + +restore_playback() { + result=$? + trap - EXIT + if [ "$was_running" = 1 ]; then + if ! "$launcher" service start; then + printf 'Klicky did not restart. Check its service status.\n' >&2 + exit 1 + fi + if [ "$was_paused" = 1 ] && ! "$launcher" pause; then + printf 'Klicky restarted but could not restore Pause.\n' >&2 + exit 1 + fi + fi + exit "$result" +} + +"$launcher" service stop || exit 1 +trap restore_playback EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'exit 129' HUP + +case "$manager" in + homebrew) + brew update && brew upgrade muneer320/tap/klicky || exit $? + # Its ProgramArguments use the stable opt launcher. Restarting the loaded + # job picks up the new wrapper without enabling login startup or an opt-out. + if [ "$menu_running" = 1 ]; then launchctl kickstart -k "$menu_job"; fi + ;; + apt) sudo apt-get update && sudo apt-get install --only-upgrade klicky ;; + pacman) sudo pacman -Syu ;; + *) printf 'Unrecognized update owner; no package was changed.\n' >&2; exit 1 ;; +esac diff --git a/src/update/windows.ps1 b/src/update/windows.ps1 index 9159006..b156efe 100644 --- a/src/update/windows.ps1 +++ b/src/update/windows.ps1 @@ -12,18 +12,16 @@ try { } } if ($Channel -eq 'Standalone') { - Invoke-RestMethod 'https://klicky.muneer320.tech/install.ps1' | Invoke-Expression + $installer = Invoke-RestMethod 'https://klicky.muneer320.tech/install.ps1' -TimeoutSec 30 + & ([scriptblock]::Create($installer)) -Update } else { - $status = (& $Cli status) - if ($LASTEXITCODE -ne 0) { throw 'Cannot read playback state' } - $running = ($status -join "`n") -notmatch 'Klicky is not running' - if ($running) { - $state = (& $Cli diagnostics | ConvertFrom-Json) - if ($LASTEXITCODE -ne 0) { throw 'Cannot preserve playback state; update with Scoop manually.' } - & $Cli service stop - if ($LASTEXITCODE -ne 0) { throw 'Klicky did not stop' } + $receipt = @(& $Cli service prepare-update) + if ($LASTEXITCODE -ne 0 -or $receipt.Count -ne 1 -or $receipt[0] -notmatch '^KLICKY_UPDATE_V1 ([01]) ([01])$') { + throw 'Klicky did not confirm update preparation; update with Scoop manually.' } + $running = $Matches[1] -eq '1' + $paused = $Matches[2] -eq '1' try { scoop update if ($LASTEXITCODE -ne 0) { throw 'Scoop refresh failed' } @@ -32,7 +30,7 @@ try { } finally { if ($running) { - if ($state.snapshot.state -eq 'paused') { & $Cli service start --paused } + if ($paused) { & $Cli service start --paused } else { & $Cli service start } if ($LASTEXITCODE -ne 0) { Write-Warning 'Klicky did not restart; use its Start shortcut.' } } From 267bbf60c9896d00a26879e29d08b0204fc000d9 Mon Sep 17 00:00:00 2001 From: muneer320 Date: Sat, 21 Nov 2026 03:24:52 +0530 Subject: [PATCH 3/4] fix: verify update ownership and bootstrap compatibility --- Cargo.toml | 2 +- docs/INSTALLATION.md | 4 ++-- packaging/arch/.SRCINFO | 1 + packaging/arch/PKGBUILD | 2 +- src/update.rs | 36 ++++++++++++++++++++++++++---------- src/update/windows.ps1 | 7 ++++++- 6 files changed, 37 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e42f764..7422fd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ evdev = "0.13" maintainer = "Muneer Alam " copyright = "2026, Muneer Alam" license-file = ["LICENSE", "0"] -depends = "$auto, systemd, udev" +depends = "$auto, systemd, udev, curl" section = "sound" priority = "optional" extended-description = """\ diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 4f82ff8..c16e74e 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -17,11 +17,11 @@ klicky update - **Microsoft Store:** opens Store's Downloads and updates page. Store controls which version is available. - **Windows standalone installer:** opens an update terminal and the official installer wizard. Existing settings and custom packs remain. -- **Scoop:** opens a terminal, stops a running copy, refreshes Scoop and updates Klicky. A running/paused copy is restarted in its previous playback state; a stopped copy stays stopped. +- **Scoop (per-user):** opens a terminal, stops a running copy, refreshes Scoop and updates Klicky. A running/paused copy is restarted in its previous playback state; a stopped copy stays stopped. - **Homebrew:** updates the tap and formula. A previously running engine and menu helper are restarted; the engine's paused state is restored. Login-startup preferences are not enabled by the updater. - **APT:** refreshes repository metadata and upgrades the installed `klicky` package. It may request `sudo` approval. - **pacman:** offers a full `pacman -Syu` system upgrade, rather than a partial upgrade. Review pacman's transaction before accepting it. -- **Source, portable or unknown copies:** shows manual guidance instead of guessing an installation method or replacing files. +- **Source, portable, global Scoop or unknown copies:** shows manual guidance instead of guessing an installation method or replacing files. Package-manager versions can arrive later than the GitHub release. A successful check is not proof that your manager already offers that version, and a Windows terminal handoff is not confirmation that installation completed. Use `klicky --version` in a new terminal afterward. The standalone Windows CLI currently requires its full path unless you have added it to PATH. diff --git a/packaging/arch/.SRCINFO b/packaging/arch/.SRCINFO index e7d7f8e..7040ebd 100644 --- a/packaging/arch/.SRCINFO +++ b/packaging/arch/.SRCINFO @@ -8,6 +8,7 @@ pkgbase = klicky makedepends = cargo makedepends = git depends = alsa-lib + depends = curl depends = gcc-libs depends = glibc depends = systemd diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index f61bc88..01fb181 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -6,7 +6,7 @@ pkgdesc="Low-latency mechanical keyboard sounds for Linux" arch=('x86_64') url="https://github.com/Muneer320/klicky" license=('MIT') -depends=('alsa-lib' 'gcc-libs' 'glibc' 'systemd') +depends=('alsa-lib' 'curl' 'gcc-libs' 'glibc' 'systemd') makedepends=('cargo' 'git') options=('!debug') source=("$pkgname::git+$url.git#tag=v$pkgver" 'check-stopped.sh' 'klicky-stopped.hook') diff --git a/src/update.rs b/src/update.rs index ca25949..b5e9e17 100644 --- a/src/update.rs +++ b/src/update.rs @@ -26,7 +26,7 @@ impl Route { match self { Self::Store => "Microsoft Store (Store manages the offered version)", Self::Standalone => "Windows standalone installer", - Self::Scoop => "Scoop", + Self::Scoop => "Scoop (per-user)", Self::Homebrew => "Homebrew", Self::Apt => "APT", Self::Pacman => "pacman", @@ -136,7 +136,7 @@ pub fn check() -> Result { RELEASE_API, ]) .output() - .context("run curl for the explicit update check")?; + .context("could not run curl for the update check; install curl or use your package manager directly")?; if !output.status.success() { bail!( "Update check failed; nothing was changed. {}", @@ -195,15 +195,24 @@ pub fn run(check_only: bool, yes: bool) -> Result<()> { #[cfg(target_os = "windows")] fn detect(exe: &Path) -> Result { + let scoop = std::env::var_os("SCOOP") + .map(std::path::PathBuf::from) + .or_else(|| dirs::home_dir().map(|p| p.join("scoop"))); windows_route( exe, dirs::data_local_dir().as_deref(), + scoop.as_deref(), crate::windows::package::current()?, ) } #[cfg(target_os = "windows")] -fn windows_route(exe: &Path, local: Option<&Path>, packaged: bool) -> Result { +fn windows_route( + exe: &Path, + local: Option<&Path>, + scoop: Option<&Path>, + packaged: bool, +) -> Result { if packaged { return Ok(Route::Store); } @@ -218,13 +227,20 @@ fn windows_route(exe: &Path, local: Option<&Path>, packaged: bool) -> Result Date: Sat, 21 Nov 2026 03:39:22 +0530 Subject: [PATCH 4/4] fix: recover update preparation and silence tray notifications --- src/update/unix.sh | 3 ++- src/windows/desktop.rs | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/update/unix.sh b/src/update/unix.sh index 950b13f..951be1d 100644 --- a/src/update/unix.sh +++ b/src/update/unix.sh @@ -28,11 +28,12 @@ restore_playback() { exit "$result" } -"$launcher" service stop || exit 1 trap restore_playback EXIT trap 'exit 130' INT trap 'exit 143' TERM trap 'exit 129' HUP +"$launcher" service stop || exit 1 +"$launcher" stop || exit 1 case "$manager" in homebrew) diff --git a/src/windows/desktop.rs b/src/windows/desktop.rs index d50291f..fb8b49d 100644 --- a/src/windows/desktop.rs +++ b/src/windows/desktop.rs @@ -214,6 +214,7 @@ struct State { refreshing: bool, checking_updates: bool, update_check: Option, + update_error: Option, menu_open: bool, taskbar_created: u32, icon_added: bool, @@ -299,6 +300,7 @@ fn run_ui(paths: Paths, controller: Controller) -> Result<()> { refreshing: true, checking_updates: false, update_check: None, + update_error: None, menu_open: false, taskbar_created: unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) }, icon_added: false, @@ -573,14 +575,19 @@ fn take_metadata(hwnd: HWND) -> Result<()> { } if let Some(result) = update.handoff { state.checking_updates = false; - if let Err(error) = result { - state.operation_error = Some(error); + match result { + Ok(()) => { + state.update_error = None; + state.update_check = None; + } + Err(error) => state.update_error = Some(error), } } if let Some(result) = update.release { state.checking_updates = false; let text = match result { Ok(check) => { + state.update_error = None; let text = if check.newer { format!("Klicky {} is available (installed {}). Reopen the tray menu for the update route.", check.latest, env!("CARGO_PKG_VERSION")) } else { @@ -595,14 +602,14 @@ fn take_metadata(hwnd: HWND) -> Result<()> { } Err(error) => { state.update_check = None; - state.operation_error = Some(error.clone()); + state.update_error = Some(error.clone()); error } }; if !state.view.finished { let mut data = icon_data(hwnd); data.uFlags = NIF_INFO; - data.dwInfoFlags = NIIF_INFO; + data.dwInfoFlags = NIIF_INFO | NIIF_NOSOUND; copy_utf16("Klicky updates", &mut data.szInfoTitle); copy_utf16(&text, &mut data.szInfo); unsafe { @@ -934,6 +941,9 @@ fn show_menu(hwnd: HWND) -> Result<()> { )?; { let state = state_ref(hwnd).borrow(); + if let Some(error) = &state.update_error { + menu.item(0, &menu_text(error), MF_GRAYED)?; + } if let Some(check) = &state.update_check { menu.item( 0,