kagikey 0.2.0

Cross-platform key mapper with first-class IME control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! `kagi service` — register kagi as a per-user background service.
//!
//! Each platform gets the mechanism that actually fits a key-mapping daemon,
//! rather than one lowest-common-denominator autostart entry:
//!
//! * macOS — a launchd **LaunchAgent**. `ProcessType = Interactive` keeps
//!   launchd from throttling keyboard handling behind background QoS.
//! * Linux — a **systemd user unit** bound to the graphical session. kagi
//!   grabs evdev devices, so it must come up with the session and go down
//!   with it; a `.desktop` autostart entry gives neither restart-on-failure
//!   nor an ordering guarantee.
//! * Windows — a **logon scheduled task** driving a `wscript` shim, because a
//!   console binary started from the Startup folder leaves a window on screen
//!   for as long as the daemon runs.
//!
//! Everything is per-user. Nothing here needs root or an installer.

use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::process::Command;

fn exe() -> Result<PathBuf> {
    let exe = std::env::current_exe().context("locating the running kagi binary")?;
    // `current_exe` can hand back a symlink in the target directory; resolve
    // it so the service keeps pointing at the same binary after a rebuild.
    Ok(std::fs::canonicalize(&exe).unwrap_or(exe))
}

fn home() -> Result<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .context("cannot locate a home directory")
}

/// Run `program` and turn a non-zero exit into an error carrying stderr.
fn run(program: &str, args: &[&str]) -> Result<String> {
    let out = Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("running `{program}`"))?;
    if !out.status.success() {
        bail!(
            "`{program} {}` failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Same, but a failure is expected and uninteresting (tearing down something
/// that may not be registered).
fn run_quiet(program: &str, args: &[&str]) {
    let _ = Command::new(program).args(args).output();
}

fn write_file(path: &Path, contents: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}

/// The `run` arguments the service is registered with.
fn run_args(config: Option<&Path>) -> Vec<String> {
    match config {
        Some(c) => vec!["--config".into(), c.display().to_string(), "run".into()],
        None => vec!["run".into()],
    }
}

// ===========================================================================
// macOS
// ===========================================================================

#[cfg(target_os = "macos")]
mod imp {
    use super::*;

    /// launchd job label, and the plist filename.
    const LABEL: &str = "com.yukimemi.kagi";

    fn plist_path() -> Result<PathBuf> {
        Ok(home()?
            .join("Library")
            .join("LaunchAgents")
            .join(format!("{LABEL}.plist")))
    }

    /// launchd addresses a per-user domain by uid. `id -u` avoids pulling in
    /// libc just for `getuid`.
    fn domain() -> Result<String> {
        let uid = run("id", &["-u"])?;
        Ok(format!("gui/{}", uid.trim()))
    }

    fn target() -> Result<String> {
        Ok(format!("{}/{LABEL}", domain()?))
    }

    fn xml_escape(s: &str) -> String {
        s.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    }

    fn plist(exe: &Path, config: Option<&Path>) -> String {
        let mut args = String::new();
        args.push_str(&format!(
            "    <string>{}</string>\n",
            xml_escape(&exe.display().to_string())
        ));
        for a in run_args(config) {
            args.push_str(&format!("    <string>{}</string>\n", xml_escape(&a)));
        }
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Generated by `kagi service install`. Re-run it to regenerate. -->
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>{LABEL}</string>

  <key>ProgramArguments</key>
  <array>
{args}  </array>

  <key>EnvironmentVariables</key>
  <dict>
    <!-- macOS keys Accessibility and Input Monitoring to this binary. A
         background self-update swaps it out, and the agent then runs unable
         to see any key until the grants are renewed, with no prompt because
         nothing is in the foreground. Update deliberately: `kagi update`. -->
    <key>KAGI_NO_AUTOUPDATE</key>
    <string>1</string>
  </dict>

  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>

  <!-- Keyboard handling must not be throttled behind background QoS. -->
  <key>ProcessType</key>
  <string>Interactive</string>

  <key>StandardOutPath</key>
  <string>{log}</string>
  <key>StandardErrorPath</key>
  <string>{log}</string>
</dict>
</plist>
"#,
            log = xml_escape(&log_path().display().to_string()),
        )
    }

    /// `~/Library/Logs` is where a user agent's log belongs, and unlike
    /// `std::env::temp_dir()` (a per-boot `/var/folders/...` path on macOS) it
    /// stays quotable and survives reboots.
    pub fn log_path() -> PathBuf {
        match home() {
            Ok(h) => h.join("Library").join("Logs").join("kagi.log"),
            Err(_) => PathBuf::from("/tmp/kagi.log"),
        }
    }

    pub fn install(config: Option<&Path>) -> Result<()> {
        let path = plist_path()?;
        write_file(&path, &plist(&exe()?, config))?;
        println!("wrote {}", path.display());

        // Replace any previous registration; `bootout` fails when nothing is
        // loaded, which is fine.
        run_quiet("launchctl", &["bootout", &target()?]);
        run(
            "launchctl",
            &["bootstrap", &domain()?, &path.display().to_string()],
        )?;
        println!("loaded {}", target()?);
        Ok(())
    }

    pub fn uninstall() -> Result<()> {
        run_quiet("launchctl", &["bootout", &target()?]);
        let path = plist_path()?;
        if path.exists() {
            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
            println!("removed {}", path.display());
        }
        println!("unloaded {}", target()?);
        Ok(())
    }

    pub fn start() -> Result<()> {
        run("launchctl", &["kickstart", "-k", &target()?])?;
        println!("started {}", target()?);
        Ok(())
    }

    pub fn stop() -> Result<()> {
        run("launchctl", &["kill", "SIGTERM", &target()?])?;
        println!("signalled {}", target()?);
        Ok(())
    }

    pub fn status() -> Result<()> {
        let path = plist_path()?;
        println!("plist: {} ({})", path.display(), exists(&path));
        match Command::new("launchctl")
            .args(["print", &target()?])
            .output()
        {
            Ok(out) if out.status.success() => {
                let text = String::from_utf8_lossy(&out.stdout);
                for line in text.lines() {
                    let t = line.trim();
                    if t.starts_with("state =")
                        || t.starts_with("pid =")
                        || t.starts_with("last exit code =")
                    {
                        println!("{t}");
                    }
                }
            }
            _ => println!("state = not loaded"),
        }
        println!("log: {}", log_path().display());
        Ok(())
    }

    /// Permission note printed after a successful install.
    pub fn after_install() -> Result<()> {
        println!(
            "\nmacOS grants Accessibility and Input Monitoring per binary, and the\n\
             agent is not the terminal you just used. The first run therefore fails\n\
             with `CGEventTapCreate failed` until you add\n  {}\n\
             under System Settings > Privacy & Security > Accessibility, and again\n\
             under Input Monitoring. Then:\n  launchctl kickstart -k {}\n\
             Check progress with `kagi service status` and {}.",
            exe()?.display(),
            target()?,
            log_path().display()
        );
        Ok(())
    }
}

// ===========================================================================
// Linux
// ===========================================================================

#[cfg(target_os = "linux")]
mod imp {
    use super::*;

    const UNIT: &str = "kagi.service";

    fn unit_path() -> Result<PathBuf> {
        let base = match std::env::var_os("XDG_CONFIG_HOME") {
            Some(x) => PathBuf::from(x),
            None => home()?.join(".config"),
        };
        Ok(base.join("systemd").join("user").join(UNIT))
    }

    fn unit(exe: &Path, config: Option<&Path>) -> String {
        let args = run_args(config).join(" ");
        format!(
            "# Generated by `kagi service install`. Re-run it to regenerate.\n\
             [Unit]\n\
             Description=kagi — cross-platform key mapper with first-class IME control\n\
             Documentation=https://github.com/yukimemi/kagi\n\
             After=graphical-session.target\n\
             PartOf=graphical-session.target\n\
             \n\
             [Service]\n\
             Type=simple\n\
             ExecStart={exe} {args}\n\
             Restart=on-failure\n\
             RestartSec=2\n\
             # A key mapper that loses to the scheduler feels like broken hardware.\n\
             Nice=-5\n\
             \n\
             [Install]\n\
             WantedBy=graphical-session.target\n",
            exe = exe.display(),
        )
    }

    pub fn install(config: Option<&Path>) -> Result<()> {
        let path = unit_path()?;
        write_file(&path, &unit(&exe()?, config))?;
        println!("wrote {}", path.display());

        run("systemctl", &["--user", "daemon-reload"])?;
        run("systemctl", &["--user", "enable", "--now", UNIT])?;
        println!("enabled {UNIT}");
        Ok(())
    }

    pub fn uninstall() -> Result<()> {
        run_quiet("systemctl", &["--user", "disable", "--now", UNIT]);
        let path = unit_path()?;
        if path.exists() {
            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
            println!("removed {}", path.display());
        }
        run_quiet("systemctl", &["--user", "daemon-reload"]);
        println!("disabled {UNIT}");
        Ok(())
    }

    pub fn start() -> Result<()> {
        run("systemctl", &["--user", "restart", UNIT])?;
        println!("started {UNIT}");
        Ok(())
    }

    pub fn stop() -> Result<()> {
        run("systemctl", &["--user", "stop", UNIT])?;
        println!("stopped {UNIT}");
        Ok(())
    }

    pub fn status() -> Result<()> {
        let path = unit_path()?;
        println!("unit: {} ({})", path.display(), exists(&path));
        let out = Command::new("systemctl")
            .args(["--user", "--no-pager", "status", UNIT])
            .output();
        match out {
            Ok(o) => print!("{}", String::from_utf8_lossy(&o.stdout)),
            Err(e) => println!("systemctl unavailable: {e}"),
        }
        Ok(())
    }

    pub fn after_install() -> Result<()> {
        println!(
            "\nkagi reads /dev/input/event* and writes /dev/uinput. If the service\n\
             fails with a permission error:\n  \
             sudo usermod -aG input $USER    # then log out and back in\n  \
             echo 'KERNEL==\"uinput\", GROUP=\"input\", MODE=\"0660\"' \\\n    \
             | sudo tee /etc/udev/rules.d/99-kagi-uinput.rules\n  \
             sudo modprobe uinput && sudo udevadm control --reload-rules\n\
             Logs: journalctl --user -u kagi -f"
        );
        Ok(())
    }
}

// ===========================================================================
// Windows
// ===========================================================================

#[cfg(target_os = "windows")]
mod imp {
    use super::*;

    const TASK: &str = "kagi";

    fn shim_path() -> Result<PathBuf> {
        let base = match std::env::var_os("LOCALAPPDATA") {
            Some(x) => PathBuf::from(x),
            None => home()?.join("AppData").join("Local"),
        };
        Ok(base.join("kagi").join("kagi-hidden.vbs"))
    }

    /// `wscript` with window style 0 is the one way to start a console binary
    /// on Windows without leaving a console window on screen for the life of
    /// the process, while still running inside the interactive session — which
    /// kagi needs, because its IME calls target the foreground window.
    fn shim(exe: &Path, config: Option<&Path>) -> String {
        let mut cmd = format!("\"\"{}\"\"", exe.display());
        for a in run_args(config) {
            cmd.push_str(&format!(" \"\"{a}\"\""));
        }
        format!(
            "' Generated by `kagi service install`. Re-run it to regenerate.\r\n\
             Set sh = CreateObject(\"WScript.Shell\")\r\n\
             sh.Run \"{cmd}\", 0, False\r\n"
        )
    }

    pub fn install(config: Option<&Path>) -> Result<()> {
        let shim_file = shim_path()?;
        write_file(&shim_file, &shim(&exe()?, config))?;
        println!("wrote {}", shim_file.display());

        let action = format!("wscript.exe \"{}\"", shim_file.display());
        run(
            "schtasks",
            &[
                "/Create", "/TN", TASK, "/TR", &action, "/SC", "ONLOGON", "/RL", "LIMITED", "/F",
            ],
        )?;
        println!("registered logon task `{TASK}`");
        start()
    }

    pub fn uninstall() -> Result<()> {
        run_quiet("schtasks", &["/End", "/TN", TASK]);
        run_quiet("schtasks", &["/Delete", "/TN", TASK, "/F"]);
        let shim_file = shim_path()?;
        if shim_file.exists() {
            std::fs::remove_file(&shim_file)
                .with_context(|| format!("removing {}", shim_file.display()))?;
            println!("removed {}", shim_file.display());
        }
        println!("removed logon task `{TASK}`");
        Ok(())
    }

    pub fn start() -> Result<()> {
        run("schtasks", &["/Run", "/TN", TASK])?;
        println!("started `{TASK}`");
        Ok(())
    }

    pub fn stop() -> Result<()> {
        run("schtasks", &["/End", "/TN", TASK])?;
        println!("stopped `{TASK}`");
        Ok(())
    }

    pub fn status() -> Result<()> {
        let shim_file = shim_path()?;
        println!("shim: {} ({})", shim_file.display(), exists(&shim_file));
        match Command::new("schtasks")
            .args(["/Query", "/TN", TASK, "/FO", "LIST"])
            .output()
        {
            Ok(o) if o.status.success() => print!("{}", String::from_utf8_lossy(&o.stdout)),
            _ => println!("state = not registered"),
        }
        Ok(())
    }

    pub fn after_install() -> Result<()> {
        println!(
            "\nA low-level keyboard hook cannot see input destined for a window\n\
             running at a higher integrity level. If remapping stops working in an\n\
             elevated app, re-register with an elevated shell and `/RL HIGHEST`."
        );
        Ok(())
    }
}

fn exists(path: &Path) -> &'static str {
    if path.exists() { "present" } else { "absent" }
}

pub fn install(config: Option<&Path>) -> Result<()> {
    imp::install(config)?;
    imp::after_install()
}

pub fn uninstall() -> Result<()> {
    imp::uninstall()
}

pub fn start() -> Result<()> {
    imp::start()
}

pub fn stop() -> Result<()> {
    imp::stop()
}

pub fn status() -> Result<()> {
    imp::status()
}