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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,14 @@ o.bind("F8", "Learn from a dictation correction", "~/.local/share/localflow/app/

Raw dictation pastes the transcript as heard, without cleanup. On other
desktops, add custom shortcuts running `localflow toggle` (or `start` on
press and `stop` on release). It pastes with Ctrl+V in apps, Shift+Insert in
terminals and VS Code-family editors (their chat panels ignore a synthetic
Ctrl+V), restoring your clipboard after. Where the paste keys can't be sent
press and `stop` on release). It pastes with Ctrl+V in apps, Ctrl+Shift+V in
terminals (Ghostty, kitty, Alacritty, foot...) and Shift+Insert in VS
Code-family editors (their chat panels ignore a synthetic Ctrl+V), restoring
your clipboard after. Where the paste keys can't be sent
(GNOME's Wayland session doesn't allow `wtype`), the text stays on the
clipboard and the pill says so: press Ctrl+V.
clipboard and the pill says so: press Ctrl+V (Ctrl+Shift+V in a terminal). On Hyprland, X11 programs
running under XWayland (Ghostex, for one) get the paste keys from `xdotool`:
`wtype`'s keys reach them as other keys. Install `xdotool` for those.

## How it works

Expand Down Expand Up @@ -501,7 +504,7 @@ what `localflow --selftest` checks on yours.
- Only text on the clipboard is put back after a paste; a copied image or
file is gone.
- On Wayland desktops other than Hyprland, localflow can't see which window
has focus, so terminals there get Ctrl+V (not Shift+Insert) and coding
has focus, so terminals there get Ctrl+V (not Ctrl+Shift+V) and coding
agents aren't recognised.

## Layout
Expand Down
2 changes: 1 addition & 1 deletion crates/desktop/src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ pub fn focused_window() -> Window {
}
CFRelease(element);
}
Window { app: ns_text(bundle as *const c_void), title, pid: Some(pid as u32), tags: vec![] }
Window { app: ns_text(bundle as *const c_void), title, pid: Some(pid as u32), tags: vec![], xwayland: false }
}
}

Expand Down
101 changes: 79 additions & 22 deletions crates/desktop/src/paste.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,27 +88,47 @@ fn is_editor(class: &str) -> bool {
["cursor", "code", "code-oss", "codium", "vscodium", "windsurf"].contains(&class.to_lowercase().as_str())
}

/// wtype's arguments for the paste keys on Wayland: Shift+Insert in terminals
/// (a Hyprland "terminal" tag, as Omarchy's universal paste checks) and
/// editors, Ctrl+V elsewhere.
/// Terminal window classes on Linux (Wayland app ids and X11 classes), matched
/// whole so an app that merely contains "term" or "warp" isn't one.
#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
pub(crate) fn wayland_keys(class: &str, tags: &[String]) -> [&'static str; 6] {
if tags.iter().any(|t| t == "terminal" || t == "terminal*") || is_editor(class) {
["-M", "shift", "-k", "Insert", "-m", "shift"]
static TERMINAL_CLASS: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(
r"(?i)^(?:[\w-]+\.)*(?:ghostty|kitty|alacritty|foot|footclient|wezterm|wezterm-gui|konsole|tilix|terminator|xterm|urxvt|rxvt|st|st-256color|kgx|ptyxis|blackbox|terminology|(?:[\w]+-)?terminal(?:-server)?)$|^org\.gnome\.console$|^dev\.warp\.warp$",
)
.unwrap()
});

/// A terminal, by its class or Hyprland's "terminal" tag (dynamic tags carry
/// a trailing "*").
#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
fn is_terminal(class: &str, tags: &[String]) -> bool {
TERMINAL_CLASS.is_match(class) || tags.iter().any(|t| t.trim_end_matches('*') == "terminal")
}

/// wtype's arguments for the paste keys on Wayland: Ctrl+Shift+V in
/// terminals, Shift+Insert in editors, Ctrl+V elsewhere. Not Shift+Insert in
/// terminals: Ghostty, kitty, Alacritty and foot paste the primary selection
/// with it unless their config says otherwise, so the dictation was lost.
#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
pub(crate) fn wayland_keys(class: &str, tags: &[String]) -> &'static [&'static str] {
// An editor's own key first, even if a window rule tags it a terminal:
// Ctrl+Shift+V opens VS Code's Markdown preview.
if is_editor(class) {
&["-M", "shift", "-k", "Insert", "-m", "shift"]
} else if is_terminal(class, tags) {
&["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"]
} else {
["-M", "ctrl", "-k", "v", "-m", "ctrl"]
&["-M", "ctrl", "-k", "v", "-m", "ctrl"]
}
}

/// xdotool's paste key on X11: Ctrl+Shift+V in terminals.
#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
pub(crate) fn x11_key(class: &str) -> &'static str {
let terminal = regex::Regex::new("term|kitty|alacritty|ghostty|konsole|tilix|wezterm|foot|terminator").unwrap();
let class = class.to_lowercase();
if terminal.is_match(&class) {
"ctrl+shift+v"
} else if is_editor(&class) {
if is_editor(class) {
"shift+Insert"
} else if is_terminal(class, &[]) {
"ctrl+shift+v"
} else {
"ctrl+v"
}
Expand Down Expand Up @@ -194,23 +214,42 @@ mod linux {
if std::env::var_os("DISPLAY").is_some() { paste_x11(parts) } else { false }
}

/// The focused window as Hyprland describes it (empty elsewhere).
fn active_hyprland_window() -> crate::target::Window {
if which("hyprctl").is_none() {
return crate::target::Window::default();
}
hyprland_window(&output(command("hyprctl").args(["activewindow", "-j"]), Duration::from_secs(2)))
}

/// Send X11 keys (xdotool) rather than Wayland ones: the window runs under
/// XWayland and xdotool can reach it.
fn x11_keys_for(window: &crate::target::Window) -> bool {
window.xwayland && std::env::var_os("DISPLAY").is_some() && which("xdotool").is_some()
}

fn paste_wayland(parts: &[Part]) -> bool {
let types = output(command("wl-paste").arg("--list-types"), Duration::from_secs(2));
let old_type = types.lines().next().unwrap_or_default().to_string();
let old = if old_type.is_empty() { vec![] } else { bytes(command("wl-paste").args(["--no-newline", "--type", &old_type])) };
let (mut class, mut tags) = (String::new(), vec![]);
if which("hyprctl").is_some() {
let w = hyprland_window(&output(command("hyprctl").args(["activewindow", "-j"]), Duration::from_secs(2)));
(class, tags) = (w.app, w.tags);
}
let keys = wayland_keys(&class, &tags);
let window = active_hyprland_window();
// An XWayland window gets X11 keys: wtype's keymap doesn't reach it,
// so its Ctrl+V arrives as another key and nothing is pasted.
let x11 = x11_keys_for(&window);
let keys = wayland_keys(&window.app, &window.tags);
let x_key = x11_key(&window.app);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for (i, part) in parts.iter().enumerate() {
match part {
Part::File(path) => feed(command("wl-copy").args(["--type", "text/uri-list"]), format!("{}\r\n", file_uri(path.as_ref())).as_bytes()),
Part::Text(text) => feed(&mut command("wl-copy"), text.as_bytes()),
};
sleep(50);
if !quiet(command("wtype").args(keys)) {
let sent = if x11 {
quiet(command("xdotool").args(["key", "--clearmodifiers", x_key]))
} else {
quiet(command("wtype").args(keys))
};
if !sent {
return false;
}
if i + 1 < parts.len() {
Expand Down Expand Up @@ -260,7 +299,9 @@ mod linux {
Key::Enter => "Return",
Key::Escape => "Escape",
};
if std::env::var_os("WAYLAND_DISPLAY").is_some() && which("wtype").is_some() {
if std::env::var_os("WAYLAND_DISPLAY").is_some() && x11_keys_for(&active_hyprland_window()) {
quiet(command("xdotool").args(["key", "--clearmodifiers", name]))
} else if std::env::var_os("WAYLAND_DISPLAY").is_some() && which("wtype").is_some() {
quiet(command("wtype").args(["-k", name]))
} else if std::env::var_os("DISPLAY").is_some() {
quiet(command("xdotool").args(["key", "--clearmodifiers", name]))
Expand Down Expand Up @@ -328,11 +369,27 @@ mod tests {
#[test]
fn paste_keys_by_window() {
let tags = |t: &[&str]| t.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let ctrl_shift_v = ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"];
assert_eq!(wayland_keys("brave-browser", &[]), ["-M", "ctrl", "-k", "v", "-m", "ctrl"]);
assert_eq!(wayland_keys("com.mitchellh.ghostty", &tags(&["terminal*"]))[3], "Insert");
assert_eq!(wayland_keys("whatever", &tags(&["terminal"]))[3], "Insert");
assert_eq!(wayland_keys("com.mitchellh.ghostty", &tags(&["terminal*"])), ctrl_shift_v);
// Without Omarchy's tag (another compositor setup), by the class.
assert_eq!(wayland_keys("com.mitchellh.ghostty", &[]), ctrl_shift_v);
assert_eq!(wayland_keys("kitty", &[]), ctrl_shift_v);
assert_eq!(wayland_keys("whatever", &tags(&["terminal"])), ctrl_shift_v);
assert_eq!(wayland_keys("Cursor", &[])[3], "Insert");
assert_eq!(wayland_keys("cursor-notes", &tags(&["terminals-not"]))[3], "v");
assert_eq!(x11_key("com.mitchellh.ghostty"), "ctrl+shift+v");
// Editors keep their key even when tagged a terminal.
assert_eq!(wayland_keys("code", &tags(&["terminal*"]))[3], "Insert");
// Terminals by their whole class, not a word inside another app's.
for t in ["Alacritty", "foot", "org.wezfurlong.wezterm", "org.gnome.Terminal", "gnome-terminal-server",
"xfce4-terminal", "org.kde.konsole", "org.gnome.Console", "org.gnome.Ptyxis", "dev.warp.Warp",
"XTerm", "URxvt", "st-256color", "com.gexperts.Tilix"] {
assert_eq!(x11_key(t), "ctrl+shift+v", "{t}");
}
for app in ["app.drey.Warp", "Thermald-gui", "determination", "org.gnome.TextEditor", "steam"] {
assert_eq!(wayland_keys(app, &[])[3], "v", "{app}");
}
assert_eq!(x11_key("Alacritty"), "ctrl+shift+v");
assert_eq!(x11_key("Code"), "shift+Insert");
assert_eq!(x11_key("firefox"), "ctrl+v");
Expand Down
9 changes: 7 additions & 2 deletions crates/desktop/src/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ pub struct Window {
pub title: String,
pub pid: Option<u32>,
pub tags: Vec<String>,
/// An X11 program under XWayland (Hyprland says): synthetic Wayland keys
/// (wtype) reach it as the wrong keys, so it's sent X11 ones.
pub xwayland: bool,
}

/// The window you're typing in (empty where the desktop doesn't say: Wayland
Expand All @@ -48,7 +51,7 @@ fn linux_focused_window() -> Window {
app: get("getwindowclassname"),
title: get("getwindowname"),
pid: get("getwindowpid").parse().ok(),
tags: vec![],
..Window::default()
};
}
Window::default()
Expand All @@ -63,6 +66,7 @@ pub fn hyprland_window(json: &str) -> Window {
title: text("title"),
pid: w["pid"].as_u64().map(|p| p as u32),
tags: w["tags"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(String::from)).collect(),
xwayland: w["xwayland"].as_bool().unwrap_or(false),
}
}

Expand Down Expand Up @@ -264,7 +268,8 @@ mod tests {
#[test]
fn hyprland_json() {
let w = hyprland_window(r#"{"class": "kitty", "title": "~/p", "pid": 42, "tags": ["terminal*"]}"#);
assert_eq!(w, Window { app: "kitty".into(), title: "~/p".into(), pid: Some(42), tags: vec!["terminal*".into()] });
assert_eq!(w, Window { app: "kitty".into(), title: "~/p".into(), pid: Some(42), tags: vec!["terminal*".into()], xwayland: false });
assert!(hyprland_window(r#"{"class": "ghostex", "xwayland": true}"#).xwayland);
assert_eq!(hyprland_window("{}"), Window::default());
}
}
2 changes: 1 addition & 1 deletion crates/desktop/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub fn focused_window() -> Window {
}
CloseHandle(process);
}
Window { app, title: String::from_utf16_lossy(&title[..n]), pid: Some(pid), tags: vec![] }
Window { app, title: String::from_utf16_lossy(&title[..n]), pid: Some(pid), tags: vec![], xwayland: false }
}
}

Expand Down
Loading