diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a800c7..f09fd6f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,6 +104,38 @@ jobs: key: ${{ matrix.id }} - run: cargo clippy --workspace --all-targets --locked ${{ matrix.features }} -- -D warnings + # Windows, where mpv's IPC runs over a named pipe instead of a socket pair. aws-lc-rs builds its + # assembly with NASM, through CMake; mpv itself plays the player's tests, which skip elsewhere. + windows: + name: Windows + runs-on: windows-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + submodules: true + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + toolchain: stable + components: clippy + - name: Install NASM + run: | + choco install nasm --no-progress -y + echo "C:\Program Files\NASM" >> "$env:GITHUB_PATH" + - name: Install mpv + run: | + choco install mpv --no-progress -y + echo "C:\ProgramData\chocolatey\bin" >> "$env:GITHUB_PATH" + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + key: windows + - run: cargo build --locked -p cloofy --no-default-features --features ytmusic + - run: cargo build --locked -p cloofy --no-default-features --features spotify + - run: cargo clippy --workspace --all-targets --locked -- -D warnings + - run: cargo test --workspace --locked + env: + CLOOFY_REQUIRE_MPV: 1 + # The oldest Rust that builds cloofy from source, as Cargo.toml's rust-version says. msrv: name: rust-version diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dbb430..d202dca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to cloofy. The format follows [Keep a Changelog](https://kee ## [Unreleased] +### Added + +- **Windows.** cloofy builds and runs on Windows now: YouTube Music with mpv, Spotify, media keys and the system's Now Playing panel, sleep and wake, low power mode, toasts with the cover, and sign-ins in Credential Manager. `cloofy windows install` puts cloofy in the Start Menu, which Windows needs for notifications; `packaging/windows/install.ps1` builds and installs it. There is no Windows release to download yet, so updates say to build it here, and `cloofy login ytmusic` lists the browsers instead of guessing the default one. + ## [0.5.3] - 2026-11-12 What you asked for: every song at the same loudness, shelves you can hide, cloofy in the app menu on Linux, and a YouTube Music sign-in that lasts. diff --git a/Cargo.lock b/Cargo.lock index d0b4a75..5cb7229 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -457,6 +457,7 @@ dependencies = [ "tracing", "tracing-subscriber", "unicode-width", + "windows 0.62.2", ] [[package]] @@ -496,6 +497,8 @@ dependencies = [ "tokio", "tracing", "url", + "windows 0.62.2", + "windows-future 0.3.2", "zbus", ] @@ -5191,11 +5194,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -5207,6 +5222,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.54.0" @@ -5264,7 +5288,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -5333,6 +5368,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.6.1" @@ -5484,6 +5529,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.42.2" diff --git a/Cargo.toml b/Cargo.toml index 9901a05..993a490 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,12 @@ zeno = "0.3" # unixexec: zbus 5 always had it, for session buses reached through a command. zbus = { version = "6", default-features = false, features = ["proxy", "service", "tokio", "unixexec"] } +# Windows bindings; each crate turns on the parts it uses. +windows = { version = "0.62", default-features = false } +# What `windows` hands back from an asynchronous WinRT call, such as writing a cover into a +# stream. +windows-future = "0.3" + # vendor/ holds forks as git submodules, both on branch `cloofy`: # - librespot (github.com/parda21/librespot) with two open upstream PRs merged, DJ with # narration (librespot-org/librespot#1797) and crossfade (#1756), plus fixes on top. diff --git a/README.md b/README.md index b9d53aa..3fc4289 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,22 @@ YouTube Music needs no headers to build, and [mpv](https://mpv.io), [yt-dlp](htt +### Windows + +Windows builds from source: Rust 1.90 or newer, plus CMake and NASM for Spotify's audio. + +```powershell +cargo build --release --no-default-features --features ytmusic # or --features spotify, or both +``` + +`packaging/windows/install.ps1` builds it, copies it to `%LOCALAPPDATA%\cloofy\bin` and puts cloofy in the Start Menu, which is what lets Windows show its notifications; `-AddToPath` puts that folder on your `PATH` as well. `uninstall.ps1` takes the folder and that one entry out again, and `cloofy windows remove` only the Start Menu shortcut. `cloofy windows status` shows whether it is there. + +YouTube Music needs [mpv](https://mpv.io), [yt-dlp](https://github.com/yt-dlp/yt-dlp) and [deno](https://deno.com) on `PATH`; [scoop](https://scoop.sh) has all three. + +Covers are block art unless your terminal does Sixel: Windows Terminal 1.22 or newer does, and `images = "sixel"` in `config.toml` forces it. + +Three things differ on Windows. Releases have no Windows build yet, so the update button says **update by building it here** instead of downloading. `cloofy login ytmusic` lists the browsers that have a profile instead of guessing the default one, which cloofy doesn't read from the registry. And plugging in headphones or switching the default output doesn't pause playback. `packaging/windows/README.md` lists what to check by hand. + ## Setup Set up the services you installed; the installer does it with you. With both, `cloofy login` signs in to each in turn, and asks before YouTube Music, which plays without an account. @@ -269,10 +285,10 @@ On [Omarchy](https://omarchy.org), cloofy takes its colors from the theme and fo | Ghostty, kitty, WezTerm | Real images | Built in | Yes | | iTerm2 | Real images | With a Nerd Font | Yes | | foot, Konsole, VS Code, xterm, mlterm | Real images | With a Nerd Font | On Linux | -| Windows Terminal | Real images | With a Nerd Font | No | +| Windows Terminal | Real images | With a Nerd Font | Yes | | Others | Real images with Sixel, else blocks | With a Nerd Font | On Linux | -Every terminal needs true color. Without a Nerd Font, pick text icons in Settings. VS Code shows images once `terminal.integrated.enableImages` is on, xterm when started with `-ti 340`, and Windows Terminal from version 1.22. Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. On Linux, terminals without notifications of their own get them from the desktop, with the cover, and on Hyprland and Omarchy every terminal does. +Every terminal needs true color. Without a Nerd Font, pick text icons in Settings. VS Code shows images once `terminal.integrated.enableImages` is on, xterm when started with `-ti 340`, and Windows Terminal from version 1.22. Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. On Linux, terminals without notifications of their own get them from the desktop, with the cover, and on Hyprland and Omarchy every terminal does. On Windows they come from the desktop too, as toasts, which need the Start Menu shortcut `cloofy windows install` makes. ## FAQ diff --git a/crates/cloofy-core/src/config.rs b/crates/cloofy-core/src/config.rs index f58abda..4a60c47 100644 --- a/crates/cloofy-core/src/config.rs +++ b/crates/cloofy-core/src/config.rs @@ -63,7 +63,7 @@ impl Config { match self.credentials.as_deref() { None | Some("files") => Ok(false), Some("keychain") if cloofy_os::secrets::available() => Ok(true), - Some("keychain") => bail!("credentials = \"keychain\" works on macOS only for now"), + Some("keychain") => bail!("credentials = \"keychain\" works on macOS and Windows only for now"), Some(other) => bail!("credentials = \"{other}\" is unknown: use \"keychain\" or \"files\""), } } @@ -140,7 +140,10 @@ mod tests { fn keeps_sign_ins_in_files_unless_asked() { assert!(!credentials(None).keychain().unwrap()); assert!(!credentials(Some("files")).keychain().unwrap()); - assert_eq!(credentials(Some("keychain")).keychain().is_ok(), cfg!(target_os = "macos")); + assert_eq!( + credentials(Some("keychain")).keychain().is_ok(), + cfg!(any(target_os = "macos", target_os = "windows")) + ); assert!(credentials(Some("vault")).keychain().is_err()); } diff --git a/crates/cloofy-core/src/paths.rs b/crates/cloofy-core/src/paths.rs index bd9760e..05e23ce 100644 --- a/crates/cloofy-core/src/paths.rs +++ b/crates/cloofy-core/src/paths.rs @@ -105,7 +105,11 @@ impl Secret { Secret::Keychain { name, file } => { // A file wins: it was written by a login, or before the switch to the keychain. if let Some(bytes) = read_file(file)? { - cloofy_os::secrets::set(name, &bytes).context("Saving to the keychain failed")?; + match cloofy_os::secrets::set(name, &bytes) { + // Too long for the keychain: the file is where it stays. + Err(err) if err.kind() == io::ErrorKind::InvalidInput => return Ok(Some(bytes)), + result => result.context("Saving to the keychain failed")?, + } fs::remove_file(file).with_context(|| format!("{} can't be removed", file.display()))?; return Ok(Some(bytes)); } @@ -119,8 +123,15 @@ impl Secret { Secret::File(path) => { write_private(path, bytes).with_context(|| format!("{} is not writable", path.display())) } - Secret::Keychain { name, .. } => { - cloofy_os::secrets::set(name, bytes).context("Saving to the keychain failed") + Secret::Keychain { name, file } => { + match cloofy_os::secrets::set(name, bytes) { + // Credential Manager holds 2560 bytes at most, and YouTube Music's cookies are + // longer: such a secret lives in the file the keychain would have replaced. + Err(err) if err.kind() == io::ErrorKind::InvalidInput => { + write_private(file, bytes).with_context(|| format!("{} is not writable", file.display())) + } + result => result.context("Saving to the keychain failed"), + } } } } @@ -197,6 +208,24 @@ mod tests { fs::remove_dir_all(dir).unwrap(); } + /// Credential Manager holds 2560 bytes at most, and YouTube Music's cookies are longer: such + /// a secret stays in a file. Uses no keychain entry, as the store refuses it before writing. + #[cfg(target_os = "windows")] + #[test] + fn keeps_a_secret_too_long_for_the_keychain_in_a_file() { + let dir = scratch("keychain-too-long"); + let name: &'static str = format!("test-{}", std::process::id()).leak(); + let file = dir.join("cookies.txt"); + let secret = Secret::Keychain { name, file: file.clone() }; + let cookies = vec![b'x'; 3000]; + secret.write(&cookies).unwrap(); + assert_eq!(fs::read(&file).unwrap(), cookies, "it goes straight to the file"); + assert_eq!(secret.read().unwrap().as_deref(), Some(&cookies[..]), "and reads back"); + assert!(file.exists(), "reading leaves it there, as it can't move"); + secret.delete().unwrap(); + fs::remove_dir_all(dir).unwrap(); + } + /// Writes to the login keychain: run it by hand with /// `cargo test -p cloofy-core -- --ignored`. #[test] diff --git a/crates/cloofy-core/src/update.rs b/crates/cloofy-core/src/update.rs index c0dc7f3..8395b5d 100644 --- a/crates/cloofy-core/src/update.rs +++ b/crates/cloofy-core/src/update.rs @@ -182,6 +182,13 @@ fn target() -> Option<&'static str> { }) } +/// Whether a release has a build for this machine, and so updates can put it in place of the +/// running binary. Where there is none, such as Windows so far, the interface says how to update +/// instead of offering to. +pub fn supported() -> bool { + target().is_some() +} + /// The release archive of the `variant` build for `target`. Each variant has the services it is /// named after: `spotify`, `ytmusic`, or both in `full`. fn archive_name(variant: &str, target: &str) -> String { @@ -342,6 +349,13 @@ mod tests { assert_eq!(of("/usr/bin-old/cloofy"), None); } + /// Windows has no prebuilt build yet, so cloofy says how to update rather than offering to. + #[cfg(target_os = "windows")] + #[test] + fn has_no_release_to_update_to() { + assert!(!supported()); + } + #[test] fn homebrew_upgrades_the_formula_of_the_build() { let brew = |variant| PackageManager::Homebrew.how_to_update(variant); diff --git a/crates/cloofy-os/Cargo.toml b/crates/cloofy-os/Cargo.toml index 683a155..21c4d38 100644 --- a/crates/cloofy-os/Cargo.toml +++ b/crates/cloofy-os/Cargo.toml @@ -37,6 +37,22 @@ tokio.workspace = true url.workspace = true zbus.workspace = true +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = [ + "Data_Xml_Dom", + "Foundation", + "Media", + "Media_Playback", + "Storage_Streams", + "UI_Notifications", + "Win32_Foundation", + "Win32_Security_Credentials", + "Win32_System_Power", + "Win32_System_WinRT", + "Win32_UI_WindowsAndMessaging", +] } +windows-future.workspace = true + [[test]] name = "run_main" harness = false diff --git a/crates/cloofy-os/src/fallback.rs b/crates/cloofy-os/src/fallback.rs index 727863d..f1e82ee 100644 --- a/crates/cloofy-os/src/fallback.rs +++ b/crates/cloofy-os/src/fallback.rs @@ -1,6 +1,7 @@ //! Systems without an integration yet: nothing to set up, nothing shown. Linux uses the parts it -//! has nothing better for. +//! has nothing better for, Windows only the audio. +#[cfg(not(target_os = "windows"))] pub fn run_main(work: impl FnOnce() -> R) -> R { work() } @@ -18,7 +19,7 @@ pub mod audio { } } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "windows")))] pub mod power { use std::sync::Arc; @@ -29,7 +30,7 @@ pub mod power { } } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "windows")))] pub mod settings { use crate::settings::Settings; @@ -38,6 +39,7 @@ pub mod settings { } } +#[cfg(not(target_os = "windows"))] pub mod secrets { use std::io; @@ -60,7 +62,7 @@ pub mod secrets { } } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "windows")))] pub mod media { use std::sync::Arc; diff --git a/crates/cloofy-os/src/lib.rs b/crates/cloofy-os/src/lib.rs index f577e66..4a67965 100644 --- a/crates/cloofy-os/src/lib.rs +++ b/crates/cloofy-os/src/lib.rs @@ -18,13 +18,24 @@ use macos as os; mod linux; #[cfg(target_os = "linux")] use linux as os; -/// Linux only: elsewhere the terminal's own notifications are all cloofy needs. +/// Linux and Windows have notifications of their own, with the cover; elsewhere the terminal's +/// are all cloofy needs. #[cfg(target_os = "linux")] pub use linux::notifications; +#[cfg(target_os = "windows")] +pub use windows::notifications; + +#[cfg(target_os = "windows")] +mod windows; +#[cfg(target_os = "windows")] +use windows as os; +/// The AppUserModelID and the Start Menu shortcut that Windows shows cloofy's toasts under. +#[cfg(target_os = "windows")] +pub use windows::{AUMID, shortcut_path}; #[cfg(not(target_os = "macos"))] mod fallback; -#[cfg(not(any(target_os = "macos", target_os = "linux")))] +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] use fallback as os; /// Runs `work` while the main thread serves the OS, and returns its result. diff --git a/crates/cloofy-os/src/windows/media.rs b/crates/cloofy-os/src/windows/media.rs new file mode 100644 index 0000000..384aa65 --- /dev/null +++ b/crates/cloofy-os/src/windows/media.rs @@ -0,0 +1,193 @@ +//! Now Playing and media keys through the System Media Transport Controls. +//! +//! WinRT objects belong to the apartment of the thread that made them, so the player and its +//! controls live on a thread of their own, which this module starts: `update` only tells that +//! thread what to show. + +use std::{ + sync::{Arc, mpsc}, + thread, + time::Duration, +}; + +use windows::{ + Foundation::{TimeSpan, TypedEventHandler}, + Media::{ + MediaPlaybackStatus, MediaPlaybackType, Playback::MediaPlayer, SystemMediaTransportControls, + SystemMediaTransportControlsButton, SystemMediaTransportControlsButtonPressedEventArgs, + SystemMediaTransportControlsTimelineProperties, + }, + Storage::Streams::{DataWriter, InMemoryRandomAccessStream, RandomAccessStreamReference}, + Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}, + core::{HSTRING, Result as WinResult}, +}; + +use crate::media::{Command, State, Track}; + +pub struct Controls { + /// Handed to the thread that owns the controls; it shows nothing once that thread is gone. + updates: mpsc::Sender, +} + +impl Controls { + pub fn new(on_command: Arc) -> Option { + let (updates, states) = mpsc::channel(); + let (ready, created) = mpsc::sync_channel(0); + thread::Builder::new() + .name("cloofy-media".into()) + .spawn(move || { + // SAFETY: nothing else runs on this thread, and WinRT is initialized before use. + let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + let Some(mut session) = Session::new(on_command) else { + let _ = ready.send(false); + return; + }; + let _ = ready.send(true); + while let Ok(state) = states.recv() { + session.show(state); + } + }) + .ok()?; + // Says whether the thread got a session at all; the channel reads as closed if it didn't. + created.recv().ok()?.then_some(Self { updates }) + } + + pub fn update(&self, state: State) { + let _ = self.updates.send(state); + } +} + +struct Session { + /// Kept for the session to exist: dropping the player takes it out of the system's controls. + _player: MediaPlayer, + controls: SystemMediaTransportControls, + /// The cover the system reads, with the bytes it was made from, so that an update which + /// changes only the position doesn't make another stream. + artwork: Option<(Arc<[u8]>, RandomAccessStreamReference)>, +} + +impl Session { + fn new(on_command: Arc) -> Option { + let player = MediaPlayer::new().ok()?; + // The player's command manager would drive its own source from the keys; cloofy drives + // the playback, so it handles them instead. + player.CommandManager().ok()?.SetIsEnabled(false).ok()?; + let controls = player.SystemMediaTransportControls().ok()?; + controls.SetIsPlayEnabled(true).ok()?; + controls.SetIsPauseEnabled(true).ok()?; + controls.SetIsNextEnabled(true).ok()?; + controls.SetIsPreviousEnabled(true).ok()?; + let handler = TypedEventHandler::< + SystemMediaTransportControls, + SystemMediaTransportControlsButtonPressedEventArgs, + >::new(move |_, args| { + if let Some(command) = args.as_ref().and_then(|args| args.Button().ok()).and_then(command) { + on_command(command); + } + Ok(()) + }); + controls.ButtonPressed(&handler).ok()?; + controls.SetIsEnabled(true).ok()?; + Some(Self { _player: player, controls, artwork: None }) + } + + fn show(&mut self, state: State) { + if let Err(err) = self.publish(&state) { + tracing::warn!("the media controls didn't take an update: {err}"); + } + } + + fn publish(&mut self, state: &State) -> WinResult<()> { + let Some(track) = &state.track else { + self.controls.DisplayUpdater()?.ClearAll()?; + self.controls.SetPlaybackStatus(MediaPlaybackStatus::Closed)?; + return Ok(()); + }; + let updater = self.controls.DisplayUpdater()?; + // Also drops the cover of the track before, which the next one may not have. + updater.ClearAll()?; + updater.SetType(MediaPlaybackType::Music)?; + let music = updater.MusicProperties()?; + music.SetTitle(&HSTRING::from(track.title.as_str()))?; + music.SetArtist(&HSTRING::from(track.artist.as_str()))?; + music.SetAlbumTitle(&HSTRING::from(track.album.as_str()))?; + match self.artwork(track) { + Some(artwork) => updater.SetThumbnail(&artwork)?, + None if track.artwork.is_some() => tracing::warn!("the media controls got no cover"), + None => {} + } + updater.Update()?; + + let timeline = SystemMediaTransportControlsTimelineProperties::new()?; + timeline.SetStartTime(TimeSpan { Duration: 0 })?; + timeline.SetEndTime(time_span(track.duration))?; + timeline.SetMinSeekTime(TimeSpan { Duration: 0 })?; + timeline.SetMaxSeekTime(time_span(track.duration))?; + timeline.SetPosition(time_span(state.position))?; + self.controls.UpdateTimelineProperties(&timeline)?; + let status = if state.playing { MediaPlaybackStatus::Playing } else { MediaPlaybackStatus::Paused }; + self.controls.SetPlaybackStatus(status)?; + Ok(()) + } + + /// The cover as a stream the system reads, made once per cover; `None` where it can't be. + fn artwork(&mut self, track: &Track) -> Option { + let cover = track.artwork.as_ref()?; + if let Some((shown, reference)) = &self.artwork + && Arc::ptr_eq(shown, cover) + { + return Some(reference.clone()); + } + let reference = stream(cover).inspect_err(|err| tracing::warn!("cannot read the cover: {err}")).ok()?; + self.artwork = Some((cover.clone(), reference.clone())); + Some(reference) + } +} + +/// The button a media key sends, as the command cloofy knows. Windows has no toggle key: the +/// system sends Play or Pause, by the state it shows. +fn command(button: SystemMediaTransportControlsButton) -> Option { + match button { + SystemMediaTransportControlsButton::Play => Some(Command::Play), + SystemMediaTransportControlsButton::Pause => Some(Command::Pause), + SystemMediaTransportControlsButton::Next => Some(Command::Next), + SystemMediaTransportControlsButton::Previous => Some(Command::Previous), + _ => None, + } +} + +/// A WinRT span: 100-nanosecond ticks. +fn time_span(duration: Duration) -> TimeSpan { + TimeSpan { Duration: (duration.as_nanos() / 100) as i64 } +} + +/// The encoded cover in a stream, at its start, as the display updater takes one. +fn stream(cover: &[u8]) -> WinResult { + let stream = InMemoryRandomAccessStream::new()?; + let writer = DataWriter::CreateDataWriter(&stream)?; + writer.WriteBytes(cover)?; + writer.StoreAsync()?.join()?; + writer.DetachStream()?; + stream.Seek(0)?; + RandomAccessStreamReference::CreateFromStream(&stream) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn media_keys_become_commands() { + assert_eq!(command(SystemMediaTransportControlsButton::Play), Some(Command::Play)); + assert_eq!(command(SystemMediaTransportControlsButton::Pause), Some(Command::Pause)); + assert_eq!(command(SystemMediaTransportControlsButton::Next), Some(Command::Next)); + assert_eq!(command(SystemMediaTransportControlsButton::Previous), Some(Command::Previous)); + assert_eq!(command(SystemMediaTransportControlsButton::Stop), None); + } + + #[test] + fn spans_count_ticks_of_a_hundred_nanoseconds() { + assert_eq!(time_span(Duration::from_millis(1)).Duration, 10_000); + assert_eq!(time_span(Duration::ZERO).Duration, 0); + } +} diff --git a/crates/cloofy-os/src/windows/mod.rs b/crates/cloofy-os/src/windows/mod.rs new file mode 100644 index 0000000..4f01c9d --- /dev/null +++ b/crates/cloofy-os/src/windows/mod.rs @@ -0,0 +1,53 @@ +//! Windows speaks WinRT for the media controls and the notifications, and the Win32 API for +//! sleep and wake, the settings and the secrets. Some of both want an apartment or a subscription +//! set up first, which `run_main` does. + +use std::path::PathBuf; + +use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; + +pub mod media; +pub mod notifications; +pub mod power; +pub mod secrets; +pub mod settings; + +// Audio servers move streams to a new default output themselves, and watching them here would +// take WASAPI's device notifications, which cloofy doesn't do yet. +pub use crate::fallback::audio; + +/// The AppUserModelID of cloofy's Start Menu shortcut, and of its toast notifier. The two must +/// agree: with a different one, Windows shows a toast once and then drops the rest. +pub const AUMID: &str = "dev.cloofy.cloofy"; + +/// The Start Menu shortcut, whose AppUserModelID is what Windows shows cloofy's toasts under. +/// Without it, `ToastNotificationManager` accepts the notifier and shows nothing. +pub fn shortcut_path() -> Option { + let appdata = std::env::var_os("APPDATA")?; + Some(PathBuf::from(appdata).join("Microsoft\\Windows\\Start Menu\\Programs\\cloofy.lnk")) +} + +pub fn run_main(work: impl FnOnce() -> R) -> R { + // SAFETY: called before anything of WinRT exists on this thread. + unsafe { + // `RPC_E_CHANGED_MODE` says this thread already lives in a single-threaded apartment, + // which serves the media controls just as well; there is nothing to fix then. + let _ = RoInitialize(RO_INIT_MULTITHREADED); + } + work() +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use super::*; + + #[test] + fn the_shortcut_lives_in_the_start_menu() { + let path = shortcut_path().expect("APPDATA is set on Windows"); + let appdata = std::env::var_os("APPDATA").expect("APPDATA is set on Windows"); + assert!(path.starts_with(appdata)); + assert!(path.ends_with(Path::new("Microsoft/Windows/Start Menu/Programs/cloofy.lnk")), "{}", path.display()); + } +} diff --git a/crates/cloofy-os/src/windows/notifications.rs b/crates/cloofy-os/src/windows/notifications.rs new file mode 100644 index 0000000..df629c8 --- /dev/null +++ b/crates/cloofy-os/src/windows/notifications.rs @@ -0,0 +1,194 @@ +//! Song notifications as Windows toasts, with the cover. +//! +//! Windows only shows toasts of an app it knows from a Start Menu shortcut carrying its +//! AppUserModelID; without one it accepts the notifier and shows nothing. So `new` says no +//! without the shortcut that `cloofy windows install` makes, rather than pretending it worked. + +use std::{ + fs::{self, OpenOptions}, + io::Write, + path::{Path, PathBuf}, + process, + sync::{Arc, Mutex, PoisonError}, +}; + +use windows::{ + Data::Xml::Dom::XmlDocument, + UI::Notifications::{ToastNotification, ToastNotificationManager, ToastNotifier}, + core::{HSTRING, Result as WinResult}, +}; + +use super::{AUMID, shortcut_path}; + +/// The toast the next one replaces: Windows keeps one per tag and group. +const TAG: &str = "now-playing"; +const GROUP: &str = "cloofy"; + +pub struct Notifications { + notifier: ToastNotifier, + /// The cover of the toast on screen, which its replacement takes away. + shown: Mutex, +} + +#[derive(Default)] +struct Shown { + image: Option, + written: u64, +} + +/// Whether a click on a notification brings cloofy's window to the front. It would take a COM +/// activator and a new instance, which a terminal interface has nowhere to bring forward. +pub fn click_raises() -> bool { + false +} + +impl Notifications { + /// `None` without the Start Menu shortcut, which Windows needs to show the toast at all. + pub fn new() -> Option { + let shortcut = shortcut_path()?; + if !shortcut.is_file() { + tracing::debug!("No notifications without {}: `cloofy windows install` makes it", shortcut.display()); + return None; + } + let notifier = ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID)) + .inspect_err(|err| tracing::debug!("Windows refused the toast notifier: {err}")) + .ok()?; + Some(Self { notifier, shown: Mutex::default() }) + } + + /// Shows `title` and `body`, with `image` (JPEG, PNG or WebP) where there is one, in place of + /// the notification shown before. + pub fn show(&self, title: &str, body: &str, image: Option>) { + let image = image.and_then(|image| { + let mut shown = self.shown.lock().unwrap_or_else(PoisonError::into_inner); + shown.write(&image) + }); + match toast(title, body, image.as_deref()) { + Ok(toast) => { + if let Err(err) = self.notifier.Show(&toast) { + tracing::warn!("notification: {err}"); + } + } + Err(err) => tracing::warn!("notification: {err}"), + } + } +} + +impl Drop for Notifications { + fn drop(&mut self) { + let image = self.shown.lock().unwrap_or_else(PoisonError::into_inner).image.take(); + if let Some(path) = image { + let _ = fs::remove_file(path); + } + } +} + +impl Shown { + /// Writes `image` to a file of its own, a toast taking images by path, and removes the one + /// before: the notification it belonged to is being replaced. + fn write(&mut self, image: &[u8]) -> Option { + if let Some(old) = self.image.take() { + let _ = fs::remove_file(old); + } + self.written += 1; + // The shell reads the file by itself, so it can't live in cloofy's process; Windows + // clears the temporary folder now and then, which is all this needs. + let path = std::env::temp_dir().join(format!("cloofy-{}-notification-{}.img", process::id(), self.written)); + // A new file only, as Windows may still read the one before. + let written = OpenOptions::new().write(true).create_new(true).open(&path).and_then(|mut f| f.write_all(image)); + if let Err(err) = written { + tracing::warn!("cover for the notification: {}: {err}", path.display()); + let _ = fs::remove_file(&path); + return None; + } + self.image = Some(path.clone()); + Some(path) + } +} + +/// The toast, tagged so the next one replaces it. +fn toast(title: &str, body: &str, image: Option<&Path>) -> WinResult { + let xml = XmlDocument::new()?; + xml.LoadXml(&HSTRING::from(toast_xml(title, body, image)))?; + let toast = ToastNotification::CreateToastNotification(&xml)?; + toast.SetTag(&HSTRING::from(TAG))?; + toast.SetGroup(&HSTRING::from(GROUP))?; + Ok(toast) +} + +/// The toast's content: the title, the artist and album, and the cover where there is one. +fn toast_xml(title: &str, body: &str, image: Option<&Path>) -> String { + let body = match body.is_empty() { + true => String::new(), + false => format!("{}", escape(body)), + }; + let image = match image { + Some(path) => { + let path = path.display().to_string().replace('\\', "/"); + format!(r#""#) + } + None => String::new(), + }; + format!( + "{}{body}{image}", + escape(title) + ) +} + +/// XML reads `&` and `<` as markup, so text that may hold them is escaped first. +fn escape(text: &str) -> String { + text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escapes_what_looks_like_markup() { + assert_eq!(escape("Simon & Garfunkel "), "Simon & Garfunkel <live>"); + assert_eq!(escape(r#"a "quoted" 'name'"#), "a "quoted" 'name'"); + } + + #[test] + fn puts_the_cover_and_the_text_in_the_toast() { + let cover = Path::new(r"C:\Users\sam\cloofy\cover.jpg"); + let xml = toast_xml("Strobe", "deadmau5 · For Lack of a Better Name", Some(cover)); + assert!(xml.starts_with("")); + assert!(xml.contains("Strobe")); + assert!(xml.contains("deadmau5 · For Lack of a Better Name")); + assert!(xml.contains(r#""#)); + let xml = toast_xml("Strobe", "", None); + assert_eq!(xml.matches("").count(), 1, "no empty line without an album:\n{xml}"); + assert!(!xml.contains("; + +pub fn watch(on_event: Callback) -> bool { + let context: *mut Callback = Box::into_raw(Box::new(on_event)); + // The system reads the parameters until the subscription ends, which is when the process + // does, so neither they nor the context are ever freed. + let parameters = Box::into_raw(Box::new(DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS { + Callback: Some(callback), + Context: context.cast(), + })); + // SAFETY: as above: what the handle points at outlives every call the system may make. + match unsafe { RegisterSuspendResumeNotification(HANDLE(parameters.cast()), DEVICE_NOTIFY_CALLBACK) } { + Ok(_) => true, + Err(err) => { + tracing::warn!("cannot watch for sleep and wake: {err}"); + false + } + } +} + +/// `DEVICE_NOTIFY_CALLBACK_ROUTINE`: runs on a thread of the system's. +unsafe extern "system" fn callback(context: *const c_void, notification: u32, _setting: *const c_void) -> u32 { + // SAFETY: `context` is the `Arc` that `watch` leaked, which outlives the subscription. + let on_event = unsafe { &*context.cast::() }; + match notification { + PBT_APMSUSPEND => on_event(Event::Sleep), + PBT_APMRESUMEAUTOMATIC => on_event(Event::Wake), + _ => {} + } + // ERROR_SUCCESS: whatever it does next may carry on. + 0 +} diff --git a/crates/cloofy-os/src/windows/secrets.rs b/crates/cloofy-os/src/windows/secrets.rs new file mode 100644 index 0000000..88c6405 --- /dev/null +++ b/crates/cloofy-os/src/windows/secrets.rs @@ -0,0 +1,110 @@ +//! Generic credentials in Windows' Credential Manager, under the target "cloofy:". +//! +//! A credential holds 2560 bytes at most; anything longer is refused, and cloofy keeps such a +//! secret in a file instead. + +use std::{ffi::c_void, io, ptr}; + +use windows::{ + Win32::{ + Foundation::ERROR_NOT_FOUND, + Security::Credentials::{ + CRED_PERSIST_LOCAL_MACHINE, CRED_TYPE_GENERIC, CREDENTIALW, CredDeleteW, CredFree, CredReadW, CredWriteW, + }, + }, + core::{HRESULT, PCWSTR, PWSTR}, +}; + +pub const AVAILABLE: bool = true; + +/// The longest secret Credential Manager takes, in bytes. +const MAX_LEN: usize = 2560; + +fn target(name: &str) -> Vec { + format!("cloofy:{name}").encode_utf16().chain(Some(0)).collect() +} + +pub fn get(name: &str) -> io::Result>> { + let target = target(name); + let mut credential: *mut CREDENTIALW = ptr::null_mut(); + // SAFETY: the target outlives the call, and what the call hands back is freed below. + if let Err(err) = unsafe { CredReadW(PCWSTR(target.as_ptr()), CRED_TYPE_GENERIC, None, &mut credential) } { + return match err.code() == HRESULT::from_win32(ERROR_NOT_FOUND.0) { + true => Ok(None), + false => Err(io::Error::other(err)), + }; + } + // SAFETY: a successful read hands back one credential, and an empty blob is no pointer at all. + let secret = unsafe { + let credential = &*credential; + let secret = match credential.CredentialBlobSize { + 0 => Vec::new(), + len => std::slice::from_raw_parts(credential.CredentialBlob, len as usize).to_vec(), + }; + CredFree(credential as *const CREDENTIALW as *const c_void); + secret + }; + Ok(Some(secret)) +} + +pub fn set(name: &str, secret: &[u8]) -> io::Result<()> { + check_len(secret)?; + let mut target = target(name); + let credential = CREDENTIALW { + Type: CRED_TYPE_GENERIC, + TargetName: PWSTR(target.as_mut_ptr()), + CredentialBlobSize: secret.len() as u32, + // The call copies the blob, it doesn't write through it. + CredentialBlob: secret.as_ptr().cast_mut(), + Persist: CRED_PERSIST_LOCAL_MACHINE, + ..Default::default() + }; + // SAFETY: every pointer in the credential points at memory that outlives the call. + unsafe { CredWriteW(&credential, 0) }.map_err(io::Error::other) +} + +pub fn delete(name: &str) -> io::Result<()> { + let target = target(name); + // SAFETY: the target outlives the call. + match unsafe { CredDeleteW(PCWSTR(target.as_ptr()), CRED_TYPE_GENERIC, None) } { + Err(err) if err.code() != HRESULT::from_win32(ERROR_NOT_FOUND.0) => Err(io::Error::other(err)), + _ => Ok(()), + } +} + +/// Refuses a secret Credential Manager can't hold, so the caller can keep it elsewhere. +fn check_len(secret: &[u8]) -> io::Result<()> { + match secret.len() <= MAX_LEN { + true => Ok(()), + false => Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Credential Manager holds {MAX_LEN} bytes at most"), + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_a_secret_that_does_not_fit() { + assert!(check_len(&[0; MAX_LEN]).is_ok()); + assert_eq!(check_len(&[0; MAX_LEN + 1]).unwrap_err().kind(), io::ErrorKind::InvalidInput); + } + + /// Writes to the user's credential store, which the tests shouldn't: run it by hand with + /// `cargo test -p cloofy-os -- --ignored`. + #[test] + #[ignore = "uses the credential store"] + fn keeps_and_forgets_a_secret() { + let name = format!("test-{}", std::process::id()); + assert_eq!(get(&name).unwrap(), None); + set(&name, b"one").unwrap(); + set(&name, b"two").unwrap(); + assert_eq!(get(&name).unwrap().as_deref(), Some(&b"two"[..])); + delete(&name).unwrap(); + delete(&name).unwrap(); + assert_eq!(get(&name).unwrap(), None); + } +} diff --git a/crates/cloofy-os/src/windows/settings.rs b/crates/cloofy-os/src/windows/settings.rs new file mode 100644 index 0000000..e743675 --- /dev/null +++ b/crates/cloofy-os/src/windows/settings.rs @@ -0,0 +1,49 @@ +//! The settings cloofy follows: the animation switch and the battery saver of the system. + +use std::ffi::c_void; + +use windows::Win32::{ + System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS}, + UI::WindowsAndMessaging::{SPI_GETCLIENTAREAANIMATION, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW}, +}; +use windows::core::BOOL; + +use crate::settings::Settings; + +pub fn current() -> Settings { + let mut animations = BOOL(1); + // SAFETY: `SPI_GETCLIENTAREAANIMATION` writes one `BOOL` into the pointer it is given. + let animations = unsafe { + SystemParametersInfoW( + SPI_GETCLIENTAREAANIMATION, + 0, + Some(&mut animations as *mut BOOL as *mut c_void), + SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0), + ) + } + .map(|()| animations.as_bool()) + .unwrap_or(true); + let mut status = SYSTEM_POWER_STATUS::default(); + // SAFETY: the call fills in the status it is given, whose size it knows. + let saving = unsafe { GetSystemPowerStatus(&mut status) }.is_ok() && status.SystemStatusFlag == 1; + settings(animations, saving) +} + +/// The two readings as the settings: without animations there is less motion, and while the +/// battery saver runs the system is saving energy. +fn settings(animations: bool, saving: bool) -> Settings { + Settings { reduce_motion: !animations, low_power: saving } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_both_switches() { + assert_eq!(settings(true, false), Settings::default(), "animations on, no battery saver"); + let hidden = settings(false, true); + assert!(hidden.reduce_motion); + assert!(hidden.low_power); + } +} diff --git a/crates/cloofy-tui/src/app/mod.rs b/crates/cloofy-tui/src/app/mod.rs index 69467a8..2b681f6 100644 --- a/crates/cloofy-tui/src/app/mod.rs +++ b/crates/cloofy-tui/src/app/mod.rs @@ -23,7 +23,7 @@ use cloofy_core::{ lyrics::Lyrics, paths::Paths, player::{CurrentTrack, PlayerEvent}, - update::{PackageManager, Release}, + update::{self, PackageManager, Release}, }; use cloofy_os::settings::Settings; use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; @@ -152,6 +152,8 @@ pub enum Update { release: Release, manager: PackageManager, }, + /// Out, but this system has no prebuilt build to download; the user updates it by building. + Unsupported(Release), /// Downloading, with the percentage once the size is known. Installing { release: Release, @@ -171,6 +173,12 @@ fn managed_update(release: &Release, manager: PackageManager) -> String { format!("cloofy {} is out · {}", release.version(), manager.how_to_update(variant)) } +/// That `release` is out, where there is no build for this system to download: updating it means +/// building it here. +fn unsupported_update(release: &Release) -> String { + format!("cloofy {} is out · update by building it here", release.version()) +} + /// Reduced motion and low power as the system has them; all off in tests, whatever the machine. fn system_settings() -> Settings { if cfg!(test) { Settings::default() } else { cloofy_os::settings::current() } @@ -934,6 +942,9 @@ impl App { } let update = match PackageManager::of_running() { Some(manager) => Update::Managed { release, manager }, + // A system without a build to download says how to update, instead of failing when + // the button is pressed. + None if !update::supported() => Update::Unsupported(release), None => Update::Available(release), }; if self.update.as_ref() != Some(&update) { @@ -947,6 +958,7 @@ impl App { match update { Update::Available(release) => self.notice(format!("cloofy {} is out · U updates", release.version())), Update::Managed { release, manager } => self.notice(managed_update(release, *manager)), + Update::Unsupported(release) => self.notice(unsupported_update(release)), Update::Installing { .. } | Update::Installed { .. } => {} } } @@ -961,6 +973,7 @@ impl App { self.check_for_update(true); } Some(update @ Update::Managed { .. }) => self.announce(&update), + Some(update @ Update::Unsupported(_)) => self.announce(&update), Some(Update::Available(release)) => { self.notice(format!("Updating to cloofy {}…", release.version())); self.loader.install_update(release.clone()); @@ -980,6 +993,7 @@ impl App { None => Command::Update.label().to_owned(), Some(Update::Available(release)) => format!("Update to cloofy {}", release.version()), Some(Update::Managed { release, manager }) => managed_update(release, *manager), + Some(Update::Unsupported(release)) => unsupported_update(release), Some(Update::Installing { .. }) => "Updating cloofy…".to_owned(), Some(Update::Installed { release, .. }) => format!("Restart into cloofy {}", release.version()), } diff --git a/crates/cloofy-tui/src/notify.rs b/crates/cloofy-tui/src/notify.rs index 2619f89..f0f8d6d 100644 --- a/crates/cloofy-tui/src/notify.rs +++ b/crates/cloofy-tui/src/notify.rs @@ -1,8 +1,8 @@ //! Desktop notifications for new tracks while cloofy's window is in the background. They go //! through the terminal's own escape sequence, so they need no permission of their own and a -//! click leads back to the terminal. On Linux they go to the desktop directly in terminals -//! without notifications of their own, and on Hyprland in all of them: the desktop shows the -//! cover with them, and there a click brings cloofy's window to the front. +//! click leads back to the terminal. On Linux and Windows they go to the desktop directly in +//! terminals without notifications of their own, and on Hyprland in all of them: the desktop +//! shows the cover with them, and on Hyprland a click brings cloofy's window to the front. use std::{sync::Arc, time::Duration}; @@ -41,19 +41,19 @@ enum Channel { }, /// The desktop's notification server: its notifications show the cover, and on Hyprland a /// click on one brings cloofy's window to the front. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "windows"))] Desktop(cloofy_os::notifications::Notifications), } impl Notifier { - /// The terminal's notifications, or the desktop's on Linux where they do better. `None` - /// without either. + /// The terminal's notifications, or the desktop's on Linux and Windows, where they do + /// better. `None` without either. pub fn detect() -> Option { let terminal = Protocol::detect().map(|protocol| Channel::Terminal { protocol, tmux: set("TMUX") }); // A click on the terminal's notification brings its window to the front, which only // Hyprland lets cloofy do for the desktop's. Over SSH the desktop's session bus belongs // to another computer, whose screen nobody is looking at. - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "windows"))] if (terminal.is_none() || cloofy_os::notifications::click_raises()) && !set("SSH_CONNECTION") && let Some(desktop) = cloofy_os::notifications::Notifications::new() @@ -103,11 +103,11 @@ impl Notifier { } } - #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] + #[cfg_attr(not(any(target_os = "linux", target_os = "windows")), allow(unused_variables))] fn announce(&self, track: &CurrentTrack, artwork: Option<&Arc<[u8]>>) -> Option { match &self.channel { Channel::Terminal { protocol, tmux } => Some(sequence(*protocol, *tmux, &track.name, &byline(track))), - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "windows"))] Channel::Desktop(desktop) => { desktop.show(&track.name, &byline(track), artwork.cloned()); None diff --git a/crates/cloofy-tui/src/scenarios.rs b/crates/cloofy-tui/src/scenarios.rs index a4f92a6..97e0021 100644 --- a/crates/cloofy-tui/src/scenarios.rs +++ b/crates/cloofy-tui/src/scenarios.rs @@ -6,12 +6,30 @@ use std::time::Duration; use crossterm::event::KeyCode::{self, Char, Down, Enter, Esc}; +use crate::app::AppEvent; use crate::harness::Harness; +use crate::loader::DataEvent; mod playback; const DEBOUNCE: Duration = Duration::from_millis(250); +/// Windows has no build of a new release to download, so the top bar says what's out, and +/// U says how to update without asking GitHub again. +#[cfg(target_os = "windows")] +#[tokio::test] +async fn an_update_says_to_build_it_here() { + let mut h = Harness::demo().await; + let release = cloofy_core::update::Release { tag: "v99.0.0".into() }; + h.app.on_event(AppEvent::Data(DataEvent::UpdateAvailable(release))); + h.settle().await; + let said = "cloofy 99.0.0 is out · update by building it here"; + assert!(h.shows(said), "{}", h.screen()); + h.press(Char('U')).await; + assert!(h.shows(said), "{}", h.screen()); + assert!(!h.shows("Looking for updates"), "pressing U doesn't ask again"); +} + #[tokio::test] async fn starts_at_home() { let h = Harness::demo().await; diff --git a/crates/cloofy-tui/src/ui/topbar.rs b/crates/cloofy-tui/src/ui/topbar.rs index 42b23cb..a863048 100644 --- a/crates/cloofy-tui/src/ui/topbar.rs +++ b/crates/cloofy-tui/src/ui/topbar.rs @@ -98,6 +98,10 @@ fn update_button(buf: &mut Buffer, app: &mut App, right: u16, y: u16, padding: u Update::Managed { release, .. } => { (icons().update, [format!("v{} is out", release.version()), format!("v{}", release.version())]) } + // Nothing to download here either: the button says what's out, and a click how to update. + Update::Unsupported(release) => { + (icons().update, [format!("v{} is out", release.version()), format!("v{}", release.version())]) + } Update::Installing { percent, .. } => { let percent = percent.map(|percent| format!("{percent}%")).unwrap_or_default(); (text::spinner(app.frame()), [format!("Updating {percent}").trim_end().to_owned(), percent]) diff --git a/crates/cloofy-ytmusic/src/auth.rs b/crates/cloofy-ytmusic/src/auth.rs index 8d2f835..15b7c6a 100644 --- a/crates/cloofy-ytmusic/src/auth.rs +++ b/crates/cloofy-ytmusic/src/auth.rs @@ -49,6 +49,8 @@ const fn known(ids: &'static [&'static str], name: &'static str, reader: &'stati Known { ids, name, reader, dir, fork: false } } +/// Browsers whose profiles yt-dlp reads as another's, on systems with such forks. +#[cfg(not(windows))] const fn fork(ids: &'static [&'static str], name: &'static str, reader: &'static str, dir: &'static str) -> Known { Known { ids, name, reader, dir, fork: true } } @@ -71,7 +73,7 @@ const KNOWN: &[Known] = &[ "Library/Application Support/librewolf", ), ]; -#[cfg(not(target_os = "macos"))] +#[cfg(all(not(target_os = "macos"), not(windows)))] const KNOWN: &[Known] = &[ known(&["chromium.desktop", "chromium-browser.desktop"], "Chromium", "chromium", ".config/chromium"), known(&["brave-browser.desktop", "brave.desktop"], "Brave", "brave", ".config/BraveSoftware/Brave-Browser"), @@ -87,19 +89,29 @@ const KNOWN: &[Known] = &[ fork(&["librewolf.desktop"], "LibreWolf", "firefox", ".librewolf"), fork(&["floorp.desktop"], "Floorp", "firefox", ".floorp"), ]; +/// Chromium-based browsers keep their profiles in the local app data folder, Firefox in the +/// roaming one, which `homes` searches. +#[cfg(windows)] +const KNOWN: &[Known] = &[ + known(&[], "Google Chrome", "chrome", "Google/Chrome/User Data"), + known(&[], "Chromium", "chromium", "Chromium/User Data"), + known(&[], "Microsoft Edge", "edge", "Microsoft/Edge/User Data"), + known(&[], "Brave", "brave", "BraveSoftware/Brave-Browser/User Data"), + known(&[], "Vivaldi", "vivaldi", "Vivaldi/User Data"), + known(&[], "Firefox", "firefox", "Mozilla/Firefox"), +]; impl Known { - /// The browser, when it has a profile in its folder: a folder alone may be left over, or + /// The browser, when it has a profile in one of `homes`: a folder alone may be left over, or /// made by another program. - fn found(&self, home: &Path) -> Option { - let dir = home.join(self.dir); - let profile = match self.reader { + fn found(&self, homes: &[PathBuf]) -> Option { + let dir = homes.iter().map(|home| home.join(self.dir)).find(|dir| match self.reader { "firefox" => dir.join("profiles.ini").is_file(), "safari" => dir.is_dir(), _ => dir.join("Local State").is_file(), - }; + })?; let spec = if self.fork { format!("{}:{}", self.reader, dir.display()) } else { self.reader.into() }; - profile.then(|| Browser { name: self.name.into(), spec }) + Some(Browser { name: self.name.into(), spec }) } } @@ -115,15 +127,23 @@ const ADD_ACCOUNT_URL: &str = "https://accounts.google.com/AddSession?service=yo /// yt-dlp exports the cookies of every site; this many seconds is plenty for that. const EXPORT_TIMEOUT: Duration = Duration::from_secs(120); -fn home() -> Option { - std::env::var_os("HOME").map(PathBuf::from) +/// The folders browsers keep their profiles in. Chromium-based ones and Firefox split between +/// the local and the roaming app data folders on Windows; elsewhere they are all under home. +#[cfg(not(windows))] +fn homes() -> Vec { + std::env::var_os("HOME").map(PathBuf::from).into_iter().collect() +} + +#[cfg(windows)] +fn homes() -> Vec { + ["LOCALAPPDATA", "APPDATA"].into_iter().filter_map(std::env::var_os).map(PathBuf::from).collect() } /// The browsers on this computer that have a profile yt-dlp could read cookies from. pub fn browsers() -> Vec { - let Some(home) = home() else { return Vec::new() }; + let homes = homes(); let mut found: Vec = Vec::new(); - for browser in KNOWN.iter().filter_map(|known| known.found(&home)) { + for browser in KNOWN.iter().filter_map(|known| known.found(&homes)) { if !found.iter().any(|b| b.name == browser.name) { found.push(browser); } @@ -134,12 +154,12 @@ pub fn browsers() -> Vec { /// The browser that opens links, when cloofy knows it and it has a profile. pub fn default_browser() -> Option { let id = default_browser_id()?; - let home = home()?; - KNOWN.iter().filter(|known| known.ids.contains(&id.as_str())).find_map(|known| known.found(&home)) + let homes = homes(); + KNOWN.iter().filter(|known| known.ids.contains(&id.as_str())).find_map(|known| known.found(&homes)) } /// The desktop entry of the browser that opens links. -#[cfg(not(target_os = "macos"))] +#[cfg(all(not(target_os = "macos"), not(windows)))] fn default_browser_id() -> Option { // Omarchy's own entry only hands links on to the browser it names. let asks: [(&str, &[&str]); 3] = [ @@ -154,10 +174,18 @@ fn default_browser_id() -> Option { }) } +/// The browser that opens links is left out on Windows: telling it means the registry's +/// per-user choice, which cloofy doesn't read yet, so the sign-in asks which browser. +#[cfg(windows)] +fn default_browser_id() -> Option { + None +} + /// The bundle id of the app that opens https links; Safari unless another was picked. #[cfg(target_os = "macos")] fn default_browser_id() -> Option { - let plist = home()?.join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"); + let plist = + homes().first()?.join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"); let handlers = std::process::Command::new("plutil") .args(["-extract", "LSHandlers", "json", "-o", "-"]) .arg(plist) @@ -508,24 +536,54 @@ mod tests { let home = std::env::temp_dir().join(format!("cloofy-ytm-browsers-{}", std::process::id())); let _ = fs::remove_dir_all(&home); let chromium = known(&[], "Chromium", "chromium", "chromium"); - let origin = fork(&[], "Brave Origin", "brave", "Brave-Origin"); let firefox = known(&[], "Firefox", "firefox", "firefox"); + let homes = [home.clone()]; // Folders another program left, without a profile. fs::create_dir_all(home.join("chromium/NativeMessagingHosts")).unwrap(); fs::create_dir_all(home.join("firefox")).unwrap(); - assert_eq!(chromium.found(&home), None); - assert_eq!(firefox.found(&home), None); + assert_eq!(chromium.found(&homes), None); + assert_eq!(firefox.found(&homes), None); fs::write(home.join("chromium/Local State"), "{}").unwrap(); fs::write(home.join("firefox/profiles.ini"), "").unwrap(); - assert_eq!(chromium.found(&home).unwrap().spec, "chromium"); - assert_eq!(firefox.found(&home).unwrap().spec, "firefox"); + assert_eq!(chromium.found(&homes).unwrap().spec, "chromium"); + assert_eq!(firefox.found(&homes).unwrap().spec, "firefox"); // yt-dlp doesn't know forks, so it gets their folder. - fs::create_dir_all(home.join("Brave-Origin")).unwrap(); - fs::write(home.join("Brave-Origin/Local State"), "{}").unwrap(); - assert_eq!(origin.found(&home).unwrap().spec, format!("brave:{}", home.join("Brave-Origin").display())); + #[cfg(not(windows))] + { + let origin = fork(&[], "Brave Origin", "brave", "Brave-Origin"); + fs::create_dir_all(home.join("Brave-Origin")).unwrap(); + fs::write(home.join("Brave-Origin/Local State"), "{}").unwrap(); + assert_eq!(origin.found(&homes).unwrap().spec, format!("brave:{}", home.join("Brave-Origin").display())); + } fs::remove_dir_all(&home).unwrap(); } + /// Windows keeps Chromium-based browsers' profiles in the local app data folder, and + /// Firefox's in the roaming one. + #[cfg(windows)] + #[test] + fn finds_the_windows_browsers_with_a_profile() { + let root = std::env::temp_dir().join(format!("cloofy-ytm-windows-browsers-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (local, roaming) = (root.join("local"), root.join("roaming")); + let chrome = known(&[], "Google Chrome", "chrome", "Google/Chrome/User Data"); + let firefox = known(&[], "Firefox", "firefox", "Mozilla/Firefox"); + let homes = [local.clone(), roaming.clone()]; + + // A folder alone, without the Local State or profiles.ini a real profile has. + fs::create_dir_all(local.join("Google/Chrome/User Data/Default")).unwrap(); + fs::create_dir_all(roaming.join("Mozilla/Firefox/Profiles/x")).unwrap(); + assert_eq!(chrome.found(&homes), None); + assert_eq!(firefox.found(&homes), None); + + fs::write(local.join("Google/Chrome/User Data/Local State"), "{}").unwrap(); + fs::write(roaming.join("Mozilla/Firefox/profiles.ini"), "").unwrap(); + fs::write(roaming.join("Mozilla/Firefox/Profiles/x/cookies.sqlite"), "").unwrap(); + assert_eq!(chrome.found(&homes).unwrap().spec, "chrome"); + assert_eq!(firefox.found(&homes).unwrap().spec, "firefox"); + fs::remove_dir_all(&root).unwrap(); + } + #[test] fn names_the_keyring_before_the_profiles() { assert_eq!(with_keyring("chromium", "gnomekeyring"), "chromium+gnomekeyring"); diff --git a/crates/cloofy-ytmusic/src/player/mod.rs b/crates/cloofy-ytmusic/src/player/mod.rs index 96e1cb5..425a238 100644 --- a/crates/cloofy-ytmusic/src/player/mod.rs +++ b/crates/cloofy-ytmusic/src/player/mod.rs @@ -1257,6 +1257,8 @@ mod tests { assert!(filters(&mut engine).await.is_empty()); } + /// Unix only: what mpv holds up needs a FIFO nothing writes to. + #[cfg(unix)] #[tokio::test] async fn a_seek_mpv_turns_down_holds_nothing_back() { let Some((mut engine, (mut events, _))) = engine("seek").await else { return }; diff --git a/crates/cloofy-ytmusic/src/player/mpv.rs b/crates/cloofy-ytmusic/src/player/mpv.rs index e24dfd6..191c494 100644 --- a/crates/cloofy-ytmusic/src/player/mpv.rs +++ b/crates/cloofy-ytmusic/src/player/mpv.rs @@ -3,13 +3,13 @@ //! The IPC runs over one end of a socket pair that mpv inherits (`--input-ipc-client=fd://N`) //! instead of a socket file: mpv quits by itself once that connection closes, which happens //! when cloofy exits in any way, a crash or `kill -9` included. No mpv is left behind playing. +//! +//! Windows has no socket pair to hand over, so there mpv serves its IPC on a named pipe of its +//! own (`--input-ipc-server`). mpv doesn't quit when that pipe's client goes away, so stopping it +//! relies on `kill_on_drop` and [`Mpv::quit`]; the pipe disappears with its handle. use std::{ collections::HashMap, - os::{ - fd::{AsRawFd, RawFd}, - unix::net::UnixStream as StdStream, - }, process::Stdio, sync::{ Arc, Mutex, @@ -21,15 +21,41 @@ use std::{ use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use tokio::{ - io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, - net::{UnixStream, unix::OwnedWriteHalf}, + io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}, process::{Child, Command}, sync::{mpsc::UnboundedSender, oneshot}, }; +#[cfg(unix)] +use std::os::{ + fd::{AsRawFd, RawFd}, + unix::net::UnixStream as StdStream, +}; +#[cfg(unix)] +use tokio::net::UnixStream; +#[cfg(windows)] +use tokio::net::windows::named_pipe::ClientOptions; + /// Waits this long for mpv to answer a command. const REPLY_TIMEOUT: Duration = Duration::from_secs(5); +/// How long mpv may take to serve the pipe it was told to create. Starting is a few +/// milliseconds even with a cold disk; waiting longer only delays the complaint about an mpv +/// that never got there. +#[cfg(windows)] +const PIPE_DEADLINE: Duration = Duration::from_secs(2); +/// Between attempts to open that pipe, for the moment mpv takes to create it. +#[cfg(windows)] +const PIPE_RETRY: Duration = Duration::from_millis(10); +/// Keeps mpv, a console program, from flashing a window of its own. +#[cfg(windows)] +const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +/// The read end of mpv's IPC, which [`read`] takes over. +type ReadEnd = Box; +/// The write end, which [`Mpv`] keeps to send commands. +type WriteEnd = Box; + /// Properties observed, by the ID mpv reports them with. pub(crate) const TIME_POS: u64 = 1; pub(crate) const PAUSE: u64 = 2; @@ -61,7 +87,7 @@ pub(crate) struct Mpv { /// Which mpv this is, as its events say. pub instance: u64, child: Child, - writer: OwnedWriteHalf, + writer: WriteEnd, pending: Pending, next_id: u64, /// `loadfile` takes options as its fourth argument since mpv 0.38, as its third before. @@ -71,8 +97,6 @@ pub(crate) struct Mpv { impl Mpv { pub async fn spawn(args: &[String], events: Events) -> Result { let instance = INSTANCES.fetch_add(1, Ordering::Relaxed) + 1; - let (ours, theirs) = StdStream::pair().context("Can't create a socket for mpv")?; - let fd = theirs.as_raw_fd(); let mut command = Command::new("mpv"); command .args([ @@ -100,16 +124,12 @@ impl Mpv { "--keep-open=no", "--msg-level=all=error", ]) - .arg(format!("--input-ipc-client=fd://{fd}")) .args(args) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .kill_on_drop(true); - // SAFETY: only async-signal-safe calls between fork and exec. - unsafe { - command.pre_exec(move || inherit(fd)); - } + let ipc = Ipc::new(&mut command, instance)?; let mut child = match command.spawn() { Ok(child) => child, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { @@ -117,7 +137,6 @@ impl Mpv { } Err(err) => return Err(err).context("Can't start mpv"), }; - drop(theirs); // mpv only prints errors; the last one explains a failed start. let last_error: Arc>> = Arc::default(); if let Some(stderr) = child.stderr.take() { @@ -130,18 +149,16 @@ impl Mpv { } }); } - ours.set_nonblocking(true)?; - let (reader, writer) = UnixStream::from_std(ours)?.into_split(); + let (reader, writer) = match ipc.connect().await { + Ok(pair) => pair, + Err(err) => return Err(start_error(&mut child, &last_error, err).await), + }; let pending: Pending = Arc::default(); tokio::spawn(read(reader, pending.clone(), instance, events)); let mut mpv = Mpv { instance, child, writer, pending, next_id: 0, legacy_loadfile: false }; let version = match mpv.get("mpv-version").await { Ok(version) => version, - Err(err) => { - let _ = tokio::time::timeout(Duration::from_secs(1), mpv.child.wait()).await; - let reason = last_error.lock().unwrap().take(); - return Err(err.context(reason.unwrap_or_else(|| "mpv didn't start".into()))); - } + Err(err) => return Err(start_error(&mut mpv.child, &last_error, err).await), }; mpv.legacy_loadfile = version.as_str().is_some_and(older_than_0_38); for (id, name) in [(TIME_POS, "time-pos"), (PAUSE, "pause"), (DURATION, "duration")] { @@ -203,6 +220,81 @@ impl Mpv { } } +/// Why mpv failed to start, with the last line it printed before it did. +async fn start_error(child: &mut Child, last_error: &Mutex>, err: anyhow::Error) -> anyhow::Error { + let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await; + let reason = last_error.lock().unwrap().take(); + err.context(reason.unwrap_or_else(|| "mpv didn't start".into())) +} + +/// mpv's end of the IPC, which differs by platform: a socket pair cloofy passes as a descriptor, +/// or a named pipe mpv creates once it runs. +#[cfg(unix)] +struct Ipc { + ours: StdStream, + /// Never read here, just held open until mpv has inherited it; then dropped, so cloofy keeps + /// no copy of mpv's end and a gone mpv reads as end of file. + theirs: StdStream, +} + +#[cfg(unix)] +impl Ipc { + fn new(command: &mut Command, _instance: u64) -> Result { + let (ours, theirs) = StdStream::pair().context("Can't create a socket for mpv")?; + let fd = theirs.as_raw_fd(); + command.arg(format!("--input-ipc-client=fd://{fd}")); + // SAFETY: only async-signal-safe calls between fork and exec. + unsafe { + command.pre_exec(move || inherit(fd)); + } + Ok(Self { ours, theirs }) + } + + async fn connect(self) -> Result<(ReadEnd, WriteEnd)> { + drop(self.theirs); + self.ours.set_nonblocking(true)?; + let (reader, writer) = UnixStream::from_std(self.ours)?.into_split(); + Ok((Box::new(reader), Box::new(writer))) + } +} + +/// The pipe mpv serves its IPC on. The process ID keeps cloofy's own mpvs apart, the instance +/// every mpv of this process, so two cloofys or two restarts never meet on one pipe. +#[cfg(windows)] +fn pipe_name(instance: u64) -> String { + format!(r"\\.\pipe\cloofy-{}-{instance}", std::process::id()) +} + +#[cfg(windows)] +struct Ipc(String); + +#[cfg(windows)] +impl Ipc { + fn new(command: &mut Command, instance: u64) -> Result { + let name = pipe_name(instance); + command.arg(format!("--input-ipc-server={name}")).creation_flags(CREATE_NO_WINDOW); + Ok(Self(name)) + } + + /// Opens the pipe mpv creates. It exists only a few milliseconds after mpv starts, so the + /// first attempt is expected to find nothing. + async fn connect(self) -> Result<(ReadEnd, WriteEnd)> { + let deadline = tokio::time::Instant::now() + PIPE_DEADLINE; + loop { + match ClientOptions::new().open(&self.0) { + Ok(stream) => { + let (reader, writer) = tokio::io::split(stream); + return Ok((Box::new(reader), Box::new(writer))); + } + Err(err) if tokio::time::Instant::now() >= deadline => { + return Err(err).context("Can't connect to mpv's pipe"); + } + Err(_) => tokio::time::sleep(PIPE_RETRY).await, + } + } + } +} + /// The options of a `loadfile`: where to start, and the title mixers and the window show. mpv /// takes `%%` before a value as its quoting, so a title may have commas and `=`. fn load_options(start: Option, title: &str) -> String { @@ -214,6 +306,7 @@ fn load_options(start: Option, title: &str) -> String { } /// Runs in the child before mpv starts: keeps mpv's end of the socket open across exec. +#[cfg(unix)] fn inherit(fd: RawFd) -> std::io::Result<()> { // SAFETY: fcntl on a descriptor this process owns. if unsafe { libc::fcntl(fd, libc::F_SETFD, 0) } == -1 { @@ -222,7 +315,7 @@ fn inherit(fd: RawFd) -> std::io::Result<()> { Ok(()) } -async fn read(reader: tokio::net::unix::OwnedReadHalf, pending: Pending, instance: u64, events: Events) { +async fn read(reader: impl AsyncRead + Unpin + Send + 'static, pending: Pending, instance: u64, events: Events) { let mut lines = BufReader::new(reader).lines(); while let Ok(Some(line)) = lines.next_line().await { let Ok(message) = serde_json::from_str::(&line) else { continue }; @@ -308,4 +401,14 @@ mod tests { assert_eq!(parse_event(&event), Some(MpvEvent::Property { id: 1, data: json!(1.5) })); assert_eq!(parse_event(&json!({ "event": "audio-reconfig" })), None); } + + /// Two mpvs must not meet on one pipe, nor must two cloofys. + #[test] + #[cfg(windows)] + fn names_a_pipe_of_its_own() { + let first = pipe_name(1); + assert!(first.starts_with(r"\\.\pipe\cloofy-"), "{first}"); + assert!(first.contains(&std::process::id().to_string()), "{first}"); + assert_ne!(pipe_name(1), pipe_name(2)); + } } diff --git a/crates/cloofy/Cargo.toml b/crates/cloofy/Cargo.toml index 8a33ef0..2ce1ee3 100644 --- a/crates/cloofy/Cargo.toml +++ b/crates/cloofy/Cargo.toml @@ -38,6 +38,19 @@ tracing-subscriber.workspace = true serde.workspace = true unicode-width.workspace = true +# The Start Menu shortcut that Windows shows cloofy's notifications under. +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Storage_EnhancedStorage", + "Win32_Storage_FileSystem", + "Win32_System_Com", + "Win32_System_Com_StructuredStorage", + "Win32_System_Variant", + "Win32_UI_Shell", + "Win32_UI_Shell_PropertiesSystem", +] } + # Looks up the sample's songs on Spotify. [[example]] name = "demo_fixture" diff --git a/crates/cloofy/src/main.rs b/crates/cloofy/src/main.rs index 84051ce..68c8d0d 100644 --- a/crates/cloofy/src/main.rs +++ b/crates/cloofy/src/main.rs @@ -20,6 +20,8 @@ mod prompt; mod spotify; mod style; mod update; +#[cfg(target_os = "windows")] +mod windows; #[cfg(feature = "ytmusic")] mod ytmusic; @@ -109,6 +111,12 @@ enum Command { #[command(subcommand)] action: omarchy::Action, }, + /// Put cloofy in the Start Menu, which Windows needs for its notifications + #[cfg(target_os = "windows")] + Windows { + #[command(subcommand)] + action: windows::Action, + }, } /// The version and the music services built in, like `0.4.0 (spotify)`. The installer reads @@ -193,6 +201,8 @@ async fn run() -> Result<()> { Some(Command::Launcher { action }) => launcher::run(action), #[cfg(target_os = "linux")] Some(Command::Omarchy { action }) => omarchy::run(action), + #[cfg(target_os = "windows")] + Some(Command::Windows { action }) => windows::run(action), None => update::restart_if_asked(cloofy_tui::run(&paths).await?), } } diff --git a/crates/cloofy/src/windows.rs b/crates/cloofy/src/windows.rs new file mode 100644 index 0000000..e261669 --- /dev/null +++ b/crates/cloofy/src/windows.rs @@ -0,0 +1,219 @@ +//! `cloofy windows`: the Start Menu shortcut whose AppUserModelID Windows shows cloofy's toasts +//! under, and without which it shows none. + +use std::{env, fs, io, path::Path, process}; + +use anyhow::{Context, Result}; +use clap::Subcommand; +use cloofy_os::{AUMID, shortcut_path}; +use windows::{ + Win32::{ + Storage::EnhancedStorage::PKEY_AppUserModel_ID, + System::{ + Com::{ + CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemAlloc, + IPersistFile, STGM_READ, + StructuredStorage::{PROPVARIANT, PROPVARIANT_0, PROPVARIANT_0_0, PROPVARIANT_0_0_0, PropVariantClear}, + }, + Variant::VT_LPWSTR, + }, + UI::Shell::{IShellLinkW, PropertiesSystem::IPropertyStore, ShellLink}, + }, + core::{HSTRING, Interface, PWSTR}, +}; + +use crate::style; + +/// Windows stores a shortcut's target path in at most `MAX_PATH` characters. +const MAX_PATH: usize = 260; + +/// COM asks every thread which apartment it uses. `run_main` did it for the thread a command runs +/// on, and a test thread needs its own; a second call only says the apartment is already chosen. +fn init_com() { + // SAFETY: no other thread's COM state is touched, and the code only reports a failure. + unsafe { + let _ = CoInitializeEx(None, COINIT_MULTITHREADED); + } +} + +#[derive(Subcommand)] +pub enum Action { + /// Put cloofy in the Start Menu, where Windows finds it for notifications + Install, + /// Show whether that shortcut is there, and where it points + Status, + /// Take that shortcut out again + Remove, +} + +pub fn run(action: Action) -> Result<()> { + let path = shortcut_path().context("APPDATA is not set, so there is no Start Menu to put it in")?; + match action { + Action::Install => install(&path), + Action::Status => status(&path), + Action::Remove => remove(&path), + } +} + +fn install(path: &Path) -> Result<()> { + println!("\n {}\n", style::bold("cloofy for Windows")); + let exe = env::current_exe().context("Can't tell where cloofy is")?; + write_shortcut(path, &exe)?; + ok("Start Menu", &format!("{}, notifications show from it", path.display())); + println!("\n Done. {} takes it out again.\n", style::bold("cloofy windows remove")); + Ok(()) +} + +fn status(path: &Path) -> Result<()> { + println!("\n {}\n", style::bold("cloofy for Windows")); + if !path.is_file() { + skipped("Start Menu", "not installed · `cloofy windows install` adds it"); + println!(); + process::exit(1); + } + let link = open_shortcut(path)?; + let target = target_of(&link).unwrap_or_else(|| "unknown".into()); + let id = aumid_of(&link); + match id.as_deref() { + Some(id) if id == AUMID => ok("Start Menu", &format!("{target}, notifications show")), + // A shortcut without the ID, or with another one, is a toast Windows never shows. + Some(id) => skipped("Start Menu", &format!("{target}, but its AppUserModelID is {id}")), + None => skipped("Start Menu", &format!("{target}, but it has no AppUserModelID")), + } + println!(); + if id.as_deref() != Some(AUMID) { + println!(" {} brings it up to date.\n", style::bold("cloofy windows install")); + process::exit(1); + } + Ok(()) +} + +fn remove(path: &Path) -> Result<()> { + println!("\n {}\n", style::bold("cloofy for Windows")); + match fs::remove_file(path) { + Ok(()) => ok("Start Menu", "removed"), + Err(err) if err.kind() == io::ErrorKind::NotFound => skipped("Start Menu", "it wasn't there"), + Err(err) => return Err(err).with_context(|| format!("Couldn't remove {}", path.display())), + } + println!(); + Ok(()) +} + +/// Writes the shortcut that points at `exe`, with cloofy's AppUserModelID on it. +fn write_shortcut(path: &Path, exe: &Path) -> Result<()> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).with_context(|| format!("Couldn't create {}", dir.display()))?; + } + init_com(); + let link: IShellLinkW = unsafe { CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER) } + .context("Windows didn't give a shortcut to write")?; + // SAFETY: every pointer below points at memory that outlives the call. + unsafe { + link.SetPath(&HSTRING::from(exe)).with_context(|| format!("The shortcut didn't take {}", exe.display()))?; + link.SetDescription(&HSTRING::from("cloofy")).ok(); + let store: IPropertyStore = link.cast().context("The shortcut can't carry properties")?; + let mut id = propvariant(AUMID); + let set = store.SetValue(&PKEY_AppUserModel_ID, &id); + let _ = PropVariantClear(&mut id); + set.context("The shortcut didn't take cloofy's AppUserModelID")?; + store.Commit().context("The shortcut's properties can't be saved")?; + let file: IPersistFile = link.cast().context("The shortcut can't be written")?; + file.Save(&HSTRING::from(path), true).with_context(|| format!("Couldn't write {}", path.display()))?; + } + Ok(()) +} + +/// The shortcut at `path`, read. +fn open_shortcut(path: &Path) -> Result { + init_com(); + let link: IShellLinkW = unsafe { CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER) } + .context("Windows didn't give a shortcut to read")?; + let file: IPersistFile = link.cast().context("Not a shortcut file")?; + // SAFETY: the path outlives the call. + unsafe { file.Load(&HSTRING::from(path), STGM_READ) } + .with_context(|| format!("Couldn't read {}", path.display()))?; + Ok(link) +} + +/// Where the shortcut points. +fn target_of(link: &IShellLinkW) -> Option { + let mut target = [0u16; MAX_PATH]; + // SAFETY: the buffer outlives the call, and no find data is asked for. + unsafe { link.GetPath(&mut target, std::ptr::null_mut(), 0) }.ok()?; + let len = target.iter().position(|&c| c == 0).unwrap_or(target.len()); + Some(String::from_utf16_lossy(&target[..len])) +} + +/// The shortcut's AppUserModelID. +fn aumid_of(link: &IShellLinkW) -> Option { + let store: IPropertyStore = link.cast().ok()?; + let mut value = unsafe { store.GetValue(&PKEY_AppUserModel_ID) }.ok()?; + // SAFETY: the string is read only under the type that makes it one, and freed below. + let id = unsafe { + let value = &*value.Anonymous.Anonymous; + match value.vt == VT_LPWSTR { + true => value.Anonymous.pwszVal.to_string().ok(), + false => None, + } + }; + let _ = unsafe { PropVariantClear(&mut value) }; + id +} + +/// `text` as the property store takes a string: a `VT_LPWSTR` the system's allocator holds, for +/// `PropVariantClear` to free. +fn propvariant(text: &str) -> PROPVARIANT { + let wide: Vec = text.encode_utf16().chain(Some(0)).collect(); + let mut value = PROPVARIANT::default(); + // SAFETY: the memory is allocated by the allocator `PropVariantClear` frees it with. + unsafe { + let memory = CoTaskMemAlloc(wide.len() * size_of::()) as *mut u16; + if memory.is_null() { + return value; + } + std::ptr::copy_nonoverlapping(wide.as_ptr(), memory, wide.len()); + value.Anonymous = PROPVARIANT_0 { + Anonymous: std::mem::ManuallyDrop::new(PROPVARIANT_0_0 { + vt: VT_LPWSTR, + wReserved1: 0, + wReserved2: 0, + wReserved3: 0, + Anonymous: PROPVARIANT_0_0_0 { pwszVal: PWSTR(memory) }, + }), + }; + } + value +} + +fn ok(name: &str, detail: &str) { + println!(" {} {name:<16}{}", style::green("✓"), style::dim(detail)); +} + +fn skipped(name: &str, detail: &str) { + println!(" {}", style::dim(&format!("– {name:<16}{detail}"))); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_aumid_is_the_one_the_notifications_use() { + assert_eq!(AUMID, "dev.cloofy.cloofy"); + } + + #[test] + fn a_shortcut_can_be_written_read_and_removed() { + let dir = env::temp_dir().join(format!("cloofy-windows-shortcut-{}", process::id())); + let _ = fs::remove_dir_all(&dir); + let path = dir.join("cloofy.lnk"); + let exe = env::current_exe().unwrap(); + + write_shortcut(&path, &exe).unwrap(); + let link = open_shortcut(&path).unwrap(); + assert_eq!(target_of(&link).as_deref(), Some(exe.to_string_lossy().as_ref())); + assert_eq!(aumid_of(&link).as_deref(), Some(AUMID)); + + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/packaging/windows/README.md b/packaging/windows/README.md new file mode 100644 index 0000000..7dceb75 --- /dev/null +++ b/packaging/windows/README.md @@ -0,0 +1,71 @@ +# Windows + +cloofy on Windows: the [install.ps1](install.ps1) route is the one that works today, and the +[scoop manifests](#scoop) are templates for when releases ship Windows builds. + +## Install + +You need Rust 1.90 or newer with the MSVC toolchain, and CMake and NASM for Spotify's audio +(`scoop install cmake nasm`, or the Visual Studio Build Tools' CMake). YouTube Music needs +[mpv](https://mpv.io), [yt-dlp](https://github.com/yt-dlp/yt-dlp) and +[deno](https://deno.com) on `PATH` to play; `scoop install mpv yt-dlp deno` has all three. + +From a checkout: + +```powershell +.\packaging\windows\install.ps1 # YouTube Music +.\packaging\windows\install.ps1 -Service spotify # Spotify +.\packaging\windows\install.ps1 -Service both # both +.\packaging\windows\install.ps1 -AddToPath # and `cloofy` on your PATH +``` + +It builds the release binary, copies it to `%LOCALAPPDATA%\cloofy\bin`, runs +`cloofy windows install` for the Start Menu shortcut, and only with `-AddToPath` adds that folder +to your user `PATH`. Without it, run cloofy as `%LOCALAPPDATA%\cloofy\bin\cloofy.exe`. + +Then set it up as on Linux: `cloofy login` signs in to the services built in, and `cloofy doctor` +checks mpv, yt-dlp, deno, the service and a stream. + +## The Start Menu shortcut + +`cloofy windows install` writes `%APPDATA%\Microsoft\Windows\Start Menu\Programs\cloofy.lnk`, +pointing at the running `cloofy.exe`, with the AppUserModelID `dev.cloofy.cloofy`. Windows only +shows toasts for an app whose shortcut carries one, so song notifications need it; without it +cloofy says so in its log and sends none. `cloofy windows status` shows whether the shortcut is +there, where it points and whether its AppUserModelID matches, and `cloofy windows remove` deletes +the shortcut and nothing else. + +`install.ps1` again brings the shortcut up to date after an update or a move. + +## Scoop + +[`cloofy-ytmusic.json`](cloofy-ytmusic.json) and [`cloofy-spotify.json`](cloofy-spotify.json) are +templates, like the Homebrew formulas and AUR PKGBUILDs: they name a release archive that no +release produces yet, and a checksum to fill in then. Their `post_install` and `pre_uninstall` +run `cloofy windows install` and `cloofy windows remove`. + +## Uninstall + +```powershell +.\packaging\windows\uninstall.ps1 +``` + +It removes the shortcut, deletes `%LOCALAPPDATA%\cloofy\bin` and takes that one folder off your +user `PATH`, where `install.ps1` put it. Your configuration and cache in `%APPDATA%\cloofy` and +`%LOCALAPPDATA%\cloofy\cache`, and your sign-ins wherever `credentials` keeps them, stay. + +## Check by hand + +Tests cover the interface and the system's API calls, but these need ears and eyes: + +- Play a song with `CLOOFY_REQUIRE_MPV=1 cargo test -p cloofy-ytmusic` with mpv installed: the + tests start mpv and talk to it over the named pipe. +- Media keys play, pause and skip, and the system's media panel shows the song, the artist and + the cover. +- A new song in the background shows a toast with the cover, and the next one replaces it. +- After `cloofy windows remove`, no toast shows. +- Sleeping and waking the computer leaves playback working. +- In Settings, **Reduce motion** follows Windows' animation setting, and Low Power Mode follows + battery saver. +- `cloofy login ytmusic` lists the browsers with a profile, and importing from one works. +- A Spotify build plays sound, with Spotify Premium and your own client ID. diff --git a/packaging/windows/cloofy-spotify.json b/packaging/windows/cloofy-spotify.json new file mode 100644 index 0000000..fb97844 --- /dev/null +++ b/packaging/windows/cloofy-spotify.json @@ -0,0 +1,25 @@ +{ + "version": "@VERSION@", + "description": "Spotify in your terminal", + "homepage": "https://github.com/parda21/cloofy", + "license": "MIT", + "architecture": { + "64bit": { + "url": "https://github.com/parda21/cloofy/releases/download/v@VERSION@/cloofy-spotify-x86_64-pc-windows-msvc.zip", + "hash": "@SHA256_SPOTIFY_X86_64_PC_WINDOWS_MSVC@" + } + }, + "bin": "cloofy.exe", + "post_install": ["cloofy windows install"], + "pre_uninstall": ["cloofy windows remove"], + "checkver": { + "github": "https://github.com/parda21/cloofy" + }, + "autoupdate": { + "architecture": { + "64bit": { + "url": "https://github.com/parda21/cloofy/releases/download/v$version/cloofy-spotify-x86_64-pc-windows-msvc.zip" + } + } + } +} diff --git a/packaging/windows/cloofy-ytmusic.json b/packaging/windows/cloofy-ytmusic.json new file mode 100644 index 0000000..b5569a6 --- /dev/null +++ b/packaging/windows/cloofy-ytmusic.json @@ -0,0 +1,26 @@ +{ + "version": "@VERSION@", + "description": "YouTube Music in your terminal", + "homepage": "https://github.com/parda21/cloofy", + "license": "MIT", + "architecture": { + "64bit": { + "url": "https://github.com/parda21/cloofy/releases/download/v@VERSION@/cloofy-ytmusic-x86_64-pc-windows-msvc.zip", + "hash": "@SHA256_YTMUSIC_X86_64_PC_WINDOWS_MSVC@" + } + }, + "bin": "cloofy.exe", + "depends": ["deno", "mpv", "yt-dlp"], + "post_install": ["cloofy windows install"], + "pre_uninstall": ["cloofy windows remove"], + "checkver": { + "github": "https://github.com/parda21/cloofy" + }, + "autoupdate": { + "architecture": { + "64bit": { + "url": "https://github.com/parda21/cloofy/releases/download/v$version/cloofy-ytmusic-x86_64-pc-windows-msvc.zip" + } + } + } +} diff --git a/packaging/windows/install.ps1 b/packaging/windows/install.ps1 new file mode 100644 index 0000000..4cedf21 --- /dev/null +++ b/packaging/windows/install.ps1 @@ -0,0 +1,45 @@ +# Builds cloofy for Windows, puts it in %LOCALAPPDATA%\cloofy\bin and adds the Start Menu +# shortcut Windows shows its notifications under. +# +# .\packaging\windows\install.ps1 YouTube Music +# .\packaging\windows\install.ps1 -Service spotify Spotify +# .\packaging\windows\install.ps1 -Service both both +# .\packaging\windows\install.ps1 -AddToPath and on your PATH, to run `cloofy` +param( + [ValidateSet('ytmusic', 'spotify', 'both')] + [string]$Service = 'ytmusic', + [switch]$AddToPath +) + +$ErrorActionPreference = 'Stop' + +$repo = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$features = if ($Service -eq 'both') { 'spotify,ytmusic' } else { $Service } +$bin = Join-Path $env:LOCALAPPDATA 'cloofy\bin' +$exe = Join-Path $bin 'cloofy.exe' + +Write-Host "`n cloofy for Windows: $Service build`n" + +Push-Location $repo +try { + cargo build --release --locked -p cloofy --no-default-features --features $features +} finally { + Pop-Location +} + +New-Item -ItemType Directory -Force -Path $bin | Out-Null +Copy-Item (Join-Path $repo 'target\release\cloofy.exe') $exe -Force +Write-Host " cloofy is in $bin" + +& $exe windows install + +if ($AddToPath) { + $path = [Environment]::GetEnvironmentVariable('PATH', 'User') + if (($path -split ';') -notcontains $bin) { + $path = if ([string]::IsNullOrEmpty($path)) { $bin } else { $path.TrimEnd(';') + ';' + $bin } + [Environment]::SetEnvironmentVariable('PATH', $path, 'User') + Write-Host " $bin is on your PATH; open a new terminal to run cloofy" + } +} + +Write-Host "`n Done. Run cloofy login to set it up, then cloofy.`n" diff --git a/packaging/windows/uninstall.ps1 b/packaging/windows/uninstall.ps1 new file mode 100644 index 0000000..c6d622a --- /dev/null +++ b/packaging/windows/uninstall.ps1 @@ -0,0 +1,29 @@ +# Takes out what install.ps1 added: the Start Menu shortcut, %LOCALAPPDATA%\cloofy\bin, and that +# one PATH entry where install.ps1 put it. Your configuration, cache and sign-ins stay. +$ErrorActionPreference = 'Stop' + +$bin = Join-Path $env:LOCALAPPDATA 'cloofy\bin' +$exe = Join-Path $bin 'cloofy.exe' + +Write-Host "`n cloofy for Windows`n" + +if (Test-Path $exe) { + & $exe windows remove +} + +# Only the entry install.ps1 adds, and only where it is; the rest of the PATH stays as it is. +$path = [Environment]::GetEnvironmentVariable('PATH', 'User') +if ($path) { + $entries = $path -split ';' | Where-Object { $_ -and $_ -ne $bin } + if ($entries.Count -ne ($path -split ';' | Where-Object { $_ }).Count) { + [Environment]::SetEnvironmentVariable('PATH', ($entries -join ';'), 'User') + Write-Host " $bin is off your PATH" + } +} + +if (Test-Path $bin) { + Remove-Item $bin -Recurse -Force + Write-Host " removed $bin" +} + +Write-Host "`n Done. Your configuration, cache and sign-ins stay in %APPDATA% and %LOCALAPPDATA%\cloofy.`n"