taskbar-focus 0.5.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! Starting with Windows, through the documented per-user `Run` key.
//!
//! The value exists only while the setting is on. Task Manager's own startup
//! switch is never touched. A debug build never writes it.

use std::path::{Path, PathBuf};

use windows::Win32::System::Registry::{KEY_READ, KEY_SET_VALUE};

use crate::os::registry::Key;

pub const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
pub const VALUE: &str = "taskbar-focus";
/// The documented limit for a `Run` command line.
const MAX_COMMAND: usize = 260;

/// The command currently registered, if any.
pub fn current() -> Option<String> {
    Key::open(RUN_KEY, KEY_READ)?.get_string(VALUE)
}

pub fn is_on() -> bool {
    current().is_some()
}

/// Turn starting with Windows on or off. Turning it on again also corrects the
/// path of a program that was moved.
pub fn set(on: bool) -> Result<(), String> {
    let done = match current() {
        Some(now) => on && command().is_ok_and(|wanted| wanted == now),
        None => !on,
    };
    if done {
        return Ok(());
    }
    if cfg!(debug_assertions) {
        crate::audit::log("autostart: debug build, so the Run value was not changed");
        return Ok(());
    }
    let key = Key::open(RUN_KEY, KEY_READ | KEY_SET_VALUE)
        .ok_or("Windows did not allow the startup setting to be changed.")?;
    if !on {
        crate::audit::log("autostart: removing the Run value");
        return key
            .delete(VALUE)
            .then_some(())
            .ok_or_else(|| "The startup setting could not be removed.".into());
    }
    let command = command()?;
    crate::audit::log(&format!("autostart: setting the Run value to {command}"));
    key.set_string(VALUE, &command)
        .then_some(())
        .ok_or_else(|| "The startup setting could not be saved.".into())
}

/// The quoted command that would be registered.
pub fn command() -> Result<String, String> {
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    let command = format!("\"{}\"", stable_path(&exe).display());
    if command.encode_utf16().count() > MAX_COMMAND {
        return Err("The program's path is too long for Windows to start it.".into());
    }
    Ok(command)
}

/// Where the program will still be after an update. Scoop installs each version
/// in its own directory and keeps a shim, and a `current` link, that survive.
fn stable_path(exe: &Path) -> PathBuf {
    let scoop = || {
        let version = exe.parent()?;
        let app = version.parent()?;
        let apps = app.parent()?;
        if !apps.file_name()?.eq_ignore_ascii_case("apps") {
            return None;
        }
        let name = exe.file_name()?;
        let shim = apps.parent()?.join("shims").join(name);
        let current = app.join("current").join(name);
        [shim, current].into_iter().find(|p| p.exists())
    };
    scoop().unwrap_or_else(|| exe.to_path_buf())
}