Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Tiny cross-platform (macOS, Windows, Linux/X11) tray app: a global shortcut open
- Size check: `cargo build --release && ls -lh target/release/appkey`
- Linux end-to-end on Xvfb + Openbox, both in CI and in `/verify`: `scripts/test-x11.sh <binary>` (focus behaviour), `scripts/test-settings-ui.sh <binary>` (record shortcut → save → daemon reload → shortcut works)
- Wayland e2e (containers; see `/verify` and docs/DESIGN.md "Testing Wayland"): `scripts/wayland/test-{gnome,kde,hyprland}.sh`
- See the settings window without screen-recording permission (debug builds): `APPKEY_SCREENSHOT=/tmp/s.png cargo run -- settings`, add `APPKEY_SCREENSHOT_SCENE=picker` for the app picker. Then Read the PNG. Do this after any UI change.
- See the settings window without screen-recording permission (debug builds): `APPKEY_SCREENSHOT=/tmp/s.png cargo run -- settings`, add `APPKEY_SCREENSHOT_SCENE=picker` for the app picker, `=memory` for the Memory tab (Linux). `APPKEY_SCREENSHOT=/tmp/m.png cargo run -- memory` for the warning window. Then Read the PNG. Do this after any UI change.

## Releases

Expand All @@ -27,6 +27,7 @@ Every push to `main` runs `.github/workflows/release.yml`: CI → installers on
- `src/matcher.rs`: how a configured `app` name is compared to what the OS reports
- `src/platform/{macos,windows}.rs`, `src/platform/linux/`: one backend per OS, **same public functions in each** (listed in `platform/mod.rs`). `desktop_entry.rs` / `lnk.rs` are pure parsers compiled for tests on every host.
- `src/platform/linux/`: `mod.rs` picks a backend per session/desktop. `x11.rs`, `gnome.rs` (+ `packaging/gnome-extension/`), `kde.rs`, `hyprland.rs` implement `WindowSystem`. `portal.rs` = GlobalShortcuts portal, `xkb.rs` = key syntax conversions. See the table in docs/DESIGN.md.
- `src/memory/`: Ubuntu/Mint only: low-memory detection (`/proc/meminfo`, PSI), grouping and signalling the user's processes, Magic SysRq (`sysrq.rs`). Parsers compile on every host for tests. UI: `ui/memory.rs` (settings tab), `ui/pressure.rs` (`appkey memory [--alert]` window)
- `src/hotkeys.rs`: `Hotkeys` trait; global-hotkey on macOS/Windows/X11, desktop-specific ones on Wayland

## Rules
Expand All @@ -38,6 +39,7 @@ Every push to `main` runs `.github/workflows/release.yml`: CI → installers on
- Launch commands run without a shell (argv list only).
- The config is refused if other users can write to it.
- Never bypass OS protections: no focus-stealing hacks, no `SendInput` tricks, no elevation, no injecting into other processes. If the OS needs the user to grant something, detect it, explain it, and let the OS show its own prompt.
- The one thing that needs root (the SysRq setting, Memory tab) runs fixed argvs through `pkexec`, so the desktop shows its own password prompt. appkey's own binary never runs as root.
- Every `unsafe` block needs a `// SAFETY:` comment.
- Errors: `anyhow` with context that tells the user what to do. Hotkey failures go to the tray status/tooltip, not just stderr. In a tray app nobody sees stderr.
- Keep `README.md` (user-facing) and `docs/DESIGN.md` (decisions, platform matrix) in sync with behaviour changes.
Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,33 @@ Combinations with two modifiers are the safest: <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+*

---

## Low memory and frozen desktops (Ubuntu, Linux Mint)

On Ubuntu, Linux Mint and other Ubuntu-based systems, the settings window has a **Memory** tab with two tools.

**Low-memory warning.** Tick *Warn me before the computer runs out of memory* and click **Save**. When free memory stays below the limit you set (10% by default), or programs keep waiting on memory (20% of the time by default), appkey opens a window listing your biggest programs. Tick the ones you don't need and click **Close selected**: they're asked to quit, like closing their windows, so they can save first. If one doesn't react within 5 seconds, a **Force quit** button appears. **Snooze for an hour** keeps the warning away for an hour; **Dismiss** for 5 minutes. You can open the same window any time with **Show memory use now…** or `appkey memory`. appkey only offers your own programs, never parts of the desktop itself.

**Emergency keys (Magic SysRq).** If the computer freezes before you can react, these keys still work because the Linux kernel handles them, not the desktop. Hold <kbd>Alt</kbd> and <kbd>PrtSc</kbd> (SysRq), then press:

| Key | What it does |
|---|---|
| <kbd>F</kbd> | Closes the program using the most memory. Press once and wait a few seconds. |
| <kbd>R</kbd> <kbd>E</kbd> <kbd>I</kbd> <kbd>S</kbd> <kbd>U</kbd> <kbd>B</kbd> | Safe restart when nothing else helps. Press the letters slowly, about 2 seconds apart. |
| <kbd>H</kbd> | Test: only writes help to the kernel log (`sudo dmesg \| tail`). |

Ubuntu and Mint switch <kbd>F</kbd> off by default (setting 176). Choose **Recommended (240)** and click **Apply…**. Your system asks for your password, possibly twice: once to save the setting to `/etc/sysctl.d/90-appkey-sysrq.conf` and once to apply it now. Prefer a terminal? The tab shows the equivalent command to copy. It's off by default because on shared computers someone at a locked screen could use it to close the lock screen, and because <kbd>Alt</kbd>+<kbd>PrtSc</kbd> is also the window-screenshot shortcut. On a computer only you use, 240 is a sensible middle ground.

In the config file, the warning looks like this:

```toml
[memory_watch]
enabled = true
min_available_percent = 10 # warn below this much free memory (2–50)
max_pressure_percent = 20 # …or when programs wait on memory this often (0 = never)
```

---

## Command line

appkey also has a few terminal commands. They're optional, but useful for setup and troubleshooting:
Expand All @@ -136,6 +163,7 @@ appkey also has a few terminal commands. They're optional, but useful for setup
| `appkey list` | Show open apps and the names to use for `app` |
| `appkey check` | Check your config for mistakes and show notes for your system |
| `appkey open firefox` | Do exactly what a shortcut for `firefox` would do, once |
| `appkey memory` | Show the programs using the most memory, and close them (Ubuntu, Mint) |
| `appkey config` | Show where the config file is |

On Windows, tick **Add appkey to PATH** in the installer to use these from a terminal.
Expand All @@ -146,6 +174,7 @@ On Windows, tick **Add appkey to PATH** in the installer to use these from a ter

- appkey needs **no special permissions** on any system. It doesn't read your keystrokes: it asks the system to tell it when *your* shortcuts are pressed.
- It never runs commands through a shell. `launch` starts exactly the program you list.
- **Linux:** the low-memory window can only close your own programs, and it never runs as administrator. Changing the SysRq setting is the one thing that needs administrator rights: your system's own password prompt asks for it, and only for writing that one setting.
- Your config decides which programs run, so on macOS and Linux appkey refuses to use it if other users on the computer could edit it.
- **Windows:** an app running *as administrator* can only be brought to the front if appkey also runs as administrator. appkey tells you when this happens rather than working around Windows' protection.

Expand Down
11 changes: 11 additions & 0 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,24 @@ The daemon and the settings window are **two processes from the same binary**. E
- **The tray is optional.** If it can't be created (no StatusNotifier host / D-Bus), shortcuts still work, and settings open with `appkey settings`.
- **Hand-rolled CLI.** Five subcommands don't justify `clap`'s size.

## Low memory and Magic SysRq (Ubuntu / Linux Mint)

The settings window has a **Memory** tab, shown only when `/etc/os-release` says Ubuntu or a derivative (`ID`/`ID_LIKE` contains `ubuntu` or `linuxmint`). The code lives in `src/memory/` (parsers, shared by all hosts for tests), `ui/memory.rs` (the tab) and `ui/pressure.rs` (the warning window).

- **Detection: `MemAvailable` and PSI, once a second in the daemon.** We warn when available memory is below `min_available_percent` of RAM, or when `/proc/pressure/memory` `some avg10` reaches `max_pressure_percent`. The condition must hold for 3 consecutive ticks, then we stay quiet for 5 min after the window closes (1 h if snoozed; the window exits with code 3 to say so). Reading two small `/proc` files a second costs nothing measurable.
- **The warning is a separate process** (`appkey memory --alert`), like settings, so the daemon never loads GL. It starts while memory is low but not yet exhausted, which is why the default thresholds are early ones. It's always-on-top, but doesn't take focus by force.
- **Closing programs is `SIGTERM`, then optionally `SIGKILL`,** grouped by process name (all `firefox` processes together), only for our own uid, and never for session/desktop processes (`memory::PROTECTED`). Before signalling we re-read `/proc/<pid>/status` so a pid reused since the list was drawn is left alone. No elevation: other users' processes aren't listed at all.
- **SysRq needs root, so it goes through the OS's own prompt.** `pkexec` runs two fixed argvs, `/usr/bin/tee /etc/sysctl.d/90-appkey-sysrq.conf` (contents on stdin) and `/usr/sbin/sysctl -q -p` on that file. No shell, absolute paths, and appkey itself never runs as root. That can mean two password prompts; we accept that over running our own binary as root. The `90-` name sorts after Ubuntu's `10-magic-sysrq.conf`, so it wins at boot. The tab also shows the equivalent terminal command.
- **Why not more distros:** asked for Ubuntu/Mint. Nothing here is Ubuntu-specific except the default (176) we describe; widening means changing `is_supported_distro`.

## Security & permissions by OS

| OS | What's needed | How we handle it |
|---|---|---|
| macOS | Nothing. Carbon hotkeys and LaunchServices need no Accessibility, Input Monitoring or Automation permission. | If we ever need per-window control (AXUIElement), we must call `AXIsProcessTrustedWithOptions` with the prompt option and explain why first. Unsigned downloads are quarantined by Gatekeeper; signing/notarization is a release task. |
| Windows | Nothing. | UIPI: windows of elevated processes can't be fully controlled from a non-elevated appkey. We report it rather than auto-elevating. Unsigned exes trigger SmartScreen; signing is a release task. |
| Linux X11 | Nothing. X11 has no permission model. | n/a |
| Linux (Ubuntu / Mint), Memory tab | Changing `kernel.sysrq` needs root. | `pkexec` with fixed argvs shows the desktop's own password prompt; cancelling is reported, not retried. The warning window only signals the user's own processes. |
| Linux Wayland | GNOME: the user keeps an extension enabled (visible and switchable in the Extensions app). KDE: the user approves shortcuts in KDE's dialog. Hyprland: nothing. | We never bypass the desktop: the extension only acts on appkey's D-Bus calls, the KDE dialog is the portal's own, and a cancelled approval is respected (reported, never overridden). The GNOME extension's D-Bus methods are reachable by any process of the same user, which can already control the session. |

## Linux backends
Expand Down
19 changes: 18 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ pub struct App {
/// Modification time of the config we last loaded.
loaded_mtime: Option<SystemTime>,
settings_window: Option<Child>,
#[cfg(target_os = "linux")]
memory_watch: config::MemoryWatch,
#[cfg(target_os = "linux")]
memory: crate::memory::Watcher,
}

impl std::fmt::Debug for App {
Expand Down Expand Up @@ -114,6 +118,10 @@ impl App {
quit: quit.id().clone(),
loaded_mtime: None,
settings_window: None,
#[cfg(target_os = "linux")]
memory_watch: config::MemoryWatch::default(),
#[cfg(target_os = "linux")]
memory: crate::memory::Watcher::default(),
};
app.reload();
Ok(app)
Expand Down Expand Up @@ -149,6 +157,10 @@ impl App {
} else if config_mtime(&self.config_path) != self.loaded_mtime {
self.reload();
}
#[cfg(target_os = "linux")]
if let Err(e) = self.memory.tick(self.memory_watch) {
self.set_status(&format!("{e:#}"));
}
}
}
Flow::Continue
Expand Down Expand Up @@ -176,12 +188,17 @@ impl App {
fn reload(&mut self) {
self.active.clear();
self.loaded_mtime = config_mtime(&self.config_path);
let cfg = config::load_or_init(&self.config_path);
#[cfg(target_os = "linux")]
{
self.memory_watch = cfg.as_ref().map(|c| c.memory_watch).unwrap_or_default();
}

let Some(hotkeys) = self.hotkeys.as_mut() else {
let msg = format!("shortcuts unavailable: {}", self.hotkeys_error);
return self.set_status(&msg);
};
let cfg = match config::load_or_init(&self.config_path) {
let cfg = match cfg {
Ok(cfg) => cfg,
Err(e) => {
hotkeys.set(&[]);
Expand Down
107 changes: 89 additions & 18 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,57 @@ use anyhow::{Context, Result, bail};
use global_hotkey::hotkey::HotKey;
use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Deserialize, Serialize)]
/// The whole file exactly as written (unvalidated). The settings window edits
/// this and writes it back.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
pub struct Document {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory_watch: Option<MemoryWatch>,
#[serde(default, rename = "shortcut")]
shortcuts: Vec<Entry>,
pub shortcuts: Vec<Entry>,
}

/// `[memory_watch]`: warn before the system runs out of memory (Ubuntu / Linux Mint only;
/// kept but ignored elsewhere).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MemoryWatch {
pub enabled: bool,
/// Warn when available memory drops below this share of RAM.
pub min_available_percent: u8,
/// Also warn when tasks stall on memory this share of the time (PSI "some", 10 s
/// average). 0 turns this check off.
pub max_pressure_percent: u8,
}

impl Default for MemoryWatch {
fn default() -> Self {
Self { enabled: false, min_available_percent: 10, max_pressure_percent: 20 }
}
}

impl MemoryWatch {
pub const AVAILABLE_RANGE: std::ops::RangeInclusive<u8> = 2..=50;
pub const PRESSURE_RANGE: std::ops::RangeInclusive<u8> = 0..=90;

pub fn validate(self) -> Result<()> {
if !Self::AVAILABLE_RANGE.contains(&self.min_available_percent) {
bail!(
"memory_watch: min_available_percent must be between {} and {}",
Self::AVAILABLE_RANGE.start(),
Self::AVAILABLE_RANGE.end()
);
}
if !Self::PRESSURE_RANGE.contains(&self.max_pressure_percent) {
bail!(
"memory_watch: max_pressure_percent must be between {} and {} (0 = off)",
Self::PRESSURE_RANGE.start(),
Self::PRESSURE_RANGE.end()
);
}
Ok(())
}
}

/// One `[[shortcut]]` exactly as written in the file (unvalidated). The settings
Expand Down Expand Up @@ -54,6 +100,8 @@ pub struct Shortcut {
#[derive(Debug, Default)]
pub struct Config {
pub shortcuts: Vec<Shortcut>,
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub memory_watch: MemoryWatch,
}

pub const CURRENT_OS: &str = std::env::consts::OS;
Expand All @@ -78,20 +126,19 @@ pub fn ensure_exists(path: &Path) -> Result<bool> {
/// Loads and validates the config, creating the example file on first run.
pub fn load_or_init(path: &Path) -> Result<Config> {
ensure_exists(path)?;
validate(read_entries(path)?).with_context(|| format!("in {}", path.display()))
validate_document(read_document(path)?).with_context(|| format!("in {}", path.display()))
}

/// Reads the raw entries (all OSes) without validating them.
pub fn read_entries(path: &Path) -> Result<Vec<Entry>> {
/// Reads the whole file (shortcuts for all OSes) without validating it.
pub fn read_document(path: &Path) -> Result<Document> {
check_permissions(path)?;
let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let raw: RawConfig = toml::from_str(&text).with_context(|| format!("in {}", path.display()))?;
Ok(raw.shortcuts)
toml::from_str(&text).with_context(|| format!("in {}", path.display()))
}

/// Writes entries atomically (temp file + rename), readable only by the user.
pub fn save_entries(path: &Path, entries: &[Entry]) -> Result<()> {
let body = toml::to_string(&RawConfig { shortcuts: entries.to_vec() })?;
/// Writes the file atomically (temp file + rename), readable only by the user.
pub fn save_document(path: &Path, doc: &Document) -> Result<()> {
let body = toml::to_string(doc)?;
let tmp = path.with_extension("toml.tmp");
let _ = fs::remove_file(&tmp);
write_new(&tmp, &format!("{SAVED_HEADER}\n{body}"))?;
Expand All @@ -105,8 +152,14 @@ const SAVED_HEADER: &str = "\

#[cfg(test)]
fn parse(text: &str) -> Result<Config> {
let raw: RawConfig = toml::from_str(text)?;
validate(raw.shortcuts)
validate_document(toml::from_str(text)?)
}

/// Validates everything in the file that applies to this OS.
pub fn validate_document(doc: Document) -> Result<Config> {
let memory_watch = doc.memory_watch.unwrap_or_default();
memory_watch.validate()?;
Ok(Config { memory_watch, ..validate(doc.shortcuts)? })
}

/// Checks entries for the current OS and turns them into registrable shortcuts.
Expand Down Expand Up @@ -137,7 +190,7 @@ pub fn validate(entries: Vec<Entry>) -> Result<Config> {
}
shortcuts.push(Shortcut { hotkey, keys: s.keys, app: s.app, launch: s.launch });
}
Ok(Config { shortcuts })
Ok(Config { shortcuts, memory_watch: MemoryWatch::default() })
}

/// The config decides which programs we execute, so on Unix refuse a file that
Expand Down Expand Up @@ -258,6 +311,19 @@ mod tests {
}
}

#[test]
fn memory_watch_defaults_and_limits() {
assert_eq!(parse("").unwrap().memory_watch, MemoryWatch::default());
let cfg = parse("[memory_watch]\nenabled = true\nmin_available_percent = 5").unwrap();
assert_eq!(
cfg.memory_watch,
MemoryWatch { enabled: true, min_available_percent: 5, max_pressure_percent: 20 }
);
assert!(parse("[memory_watch]\nmin_available_percent = 0").is_err());
assert!(parse("[memory_watch]\nmax_pressure_percent = 100").is_err());
assert!(parse("[memory_watch]\nfoo = 1").is_err());
}

#[test]
fn parses_launch_and_keys() {
let cfg = parse(
Expand Down Expand Up @@ -290,10 +356,15 @@ mod tests {
..Entry::default()
},
];
save_entries(&path, &entries).unwrap();
assert_eq!(read_entries(&path).unwrap(), entries);
save_entries(&path, &entries[..1]).unwrap(); // overwrite works
assert_eq!(read_entries(&path).unwrap().len(), 1);
let doc = Document {
shortcuts: entries,
memory_watch: Some(MemoryWatch { enabled: true, ..MemoryWatch::default() }),
};
save_document(&path, &doc).unwrap();
assert_eq!(read_document(&path).unwrap(), doc);
let one = Document { shortcuts: doc.shortcuts[..1].to_vec(), memory_watch: None };
save_document(&path, &one).unwrap(); // overwrite works
assert_eq!(read_document(&path).unwrap(), one);
fs::remove_dir_all(&dir).unwrap();
}

Expand Down
Loading
Loading