diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ab3328..d9f26a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: sudo apt-get install -y --no-install-recommends libgtk-4-dev libadwaita-1-dev libdbus-1-dev pkg-config build-essential \ gnome-shell mutter kwin-wayland kde-spectacle qtwayland5 wl-clipboard sqlite3 dbus-user-session \ xdg-desktop-portal xdg-desktop-portal-gtk python3-gi gir1.2-gtk-4.0 psmisc procps \ - imagemagick dbus-bin dbus-x11 libglib2.0-bin + imagemagick fonts-dejavu-core tesseract-ocr dbus-bin dbus-x11 libglib2.0-bin - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - run: cargo build diff --git a/CHANGELOG.md b/CHANGELOG.md index 26d0b63..fe28ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## Unreleased + +### What is new + +- **Window snapping** with the Mac's 17 positions, from the palette (`window left`, `corner`, `third`, `center`...) and the shortcuts `Ctrl+Alt+Shift+Arrows` and `Ctrl+Alt+Enter`. On KDE Plasma it works out of the box; on GNOME it needs the Menew extension version 2 (log out and in after updating). +- **Quick actions** in the palette: mute the microphone (`Ctrl+Alt+M`) or the sound, switch the sound output and input, dark mode, keep awake (also `awake 2h`), lock screen, empty trash, color picker, plain text clipboard, eject disks, brightness (also external displays with `ddcutil`), quit or force quit apps (`quit firefox`, `kill firefox`, "Quit all apps" with a never-quit list) and stop a server on a port (`port 3000`). +- **New note** with `Ctrl+Alt+J`. +- `menew run ` runs any of these from a terminal or a custom shortcut (`menew run qa.mic`, `menew run win.left`, `menew run note.new`), for GNOME 45 to 47, which have no GlobalShortcuts portal. + +### Known limitations + +- Quitting apps sends a signal: Wayland can't ask an app to close its windows. +- Snapping needs KWin or the GNOME extension; X11 sessions without either can't snap. +- Audio devices, brightness, eject and the new shortcuts were tested only on headless GNOME Shell 46 and KWin 5.27. + ## 0.1.0-alpha.2 **Early preview for testers.** Screenshots with annotations, text from the screen, QR codes and the system monitor join the command palette, the clipboard history and notes. If you installed 0.1.0-alpha.1, Menew offers this update by itself. diff --git a/Cargo.lock b/Cargo.lock index 4baec17..f2e54ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1065,6 +1065,7 @@ dependencies = [ "libadwaita", "menew-clipboard", "menew-core", + "menew-desktop", "menew-shortcuts", "menew-tray", "menew-ui", @@ -1104,6 +1105,16 @@ dependencies = [ "walkdir", ] +[[package]] +name = "menew-desktop" +version = "0.1.0-alpha.2" +dependencies = [ + "ashpd", + "tokio", + "tracing", + "zbus", +] + [[package]] name = "menew-shortcuts" version = "0.1.0-alpha.2" diff --git a/Cargo.toml b/Cargo.toml index b000753..818c2e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "crates/menew-shortcuts", "crates/menew-clipboard", "crates/menew-ui", + "crates/menew-desktop", "crates/menew", ] resolver = "2" diff --git a/README.md b/README.md index 5ffe31a..c03fcd4 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,18 @@ Every file in `~/.local/share/menew/scripts` (shell, Python, Node, Ruby) becomes +
+🪟 Windows and quick actions: window left, mute, dark mode, awake 2h, port 3000 + +- **Window snapping** with the Mac's 17 positions (halves, corners, thirds, two thirds, center, almost full, fill, next display) from the palette, Ctrl Alt Shift ←/→/↑/↓ and Ctrl Alt Enter. KDE Plasma moves the window through a KWin script; GNOME needs the bundled Menew extension (version 2: log out and in after updating it). +- **Microphone and sound**: mute or unmute (Ctrl Alt M for the mic), and switch the output or input device (`pactl`, PipeWire or PulseAudio). +- **Dark mode**, **keep awake** (`awake 2h`, `acordado 90m`, or until you turn it off), **lock screen**, **empty trash** (asks first), **color picker** (the `#RRGGBB` is copied), **plain text clipboard**, **eject disks**, **brightness** (`brightness 40`, also external displays with `ddcutil`). +- **Quit apps**: `quit firefox`, `kill firefox` (force), "Quit all apps" skips the apps in `never_quit` (`config.json`). Wayland has no way to ask an app to close its windows, so Menew sends it a signal. +- **Ports in use**: `port 3000` shows the server listening there and Enter stops it. +- Every action also runs from a terminal or a custom shortcut: `menew run qa.mic`, `menew run win.left`, `menew run note.new`. + +
+
🔔 Tray icon and start at login @@ -194,7 +206,7 @@ The language follows `LC_ALL` / `LANG`.
-Not here yet (see [docs/parity.md](docs/parity.md)): Memory, recordings, pinning a screenshot on the screen, screen recording, scrolling capture, asking about the screen, window management, on-device AI and agents. They are on the roadmap of the Mac app and will come to Linux as far as the platform allows. +Not here yet (see [docs/parity.md](docs/parity.md)): Memory, recordings, pinning a screenshot on the screen, screen recording, scrolling capture, asking about the screen, on-device AI and agents. They are on the roadmap of the Mac app and will come to Linux as far as the platform allows. ## Install @@ -240,6 +252,10 @@ cargo run -p menew | Ctrl Alt N | Paste the next item of the paste queue | | Ctrl Alt Shift S | Capture the screen and annotate it | | Ctrl Alt Shift T | Copy the text of an area of the screen | +| Ctrl Alt M | Mute or unmute the microphone | +| Ctrl Alt Shift ← → ↑ ↓ | Snap the window to that half | +| Ctrl Alt Enter | Make the window fill the screen | +| Ctrl Alt J | New note | | Ctrl Z / Ctrl S / Ctrl C | In the editor: undo / save / copy | | Tab | Switch between Apps and Clipboard in the palette | | ↑ ↓ / Enter / Esc | Move / run or copy / close | @@ -264,6 +280,7 @@ The app has **no telemetry, no analytics and no account**, and makes no network - Your recent picks are stored in `~/.local/share/menew/recents.json` (item ids only, never copied text); scripts, quick links and world clocks live in `~/.local/share/menew/scripts` and `~/.config/menew/config.json`. - "Clear history" in the tray deletes every unpinned entry and the image files that go with them. - Notes live in `~/.local/share/menew/notes/notes.json` (the same format as the Mac). **Normal notes are plain text in that file.** Protected and password notes keep only their title there: the rest is in the Secret Service of your keyring (`application=app.menew.Menew`), never in a plain file. Opening one asks for your password through polkit; where the polkit policy is not installed (AppImage) or there is no authentication agent, the keyring unlocked at login is the only protection, and the notes window says so. +- Quick actions and window snapping run your desktop's own tools locally (`pactl`, `gsettings`, `systemd-inhibit`, `loginctl`, `gio`, `lsblk`, `udisksctl`, `ddcutil`, a KWin script or the Menew GNOME extension) and send nothing anywhere. The color picker goes through the screenshot portal and keeps only the color. - The optional paste simulation only writes a Ctrl V key press to `/dev/uinput`; it never reads keyboard input. ## FAQ diff --git a/crates/menew-core/src/config.rs b/crates/menew-core/src/config.rs index 4eb8430..63f82cd 100644 --- a/crates/menew-core/src/config.rs +++ b/crates/menew-core/src/config.rs @@ -42,6 +42,8 @@ pub struct Config { pub auto_update_check: bool, /// Metrics shown in the tray Title and ToolTip, from `cpu cpuGraph ram net disk battery` (the Mac's `menuBarItems`). Empty (the default) samples nothing until the settings window of Phase 11 lets the user opt in. pub monitor_tray_items: Vec, + /// Apps "Quit all apps" never closes (`neverQuit` on the Mac): desktop ids or program names. + pub never_quit: Vec, } impl Default for Config { @@ -57,6 +59,7 @@ impl Default for Config { clipboard_ocr: true, auto_update_check: true, monitor_tray_items: Vec::new(), + never_quit: vec![], } } } diff --git a/crates/menew-core/src/lib.rs b/crates/menew-core/src/lib.rs index 6e4035e..1c092a4 100644 --- a/crates/menew-core/src/lib.rs +++ b/crates/menew-core/src/lib.rs @@ -20,6 +20,7 @@ pub mod markdown; pub mod monitor; pub mod notes; pub mod palette; +pub mod quick_actions; pub mod ocr; pub mod paste; pub mod paste_queue; @@ -31,11 +32,14 @@ pub mod search; pub mod sha256; pub mod snippets; pub mod strings; +mod strings_r1; +pub mod sys; pub mod text_transforms; pub mod time_zones; pub mod timers; #[cfg(unix)] pub mod updates; +pub mod windows; pub use calculator::{evaluate, CalcResult}; pub use clipboard_db::{ClipKind, ClipboardDatabase, ClipboardEntry}; diff --git a/crates/menew-core/src/palette.rs b/crates/menew-core/src/palette.rs index 1607820..c705c41 100644 --- a/crates/menew-core/src/palette.rs +++ b/crates/menew-core/src/palette.rs @@ -128,6 +128,9 @@ pub enum ItemAction { QrShow(Option), /// Show the QR window in its Wi-Fi mode. QrWifi, + /// A command run by the daemon (quick actions `qa.*`, notes `note.*`, screenshots `cap.*`, + /// windows `win.*`, the Menew window `win.open:*`...), see `crates/menew/src/commands.rs`. + Command(String), } impl ItemAction { @@ -180,6 +183,7 @@ impl ItemAction { ItemAction::QrShow(None) => "qr-show".into(), ItemAction::QrShow(Some(t)) => format!("qr-show:{t}"), ItemAction::QrWifi => "qr-wifi".into(), + ItemAction::Command(c) => format!("command:{c}"), } } } @@ -287,6 +291,9 @@ pub struct PaletteContext<'a> { pub clip: ClipContext<'a>, /// The notes: protected ones have only their title in `text`. pub notes: &'a [Note], + /// Items of the other features (quick actions, notes, screenshots, windows), already built for + /// the text typed. They are searched and ranked like the Menew actions. + pub extra: &'a [PaletteItem], } const SUGGESTIONS: [&str; 4] = ["action.clipboard", "action.focus", "action.clearclip", "action.uuid"]; @@ -590,6 +597,7 @@ fn commands(ctx: &PaletteContext) -> Vec { .icon(Icon::Symbol("application-exit-symbolic")) .act(ItemAction::Quit), ); + out.extend(ctx.extra.iter().cloned()); for app in ctx.apps { let sub = app.generic_name.as_deref().or(app.comment.as_deref()).unwrap_or(""); let kw = format!("{} {}", app.keywords.join(" "), app.generic_name.clone().unwrap_or_default()); @@ -769,6 +777,7 @@ mod tests { autostart_on: false, clip: Default::default(), notes: &[], + extra: &[], }; results(&ctx, query, &|_| vec![]) } @@ -847,6 +856,7 @@ mod tests { autostart_on: false, clip: Default::default(), notes: &[], + extra: &[], }; let out = results(&ctx, "appy", &|_| vec![]); assert_eq!(out.len(), MAX_RESULTS + 1); @@ -872,6 +882,7 @@ mod tests { autostart_on: false, clip: Default::default(), notes: &[], + extra: &[], }; let hit = |id: i64, t: &str| ClipHit { id, title: t.into(), text: t.into(), kind: ClipKind::Text }; let out = results(&ctx, "history", &|_| vec![hit(1, "my history notes")]); diff --git a/crates/menew-core/src/quick_actions.rs b/crates/menew-core/src/quick_actions.rs new file mode 100644 index 0000000..499504e --- /dev/null +++ b/crates/menew-core/src/quick_actions.rs @@ -0,0 +1,857 @@ +//! Quick actions (port of `Toolbox.swift`, `AppControl.swift`, `Ports.swift` and the display part of +//! `Hardware.swift`): mute the microphone or the sound, switch the audio output and input, dark mode, +//! keep awake, lock the screen, empty the trash, eject disks, brightness, quit apps and stop servers. +//! +//! The parsing is pure and tested; the calls go to the tools every GNOME and KDE system has: +//! `pactl` (PipeWire or PulseAudio), `gsettings`, `plasma-apply-colorscheme`, `systemd-inhibit`, +//! `loginctl`, `gio`, `lsblk` + `udisksctl`, `busctl` (logind `SetBrightness`) and `ddcutil`. +//! +//! The palette shows these as [`ItemAction::Command`] items with an id like `qa.mic`; the daemon +//! runs them with [`run`]. + +use crate::desktop_entry::DesktopApp; +use crate::i18n::Language; +use crate::palette::{Icon, ItemAction, Kind, PaletteItem}; +use crate::search::fold; +use crate::strings::tr; +use crate::sys::{self, Desktop}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; + +// --------------------------------------------------------------------------------------------- +// Audio +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AudioDevice { + /// The PulseAudio name (`alsa_output.pci-0000_00_1f.3.analog-stereo`). + pub name: String, + /// What people read (`Built-in Audio Analog Stereo`). + pub description: String, +} + +/// Parse `pactl -f json list sinks` or `... sources`. Monitors of outputs are left out. +pub fn parse_devices(json: &str) -> Vec { + let Ok(serde_json::Value::Array(items)) = serde_json::from_str::(json) else { + return vec![]; + }; + items + .iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?.to_string(); + if name.ends_with(".monitor") { + return None; + } + let description = d.get("description").and_then(|v| v.as_str()).unwrap_or(&name).to_string(); + Some(AudioDevice { name, description }) + }) + .collect() +} + +/// `Mute: yes` from `pactl get-sink-mute`, or `[MUTED]` from `wpctl get-volume`. +pub fn parse_muted(out: &str) -> Option { + let t = out.trim(); + if let Some(v) = t.strip_prefix("Mute:") { + return Some(v.trim() == "yes"); + } + if t.starts_with("Volume:") { + return Some(t.contains("[MUTED]")); + } + None +} + +fn pa_target(input: bool) -> (&'static str, &'static str) { + if input { + ("source", "@DEFAULT_SOURCE@") + } else { + ("sink", "@DEFAULT_SINK@") + } +} + +pub fn is_muted(input: bool) -> Option { + let (kind, target) = pa_target(input); + if let Some(out) = sys::output("pactl", &[&format!("get-{kind}-mute"), target]) { + return parse_muted(&out); + } + let wp = if input { "@DEFAULT_AUDIO_SOURCE@" } else { "@DEFAULT_AUDIO_SINK@" }; + sys::output("wpctl", &["get-volume", wp]).and_then(|o| parse_muted(&o)) +} + +/// Toggle the mute of the default output (or input) and return the new state. +pub fn toggle_mute(input: bool) -> Option { + let (kind, target) = pa_target(input); + let ok = sys::run("pactl", &[&format!("set-{kind}-mute"), target, "toggle"]) + || sys::run("wpctl", &["set-mute", if input { "@DEFAULT_AUDIO_SOURCE@" } else { "@DEFAULT_AUDIO_SINK@" }, "toggle"]); + if ok { + is_muted(input) + } else { + None + } +} + +pub fn devices(input: bool) -> Vec { + let list = if input { "sources" } else { "sinks" }; + sys::output("pactl", &["-f", "json", "list", list]).map(|j| parse_devices(&j)).unwrap_or_default() +} + +pub fn default_device(input: bool) -> Option { + let cmd = if input { "get-default-source" } else { "get-default-sink" }; + sys::output("pactl", &[cmd]).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) +} + +pub fn set_default_device(input: bool, name: &str) -> bool { + let cmd = if input { "set-default-source" } else { "set-default-sink" }; + sys::run("pactl", &[cmd, name]) +} + +// --------------------------------------------------------------------------------------------- +// Dark mode +// --------------------------------------------------------------------------------------------- + +/// `'prefer-dark'` from `gsettings get org.gnome.desktop.interface color-scheme`. +pub fn parse_gnome_scheme(out: &str) -> bool { + out.trim().trim_matches('\'') == "prefer-dark" +} + +/// The `ColorScheme` of `[General]` in `kdeglobals`. +pub fn parse_kde_scheme(kdeglobals: &str) -> Option { + let mut in_general = false; + for line in kdeglobals.lines() { + let l = line.trim(); + if l.starts_with('[') { + in_general = l == "[General]"; + } else if in_general { + if let Some(v) = l.strip_prefix("ColorScheme=") { + return Some(v.trim().to_string()); + } + } + } + None +} + +fn kdeglobals_path() -> PathBuf { + crate::config::config_dir().join("kdeglobals") +} + +pub fn is_dark(desktop: Desktop) -> Option { + if desktop == Desktop::Kde { + let text = std::fs::read_to_string(kdeglobals_path()).ok()?; + return Some(parse_kde_scheme(&text).map(|s| s.to_lowercase().contains("dark")).unwrap_or(false)); + } + sys::output("gsettings", &["get", "org.gnome.desktop.interface", "color-scheme"]).map(|o| parse_gnome_scheme(&o)) +} + +pub fn set_dark(desktop: Desktop, dark: bool) -> bool { + if desktop == Desktop::Kde { + return sys::run("plasma-apply-colorscheme", &[if dark { "BreezeDark" } else { "BreezeLight" }]); + } + // GNOME 42+; `default` is the light look (GNOME 47 also knows `prefer-light`) + let ok = sys::run("gsettings", &["set", "org.gnome.desktop.interface", "color-scheme", if dark { "prefer-dark" } else { "default" }]); + // GTK 3 apps follow the theme name, not the color scheme + let _ = sys::run("gsettings", &["set", "org.gnome.desktop.interface", "gtk-theme", if dark { "Adwaita-dark" } else { "Adwaita" }]); + ok +} + +// --------------------------------------------------------------------------------------------- +// Keep awake +// --------------------------------------------------------------------------------------------- + +/// Why keep awake could not start. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AwakeError { + /// `systemd-inhibit` is not installed. + Missing, + /// It started and exited at once: logind refused the lock. + Refused, +} + +/// Keeps the screen on with `systemd-inhibit` (logind), like the Mac's `IOPMAssertion`. +#[derive(Default)] +pub struct KeepAwake { + child: Option, + /// When it turns itself off (seconds since the epoch), `None` = until turned off. + pub until: Option, +} + +impl KeepAwake { + pub fn is_on(&mut self) -> bool { + match self.child.as_mut().map(|c| c.try_wait()) { + Some(Ok(None)) => true, + Some(_) => { + self.child = None; + self.until = None; + false + } + None => false, + } + } + + /// Turn it on for that many minutes (or until turned off). + pub fn start(&mut self, minutes: Option, now: f64, why: &str) -> Result<(), AwakeError> { + self.stop(); + let mut child = Command::new("systemd-inhibit") + .args(["--what=idle:sleep", "--who=Menew", &format!("--why={why}"), "--mode=block", "sleep", "infinity"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map_err(|_| AwakeError::Missing)?; + // systemd-inhibit exits at once when logind refuses the lock (no session, a container...): + // give it a moment so Menew doesn't say it is on when nothing holds the lock + for _ in 0..10 { + std::thread::sleep(std::time::Duration::from_millis(25)); + if !matches!(child.try_wait(), Ok(None)) { + let _ = child.wait(); + return Err(AwakeError::Refused); + } + } + self.child = Some(child); + self.until = minutes.map(|m| now + m as f64 * 60.0); + Ok(()) + } + + pub fn stop(&mut self) { + if let Some(mut c) = self.child.take() { + let _ = c.kill(); + let _ = c.wait(); + } + self.until = None; + } + + /// Called once a second: true when the time ran out and it turned off. + pub fn tick(&mut self, now: f64) -> bool { + if let Some(u) = self.until { + if now >= u && self.is_on() { + self.stop(); + return true; + } + } + false + } +} + +impl Drop for KeepAwake { + fn drop(&mut self) { + self.stop(); + } +} + +/// `awake 2h`, `acordado 90m`, `wach 30`: minutes, at most 24 h. +pub fn parse_duration_minutes(s: &str) -> Option { + let s = s.trim().to_lowercase(); + let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect(); + let n: u32 = digits.parse().ok()?; + let unit = s[digits.len()..].trim(); + let minutes = match unit { + "" | "m" | "min" | "mins" | "minutes" | "minutos" | "minuten" | "分钟" => n, + "h" | "hr" | "hrs" | "hour" | "hours" | "hora" | "horas" | "std" | "stunde" | "stunden" | "小时" => n.checked_mul(60)?, + _ => return None, + }; + (1..=24 * 60).contains(&minutes).then_some(minutes) +} + +// --------------------------------------------------------------------------------------------- +// Lock, trash +// --------------------------------------------------------------------------------------------- + +pub fn lock_screen() -> bool { + sys::run("loginctl", &["lock-session"]) + || sys::run("dbus-send", &["--session", "--dest=org.freedesktop.ScreenSaver", "--type=method_call", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver.Lock"]) + || sys::run("xdg-screensaver", &["lock"]) +} + +/// How many items the trash has (`gio trash --list`, GLib 2.70+). +pub fn trash_count() -> Option { + sys::output("gio", &["trash", "--list"]).map(|o| o.lines().filter(|l| !l.trim().is_empty()).count()) +} + +pub fn empty_trash() -> bool { + sys::run("gio", &["trash", "--empty"]) +} + +// --------------------------------------------------------------------------------------------- +// Eject +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Volume { + /// `/dev/sdb1` + pub device: String, + /// `/dev/sdb`, powered off after unmounting. + pub disk: Option, + pub mountpoint: String, +} + +/// Parse `lsblk -J -o PATH,PKNAME,RM,HOTPLUG,MOUNTPOINT,TYPE`: mounted partitions of removable or +/// hot-plugged disks (USB sticks, SD cards, external drives). The system disk is never listed. +pub fn parse_lsblk(json: &str) -> Vec { + fn walk(v: &serde_json::Value, parent_removable: bool, out: &mut Vec) { + let flag = |k: &str| match v.get(k) { + Some(serde_json::Value::Bool(b)) => *b, + Some(serde_json::Value::String(s)) => s == "1" || s == "true", + Some(serde_json::Value::Number(n)) => n.as_i64() == Some(1), + _ => false, + }; + let removable = parent_removable || flag("rm") || flag("hotplug"); + if let (Some(path), Some(mp)) = (v.get("path").and_then(|p| p.as_str()), v.get("mountpoint").and_then(|m| m.as_str())) { + let system = mp == "/" || mp.starts_with("/boot") || mp == "[SWAP]" || mp.starts_with("/usr") || mp.starts_with("/var") || mp == "/home"; + if removable && !system { + let disk = v.get("pkname").and_then(|p| p.as_str()).map(|p| format!("/dev/{p}")); + out.push(Volume { device: path.to_string(), disk, mountpoint: mp.to_string() }); + } + } + if let Some(serde_json::Value::Array(children)) = v.get("children") { + for c in children { + walk(c, removable, out); + } + } + } + let Ok(root) = serde_json::from_str::(json) else { return vec![] }; + let mut out = vec![]; + if let Some(serde_json::Value::Array(devs)) = root.get("blockdevices") { + for d in devs { + walk(d, false, &mut out); + } + } + out +} + +pub fn ejectable() -> Vec { + sys::output("lsblk", &["-J", "-o", "PATH,PKNAME,RM,HOTPLUG,MOUNTPOINT,TYPE"]).map(|j| parse_lsblk(&j)).unwrap_or_default() +} + +/// Unmount every ejectable volume and power off its disk. Returns how many were unmounted. +pub fn eject_all() -> usize { + let vols = ejectable(); + let mut done = 0; + let mut disks: Vec = vec![]; + for v in &vols { + if sys::run("udisksctl", &["unmount", "-b", &v.device, "--no-user-interaction"]) || sys::run("gio", &["mount", "-u", &v.mountpoint]) { + done += 1; + if let Some(d) = &v.disk { + if !disks.contains(d) { + disks.push(d.clone()); + } + } + } + } + for d in disks { + let _ = sys::run("udisksctl", &["power-off", "-b", &d, "--no-user-interaction"]); + } + done +} + +// --------------------------------------------------------------------------------------------- +// Brightness +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Backlight { + pub name: String, + pub value: u32, + pub max: u32, +} + +impl Backlight { + pub fn percent(&self) -> u32 { + if self.max == 0 { + 0 + } else { + ((self.value as f64 / self.max as f64) * 100.0).round() as u32 + } + } +} + +pub fn read_backlight_in(dir: &Path) -> Option { + let mut entries: Vec<_> = std::fs::read_dir(dir).ok()?.filter_map(Result::ok).collect(); + entries.sort_by_key(|e| e.file_name()); + // the firmware interfaces last, like the kernel's own preference (raw > platform > firmware) + let rank = |p: &Path| match std::fs::read_to_string(p.join("type")).unwrap_or_default().trim() { + "raw" => 0, + "platform" => 1, + _ => 2, + }; + entries.sort_by_key(|e| rank(&e.path())); + let e = entries.first()?; + let read = |f: &str| std::fs::read_to_string(e.path().join(f)).ok()?.trim().parse::().ok(); + Some(Backlight { name: e.file_name().to_string_lossy().into_owned(), value: read("brightness")?, max: read("max_brightness")? }) +} + +pub fn backlight() -> Option { + read_backlight_in(Path::new("/sys/class/backlight")) +} + +/// Set the built-in screen (through logind, no root needed) and external displays (DDC/CI with +/// `ddcutil`, when installed) to `percent`. Returns whether anything changed. +pub fn set_brightness(percent: u32) -> bool { + let p = percent.clamp(1, 100); + let mut ok = false; + if let Some(b) = backlight() { + let value = ((b.max as f64) * p as f64 / 100.0).round().max(1.0) as u32; + ok |= sys::run( + "busctl", + &["call", "org.freedesktop.login1", "/org/freedesktop/login1/session/auto", "org.freedesktop.login1.Session", "SetBrightness", "ssu", "backlight", &b.name, &value.to_string()], + ); + } + if sys::has("ddcutil") { + ok |= sys::run("ddcutil", &["setvcp", "10", &p.to_string()]); + } + ok +} + +// --------------------------------------------------------------------------------------------- +// Running apps (quit, force quit) +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunningApp { + pub app_id: String, + pub name: String, + pub icon: Option, + pub pids: Vec, +} + +/// The program a desktop entry starts: the first word of `Exec` that is not `env` or a variable, +/// without its folder (`/usr/bin/firefox %u` -> `firefox`). +pub fn exec_program(exec: &str) -> Option { + // split into words, keeping "quoted paths with spaces" together + let mut words: Vec = vec![]; + let mut cur = String::new(); + let mut quoted = false; + for c in exec.chars() { + match c { + '"' => quoted = !quoted, + c if c.is_whitespace() && !quoted => { + if !cur.is_empty() { + words.push(std::mem::take(&mut cur)); + } + } + c => cur.push(c), + } + } + if !cur.is_empty() { + words.push(cur); + } + let w = words.into_iter().find(|w| !(w == "env" || w.contains('=') || w.starts_with('-')))?; + if w.starts_with('%') { + return None; + } + Some(w.rsplit('/').next().unwrap_or(&w).to_string()) +} + +/// Programs that are never offered for quitting: the desktop itself and Menew. +const NEVER_QUIT: [&str; 14] = [ + "menew", "gnome-shell", "plasmashell", "kwin_wayland", "kwin_x11", "Xwayland", "systemd", "dbus-daemon", "pipewire", "wireplumber", + "gnome-session-binary", "ksmserver", "xdg-desktop-portal", "nautilus-desktop", +]; + +/// Match the processes of this user (`comm` or the executable's name) with the desktop entries. +/// `procs` is `(pid, uid, comm, exe name)`. +pub fn match_running(apps: &[DesktopApp], procs: &[(u32, u32, String, String)], uid: u32, never: &[String]) -> Vec { + let mut out: Vec = vec![]; + for app in apps { + if app.terminal { + continue; + } + let Some(prog) = exec_program(&app.exec) else { continue }; + if NEVER_QUIT.contains(&prog.as_str()) || never.iter().any(|n| n.trim_end_matches(".desktop") == app.id.trim_end_matches(".desktop") || n == &prog) { + continue; + } + // comm is cut at 15 characters by the kernel + let short: String = prog.chars().take(15).collect(); + let pids: Vec = procs.iter().filter(|p| p.1 == uid && (p.3 == prog || p.2 == short)).map(|p| p.0).collect(); + if !pids.is_empty() && !out.iter().any(|r| r.pids == pids) { + out.push(RunningApp { app_id: app.id.clone(), name: app.name.clone(), icon: app.icon.clone(), pids }); + } + } + out.sort_by_key(|a| a.name.to_lowercase()); + out +} + +/// Every process of `/proc`: `(pid, uid, comm, exe name)`. +pub fn processes() -> Vec<(u32, u32, String, String)> { + let Ok(rd) = std::fs::read_dir("/proc") else { return vec![] }; + rd.filter_map(Result::ok) + .filter_map(|e| { + let pid: u32 = e.file_name().to_str()?.parse().ok()?; + let dir = e.path(); + let comm = std::fs::read_to_string(dir.join("comm")).ok()?.trim().to_string(); + let status = std::fs::read_to_string(dir.join("status")).ok()?; + let uid = status.lines().find_map(|l| l.strip_prefix("Uid:"))?.split_whitespace().next()?.parse().ok()?; + let exe = std::fs::read_link(dir.join("exe")).ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); + Some((pid, uid, comm, exe)) + }) + .collect() +} + +pub fn current_uid() -> u32 { + #[cfg(target_os = "linux")] + { + // SAFETY: getuid never fails + unsafe { libc::getuid() } + } + #[cfg(not(target_os = "linux"))] + { + 0 + } +} + +pub fn running_apps(apps: &[DesktopApp], never: &[String]) -> Vec { + match_running(apps, &processes(), current_uid(), never) +} + +/// SIGTERM (apps can save) or SIGKILL (force quit) to every process of the app. +pub fn quit_pids(pids: &[u32], force: bool) -> bool { + let sig = if force { 9 } else { 15 }; + let mut ok = false; + for p in pids { + ok |= sys::signal(*p, sig); + } + ok +} + +// --------------------------------------------------------------------------------------------- +// Ports in use +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ListeningPort { + pub port: u16, + pub pid: u32, + pub command: String, +} + +/// The listening TCP sockets of `/proc/net/tcp` (or `tcp6`): `(port, inode)`. +pub fn parse_proc_net_tcp(text: &str) -> Vec<(u16, u64)> { + text.lines() + .skip(1) + .filter_map(|l| { + let f: Vec<&str> = l.split_whitespace().collect(); + if f.len() < 10 || f[3] != "0A" { + return None; + } + let port = u16::from_str_radix(f[1].rsplit(':').next()?, 16).ok()?; + let inode = f[9].parse().ok()?; + Some((port, inode)) + }) + .collect() +} + +/// Servers this user runs, one row per port (like `lsof -iTCP -sTCP:LISTEN` on the Mac). +pub fn listening_ports() -> Vec { + let mut socks: Vec<(u16, u64)> = vec![]; + for f in ["/proc/net/tcp", "/proc/net/tcp6"] { + socks.extend(parse_proc_net_tcp(&std::fs::read_to_string(f).unwrap_or_default())); + } + if socks.is_empty() { + return vec![]; + } + let uid = current_uid(); + let mut out: Vec = vec![]; + for (pid, puid, comm, _) in processes() { + if puid != uid { + continue; + } + let Ok(fds) = std::fs::read_dir(format!("/proc/{pid}/fd")) else { continue }; + for fd in fds.filter_map(Result::ok) { + let Ok(target) = std::fs::read_link(fd.path()) else { continue }; + let t = target.to_string_lossy(); + let Some(inode) = t.strip_prefix("socket:[").and_then(|r| r.strip_suffix(']')).and_then(|n| n.parse::().ok()) else { continue }; + for (port, _) in socks.iter().filter(|s| s.1 == inode) { + if !out.iter().any(|p| p.port == *port) { + out.push(ListeningPort { port: *port, pid, command: comm.clone() }); + } + } + } + } + out.sort_by_key(|p| p.port); + out +} + +// --------------------------------------------------------------------------------------------- +// State and palette items +// --------------------------------------------------------------------------------------------- + +/// What the quick actions show right now (read when the palette opens). +#[derive(Debug, Clone, Default)] +pub struct ToolState { + pub mic_muted: Option, + pub sound_muted: Option, + pub dark: Option, + pub awake: bool, + pub outputs: Vec, + pub inputs: Vec, + pub output: Option, + pub input: Option, + pub ejectable: usize, + pub has_backlight: bool, +} + +impl ToolState { + /// Read everything (a few short process calls; run it off the GTK thread). + pub fn read(desktop: Desktop) -> Self { + Self { + mic_muted: is_muted(true), + sound_muted: is_muted(false), + dark: is_dark(desktop), + awake: false, + outputs: devices(false), + inputs: devices(true), + output: default_device(false), + input: default_device(true), + ejectable: ejectable().len(), + has_backlight: backlight().is_some() || sys::has("ddcutil"), + } + } +} + +fn cmd(id: &str, title: &str, icon: &'static str, kw: &str, command: &str) -> PaletteItem { + PaletteItem::new(&format!("action.{id}"), Kind::Action, title).kw(kw).icon(Icon::Symbol(icon)).act(ItemAction::Command(command.to_string())) +} + +/// The quick actions of the palette (the Mac's `Palette.commands`, `Module.actions` part). +pub fn items(st: &ToolState, lang: Language) -> Vec { + let mut out = vec![]; + let muted = st.mic_muted == Some(true); + out.push( + cmd("mic", &tr(if muted { "qa_mic_on" } else { "qa_mic_off" }, lang, &[]), if muted { "microphone-sensitivity-muted-symbolic" } else { "audio-input-microphone-symbolic" }, + "mic microphone microfone mute mudo silenciar reunião meeting mikrofon micrófono 麦克风 静音", "qa.mic") + .shortcut("Ctrl+Alt+M"), + ); + let smuted = st.sound_muted == Some(true); + out.push(cmd("sound", &tr(if smuted { "qa_sound_on" } else { "qa_sound_off" }, lang, &[]), if smuted { "audio-volume-muted-symbolic" } else { "audio-volume-high-symbolic" }, + "sound som volume audio áudio mute mudo ton sonido 声音 静音", "qa.sound")); + let dark = st.dark == Some(true); + out.push(cmd("dark", &tr(if dark { "qa_light" } else { "qa_dark" }, lang, &[]), if dark { "weather-clear-symbolic" } else { "weather-clear-night-symbolic" }, + "dark mode escuro claro light tema theme aparência appearance dunkel oscuro 深色 浅色", "qa.dark")); + for d in st.outputs.iter().filter(|d| Some(&d.name) != st.output.as_ref()) { + out.push(cmd(&format!("out.{}", d.name), &tr("qa_output", lang, &[&d.description]), "audio-speakers-symbolic", + &format!("som saída output audio áudio speaker fone headphone ausgabe salida 输出 {}", d.description), &format!("qa.out:{}", d.name))); + } + for d in st.inputs.iter().filter(|d| Some(&d.name) != st.input.as_ref()) { + out.push(cmd(&format!("in.{}", d.name), &tr("qa_input", lang, &[&d.description]), "audio-input-microphone-symbolic", + &format!("microfone mic input entrada audio áudio mikrofon micrófono 麦克风 {}", d.description), &format!("qa.in:{}", d.name))); + } + let mut awake = cmd("awake", &tr(if st.awake { "qa_awake_off" } else { "qa_awake" }, lang, &[]), "preferences-desktop-screensaver-symbolic", + "awake acordado caffeine cafe café sleep dormir tela amphetamine wach despierto 唤醒 保持", "qa.awake"); + if !st.awake { + awake = awake.subtitle(&tr("qa_awake_sub", lang, &[])); + } + out.push(awake); + out.push(cmd("lock", &tr("qa_lock", lang, &[]), "system-lock-screen-symbolic", "lock bloquear tela screen sperren bloquear pantalla 锁定 锁屏", "qa.lock")); + out.push(cmd("trash", &tr("qa_trash", lang, &[]), "user-trash-full-symbolic", "trash lixeira lixo esvaziar empty papierkorb papelera 废纸篓 清空", "qa.trash")); + out.push(cmd("color", &tr("qa_color", lang, &[]), "color-select-symbolic", "color cor picker conta-gotas eyedropper hex farbe pipette 颜色 取色", "qa.color")); + out.push(cmd("plain", &tr("qa_plain", lang, &[]), "edit-clear-symbolic", "plain text texto puro sem formatação formatting clipboard reiner text texto plano 纯文本", "qa.plain")); + if st.ejectable > 0 { + out.push(cmd("eject", &tr("qa_eject", lang, &[]), "media-eject-symbolic", "eject ejetar disco disk usb pendrive auswerfen expulsar 弹出", "qa.eject") + .subtitle(&tr("qa_eject_sub", lang, &[&st.ejectable.to_string()]))); + } + if st.has_backlight { + out.push(cmd("brightness", &tr("qa_brightness", lang, &[]), "display-brightness-symbolic", "brightness brilho tela screen helligkeit brillo 亮度", "") + .subtitle(&tr("qa_brightness_sub", lang, &[])).forget().keep_open().act(ItemAction::FillQuery(tr("qa_brightness_word", lang, &[]) + " "))); + } + out.push(cmd("quitall", &tr("qa_quit_all", lang, &[]), "window-close-symbolic", "fechar todos quit all close apps encerrar sair alle beenden cerrar todas 退出 全部", "qa.quitall")); + out.push(cmd("ports", &tr("qa_ports", lang, &[]), "network-server-symbolic", "port porta ports portas server servidor localhost listen dev stop kill", "") + .forget().keep_open().act(ItemAction::FillQuery(tr("qa_ports_word", lang, &[]) + " "))); + out +} + +/// Typed items: `awake 2h`, `brightness 50`, `quit firefox`, `port 3000`. +pub fn typed_items(q: &str, running: &dyn Fn() -> Vec, ports: &dyn Fn() -> Vec, lang: Language) -> Vec { + let q = fold(q.trim()); + let (word, rest) = match q.split_once(' ') { + Some((w, r)) => (w, r.trim()), + None => (q.as_str(), ""), + }; + let mut out = vec![]; + let is = |words: &[&str]| words.iter().any(|w| fold(w) == word); + if is(&["awake", "acordado", "wach", "despierto", "唤醒", "caffeine"]) { + if let Some(m) = parse_duration_minutes(rest) { + out.push(PaletteItem::new("qa.awake.timed", Kind::Action, &tr("qa_awake_for", lang, &[&crate::timers::span_text(m as f64 * 60.0)])) + .kw(&q).icon(Icon::Symbol("preferences-desktop-screensaver-symbolic")).forget().act(ItemAction::Command(format!("qa.awake:{m}")))); + } + } + if is(&["brightness", "brilho", "helligkeit", "brillo", "亮度"]) { + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + if let Ok(p) = digits.parse::() { + if (1..=100).contains(&p) { + out.push(PaletteItem::new("qa.brightness.set", Kind::Action, &tr("qa_brightness_to", lang, &[&p.to_string()])) + .kw(&q).icon(Icon::Symbol("display-brightness-symbolic")).forget().act(ItemAction::Command(format!("qa.bright:{p}")))); + } + } + } + if is(&["quit", "fechar", "close", "beenden", "cerrar", "退出", "kill", "force", "forcar"]) { + let force = is(&["kill", "force", "forcar"]); + let needle = fold(rest); + for app in running() { + if needle.is_empty() || fold(&app.name).contains(&needle) { + let pids = app.pids.iter().map(|p| p.to_string()).collect::>().join(","); + let key = if force { "qa_force_quit_app" } else { "qa_quit_app" }; + out.push(PaletteItem::new(&format!("qa.quit.{}", app.app_id), Kind::Action, &tr(key, lang, &[&app.name])) + .kw(&q).icon(Icon::App(app.icon.clone())).forget().act(ItemAction::Command(format!("qa.{}:{pids}", if force { "force" } else { "quit" })))); + } + } + } + if is(&["port", "porta", "ports", "portas", "puerto", "端口"]) { + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + for p in ports() { + if digits.is_empty() || p.port.to_string().starts_with(&digits) { + out.push(PaletteItem::new(&format!("qa.port.{}", p.port), Kind::Action, &tr("qa_port_stop", lang, &[&p.port.to_string(), &p.command])) + .subtitle(&format!("PID {}", p.pid)).kw(&q).icon(Icon::Symbol("network-server-symbolic")).forget() + .act(ItemAction::Command(format!("qa.port:{}", p.pid)))); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn audio_devices_from_pactl_json() { + let json = r#"[{"index":1,"name":"alsa_output.pci.analog-stereo","description":"Built-in Audio"}, + {"index":2,"name":"alsa_output.pci.analog-stereo.monitor","description":"Monitor of Built-in"}, + {"index":3,"name":"bluez_output.AA","description":"Headphones"}]"#; + let d = parse_devices(json); + assert_eq!(d.len(), 2); + assert_eq!(d[1].description, "Headphones"); + assert!(parse_devices("not json").is_empty()); + } + + #[test] + fn mute_state_from_pactl_and_wpctl() { + assert_eq!(parse_muted("Mute: yes\n"), Some(true)); + assert_eq!(parse_muted("Mute: no"), Some(false)); + assert_eq!(parse_muted("Volume: 0.40 [MUTED]"), Some(true)); + assert_eq!(parse_muted("Volume: 0.40"), Some(false)); + assert_eq!(parse_muted("??"), None); + } + + #[test] + fn dark_mode_state() { + assert!(parse_gnome_scheme("'prefer-dark'\n")); + assert!(!parse_gnome_scheme("'default'")); + let kde = "[Colors:View]\nColorScheme=Nope\n[General]\nColorScheme=BreezeDark\nfont=x\n"; + assert_eq!(parse_kde_scheme(kde).as_deref(), Some("BreezeDark")); + assert_eq!(parse_kde_scheme("[General]\nfoo=1\n"), None); + } + + #[test] + fn durations_like_the_mac() { + assert_eq!(parse_duration_minutes("2h"), Some(120)); + assert_eq!(parse_duration_minutes("90m"), Some(90)); + assert_eq!(parse_duration_minutes("45"), Some(45)); + assert_eq!(parse_duration_minutes("1 hora"), Some(60)); + assert_eq!(parse_duration_minutes("0"), None); + assert_eq!(parse_duration_minutes("25h"), None); + assert_eq!(parse_duration_minutes("2x"), None); + } + + #[test] + fn only_removable_mounted_volumes_are_ejectable() { + let json = r#"{"blockdevices":[ + {"path":"/dev/nvme0n1","pkname":null,"rm":false,"hotplug":false,"mountpoint":null,"type":"disk","children":[ + {"path":"/dev/nvme0n1p1","pkname":"nvme0n1","rm":false,"hotplug":false,"mountpoint":"/boot/efi","type":"part"}, + {"path":"/dev/nvme0n1p2","pkname":"nvme0n1","rm":false,"hotplug":false,"mountpoint":"/","type":"part"}]}, + {"path":"/dev/sdb","pkname":null,"rm":true,"hotplug":true,"mountpoint":null,"type":"disk","children":[ + {"path":"/dev/sdb1","pkname":"sdb","rm":true,"hotplug":true,"mountpoint":"/media/u/STICK","type":"part"}, + {"path":"/dev/sdb2","pkname":"sdb","rm":true,"hotplug":true,"mountpoint":null,"type":"part"}]}, + {"path":"/dev/sdc","pkname":null,"rm":"0","hotplug":"1","mountpoint":"/run/media/u/EXT","type":"disk"} + ]}"#; + let v = parse_lsblk(json); + assert_eq!(v.len(), 2, "{v:?}"); + assert_eq!(v[0], Volume { device: "/dev/sdb1".into(), disk: Some("/dev/sdb".into()), mountpoint: "/media/u/STICK".into() }); + assert_eq!(v[1].device, "/dev/sdc"); + } + + #[test] + fn backlight_from_sysfs() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("intel_backlight"); + std::fs::create_dir(&b).unwrap(); + std::fs::write(b.join("brightness"), "480\n").unwrap(); + std::fs::write(b.join("max_brightness"), "960\n").unwrap(); + std::fs::write(b.join("type"), "raw\n").unwrap(); + let a = dir.path().join("acpi_video0"); + std::fs::create_dir(&a).unwrap(); + std::fs::write(a.join("brightness"), "1\n").unwrap(); + std::fs::write(a.join("max_brightness"), "10\n").unwrap(); + std::fs::write(a.join("type"), "firmware\n").unwrap(); + let bl = read_backlight_in(dir.path()).unwrap(); + assert_eq!(bl.name, "intel_backlight"); + assert_eq!(bl.percent(), 50); + } + + #[test] + fn exec_program_of_desktop_entries() { + assert_eq!(exec_program("/usr/bin/firefox %u").as_deref(), Some("firefox")); + assert_eq!(exec_program("env GDK_BACKEND=x11 code --new-window %F").as_deref(), Some("code")); + assert_eq!(exec_program("\"/opt/My App/app\" --x").as_deref(), Some("app")); + assert_eq!(exec_program("%u"), None); + } + + fn app(id: &str, name: &str, exec: &str) -> DesktopApp { + DesktopApp::parse_content(&format!("[Desktop Entry]\nType=Application\nName={name}\nExec={exec}\n"), Path::new(&format!("/x/{id}"))).unwrap() + } + + #[test] + fn running_apps_are_matched_by_program_and_owner() { + let apps = vec![app("firefox.desktop", "Firefox", "firefox %u"), app("gedit.desktop", "Text Editor", "gedit"), app("menew.desktop", "Menew", "menew")]; + let procs = vec![ + (100, 1000, "firefox".to_string(), "firefox".to_string()), + (101, 1000, "Isolated Web Co".to_string(), "firefox".to_string()), + (200, 0, "gedit".to_string(), "gedit".to_string()), + (300, 1000, "menew".to_string(), "menew".to_string()), + ]; + let r = match_running(&apps, &procs, 1000, &[]); + assert_eq!(r.len(), 1, "{r:?}"); + assert_eq!(r[0].pids, vec![100, 101]); + assert!(match_running(&apps, &procs, 1000, &["firefox.desktop".to_string()]).is_empty()); + } + + #[test] + fn listening_sockets_from_proc_net_tcp() { + let text = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n 0: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000000000000000 100 0 0 10 0\n 1: 0100007F:A1B2 0100007F:0BB8 01 00000000:00000000 00:00000000 00000000 1000 0 999 1\n"; + assert_eq!(parse_proc_net_tcp(text), vec![(3000, 12345)]); + } + + #[test] + fn typed_quick_actions() { + let lang = Language::En; + let none_apps = || vec![]; + let none_ports = || vec![]; + let a = typed_items("awake 2h", &none_apps, &none_ports, lang); + assert_eq!(a[0].action, ItemAction::Command("qa.awake:120".into())); + let b = typed_items("brilho 40", &none_apps, &none_ports, Language::Pt); + assert_eq!(b[0].action, ItemAction::Command("qa.bright:40".into())); + assert!(typed_items("brightness 400", &none_apps, &none_ports, lang).is_empty()); + let apps = || vec![RunningApp { app_id: "f".into(), name: "Firefox".into(), icon: None, pids: vec![5, 6] }]; + let q = typed_items("quit fire", &apps, &none_ports, lang); + assert_eq!(q[0].action, ItemAction::Command("qa.quit:5,6".into())); + let k = typed_items("kill fire", &apps, &none_ports, lang); + assert_eq!(k[0].action, ItemAction::Command("qa.force:5,6".into())); + let ports = || vec![ListeningPort { port: 3000, pid: 42, command: "node".into() }, ListeningPort { port: 8080, pid: 43, command: "python3".into() }]; + let p = typed_items("port 30", &none_apps, &ports, lang); + assert_eq!(p.len(), 1); + assert_eq!(p[0].action, ItemAction::Command("qa.port:42".into())); + assert_eq!(typed_items("port", &none_apps, &ports, lang).len(), 2); + } + + #[test] + fn items_follow_the_state() { + let st = ToolState { + mic_muted: Some(true), + outputs: vec![AudioDevice { name: "a".into(), description: "Speakers".into() }, AudioDevice { name: "b".into(), description: "Headphones".into() }], + output: Some("a".into()), + ..ToolState::default() + }; + let items = items(&st, Language::En); + let mic = items.iter().find(|i| i.id == "action.mic").unwrap(); + assert_eq!(mic.title, tr("qa_mic_on", Language::En, &[])); + assert!(items.iter().any(|i| i.action == ItemAction::Command("qa.out:b".into()))); + assert!(!items.iter().any(|i| i.action == ItemAction::Command("qa.out:a".into()))); + assert!(!items.iter().any(|i| i.id == "action.eject")); + } +} diff --git a/crates/menew-core/src/strings.rs b/crates/menew-core/src/strings.rs index 31deed5..6a4084c 100644 --- a/crates/menew-core/src/strings.rs +++ b/crates/menew-core/src/strings.rs @@ -18,7 +18,7 @@ fn column(lang: Language) -> usize { /// Translation of `key`, or `None` if the key is not in the palette table. pub fn lookup(key: &str, lang: Language) -> Option<&'static str> { - TABLE.iter().find(|(k, _)| *k == key).map(|(_, v)| v[column(lang)]) + all().find(|(k, _)| *k == key).map(|(_, v)| v[column(lang)]) } /// Fill `{}` / `{1}` placeholders. @@ -70,11 +70,16 @@ pub fn tr(key: &str, lang: Language, args: &[&str]) -> String { /// Every key of the table (used by the tests). pub fn keys() -> impl Iterator { - TABLE.iter().map(|(k, _)| *k) + all().map(|(k, _)| *k) } pub fn row(key: &str) -> Option<&'static [&'static str; 5]> { - TABLE.iter().find(|(k, _)| *k == key).map(|(_, v)| v) + all().find(|(k, _)| *k == key).map(|(_, v)| v) +} + +/// The palette and clipboard table, then the release 1 table (`strings_r1.rs`). +fn all() -> impl Iterator { + TABLE.iter().chain(crate::strings_r1::TABLE.iter()) } #[rustfmt::skip] @@ -515,7 +520,7 @@ mod tests { #[test] fn every_key_is_filled_in_all_5_languages() { - for (key, row) in TABLE { + for (key, row) in all() { for (i, v) in row.iter().enumerate() { assert!(!v.trim().is_empty(), "{key}: empty text for {:?}", LANGS[i]); assert!(!v.contains('\u{2014}'), "{key}: em-dash in {:?}", LANGS[i]); @@ -531,7 +536,7 @@ mod tests { #[test] fn keys_are_unique() { let mut seen = std::collections::HashSet::new(); - for (k, _) in TABLE { + for (k, _) in all() { assert!(seen.insert(*k), "duplicate key {k}"); } } diff --git a/crates/menew-core/src/strings_r1.rs b/crates/menew-core/src/strings_r1.rs new file mode 100644 index 0000000..7376dd2 --- /dev/null +++ b/crates/menew-core/src/strings_r1.rs @@ -0,0 +1,88 @@ +//! Strings of the release 1 features (quick actions, window snapping and their shortcuts), in the same 5 columns as +//! `strings.rs`: en, pt, de, es, zh. Texts follow the Mac app (`L10n.swift`) where it has them. + +#[rustfmt::skip] +pub(crate) static TABLE: &[(&str, [&str; 5])] = &[ + // ---- quick actions (Toolbox.swift, AppControl.swift, Ports.swift) ---- + ("qa_mic_off", ["Mute microphone", "Mutar microfone", "Mikrofon stummschalten", "Silenciar micrófono", "麦克风静音"]), + ("qa_mic_on", ["Unmute microphone", "Ligar microfone", "Mikrofon einschalten", "Activar micrófono", "打开麦克风"]), + ("qa_mic_muted", ["Microphone muted", "Microfone mudo", "Mikrofon stumm", "Micrófono silenciado", "麦克风已静音"]), + ("qa_mic_live", ["Microphone on", "Microfone ligado", "Mikrofon an", "Micrófono activado", "麦克风已打开"]), + ("qa_sound_off", ["Mute sound", "Mutar som", "Ton stummschalten", "Silenciar sonido", "声音静音"]), + ("qa_sound_on", ["Unmute sound", "Ligar som", "Ton einschalten", "Activar sonido", "打开声音"]), + ("qa_sound_muted", ["Sound muted", "Som mudo", "Ton stumm", "Sonido silenciado", "声音已静音"]), + ("qa_sound_live", ["Sound on", "Som ligado", "Ton an", "Sonido activado", "声音已打开"]), + ("qa_cant_mute", ["This device can't be muted", "Este dispositivo não pode ser mutado", "Dieses Gerät kann nicht stummgeschaltet werden", "Este dispositivo no se puede silenciar", "此设备无法静音"]), + ("qa_dark", ["Dark mode", "Modo escuro", "Dunkelmodus", "Modo oscuro", "深色模式"]), + ("qa_light", ["Light mode", "Modo claro", "Hellmodus", "Modo claro", "浅色模式"]), + ("qa_output", ["Sound output: {}", "Saída de som: {}", "Tonausgabe: {}", "Salida de sonido: {}", "声音输出:{}"]), + ("qa_input", ["Microphone: {}", "Microfone: {}", "Mikrofon: {}", "Micrófono: {}", "麦克风:{}"]), + ("qa_switched", ["Now using {}", "Agora usando {}", "Jetzt mit {}", "Ahora usando {}", "现在使用 {}"]), + ("qa_awake", ["Keep awake", "Manter acordado", "Wach halten", "Mantener despierto", "保持唤醒"]), + ("qa_awake_off", ["Turn off keep awake", "Desligar manter acordado", "Wach halten ausschalten", "Desactivar mantener despierto", "关闭保持唤醒"]), + ("qa_awake_sub", ["Type a time, like “awake 2h”", "Digite um tempo, como “acordado 2h”", "Gib eine Zeit ein, z. B. „wach 2h“", "Escribe un tiempo, como «despierto 2h»", "输入时间,例如“唤醒 2h”"]), + ("qa_awake_for", ["Keep awake for {}", "Manter acordado por {}", "{} wach halten", "Mantener despierto {}", "保持唤醒 {}"]), + ("qa_awake_started", ["Keeping the computer awake", "Mantendo o computador acordado", "Der Computer bleibt wach", "Manteniendo el ordenador despierto", "正在保持电脑唤醒"]), + ("qa_awake_stopped", ["Keep awake turned off", "Manter acordado desligado", "Wach halten ausgeschaltet", "Mantener despierto desactivado", "已关闭保持唤醒"]), + ("qa_awake_refused", ["The system refused to keep the computer awake", "O sistema não deixou manter o computador acordado", "Das System lässt den Computer nicht wach halten", "El sistema no permitió mantener el ordenador despierto", "系统拒绝保持电脑唤醒"]), + ("qa_awake_missing", ["Keep awake needs systemd-inhibit", "Manter acordado precisa do systemd-inhibit", "Wach halten braucht systemd-inhibit", "Mantener despierto necesita systemd-inhibit", "保持唤醒需要 systemd-inhibit"]), + ("qa_lock", ["Lock screen", "Bloquear tela", "Bildschirm sperren", "Bloquear pantalla", "锁定屏幕"]), + ("qa_trash", ["Empty trash", "Esvaziar lixeira", "Papierkorb leeren", "Vaciar papelera", "清空废纸篓"]), + ("qa_trash_ask", ["Empty the trash?", "Esvaziar a lixeira?", "Papierkorb leeren?", "¿Vaciar la papelera?", "清空废纸篓?"]), + ("qa_trash_body", ["The items will be deleted for good.", "Os itens serão apagados permanentemente.", "Die Objekte werden endgültig gelöscht.", "Los elementos se borrarán para siempre.", "这些项目将被永久删除。"]), + ("qa_trash_empty_btn", ["Empty", "Esvaziar", "Leeren", "Vaciar", "清空"]), + ("qa_trash_done", ["Trash emptied", "Lixeira esvaziada", "Papierkorb geleert", "Papelera vaciada", "废纸篓已清空"]), + ("qa_trash_already", ["The trash is already empty", "A lixeira já está vazia", "Der Papierkorb ist schon leer", "La papelera ya está vacía", "废纸篓已经是空的"]), + ("cancel", ["Cancel", "Cancelar", "Abbrechen", "Cancelar", "取消"]), + ("qa_color", ["Pick a color from the screen", "Pegar uma cor da tela", "Farbe vom Bildschirm wählen", "Tomar un color de la pantalla", "从屏幕取色"]), + ("qa_color_fail", ["The color picker is not available here", "O conta-gotas não está disponível aqui", "Die Farbauswahl ist hier nicht verfügbar", "El cuentagotas no está disponible aquí", "此处无法使用取色器"]), + ("qa_plain", ["Plain text clipboard", "Clipboard em texto puro", "Zwischenablage als reiner Text", "Portapapeles en texto plano", "剪贴板转为纯文本"]), + ("qa_plain_done", ["The clipboard now has plain text", "O clipboard agora tem texto puro", "Die Zwischenablage enthält jetzt reinen Text", "El portapapeles ahora tiene texto plano", "剪贴板现在是纯文本"]), + ("qa_plain_none", ["There is no text on the clipboard", "Não há texto no clipboard", "In der Zwischenablage ist kein Text", "No hay texto en el portapapeles", "剪贴板中没有文本"]), + ("qa_eject", ["Eject all disks", "Ejetar todos os discos", "Alle Laufwerke auswerfen", "Expulsar todos los discos", "弹出所有磁盘"]), + ("qa_eject_sub", ["{} mounted", "{} montado(s)", "{} eingehängt", "{} montado(s)", "已挂载 {} 个"]), + ("qa_ejected", ["Ejected {}", "{} ejetado(s)", "{} ausgeworfen", "{} expulsado(s)", "已弹出 {} 个"]), + ("qa_eject_fail", ["Couldn't eject: a file may be open", "Não deu para ejetar: algum arquivo pode estar aberto", "Auswerfen nicht möglich: Eine Datei ist evtl. geöffnet", "No se pudo expulsar: puede haber un archivo abierto", "无法弹出:可能有文件仍在打开"]), + ("qa_brightness", ["Screen brightness", "Brilho da tela", "Bildschirmhelligkeit", "Brillo de la pantalla", "屏幕亮度"]), + ("qa_brightness_sub", ["Type a value, like “brightness 50”", "Digite um valor, como “brilho 50”", "Gib einen Wert ein, z. B. „helligkeit 50“", "Escribe un valor, como «brillo 50»", "输入数值,例如“亮度 50”"]), + ("qa_brightness_word", ["brightness", "brilho", "helligkeit", "brillo", "亮度"]), + ("qa_brightness_to", ["Set brightness to {}%", "Brilho em {}%", "Helligkeit auf {} %", "Brillo al {}%", "亮度设为 {}%"]), + ("qa_brightness_fail", ["Couldn't change the brightness", "Não deu para mudar o brilho", "Helligkeit konnte nicht geändert werden", "No se pudo cambiar el brillo", "无法调整亮度"]), + ("qa_quit_all", ["Quit all apps", "Fechar todos os apps", "Alle Apps beenden", "Cerrar todas las apps", "退出全部应用"]), + ("qa_quit_app", ["Quit {}", "Fechar {}", "{} beenden", "Cerrar {}", "退出 {}"]), + ("qa_force_quit_app", ["Force quit {}", "Forçar fechar {}", "{} sofort beenden", "Forzar cierre de {}", "强制退出 {}"]), + ("qa_quit_done", ["Asked {} apps to quit", "Pedi para {} apps fecharem", "{} Apps zum Beenden aufgefordert", "Se pidió a {} apps que se cierren", "已请求 {} 个应用退出"]), + ("qa_ports", ["Ports in use", "Portas em uso", "Belegte Ports", "Puertos en uso", "占用的端口"]), + ("qa_ports_word", ["port", "porta", "port", "puerto", "端口"]), + ("qa_port_stop", ["Stop port {} ({})", "Parar porta {} ({})", "Port {} stoppen ({})", "Detener puerto {} ({})", "停止端口 {}({})"]), + ("qa_port_stopped", ["Server stopped", "Servidor parado", "Server gestoppt", "Servidor detenido", "服务器已停止"]), + ("qa_failed", ["That didn't work here", "Não funcionou aqui", "Das hat hier nicht geklappt", "Eso no funcionó aquí", "此处无法执行"]), + // ---- global shortcuts (HotKey.swift) ---- + ("sc_mute_mic", ["Mute or unmute the microphone", "Mutar ou ligar o microfone", "Mikrofon stumm oder an", "Silenciar o activar el micrófono", "麦克风静音或打开"]), + ("sc_snap_left", ["Window: left half", "Janela: metade esquerda", "Fenster: linke Hälfte", "Ventana: mitad izquierda", "窗口:左半边"]), + ("sc_snap_right", ["Window: right half", "Janela: metade direita", "Fenster: rechte Hälfte", "Ventana: mitad derecha", "窗口:右半边"]), + ("sc_snap_top", ["Window: top half", "Janela: metade de cima", "Fenster: obere Hälfte", "Ventana: mitad superior", "窗口:上半边"]), + ("sc_snap_bottom", ["Window: bottom half", "Janela: metade de baixo", "Fenster: untere Hälfte", "Ventana: mitad inferior", "窗口:下半边"]), + ("sc_snap_max", ["Window: fill the screen", "Janela: tela cheia", "Fenster: ganzer Bildschirm", "Ventana: pantalla completa", "窗口:填满屏幕"]), + ("sc_new_note", ["New note", "Nova nota", "Neue Notiz", "Nueva nota", "新建笔记"]), + // ---- windows (Windows.swift) ---- + ("win_left", ["Window on the left half", "Janela na metade esquerda", "Fenster in die linke Hälfte", "Ventana en la mitad izquierda", "窗口置于左半边"]), + ("win_right", ["Window on the right half", "Janela na metade direita", "Fenster in die rechte Hälfte", "Ventana en la mitad derecha", "窗口置于右半边"]), + ("win_top", ["Window on the top half", "Janela na metade de cima", "Fenster in die obere Hälfte", "Ventana en la mitad superior", "窗口置于上半边"]), + ("win_bottom", ["Window on the bottom half", "Janela na metade de baixo", "Fenster in die untere Hälfte", "Ventana en la mitad inferior", "窗口置于下半边"]), + ("win_max", ["Maximize window", "Maximizar janela", "Fenster maximieren", "Maximizar ventana", "最大化窗口"]), + ("win_almost", ["Window almost full screen", "Janela quase tela cheia", "Fenster fast bildschirmfüllend", "Ventana casi a pantalla completa", "窗口接近全屏"]), + ("win_center", ["Center window", "Centralizar janela", "Fenster zentrieren", "Centrar ventana", "窗口居中"]), + ("win_topleft", ["Window in the top left corner", "Janela no canto superior esquerdo", "Fenster oben links", "Ventana arriba a la izquierda", "窗口置于左上角"]), + ("win_topright", ["Window in the top right corner", "Janela no canto superior direito", "Fenster oben rechts", "Ventana arriba a la derecha", "窗口置于右上角"]), + ("win_bottomleft", ["Window in the bottom left corner", "Janela no canto inferior esquerdo", "Fenster unten links", "Ventana abajo a la izquierda", "窗口置于左下角"]), + ("win_bottomright", ["Window in the bottom right corner", "Janela no canto inferior direito", "Fenster unten rechts", "Ventana abajo a la derecha", "窗口置于右下角"]), + ("win_leftthird", ["Window on the left third", "Janela no terço esquerdo", "Fenster im linken Drittel", "Ventana en el tercio izquierdo", "窗口置于左三分之一"]), + ("win_centerthird", ["Window on the center third", "Janela no terço do meio", "Fenster im mittleren Drittel", "Ventana en el tercio central", "窗口置于中间三分之一"]), + ("win_rightthird", ["Window on the right third", "Janela no terço direito", "Fenster im rechten Drittel", "Ventana en el tercio derecho", "窗口置于右三分之一"]), + ("win_lefttwothirds", ["Window on the left two thirds", "Janela nos dois terços da esquerda", "Fenster in den linken zwei Dritteln", "Ventana en los dos tercios izquierdos", "窗口置于左三分之二"]), + ("win_righttwothirds", ["Window on the right two thirds", "Janela nos dois terços da direita", "Fenster in den rechten zwei Dritteln", "Ventana en los dos tercios derechos", "窗口置于右三分之二"]), + ("win_display", ["Move window to the next display", "Mover janela para a outra tela", "Fenster auf den nächsten Bildschirm", "Mover ventana a la otra pantalla", "将窗口移到下一个显示器"]), + ("win_unsupported", ["Moving windows needs KDE Plasma or the Menew GNOME extension", "Mover janelas precisa do KDE Plasma ou da extensão do Menew no GNOME", "Fenster verschieben braucht KDE Plasma oder die Menew-GNOME-Erweiterung", "Mover ventanas necesita KDE Plasma o la extensión de Menew para GNOME", "移动窗口需要 KDE Plasma 或 Menew GNOME 扩展"]), + ("win_failed", ["Couldn't move the window", "Não deu para mover a janela", "Fenster konnte nicht verschoben werden", "No se pudo mover la ventana", "无法移动窗口"]), +]; diff --git a/crates/menew-core/src/sys.rs b/crates/menew-core/src/sys.rs new file mode 100644 index 0000000..4e5b08b --- /dev/null +++ b/crates/menew-core/src/sys.rs @@ -0,0 +1,100 @@ +//! Small helpers to run the desktop's own command line tools (`pactl`, `gsettings`, `loginctl`, +//! `udisksctl`...). Menew prefers these over extra crates: they are already on GNOME and KDE systems +//! and every call is visible in `ps`. Nothing here touches the network. + +use std::process::{Command, Stdio}; + +/// Run a program and return its standard output when it exits with success. +pub fn output(program: &str, args: &[&str]) -> Option { + let out = Command::new(program).args(args).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned()) +} + +/// Run a program and report whether it exited with success. +pub fn run(program: &str, args: &[&str]) -> bool { + Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) +} + +/// Whether a program is on `PATH`. +pub fn has(program: &str) -> bool { + let Some(path) = std::env::var_os("PATH") else { return false }; + std::env::split_paths(&path).any(|d| d.join(program).is_file()) +} + +/// The desktop the session runs, from `XDG_CURRENT_DESKTOP` (`ubuntu:GNOME`, `KDE`...). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Desktop { + Gnome, + Kde, + Other, +} + +impl Desktop { + pub fn from_value(v: &str) -> Self { + let v = v.to_ascii_lowercase(); + if v.split(':').any(|p| p == "kde") { + Desktop::Kde + } else if v.split(':').any(|p| p == "gnome" || p == "gnome-classic" || p == "unity") { + Desktop::Gnome + } else { + Desktop::Other + } + } + + pub fn detect() -> Self { + Self::from_value(&std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()) + } + + pub fn name(self) -> &'static str { + match self { + Desktop::Gnome => "GNOME", + Desktop::Kde => "KDE Plasma", + Desktop::Other => "other", + } + } +} + +/// Send a signal to a process (`SIGTERM` = 15, `SIGKILL` = 9). Only the user's own processes can +/// be signalled; anything else fails. +pub fn signal(pid: u32, sig: i32) -> bool { + #[cfg(target_os = "linux")] + { + if pid <= 1 { + return false; + } + // SAFETY: kill(2) has no memory effects; a wrong pid only returns an error + unsafe { libc::kill(pid as libc::pid_t, sig) == 0 } + } + #[cfg(not(target_os = "linux"))] + { + let _ = (pid, sig); + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn desktop_detection() { + assert_eq!(Desktop::from_value("ubuntu:GNOME"), Desktop::Gnome); + assert_eq!(Desktop::from_value("GNOME"), Desktop::Gnome); + assert_eq!(Desktop::from_value("KDE"), Desktop::Kde); + assert_eq!(Desktop::from_value("XFCE"), Desktop::Other); + assert_eq!(Desktop::from_value(""), Desktop::Other); + } + + #[test] + fn never_signals_init_or_pid_0() { + assert!(!signal(0, 15)); + assert!(!signal(1, 15)); + } +} diff --git a/crates/menew-core/src/windows.rs b/crates/menew-core/src/windows.rs new file mode 100644 index 0000000..32b8a5d --- /dev/null +++ b/crates/menew-core/src/windows.rs @@ -0,0 +1,68 @@ +//! Window positions in the palette (port of the `Windows.swift` palette items). The snapping itself +//! is in `menew-desktop`; here only the items, with the ids `win.`. + +use crate::i18n::Language; +use crate::palette::{Icon, ItemAction, Kind, PaletteItem}; +use crate::strings::tr; + +/// (position id, title key, extra keywords) +const POSITIONS: [(&str, &str, &str); 17] = [ + ("left", "win_left", "esquerda left links izquierda 左"), + ("right", "win_right", "direita right rechts derecha 右"), + ("top", "win_top", "cima top oben arriba 上"), + ("bottom", "win_bottom", "baixo bottom unten abajo 下"), + ("max", "win_max", "maximizar maximize cheia full maximieren maximizar 最大化"), + ("almost", "win_almost", "quase almost fast casi 几乎"), + ("center", "win_center", "centro center zentrieren centrar 居中"), + ("topleft", "win_topleft", "canto corner ecke esquina 角"), + ("topright", "win_topright", "canto corner ecke esquina 角"), + ("bottomleft", "win_bottomleft", "canto corner ecke esquina 角"), + ("bottomright", "win_bottomright", "canto corner ecke esquina 角"), + ("leftthird", "win_leftthird", "terço third drittel tercio 三分之一"), + ("centerthird", "win_centerthird", "terço third drittel tercio 三分之一"), + ("rightthird", "win_rightthird", "terço third drittel tercio 三分之一"), + ("lefttwothirds", "win_lefttwothirds", "dois terços two thirds zwei drittel dos tercios 三分之二"), + ("righttwothirds", "win_righttwothirds", "dois terços two thirds zwei drittel dos tercios 三分之二"), + ("display", "win_display", "monitor tela display screen bildschirm pantalla 显示器"), +]; + +pub fn items(lang: Language) -> Vec { + POSITIONS + .iter() + .map(|(id, key, kw)| { + let mut it = PaletteItem::new(&format!("window.{id}"), Kind::Window, &tr(key, lang, &[])) + .kw(&format!("janela window fenster ventana 窗口 snap encaixar {kw}")) + .icon(Icon::Symbol("view-grid-symbolic")) + .act(ItemAction::Command(format!("win.{id}"))); + let sc = match *id { + "left" => Some("Ctrl+Alt+Shift+←"), + "right" => Some("Ctrl+Alt+Shift+→"), + "top" => Some("Ctrl+Alt+Shift+↑"), + "bottom" => Some("Ctrl+Alt+Shift+↓"), + "max" => Some("Ctrl+Alt+↩"), + _ => None, + }; + if let Some(s) = sc { + it = it.shortcut(s); + } + it + }) + .collect() +} + +pub fn ids() -> impl Iterator { + POSITIONS.iter().map(|p| p.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_item_per_position() { + let it = items(Language::Pt); + assert_eq!(it.len(), 17); + assert_eq!(it[0].action, ItemAction::Command("win.left".into())); + assert_eq!(it[0].title, "Janela na metade esquerda"); + } +} diff --git a/crates/menew-core/tests/clipboard_spec.rs b/crates/menew-core/tests/clipboard_spec.rs index 8f34f08..8ff1d0b 100644 --- a/crates/menew-core/tests/clipboard_spec.rs +++ b/crates/menew-core/tests/clipboard_spec.rs @@ -385,6 +385,7 @@ fn palette_items_match_the_spec() { queue_len: if r[3] == "queue" { 2 } else { 0 }, }, notes: &[], + extra: &[], }; let input = if r[4] == "(empty)" { String::new() } else { r[4].clone() }; let out = results(&ctx, &input, &|_| vec![]); diff --git a/crates/menew-core/tests/notes_spec.rs b/crates/menew-core/tests/notes_spec.rs index 6b61b8d..7a3845c 100644 --- a/crates/menew-core/tests/notes_spec.rs +++ b/crates/menew-core/tests/notes_spec.rs @@ -226,6 +226,7 @@ fn palette_notes(notes: &[Note], query: &str) -> Vec Option Option { + let t = 1.0 / 3.0; + Some(match id { + "left" => Snap::Rect(0.0, 0.0, 0.5, 1.0), + "right" => Snap::Rect(0.5, 0.0, 0.5, 1.0), + "top" => Snap::Rect(0.0, 0.0, 1.0, 0.5), + "bottom" => Snap::Rect(0.0, 0.5, 1.0, 0.5), + "topleft" => Snap::Rect(0.0, 0.0, 0.5, 0.5), + "topright" => Snap::Rect(0.5, 0.0, 0.5, 0.5), + "bottomleft" => Snap::Rect(0.0, 0.5, 0.5, 0.5), + "bottomright" => Snap::Rect(0.5, 0.5, 0.5, 0.5), + "leftthird" => Snap::Rect(0.0, 0.0, t, 1.0), + "centerthird" => Snap::Rect(t, 0.0, t, 1.0), + "rightthird" => Snap::Rect(2.0 * t, 0.0, t, 1.0), + "lefttwothirds" => Snap::Rect(0.0, 0.0, 2.0 * t, 1.0), + "righttwothirds" => Snap::Rect(t, 0.0, 2.0 * t, 1.0), + "almost" => Snap::Rect(0.05, 0.05, 0.9, 0.9), + "max" => Snap::Maximize, + "center" => Snap::Center, + "display" => Snap::NextDisplay, + _ => return None, + }) + } + + /// Every id, in the order the palette lists them. + pub const IDS: [&'static str; 17] = [ + "left", "right", "top", "bottom", "max", "almost", "center", "topleft", "topright", "bottomleft", "bottomright", "leftthird", + "centerthird", "rightthird", "lefttwothirds", "righttwothirds", "display", + ]; +} + +/// The KWin script for a snap (works on KWin 5.27 and 6: `activeWindow` / `activeClient`, +/// `frameGeometry`, `sendClientToScreen`). +pub fn kwin_script(snap: Snap) -> String { + let body = match snap { + Snap::Rect(x, y, w, h) => format!( + "if (w.setMaximize) w.setMaximize(false, false);\n\ + var a = workspace.clientArea(KWin.MaximizeArea, w);\n\ + w.frameGeometry = {{x: Math.round(a.x + a.width * {x}), y: Math.round(a.y + a.height * {y}), width: Math.round(a.width * {w}), height: Math.round(a.height * {h})}};" + ), + Snap::Maximize => "if (w.setMaximize) w.setMaximize(true, true);".to_string(), + Snap::Center => "var a = workspace.clientArea(KWin.MaximizeArea, w);\n\ + var g = w.frameGeometry;\n\ + w.frameGeometry = {x: Math.round(a.x + (a.width - g.width) / 2), y: Math.round(a.y + (a.height - g.height) / 2), width: g.width, height: g.height};" + .to_string(), + Snap::NextDisplay => "if (workspace.screens) {\n\ + var i = workspace.screens.indexOf(w.output);\n\ + workspace.sendClientToScreen(w, workspace.screens[(i + 1) % workspace.screens.length]);\n\ + } else {\n\ + workspace.sendClientToScreen(w, (w.screen + 1) % workspace.numScreens);\n\ + }" + .to_string(), + }; + format!("var w = workspace.activeWindow || workspace.activeClient;\nif (w && w.moveable !== false && !w.specialWindow) {{\n{body}\n}}\n") +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SnapError { + /// Neither KWin nor the GNOME extension answered. + Unsupported, + Failed(String), +} + +#[cfg(target_os = "linux")] +mod linux { + use super::*; + use ashpd::desktop::{screenshot::Screenshot, Color}; + use tracing::{info, warn}; + + /// Ask the desktop for a screenshot. `interactive` shows its picker (area, window, screen); + /// otherwise the whole screen is taken. Returns the file the portal wrote. + pub async fn screenshot(interactive: bool) -> Result { + let req = Screenshot::request().interactive(interactive).modal(true).send().await.map_err(|e| e.to_string())?; + let shot = req.response().map_err(|e| e.to_string())?; + shot.uri().to_file_path().map_err(|_| format!("not a local file: {}", shot.uri())) + } + + /// The color under the pointer, as `#RRGGBB`. + pub async fn pick_color() -> Result { + let req = Color::pick().send().await.map_err(|e| e.to_string())?; + let c = req.response().map_err(|e| e.to_string())?; + Ok(super::hex(c.red(), c.green(), c.blue())) + } + + async fn kwin(conn: &zbus::Connection, snap: Snap) -> Result<(), String> { + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); + let path = dir.join(format!("menew-snap-{}.js", std::process::id())); + std::fs::write(&path, kwin_script(snap)).map_err(|e| e.to_string())?; + let name = "menew-snap"; + let scripting = zbus::Proxy::new(conn, "org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting").await.map_err(|e| e.to_string())?; + // a previous run that failed halfway would block the name + let _: Result = scripting.call("unloadScript", &(name,)).await; + let id: i32 = scripting.call("loadScript", &(path.to_string_lossy().as_ref(), name)).await.map_err(|e| e.to_string())?; + // Plasma 6 puts the script at /Scripting/ScriptN, Plasma 5 at /N + let mut ran = false; + for p in [format!("/Scripting/Script{id}"), format!("/{id}")] { + if let Ok(s) = zbus::Proxy::new(conn, "org.kde.KWin", p.as_str(), "org.kde.kwin.Script").await { + if s.call::<_, _, ()>("run", &()).await.is_ok() { + ran = true; + break; + } + } + } + let _: Result = scripting.call("unloadScript", &(name,)).await; + let _ = std::fs::remove_file(&path); + if ran { + Ok(()) + } else { + Err("KWin did not run the script".into()) + } + } + + async fn gnome(conn: &zbus::Connection, snap: Snap) -> Result { + let p = zbus::Proxy::new(conn, "org.menew.Shell", "/org/menew/Shell", "org.menew.Shell").await.map_err(|e| e.to_string())?; + let r: Result = match snap { + Snap::Rect(x, y, w, h) => p.call("SnapFocused", &(x, y, w, h)).await, + Snap::Maximize => p.call("MaximizeFocused", &()).await, + Snap::Center => p.call("CenterFocused", &()).await, + Snap::NextDisplay => p.call("MoveFocusedToNextMonitor", &()).await, + }; + r.map_err(|e| e.to_string()) + } + + async fn has_name(conn: &zbus::Connection, name: &str) -> bool { + let Ok(dbus) = zbus::fdo::DBusProxy::new(conn).await else { return false }; + match zbus::names::BusName::try_from(name) { + Ok(n) => dbus.name_has_owner(n).await.unwrap_or(false), + Err(_) => false, + } + } + + /// Move the front window. The caller hides the palette first, so the front window is the one + /// people were using. + pub async fn snap(snap: Snap) -> Result<(), SnapError> { + let conn = zbus::Connection::session().await.map_err(|e| SnapError::Failed(e.to_string()))?; + if has_name(&conn, "org.kde.KWin").await { + info!("Snap {:?} through KWin scripting", snap); + return kwin(&conn, snap).await.map_err(SnapError::Failed); + } + if has_name(&conn, "org.menew.Shell").await { + info!("Snap {:?} through the GNOME extension", snap); + return match gnome(&conn, snap).await { + Ok(true) => Ok(()), + Ok(false) => Err(SnapError::Failed("no front window".into())), + Err(e) => Err(SnapError::Failed(e)), + }; + } + warn!("Snap: neither KWin nor the Menew GNOME extension is on the bus"); + Err(SnapError::Unsupported) + } + + /// Whether the Menew GNOME extension (version with the window methods) is running. + pub async fn gnome_extension_running() -> bool { + match zbus::Connection::session().await { + Ok(c) => has_name(&c, "org.menew.Shell").await, + Err(_) => false, + } + } +} + +#[cfg(target_os = "linux")] +pub use linux::{gnome_extension_running, pick_color, screenshot, snap}; + +#[cfg(not(target_os = "linux"))] +pub async fn screenshot(_interactive: bool) -> Result { + Err("screenshots need Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub async fn pick_color() -> Result { + Err("the color picker needs Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub async fn snap(_snap: Snap) -> Result<(), SnapError> { + Err(SnapError::Unsupported) +} + +#[cfg(not(target_os = "linux"))] +pub async fn gnome_extension_running() -> bool { + false +} + +/// `#RRGGBB` from 0..1 components. +pub fn hex(r: f64, g: f64, b: f64) -> String { + let c = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02X}{:02X}{:02X}", c(r), c(g), c(b)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_id_is_a_snap() { + for id in Snap::IDS { + assert!(Snap::from_id(id).is_some(), "{id}"); + } + assert_eq!(Snap::from_id("nope"), None); + assert_eq!(Snap::from_id("right"), Some(Snap::Rect(0.5, 0.0, 0.5, 1.0))); + } + + #[test] + fn kwin_script_uses_the_work_area() { + let s = kwin_script(Snap::Rect(0.5, 0.0, 0.5, 1.0)); + assert!(s.contains("workspace.activeWindow || workspace.activeClient")); + assert!(s.contains("a.width * 0.5")); + assert!(s.contains("KWin.MaximizeArea")); + assert!(kwin_script(Snap::Maximize).contains("setMaximize(true, true)")); + assert!(kwin_script(Snap::NextDisplay).contains("sendClientToScreen")); + } + + #[test] + fn hex_colors() { + assert_eq!(hex(1.0, 0.5, 0.0), "#FF8000"); + assert_eq!(hex(2.0, -1.0, 0.0), "#FF0000"); + } +} diff --git a/crates/menew-shortcuts/src/lib.rs b/crates/menew-shortcuts/src/lib.rs index cc60daf..5ced5c8 100644 --- a/crates/menew-shortcuts/src/lib.rs +++ b/crates/menew-shortcuts/src/lib.rs @@ -11,8 +11,23 @@ pub enum ShortcutEvent { Capture, /// Capture an area and copy the text in it (the Mac's Ctrl+Option+Cmd+T). CaptureText, + /// A daemon command (`qa.mic`, `win.left`, `note.new`...), the same ids the palette uses. + Command(String), } +/// The shortcuts besides the palette, clipboard, paste queue and the two screen ones: (portal id, description key, +/// preferred trigger, daemon command). The Mac uses Control+Option+Command; Linux uses +/// Control+Alt (+Shift where Control+Alt is taken, like Control+Alt+T for the terminal). +pub const COMMAND_SHORTCUTS: [(&str, &str, &str, &str); 7] = [ + ("mute_mic", "sc_mute_mic", "Control+Alt+M", "qa.mic"), + ("snap_left", "sc_snap_left", "Control+Alt+Shift+Left", "win.left"), + ("snap_right", "sc_snap_right", "Control+Alt+Shift+Right", "win.right"), + ("snap_top", "sc_snap_top", "Control+Alt+Shift+Up", "win.top"), + ("snap_bottom", "sc_snap_bottom", "Control+Alt+Shift+Down", "win.bottom"), + ("snap_max", "sc_snap_max", "Control+Alt+Return", "win.max"), + ("new_note", "sc_new_note", "Control+Alt+J", "note.new"), +]; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum PortalShortcutStatus { Success(Vec), @@ -74,12 +89,12 @@ mod linux_impl { let capture_text_shortcut = NewShortcut::new("capture_text", menew_core::strings::tr("shortcut_capture_text_desc", lang, &[])) .preferred_trigger(Some("Control+Alt+Shift+T")); + let mut all = vec![shortcut, clipboard_shortcut, paste_next_shortcut, capture_shortcut, capture_text_shortcut]; + for (id, key, trigger, _) in COMMAND_SHORTCUTS { + all.push(NewShortcut::new(id, menew_core::strings::tr(key, lang, &[])).preferred_trigger(Some(trigger))); + } let response = match global_shortcuts - .bind_shortcuts( - &session, - &[shortcut, clipboard_shortcut, paste_next_shortcut, capture_shortcut, capture_text_shortcut], - Default::default(), - ) + .bind_shortcuts(&session, &all, Default::default()) .await { Ok(r) => match r.response() { @@ -127,7 +142,11 @@ mod linux_impl { "capture_text" => { let _ = tx.send(ShortcutEvent::CaptureText); } - _ => {} + other => { + if let Some((_, _, _, cmd)) = COMMAND_SHORTCUTS.iter().find(|c| c.0 == other) { + let _ = tx.send(ShortcutEvent::Command(cmd.to_string())); + } + } } } }); @@ -168,6 +187,10 @@ mod linux_impl { eprintln!(" Name: Menew Text from Screen"); eprintln!(" Command: menew capture-text"); eprintln!(" Shortcut: Ctrl+Alt+Shift+T"); + eprintln!(" Every other Menew shortcut is `menew run `:"); + for (_, key, trigger, cmd) in COMMAND_SHORTCUTS { + eprintln!(" {:<28} menew run {:<10} {}", menew_core::strings::tr(key, menew_core::current_language(), &[]), cmd, trigger.replace("Control", "Ctrl")); + } eprintln!("===================================================================="); eprintln!(); } diff --git a/crates/menew-ui/src/dialogs.rs b/crates/menew-ui/src/dialogs.rs new file mode 100644 index 0000000..535510f --- /dev/null +++ b/crates/menew-ui/src/dialogs.rs @@ -0,0 +1,48 @@ +//! Small dialogs shared by the windows (confirmations). + +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; + +/// Ask before doing something that can't be undone (`NSAlert` on the Mac). `on_ok` runs only on +/// the confirm button. +pub fn confirm(parent: Option<>k4::Window>, title: &str, body: &str, ok: &str, cancel: &str, destructive: bool, on_ok: impl Fn() + 'static) { + let d = adw::MessageDialog::builder().heading(title).body(body).modal(true).build(); + if let Some(p) = parent { + d.set_transient_for(Some(p)); + } + d.add_response("cancel", cancel); + d.add_response("ok", ok); + d.set_response_appearance("ok", if destructive { adw::ResponseAppearance::Destructive } else { adw::ResponseAppearance::Suggested }); + d.set_default_response(Some("cancel")); + d.set_close_response("cancel"); + d.connect_response(None, move |d, r| { + if r == "ok" { + on_ok(); + } + d.close(); + }); + d.present(); +} + +/// Ask for one line of text (`{input:Name}` style). +pub fn ask_text(parent: Option<>k4::Window>, title: &str, placeholder: &str, ok: &str, cancel: &str, on_ok: impl Fn(String) + 'static) { + let d = adw::MessageDialog::builder().heading(title).modal(true).build(); + if let Some(p) = parent { + d.set_transient_for(Some(p)); + } + let entry = gtk4::Entry::builder().placeholder_text(placeholder).activates_default(true).build(); + d.set_extra_child(Some(&entry)); + d.add_response("cancel", cancel); + d.add_response("ok", ok); + d.set_response_appearance("ok", adw::ResponseAppearance::Suggested); + d.set_default_response(Some("ok")); + d.set_close_response("cancel"); + d.connect_response(None, move |d, r| { + if r == "ok" { + on_ok(entry.text().to_string()); + } + d.close(); + }); + d.present(); +} diff --git a/crates/menew-ui/src/lib.rs b/crates/menew-ui/src/lib.rs index 32d8e87..41e99bf 100644 --- a/crates/menew-ui/src/lib.rs +++ b/crates/menew-ui/src/lib.rs @@ -40,6 +40,11 @@ impl PaletteState { pub type SharedState = Rc>; +/// The daemon's items for the text typed. +pub type ExtraItems = Rc Vec>; +/// The daemon's runner of a command id. +pub type CommandRunner = Rc; + /// What the palette asks of the daemon about the clipboard capture. #[derive(Clone)] pub struct ClipHooks { @@ -78,6 +83,8 @@ pub mod screen; pub mod monitor_view; #[cfg(target_os = "linux")] pub use monitor_view::{MonitorWidget, MonitorWindow}; +#[cfg(target_os = "linux")] +pub mod dialogs; #[cfg(target_os = "linux")] pub mod palette { @@ -195,6 +202,11 @@ pub mod palette { /// The text the current list was built for. last_query: RefCell, hooks: ClipHooks, + /// Items of the other features for the text typed, and the runner of their commands (set by the daemon). + extra_items: RefCell>, + command: RefCell>, + /// Called when the palette opens (the daemon refreshes the quick action state). + on_show: RefCell>>, /// Country of the locale, for the WhatsApp action. region: Option, // ---- clipboard mode ---- @@ -485,6 +497,9 @@ pub mod palette { query_empty, last_query: RefCell::new(String::new()), hooks, + extra_items: RefCell::new(None), + command: RefCell::new(None), + on_show: RefCell::new(None), region: clip_smart::region_from_env(), filter: Cell::new(ClipFilter::All), chips_box, @@ -681,6 +696,43 @@ pub mod palette { }); } + /// The daemon's items for the text typed (quick actions, notes, screenshots, windows). + pub fn set_extra_items(&self, f: ExtraItems) { + *self.extra_items.borrow_mut() = Some(f); + } + + /// The daemon's runner of [`ItemAction::Command`]. + pub fn set_command_runner(&self, f: CommandRunner) { + *self.command.borrow_mut() = Some(f); + } + + pub fn set_on_show(&self, f: Rc) { + *self.on_show.borrow_mut() = Some(f); + } + + /// The installed apps, as scanned when the palette last opened. + pub fn apps(&self) -> Vec { + self.apps.borrow().clone() + } + + /// Rebuild the list for the text in the search box (after the daemon's state changed). + pub fn refresh_now(self: &Rc) { + if self.window.is_visible() { + let q = self.search_entry.text().to_string(); + self.refresh_list(&q); + } + } + + /// The GTK application (for the other windows). + pub fn application(&self) -> adw::Application { + self.app.clone() + } + + /// Run an item action as if it was picked in the palette (tray popover, favorites). + pub fn run_item_action(self: &Rc, action: ItemAction) { + self.run_action(action); + } + pub fn mode(&self) -> PaletteMode { self.mode.get() } @@ -934,6 +986,7 @@ pub mod palette { let scripts = self.scripts(); let clip_text = self.clipboard_text(); let paused = (self.hooks.is_paused)(); + let extra = self.extra_items.borrow().as_ref().map(|f| f(raw)).unwrap_or_default(); let items = { let state = self.state.borrow(); let notes_store = self.notes.store.borrow(); @@ -958,6 +1011,7 @@ pub mod palette { queue_len: state.queue.len(), }, notes: ¬es_store.notes, + extra: &extra, }; let db = self.db.clone(); let clip_search = move |q: &str| -> Vec { @@ -1227,6 +1281,10 @@ pub mod palette { // Reload desktop files to catch newly installed apps *self.apps.borrow_mut() = DesktopScanner::scan_all(); self.read_clipboard(); + let f = self.on_show.borrow().clone(); + if let Some(f) = f { + f(); + } } self.set_mode(mode); self.window.set_visible(true); @@ -1338,7 +1396,7 @@ pub mod palette { // ---- what the items do ---- - fn notify(&self, id: &str, title: &str, body: Option<&str>) { + pub fn notify(&self, id: &str, title: &str, body: Option<&str>) { let n = gio::Notification::new(title); if let Some(b) = body { n.set_body(Some(b)); @@ -1347,12 +1405,12 @@ pub mod palette { info!("Notification sent: {}{}", title, body.map(|b| format!(" / {b}")).unwrap_or_default()); } - fn copied(&self, text: &str) { + pub fn copied(&self, text: &str) { self.copy_to_clipboard(text); self.notify("menew-copied", &tr("copied_value", current_language(), &[text]), None); } - fn open_uri(&self, uri: &str) { + pub fn open_uri(&self, uri: &str) { match gio::AppInfo::launch_default_for_uri(uri, gio::AppLaunchContext::NONE) { Ok(()) => info!("Opened {}", uri), Err(e) => tracing::warn!("Could not open {}: {}", uri, e), @@ -1489,6 +1547,13 @@ pub mod palette { ItemAction::CopyUnixTimestamp => self.copied(&dev_tools::now_secs().to_string()), ItemAction::Quit => self.app.quit(), ItemAction::CheckUpdates => (self.hooks.check_updates)(), + ItemAction::Command(c) => { + let f = self.command.borrow().clone(); + match f { + Some(f) => f(&c), + None => tracing::warn!("Palette: no runner for command {}", c), + } + } } } @@ -2311,6 +2376,24 @@ pub mod palette { } } + /// Put the clipboard's text back as plain text only (drops formatting, images, files). + pub fn plain_text_clipboard(self: &Rc) { + let Some(display) = gdk::Display::default() else { return }; + let clipboard = display.clipboard(); + let this = Rc::clone(self); + clipboard.read_text_async(gio::Cancellable::NONE, move |res| { + let lang = current_language(); + match res { + Ok(Some(text)) if !text.is_empty() => { + (this.hooks.expect_own)(own_key(ClipKind::Text, text.as_str()), true); + this.copy_to_clipboard(text.as_str()); + this.notify("menew-plain", &tr("qa_plain_done", lang, &[]), None); + } + _ => this.notify("menew-plain", &tr("qa_plain_none", lang, &[]), None), + } + }); + } + pub fn copy_to_clipboard(&self, text: &str) { self.test_mode_map_window(); if let Some(display) = gdk::Display::default() { diff --git a/crates/menew/Cargo.toml b/crates/menew/Cargo.toml index 70f5996..4398441 100644 --- a/crates/menew/Cargo.toml +++ b/crates/menew/Cargo.toml @@ -11,6 +11,7 @@ menew-tray = { path = "../menew-tray" } menew-shortcuts = { path = "../menew-shortcuts" } menew-clipboard = { path = "../menew-clipboard" } menew-ui = { path = "../menew-ui" } +menew-desktop = { path = "../menew-desktop" } tokio = { version = "1.0", features = ["full"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/crates/menew/src/commands.rs b/crates/menew/src/commands.rs new file mode 100644 index 0000000..eda6b8f --- /dev/null +++ b/crates/menew/src/commands.rs @@ -0,0 +1,325 @@ +//! The daemon side of [`ItemAction::Command`]: builds the palette items of the other features for +//! the text typed and runs their commands. Ids: +//! - `qa.*` quick actions (`menew_core::quick_actions`) +//! - `win.` window snapping (`menew_desktop::snap`) +//! - `cap.*` screenshots and screen text (`crate::capture`) +//! - `note.*` notes (`menew_ui::notes`) +//! - `open.*` the Menew window sections +//! +//! The same ids are used by the global shortcuts and by `menew run `. + +use gtk4::gio; +use gtk4::glib; +use menew_core::palette::PaletteItem; +use menew_core::quick_actions::{self as qa, KeepAwake, ToolState}; +use menew_core::strings::tr; +use menew_core::sys::Desktop; +use menew_core::{current_language, Language}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; +use tracing::{info, warn}; + +/// Extra item providers registered by the other features (notes, capture, monitor, window). +pub type Provider = Rc Vec>; +/// Runner for a command prefix (`note.`, `cap.`, `open.`): returns true when it handled the id. +pub type Runner = Rc bool>; + +pub struct Commands { + palette: Rc, + rt: Arc, + desktop: Desktop, + tools: RefCell, + pub awake: RefCell, + providers: RefCell>, + runners: RefCell>, + /// Called after something the tray or the popover shows changed (keep awake, mute). + on_change: RefCell>>, +} + +fn now() -> f64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) +} + +impl Commands { + pub fn new(palette: Rc, rt: Arc) -> Rc { + let me = Rc::new(Self { + palette, + rt, + desktop: Desktop::detect(), + tools: RefCell::new(ToolState::default()), + awake: RefCell::new(KeepAwake::default()), + providers: RefCell::new(vec![]), + runners: RefCell::new(vec![]), + on_change: RefCell::new(None), + }); + let items_me = Rc::clone(&me); + me.palette.set_extra_items(Rc::new(move |raw| items_me.items(raw))); + let run_me = Rc::clone(&me); + me.palette.set_command_runner(Rc::new(move |c| run_me.run(c))); + let show_me = Rc::clone(&me); + me.palette.set_on_show(Rc::new(move || show_me.refresh_tools())); + me.refresh_tools(); + me + } + + #[allow(dead_code)] // for the tray popover and the Menew window (next PR) + pub fn add_provider(&self, p: Provider) { + self.providers.borrow_mut().push(p); + } + + pub fn add_runner(&self, r: Runner) { + self.runners.borrow_mut().push(r); + } + + #[allow(dead_code)] // for the tray popover and the Menew window (next PR) + pub fn set_on_change(&self, f: Rc) { + *self.on_change.borrow_mut() = Some(f); + } + + fn changed(&self) { + let f = self.on_change.borrow().clone(); + if let Some(f) = f { + f(); + } + } + + #[allow(dead_code)] // for the tray popover and the Menew window (next PR) + pub fn desktop(&self) -> Desktop { + self.desktop + } + + pub fn tools(&self) -> ToolState { + let mut t = self.tools.borrow().clone(); + t.awake = self.awake.borrow_mut().is_on(); + t + } + + #[allow(dead_code)] // for the tray popover and the Menew window (next PR) + pub fn awake_until(&self) -> Option { + self.awake.borrow().until + } + + /// Read the quick action state off the GTK thread, then rebuild the open palette. + pub fn refresh_tools(self: &Rc) { + let me = Rc::clone(self); + let desktop = self.desktop; + glib::spawn_future_local(async move { + if let Ok(st) = gio::spawn_blocking(move || ToolState::read(desktop)).await { + *me.tools.borrow_mut() = st; + me.palette.refresh_now(); + me.changed(); + } + }); + } + + /// The items for the text typed. + pub fn items(&self, raw: &str) -> Vec { + let lang = current_language(); + let mut out = qa::items(&self.tools(), lang); + out.extend(menew_core::windows::items(lang)); + let q = raw.trim(); + if !q.is_empty() { + let apps = self.palette.apps(); + let never = menew_core::Config::load().never_quit; + out.extend(qa::typed_items(q, &|| qa::running_apps(&apps, &never), &qa::listening_ports, lang)); + } + for p in self.providers.borrow().iter() { + out.extend(p(raw, lang)); + } + out + } + + fn toast(&self, key: &str, args: &[&str]) { + self.palette.notify("menew-action", &tr(key, current_language(), args), None); + } + + /// Run a command id. Unknown ids are logged and ignored. + pub fn run(self: &Rc, cmd: &str) { + info!("Command: {}", cmd); + let lang = current_language(); + let (name, arg) = match cmd.split_once(':') { + Some((n, a)) => (n, Some(a)), + None => (cmd, None), + }; + match name { + "qa.mic" => match qa::toggle_mute(true) { + Some(m) => { + self.toast(if m { "qa_mic_muted" } else { "qa_mic_live" }, &[]); + self.tools.borrow_mut().mic_muted = Some(m); + self.changed(); + } + None => self.toast("qa_cant_mute", &[]), + }, + "qa.sound" => match qa::toggle_mute(false) { + Some(m) => { + self.toast(if m { "qa_sound_muted" } else { "qa_sound_live" }, &[]); + self.tools.borrow_mut().sound_muted = Some(m); + self.changed(); + } + None => self.toast("qa_cant_mute", &[]), + }, + "qa.dark" => { + let dark = self.tools.borrow().dark != Some(true); + if qa::set_dark(self.desktop, dark) { + self.tools.borrow_mut().dark = Some(dark); + self.changed(); + } else { + self.toast("qa_failed", &[]); + } + } + "qa.out" | "qa.in" => { + let input = name == "qa.in"; + let dev = arg.unwrap_or_default(); + if qa::set_default_device(input, dev) { + let st = self.tools.borrow(); + let list = if input { &st.inputs } else { &st.outputs }; + let label = list.iter().find(|d| d.name == dev).map(|d| d.description.clone()).unwrap_or_else(|| dev.to_string()); + drop(st); + self.toast("qa_switched", &[&label]); + self.refresh_tools(); + } else { + self.toast("qa_failed", &[]); + } + } + "qa.awake" => { + let minutes = arg.and_then(|a| a.parse::().ok()); + let on = self.awake.borrow_mut().is_on(); + if on && minutes.is_none() { + self.awake.borrow_mut().stop(); + self.toast("qa_awake_stopped", &[]); + } else { + match self.awake.borrow_mut().start(minutes, now(), &tr("qa_awake", lang, &[])) { + Ok(()) => self.toast("qa_awake_started", &[]), + Err(qa::AwakeError::Missing) => self.toast("qa_awake_missing", &[]), + Err(qa::AwakeError::Refused) => self.toast("qa_awake_refused", &[]), + } + } + self.changed(); + } + "qa.lock" => { + if !qa::lock_screen() { + self.toast("qa_failed", &[]); + } + } + "qa.trash" => { + let me = Rc::clone(self); + glib::spawn_future_local(async move { + let n = gio::spawn_blocking(qa::trash_count).await.ok().flatten(); + if n == Some(0) { + me.toast("qa_trash_already", &[]); + return; + } + let me2 = Rc::clone(&me); + menew_ui::dialogs::confirm( + None, + &tr("qa_trash_ask", lang, &[]), + &tr("qa_trash_body", lang, &[]), + &tr("qa_trash_empty_btn", lang, &[]), + &tr("cancel", lang, &[]), + true, + move || { + let me3 = Rc::clone(&me2); + glib::spawn_future_local(async move { + let ok = gio::spawn_blocking(qa::empty_trash).await.unwrap_or(false); + me3.toast(if ok { "qa_trash_done" } else { "qa_failed" }, &[]); + }); + }, + ); + }); + } + "qa.color" => { + let me = Rc::clone(self); + let job = self.rt.spawn(menew_desktop::pick_color()); + glib::spawn_future_local(async move { + match job.await { + Ok(Ok(hex)) => me.palette.copied(&hex), + Ok(Err(e)) => { + warn!("Color picker: {}", e); + me.toast("qa_color_fail", &[]); + } + Err(_) => {} + } + }); + } + "qa.plain" => self.palette.plain_text_clipboard(), + "qa.eject" => { + let me = Rc::clone(self); + glib::spawn_future_local(async move { + let n = gio::spawn_blocking(qa::eject_all).await.unwrap_or(0); + if n > 0 { + me.toast("qa_ejected", &[&n.to_string()]); + } else { + me.toast("qa_eject_fail", &[]); + } + me.refresh_tools(); + }); + } + "qa.bright" => { + let p = arg.and_then(|a| a.parse::().ok()).unwrap_or(50); + let me = Rc::clone(self); + glib::spawn_future_local(async move { + let ok = gio::spawn_blocking(move || qa::set_brightness(p)).await.unwrap_or(false); + if !ok { + me.toast("qa_brightness_fail", &[]); + } + }); + } + "qa.quit" | "qa.force" => { + let pids: Vec = arg.unwrap_or_default().split(',').filter_map(|p| p.parse().ok()).collect(); + if !qa::quit_pids(&pids, name == "qa.force") { + self.toast("qa_failed", &[]); + } + } + "qa.quitall" => { + let apps = self.palette.apps(); + let never = menew_core::Config::load().never_quit; + let running = qa::running_apps(&apps, &never); + let n = running.iter().filter(|a| qa::quit_pids(&a.pids, false)).count(); + self.toast("qa_quit_done", &[&n.to_string()]); + } + "qa.port" => { + let pid = arg.and_then(|a| a.parse::().ok()).unwrap_or(0); + if menew_core::sys::signal(pid, 15) { + self.toast("qa_port_stopped", &[]); + } else { + self.toast("qa_failed", &[]); + } + } + _ if name.starts_with("win.") => { + let Some(snap) = menew_desktop::Snap::from_id(&name[4..]) else { return }; + // the palette is closing: give the compositor a moment to focus the window again + let me = Rc::clone(self); + let rt = Arc::clone(&self.rt); + glib::timeout_add_local_once(std::time::Duration::from_millis(250), move || { + let job = rt.spawn(menew_desktop::snap(snap)); + glib::spawn_future_local(async move { + match job.await { + Ok(Ok(())) => {} + Ok(Err(menew_desktop::SnapError::Unsupported)) => me.toast("win_unsupported", &[]), + Ok(Err(menew_desktop::SnapError::Failed(e))) => { + warn!("Snap failed: {}", e); + me.toast("win_failed", &[]); + } + Err(_) => {} + } + }); + }); + } + _ => { + let runners = self.runners.borrow().clone(); + if !runners.iter().any(|r| r(cmd)) { + warn!("Unknown command {}", cmd); + } + } + } + } + + /// Once a second: keep awake for a time ends by itself. + pub fn tick(&self) { + if self.awake.borrow_mut().tick(now()) { + self.toast("qa_awake_stopped", &[]); + self.changed(); + } + } +} diff --git a/crates/menew/src/main.rs b/crates/menew/src/main.rs index a9d0a61..a3a4a0d 100644 --- a/crates/menew/src/main.rs +++ b/crates/menew/src/main.rs @@ -6,6 +6,8 @@ mod updater; mod updater_cli; mod portal; #[cfg(target_os = "linux")] +mod commands; +#[cfg(target_os = "linux")] use std::cell::RefCell; #[cfg(target_os = "linux")] use std::rc::Rc; @@ -50,6 +52,8 @@ enum Action { PaletteActivate(usize), /// Paste the next item of the paste queue. PasteNext, + /// `menew run `: the same ids as the palette and the shortcuts (`qa.mic`, `win.left`...). + Run(String), /// Test hook: show the clipboard list with this filter and search text, log it. ClipboardView(String, String), /// Open the notes window. @@ -101,6 +105,11 @@ fn decide(args: &[String], is_remote: bool, test_mode: bool) -> Action { if let Some(action) = test_mode.then(|| test_action(args)).flatten() { return action; } + if let Some(p) = args.iter().position(|a| a == "run") { + if let Some(c) = args.get(p + 1) { + return Action::Run(c.clone()); + } + } if args.iter().any(|a| a == "quit") { Action::Quit } else if args.iter().any(|a| a == "toggle") { @@ -350,7 +359,10 @@ fn run_gtk_app(args: Vec) { let watcher_cell: Rc>>>> = Rc::new(RefCell::new(None)); + let commands_cell: Rc>>> = Rc::new(RefCell::new(None)); + // connect_startup is guaranteed to execute ONLY on the primary instance + let c_startup = Rc::clone(&commands_cell); let p_startup = Rc::clone(&palette_cell); let u_startup = Rc::clone(&updater_cell); let rt_startup = Arc::clone(&rt); @@ -456,8 +468,18 @@ fn run_gtk_app(args: Vec) { }); }); let screen = menew_ui::screen::ScreenApp::new(application, portal); - let palette = menew_ui::PaletteWindow::create(application, db.clone(), Rc::clone(&state), Rc::clone(&push_status), hooks, notes, screen); + let palette = menew_ui::PaletteWindow::create(application, db.clone(), Rc::clone(&state), Rc::clone(&push_status), hooks, Rc::clone(¬es), screen); *p_startup.borrow_mut() = Some(Rc::clone(&palette)); + let cmds = commands::Commands::new(Rc::clone(&palette), Arc::clone(&rt_startup)); + // `note.new` (the Ctrl+Alt+J shortcut and `menew run note.new`) opens a new note + cmds.add_runner(Rc::new(move |c: &str| { + if c != "note.new" { + return false; + } + notes.new_note(); + true + })); + *c_startup.borrow_mut() = Some(Rc::clone(&cmds)); let db_tray = db.clone(); // copies reach the palette (paste queue, open list) on the GTK thread @@ -535,9 +557,11 @@ fn run_gtk_app(args: Vec) { let state = Rc::clone(&state); let app = application.clone(); let push = Rc::clone(&push_status); + let cmds = Rc::clone(&cmds); glib::timeout_add_seconds_local(1, move || { let lang = menew_core::current_language(); alerts::tick(&app, &mut state.borrow_mut(), alerts::now(), lang); + cmds.tick(); push(); glib::ControlFlow::Continue }); @@ -602,6 +626,7 @@ fn run_gtk_app(args: Vec) { }); let p_short = Rc::clone(&palette); + let c_short = Rc::clone(&cmds); glib::MainContext::default().spawn_local(async move { while let Some(ev) = shortcut_rx.recv().await { match ev { @@ -610,6 +635,7 @@ fn run_gtk_app(args: Vec) { ShortcutEvent::PasteNext => p_short.paste_next(), ShortcutEvent::Capture => p_short.screen().capture(menew_ui::screen::Purpose::Edit, true), ShortcutEvent::CaptureText => p_short.screen().capture(menew_ui::screen::Purpose::Text, true), + ShortcutEvent::Command(c) => c_short.run(&c), } } }); @@ -625,6 +651,7 @@ fn run_gtk_app(args: Vec) { // connect_command_line handles first launch and remote IPC such as `menew toggle` let p_cmd = Rc::clone(&palette_cell); + let c_cmd = Rc::clone(&commands_cell); let app_cmd = app.clone(); let upd_cmd = Rc::clone(&updater_cell); app.connect_command_line(move |_application, cmd_line| { @@ -649,6 +676,11 @@ fn run_gtk_app(args: Vec) { match action { Action::Quit => app_cmd.quit(), Action::StayHidden => {} + Action::Run(c) => { + if let Some(cmds) = c_cmd.borrow().as_ref() { + cmds.run(&c); + } + } Action::ShowClipboard => { if let Some(palette) = p_cmd.borrow().as_ref() { palette.show_mode(PaletteMode::Clipboard); @@ -911,6 +943,12 @@ mod tests { assert_eq!(decide(&v(&["__quit-process", "x"]), true, true), Action::ShowPalette); } + #[test] + fn run_takes_the_command_id() { + assert_eq!(decide(&v(&["run", "qa.mic"]), true, false), Action::Run("qa.mic".into())); + assert_eq!(decide(&v(&["run"]), true, false), Action::ShowPalette); + } + #[test] fn quit_wins_over_other_words() { assert_eq!(decide(&v(&["clipboard", "quit"]), true, false), Action::Quit); diff --git a/docs/parity.md b/docs/parity.md index 623e893..edaa718 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -80,7 +80,7 @@ Licence: GPL-3.0-only, the same as the Mac app; name and icon under `TRADEMARK.m | Feature | Mac | Linux | R1 | Notes | |---|---|---|---|---| -| Snap the front window (halves, corners, thirds, full, other display) | ✅ | 🔁 | R1 | Wayland apps can't move other windows. KWin: scripting over D-Bus. GNOME: through the Menew extension. X11: EWMH. | +| Snap the front window (halves, corners, thirds, full, other display) | ✅ | ✅ | R1 | The Mac's 17 positions from the palette and `Ctrl+Alt+Shift+Arrows` / `Ctrl+Alt+Enter`. KWin: a script loaded over `org.kde.kwin.Scripting` (Plasma 5.27 and 6). GNOME: the Menew extension exports `org.menew.Shell` (`SnapFocused`, `MaximizeFocused`, `CenterFocused`, `MoveFocusedToNextMonitor`). Headless tests read the geometry back on both. X11 without either: not done. | | Drag to snap with preview | ✅ | ❌ | | Both desktops already do edge snapping natively. | | Quick shelf (shake to open, drag out) | ✅ | 🟡 | | A shelf window is possible; "shake while dragging" is not detectable on Wayland. | | Image tools (convert, resize, rotate, strip metadata) | ✅ | ⬜ | | | @@ -93,19 +93,19 @@ Licence: GPL-3.0-only, the same as the Mac app; name and icon under `TRADEMARK.m | Feature | Mac | Linux | R1 | Notes | |---|---|---|---|---| -| Mute microphone (global shortcut) / mute sound | ✅ | 🔁 | R1 | PipeWire/PulseAudio (`wpctl`). | -| Switch audio output and input | ✅ | 🔁 | R1 | PipeWire. | -| Dark mode toggle | ✅ | 🔁 | R1 | GNOME gsettings `color-scheme`; KDE `plasma-apply-colorscheme`. | -| Keep awake (for a time / until / while an app runs) | ✅ | 🔁 | R1 | `org.freedesktop.ScreenSaver.Inhibit` / portal Inhibit. | -| Lock screen | ✅ | 🔁 | R1 | `loginctl lock-session`. | -| Empty trash | ✅ | 🔁 | R1 | `gio trash --empty`. | -| Color picker | ✅ | 🔁 | R1 | `org.freedesktop.portal.Screenshot.PickColor`. | -| Plain-text clipboard | ✅ | ⬜ | R1 | | -| Eject disks | ✅ | 🔁 | R1 | UDisks2 over D-Bus. | +| Mute microphone (global shortcut) / mute sound | ✅ | ✅ | R1 | `pactl` (PipeWire or PulseAudio), `wpctl` as fallback. `Ctrl+Alt+M`. `quick_actions.rs`. | +| Switch audio output and input | ✅ | ✅ | R1 | `pactl -f json list sinks/sources`, `set-default-sink/source`; one palette item per other device. | +| Dark mode toggle | ✅ | ✅ | R1 | GNOME: `gsettings` `color-scheme` (and the GTK 3 theme name). KDE: `plasma-apply-colorscheme BreezeDark/BreezeLight`, state read from `kdeglobals`. | +| Keep awake (for a time / until / while an app runs) | ✅ | ✅ | R1 | `systemd-inhibit --what=idle:sleep` held while on; `awake 2h` / `acordado 90m` for a time; turns itself off. "While an app runs" is not ported. | +| Lock screen | ✅ | ✅ | R1 | `loginctl lock-session`, then `org.freedesktop.ScreenSaver.Lock`, then `xdg-screensaver lock`. | +| Empty trash | ✅ | ✅ | R1 | Confirmation first (like the Mac), then `gio trash --empty`; says so when it is already empty. | +| Color picker | ✅ | ✅ | R1 | `org.freedesktop.portal.Screenshot.PickColor`; the `#RRGGBB` is copied. | +| Plain-text clipboard | ✅ | ✅ | R1 | Reads the clipboard text and puts it back as plain text only. | +| Eject disks | ✅ | ✅ | R1 | Mounted partitions of removable or hot-plugged disks from `lsblk -J`; `udisksctl unmount` (or `gio mount -u`), then `udisksctl power-off`. | | Hidden files / desktop icons / hide Dock | ✅ | 🟡 | | Depends on the desktop; GNOME has no desktop icons by default. | -| Display brightness (built-in + DDC/CI) | ✅ | 🔁 | R1 | `org.freedesktop.login1.Session.SetBrightness` (backlight) + ddcutil (external). | -| Quit apps / force quit / never-quit list | ✅ | 🟡 | R1 | Close via the toolkit is not possible on Wayland; quit by signal (SIGTERM first, apps can ask to save only if they handle it). Force quit: SIGKILL. | -| Ports in use (stop a server) | ✅ | ⬜ | R1 | `/proc/net/tcp` + process. | +| Display brightness (built-in + DDC/CI) | ✅ | ✅ | R1 | `brightness 40`: built-in panel through logind `SetBrightness` (no root), external displays through `ddcutil setvcp 10` when installed. | +| Quit apps / force quit / never-quit list | ✅ | 🟡 | R1 | Running apps are matched to their desktop entries through `/proc`. `quit firefox` (SIGTERM, apps that handle it can ask to save), `kill firefox` (SIGKILL), "Quit all apps" skips the never-quit list (`never_quit` in `config.json`). Wayland has no way to ask an app to close its windows, so it is a signal, not the Mac's polite quit. | +| Ports in use (stop a server) | ✅ | ✅ | R1 | `port 3000`: listening sockets of `/proc/net/tcp{,6}` matched to this user's processes; Enter sends SIGTERM. | | Presentation mode | ✅ | 🔁 | | Inhibit + do not disturb + pause clipboard. | | Cleaning mode (lock keyboard, black screens) | ✅ | 🟡 | | Black fullscreen windows yes; locking the keyboard needs an exclusive grab, not available on Wayland. | | Automations ("when X, do Y") | ✅ | ⬜ | | | @@ -173,7 +173,7 @@ To build for R1 (grouped into relay phases in `docs/plan-mvp.md`): 2. Clipboard: DONE in Phase 5 (images, files, filters, pause, ignore apps on GNOME, paste queue with "Paste next", smart actions, OCR, snippets). Not verified on a real desktop: that a hidden Menew may set the selection for "Paste next" (the headless test keeps the window open). 3. Notes with protected and password notes. 4. Screenshots: DONE in Phase 7 (capture through the portal, annotation editor with blur, copy text from the screen, QR codes). Not verified on a real desktop: the screenshot portal and its picker, the global shortcuts, dragging out of the editor. -5. Windows: snapping via KWin script / GNOME extension. -6. Quick actions: mic/sound/output, dark mode, keep awake, lock, trash, color picker, plain text, eject, brightness, quit apps, ports. +5. Windows: DONE (the Mac's 17 positions through a KWin script and the GNOME extension's `org.menew.Shell`, read back by `scripts/desktop-test/actions.sh`). Not verified on a real desktop: the snapping shortcuts. +6. Quick actions: DONE (mic/sound/output, dark mode, keep awake, lock, trash, color picker, plain text, eject, brightness, quit apps, ports). Not verified on a real desktop: audio devices, brightness, eject. 7. System monitor with top processes and tray metrics: DONE in Phase 10 (see the rows above and `docs/monitor-spec.md`). 8. Tray popover (Now / Actions), Menew window, settings, welcome tour, language picker, update check. diff --git a/gnome-extension/extension.js b/gnome-extension/extension.js index 75a363e..4196ed1 100644 --- a/gnome-extension/extension.js +++ b/gnome-extension/extension.js @@ -42,6 +42,114 @@ const ClipboardIfaceXml = ` `; +// Window snapping and the front app, called by the daemon (Wayland apps can't move other windows). +const ShellIfaceXml = ` + + + + + + + + + + + + + + + + + + + + + + + +`; + +/** The window people were using: Menew's own palette never counts. */ +function frontWindow() { + const win = global.display.focus_window; + if (win && win.get_gtk_application_id?.() === 'app.menew.Menew') { + // the palette is closing: take the next window of the stack + const list = global.display.get_tab_list(Meta.TabList.NORMAL, null); + return list.find(w => w !== win) || null; + } + if (!win || win.get_window_type() !== Meta.WindowType.NORMAL) + return null; + return win; +} + +function unmaximize(win) { + try { + win.unmaximize(Meta.MaximizeFlags.BOTH); + } catch (e) { + // GNOME 49 dropped the flags argument + try { win.unmaximize(); } catch (e2) { /* not maximized */ } + } +} + +class ShellService { + SnapFocused(x, y, width, height) { + const win = frontWindow(); + if (!win) + return false; + unmaximize(win); + const a = win.get_work_area_current_monitor(); + win.move_resize_frame(true, Math.round(a.x + a.width * x), Math.round(a.y + a.height * y), + Math.round(a.width * width), Math.round(a.height * height)); + win.activate(global.get_current_time()); + return true; + } + + MaximizeFocused() { + const win = frontWindow(); + if (!win) + return false; + try { + win.maximize(Meta.MaximizeFlags.BOTH); + } catch (e) { + win.maximize(); + } + return true; + } + + CenterFocused() { + const win = frontWindow(); + if (!win) + return false; + const a = win.get_work_area_current_monitor(); + const r = win.get_frame_rect(); + win.move_frame(true, Math.round(a.x + (a.width - r.width) / 2), Math.round(a.y + (a.height - r.height) / 2)); + return true; + } + + MoveFocusedToNextMonitor() { + const win = frontWindow(); + const n = global.display.get_n_monitors(); + if (!win || n < 2) + return false; + win.move_to_monitor((win.get_monitor() + 1) % n); + return true; + } + + FocusedApp() { + const win = frontWindow(); + if (!win) + return ['', '']; + const id = win.get_gtk_application_id?.() || win.get_wm_class?.() || ''; + let name = id; + try { + const app = Shell.WindowTracker.get_default().get_window_app(win); + if (app) + name = app.get_name(); + } catch (e) { /* the class is enough */ } + return [id, name]; + } +} + function isSecretType(mime) { const m = mime.toLowerCase(); return m.includes('password') || m.includes('secret') || m.includes('concealedtype') || @@ -57,6 +165,19 @@ export default class MenewClipboardExtension extends Extension { this._initDbusProxy(); this._startClipboardWatcher(); + this._exportShellService(); + } + + _exportShellService() { + try { + this._shellService = Gio.DBusExportedObject.wrapJSObject(ShellIfaceXml, new ShellService()); + this._shellService.export(Gio.DBus.session, '/org/menew/Shell'); + this._shellNameId = Gio.bus_own_name_on_connection(Gio.DBus.session, 'org.menew.Shell', + Gio.BusNameOwnerFlags.NONE, null, null); + console.log('[MenewExtension] Window service exported as org.menew.Shell'); + } catch (e) { + console.error(`[MenewExtension] Could not export org.menew.Shell: ${e.message}`); + } } disable() { @@ -71,6 +192,14 @@ export default class MenewClipboardExtension extends Extension { this._dbusProxy = null; this._lastCopiedText = null; + if (this._shellNameId) { + Gio.bus_unown_name(this._shellNameId); + this._shellNameId = 0; + } + if (this._shellService) { + this._shellService.unexport(); + this._shellService = null; + } } _initDbusProxy() { diff --git a/gnome-extension/metadata.json b/gnome-extension/metadata.json index ac49fec..5b545c4 100644 --- a/gnome-extension/metadata.json +++ b/gnome-extension/metadata.json @@ -1,8 +1,8 @@ { "name": "Menew Integration", - "description": "Bridges GNOME Wayland clipboard events to Menew daemon via D-Bus", + "description": "Bridges GNOME Wayland clipboard events and window snapping to the Menew daemon over D-Bus", "uuid": "menew-bridge@menew.web.app", "shell-version": [ "45", "46", "47", "48", "49", "50", "51" ], "url": "https://menew.web.app", - "version": 1 + "version": 2 } diff --git a/scripts/desktop-test/actions.sh b/scripts/desktop-test/actions.sh new file mode 100644 index 0000000..fad9062 --- /dev/null +++ b/scripts/desktop-test/actions.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Quick actions and window snapping checks (keep awake from the palette, dark mode, systemd-inhibit, +# `menew run win.*` read back from the compositor). Sourced by gnome.sh and kde.sh after lib.sh. Needs +# from the caller: DE, MENEW_LOG, and on GNOME shell_eval (unsafe mode) and the Menew extension +# version 2 (org.menew.Shell), on KDE KWIN_LOG. + +# snap_target : open a plain GTK window titled "Snap target" for the compositor to move +snap_target() { + python3 - "$1" >/dev/null 2>&1 <<'PY' & +import sys +import gi +gi.require_version("Gtk", "4.0") +from gi.repository import Gtk, GLib +app = Gtk.Application(application_id="org.example.SnapTarget") +def on_activate(a): + w = Gtk.ApplicationWindow(application=a, title="Snap target") + w.set_default_size(400, 300) + w.present() + GLib.timeout_add_seconds(int(sys.argv[1]), a.quit) +app.connect("activate", on_activate) +app.run([]) +PY + track $! + sleep 4 +} + +# half_ok : the window fills that half (4 px slack) +half_ok() { + local x="$1" w="$2" aw="$3" half + [ -n "$x" ] && [ -n "$w" ] && [ -n "$aw" ] || return 1 + half=$((aw / 2)) + [ "$w" -ge $((half - 4)) ] && [ "$w" -le $((half + 4)) ] || return 1 + if [ "$4" = left ]; then [ "${x#-}" -le 2 ]; else [ "$x" -ge $((half - 4)) ] && [ "$x" -le $((half + 4)) ]; fi +} + +actions_checks() { + local start before after geo x w aw probe id + + # (a) the palette offers keep awake for a typed time + start="$(log_lines)" + "$MENEW_BIN" __palette-query "awake 2h" >/dev/null 2>&1; sleep 2 + if log_since "$start" | grep -a -q 'Keep awake for 2 h'; then pass "palette 'awake 2h' offers keep awake for 2 h"; else fail "no keep awake item for 'awake 2h'"; fi + "$MENEW_BIN" toggle >/dev/null 2>&1; sleep 1 + + # (b) keep awake runs systemd-inhibit (or says it is missing), and stops + "$MENEW_BIN" run qa.awake:1 >/dev/null 2>&1; sleep 2 + if pgrep -f 'systemd-inhibit --what=idle:sleep --who=Menew' >/dev/null; then + pass "keep awake holds a systemd-inhibit lock" + elif grep -a -q 'Notification sent: The system refused to keep the computer awake\|Notification sent: Keep awake needs systemd-inhibit' "$MENEW_LOG"; then + pass "keep awake could not take the lock here (no logind) and said so" + else + fail "keep awake did nothing, or said it was on without a lock" + fi + "$MENEW_BIN" run qa.awake >/dev/null 2>&1; sleep 1 + + if [ "$DE" = gnome ]; then + # (c) dark mode flips GNOME's color-scheme, then back + before="$(gsettings get org.gnome.desktop.interface color-scheme)" + "$MENEW_BIN" run qa.dark >/dev/null 2>&1; sleep 2 + after="$(gsettings get org.gnome.desktop.interface color-scheme)" + if [ "$before" != "$after" ]; then pass "qa.dark switched color-scheme ($before -> $after)"; else fail "qa.dark did not change color-scheme ($before)"; fi + "$MENEW_BIN" run qa.dark >/dev/null 2>&1; sleep 1 + + # (d) win.left through the extension's org.menew.Shell + snap_target 40 + shell_eval "global.get_window_actors().map(a => a.meta_window).find(w => w.get_title() === 'Snap target').activate(global.get_current_time()); 1" >/dev/null + sleep 1 + "$MENEW_BIN" run win.left >/dev/null 2>&1; sleep 2 + geo="$(shell_eval "const w = global.get_window_actors().map(a => a.meta_window).find(w => w.get_title() === 'Snap target'); const r = w.get_frame_rect(); const a = w.get_work_area_current_monitor(); [r.x - a.x, r.width, a.width].join(',')" | grep -o -- '-\?[0-9]*,[0-9]*,[0-9]*' | tail -1)" + info "snap target geometry (x offset, width, work width): ${geo:-none}" + IFS=, read -r x w aw <<<"${geo:-,,}" + if half_ok "$x" "$w" "$aw" left; then + pass "win.left put the window on the left half (through org.menew.Shell)" + else + fail "win.left did not snap the window: ${geo:-no geometry}"; grep -a -i 'snap' "$MENEW_LOG" | tail -5 + fi + else + # (d) win.right through a KWin script + snap_target 30 + "$MENEW_BIN" run win.right >/dev/null 2>&1; sleep 3 + probe="$TEST_ROOT/probe.js" + cat >"$probe" <<'JS' +var list = workspace.windowList ? workspace.windowList() : workspace.clientList(); +for (var i = 0; i < list.length; i++) { + var w = list[i]; + if (w.caption && w.caption.indexOf("Snap target") === 0) { + var a = workspace.clientArea(KWin.MaximizeArea, w); + print("MENEW_GEO " + Math.round(w.frameGeometry.x - a.x) + "," + Math.round(w.frameGeometry.width) + "," + Math.round(a.width)); + } +} +JS + id="$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$probe" menew-probe | grep -o '[0-9]\+' | head -1)" + gdbus call --session --dest org.kde.KWin --object-path "/Scripting/Script$id" --method org.kde.kwin.Script.run >/dev/null 2>&1 \ + || gdbus call --session --dest org.kde.KWin --object-path "/$id" --method org.kde.kwin.Script.run >/dev/null 2>&1 + sleep 1 + geo="$(grep -a -o 'MENEW_GEO [0-9,-]*' "$KWIN_LOG" | tail -1 | cut -d' ' -f2)" + info "snap target geometry (x offset, width, work width): ${geo:-none}" + IFS=, read -r x w aw <<<"${geo:-,,}" + if half_ok "$x" "$w" "$aw" right; then + pass "win.right put the window on the right half (KWin scripting)" + else + fail "win.right did not snap the window on KWin: ${geo:-no geometry}"; grep -a -i 'snap' "$MENEW_LOG" | tail -5 + fi + fi + + if grep -a -q 'panicked' "$MENEW_LOG"; then fail "the daemon panicked"; grep -a -A3 panicked "$MENEW_LOG" | head; else pass "no panic in the daemon log"; fi +} + diff --git a/scripts/desktop-test/gnome.sh b/scripts/desktop-test/gnome.sh index 376a6f4..d7cc485 100755 --- a/scripts/desktop-test/gnome.sh +++ b/scripts/desktop-test/gnome.sh @@ -217,6 +217,8 @@ source "$HERE/phase7.sh" phase7_checks source "$HERE/phase10.sh" phase10_checks +source "$HERE/actions.sh" +actions_checks echo "----" if [ "$FAILS" -eq 0 ]; then echo "RESULT: all checks passed"; else echo "RESULT: $FAILS check(s) FAILED"; fi diff --git a/scripts/desktop-test/kde.sh b/scripts/desktop-test/kde.sh index 755addb..c39fbe6 100755 --- a/scripts/desktop-test/kde.sh +++ b/scripts/desktop-test/kde.sh @@ -212,7 +212,7 @@ if [ "$PIPELINE_OK" = "1" ]; then mkdir -p "$TEST_ROOT/fakebin2" printf '#!/bin/sh\n[ "$1" = "--list-types" ] && { printf "image/png\nx-kde-passwordManagerHint\n"; exit 0; }\ncat "$STUB_DATA"\n' > "$TEST_ROOT/fakebin2/wl-paste" chmod +x "$TEST_ROOT/fakebin2/wl-paste" - convert -background white -fill black -pointsize 40 label:"HINTED IMAGE" "$TEST_ROOT/hinted.png" + convert -font DejaVu-Sans -background white -fill black -pointsize 40 label:"HINTED IMAGE" "$TEST_ROOT/hinted.png" imgs_before="$(count_kind image)"; files_before="$(ls "$(images_dir)" | wc -l)" : | STUB_DATA="$TEST_ROOT/hinted.png" PATH="$TEST_ROOT/fakebin2:$PATH" "$MENEW_BIN" __clipboard-push 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | sed 's/^/INFO: helper: /' || true sleep 1 @@ -228,6 +228,8 @@ source "$HERE/phase7.sh" if [ "$PIPELINE_OK" = "1" ]; then phase7_checks; else skip "Phase 7 checks need the wl-copy pipeline (see SKIP above)"; fi source "$HERE/phase10.sh" phase10_checks +source "$HERE/actions.sh" +actions_checks # check 4: quit leaves no wl-paste "$MENEW_BIN" quit >/dev/null 2>&1 || true diff --git a/scripts/desktop-test/phase5.sh b/scripts/desktop-test/phase5.sh index eb36baa..1dc3765 100644 --- a/scripts/desktop-test/phase5.sh +++ b/scripts/desktop-test/phase5.sh @@ -23,7 +23,7 @@ reads_logged() { grep -a -c 'Received clipboard\|Saved clipboard item' "$MENEW_L # de_copy_uris , de_pause_probe phase5_checks() { local png="$TEST_ROOT/ocr.png" shot="$REPO_ROOT/docs/desktop-tests/$DE-clipboard-images.png" f want - convert -background white -fill black -pointsize 48 label:"MENEW OCR" "$png" + convert -font DejaVu-Sans -background white -fill black -pointsize 48 label:"MENEW OCR" "$png" # (a) a PNG copy is an image entry with a file on disk de_copy_png "$png" @@ -121,7 +121,7 @@ phase5_checks() { # an image copy marked as a password, through the real D-Bus method of the daemon (all offered types are sent along) image_hint_dbus_test() { local hex before out files_before - convert -background white -fill black -pointsize 40 label:"SECRET IMAGE" "$TEST_ROOT/secret.png" + convert -font DejaVu-Sans -background white -fill black -pointsize 40 label:"SECRET IMAGE" "$TEST_ROOT/secret.png" hex="$(xxd -p "$TEST_ROOT/secret.png" | tr -d '\n' | sed 's/\(..\)/0x\1,/g; s/,$//')" before="$(count_kind image)"; files_before="$(ls "$(images_dir)" | wc -l)" out="$(gdbus call --session --dest org.menew.ClipboardService --object-path /org/menew/Clipboard --method org.menew.ClipboardService.PushClipboardData "image/png" "@ay [$hex]" "" "" "['image/png', 'x-kde-passwordManagerHint']" 2>&1 | cut -c1-120)" diff --git a/scripts/desktop-test/phase7.sh b/scripts/desktop-test/phase7.sh index 94b1c1a..1906254 100644 --- a/scripts/desktop-test/phase7.sh +++ b/scripts/desktop-test/phase7.sh @@ -32,11 +32,11 @@ phase7_checks() { local link='https://example.com/phase7?x=1&y=2' wifi='WIFI:T:WPA;S:Casa;P:secret;;' # ---- fixtures: images made with ImageMagick, QR codes made by the app ---- - convert -background white -fill black -pointsize 64 label:"MENEW CAPTURE" "$T/text1.png" - convert -background white -fill black -pointsize 64 label:$'FIRST LINE\nSECOND LINE' "$T/text2.png" + convert -font DejaVu-Sans -background white -fill black -pointsize 64 label:"MENEW CAPTURE" "$T/text1.png" + convert -font DejaVu-Sans -background white -fill black -pointsize 64 label:$'FIRST LINE\nSECOND LINE' "$T/text2.png" convert -size 600x300 xc:white "$T/blank.png" convert -size 400x300 gradient:'#d02020-#2030d0' -seed 7 -attenuate 0.6 +noise Gaussian \ - \( -background none -fill white -pointsize 36 label:"SECRET 1234" \) -geometry +20+80 -composite -depth 8 -alpha off "PNG24:$T/base.png" + \( -font DejaVu-Sans -background none -fill white -pointsize 36 label:"SECRET 1234" \) -geometry +20+80 -composite -depth 8 -alpha off "PNG24:$T/base.png" if [ -s "$T/text1.png" ] && [ -s "$T/base.png" ]; then pass "phase 7 fixtures made (text images, a noisy 400x300 picture)"; else fail "ImageMagick could not make the phase 7 fixtures"; return; fi # ---- (a) copy text from the screen: OCR of a generated image with a known text ----