kagikey 0.6.1

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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! `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 per-user **logon scheduled task** running kagi under
//!   `conhost --headless`, because a console binary started any plainer way
//!   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();
}

#[cfg(not(target_os = "windows"))]
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")))
    }

    /// Where the agent actually runs from: inside a real `.app` bundle at
    /// `~/Applications/kagi.app`, never `current_exe()` (`~/.cargo/bin/kagi`)
    /// directly.
    ///
    /// Two things pushed this here, both load-bearing:
    ///
    /// 1. **TCC keys an Accessibility/Input Monitoring grant to the
    ///    executable path, not just its code signature**, and appears to
    ///    cache that per-path association *permanently* — exhaustively
    ///    confirmed on `~/.cargo/bin/kagi` during development: fixing the
    ///    signature (stable identifier, stable `LC_UUID`, valid Designated
    ///    Requirement — see `platform::macos::ensure_stable_identity`),
    ///    switching to a never-before-seen identifier, and the user manually
    ///    removing the Settings row with `−` and re-adding it with `+`, ALL
    ///    still failed with the identical stale `SecStaticCodeCheckValidity`
    ///    error (`errSecCSReqFailed`/`-67050` against a specific old
    ///    `cdhash`), while an *identical* binary at a fresh path granted
    ///    normally every time. `tccd` restart is SIP-blocked
    ///    (`launchctl kickstart` on `com.apple.tccd` answers "Operation not
    ///    permitted while System Integrity Protection is engaged"), and
    ///    `tccutil reset <service> <path-or-identifier>` refuses anything
    ///    that is not a real, LaunchServices-registered bundle identifier
    ///    ("No such bundle identifier"). There is no user-space fix for a
    ///    poisoned path; only moving off it works.
    /// 2. A **real bundle**, not a bare copied executable, makes that
    ///    `tccutil reset <service> <bundle-id>` command actually work if this
    ///    path *ever* gets poisoned too — a targeted reset that, unlike
    ///    `kagi permissions --reset`, does not revoke every other
    ///    application's grants for the same service. Matches
    ///    [paneru](https://github.com/karinushka/paneru)'s own
    ///    `install-app`.
    fn app_bundle() -> Result<PathBuf> {
        Ok(home()?.join("Applications").join("kagi.app"))
    }

    fn app_executable() -> Result<PathBuf> {
        Ok(app_bundle()?.join("Contents").join("MacOS").join("kagi"))
    }

    /// The bundle's `CFBundleIdentifier` — see `platform::macos::BUNDLE_ID`
    /// for the full story on why it is its own constant, not [`LABEL`] and
    /// not `crate::platform::SIGN_ID`.
    use crate::platform::BUNDLE_ID;

    fn info_plist() -> String {
        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">
<plist version="1.0">
<dict>
  <key>CFBundleIdentifier</key>
  <string>{BUNDLE_ID}</string>
  <key>CFBundleExecutable</key>
  <string>kagi</string>
  <key>CFBundleName</key>
  <string>kagi</string>
  <key>CFBundlePackageType</key>
  <string>APPL</string>
  <key>CFBundleShortVersionString</key>
  <string>{version}</string>
  <!-- No Dock icon, no menu bar: kagi has no UI of its own. -->
  <key>LSUIElement</key>
  <true/>
</dict>
</plist>
"#,
            version = env!("CARGO_PKG_VERSION"),
        )
    }

    /// Copy the current binary into a freshly (re)written `~/Applications/
    /// kagi.app`, so the registered service always runs the latest build
    /// from its own dedicated, bundle-identified path.
    fn deploy() -> Result<PathBuf> {
        let src = exe()?;
        let dst = app_executable()?;
        write_file(
            &app_bundle()?.join("Contents").join("Info.plist"),
            &info_plist(),
        )?;
        if let Some(dir) = dst.parent() {
            std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
        }
        std::fs::copy(&src, &dst)
            .with_context(|| format!("copying {} to {}", src.display(), dst.display()))?;
        // Two overrides on top of plain ad-hoc `--sign -`, both load-bearing
        // across a rebuild:
        //
        // * `--deep` covers the bundle as a whole; a bare `--sign` on just
        //   the executable leaves Info.plist unsealed and `codesign
        //   --verify` on the bundle fails with "bundle format unrecognized,
        //   invalid, or unsuitable".
        // * `-r=<expr>` pins the designated requirement to the identifier
        //   alone. Ad-hoc signing's *default* designated requirement pins
        //   the content hash instead (`designated => cdhash H"..."`),
        //   confirmed with `codesign -d -r-` on a bundle signed without
        //   this override — which changes on every `cargo install`/rebuild.
        //   TCC's grant did not survive a rebuild without this override:
        //   observed directly, a fresh `kagi service install` right after
        //   one that had just been granted came back to `CGEventTapCreate
        //   failed` / "NOT granted" again. Same fix, same reason, as
        //   `ensure_stable_identity`'s `-r=` on the raw-binary path — see
        //   its doc comment for the argv-joining gotcha (`-r=<expr>` must be
        //   one argument, not two).
        run(
            "codesign",
            &[
                "--force",
                "--deep",
                "--sign",
                "-",
                "--identifier",
                BUNDLE_ID,
                &format!("-r=designated => identifier \"{BUNDLE_ID}\""),
                &app_bundle()?.display().to_string(),
            ],
        )?;
        Ok(dst)
    }

    /// 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/>
  <!-- No ThrottleInterval override on purpose: `launchctl kickstart` blocks
       until the job actually spawns, so raising it makes `kagi service start`
       hang for that long. The repeated-prompt problem it would paper over is
       already solved by asking for a permission only once. -->

  <!-- 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<()> {
        // A concurrently respawning `KeepAlive` daemon calls
        // `platform::macos::request_permissions(Prompt::Once)` on every
        // failed start (a lightweight, non-blocking check+open) — running
        // that at the same time as this function's own interactive,
        // dialog-driven flow can pop two overlapping system prompts. Stop it
        // first; `start()` at the end brings it back once permissions are in
        // place.
        run_quiet("launchctl", &["bootout", &target()?]);

        let agent = deploy()?;
        let path = plist_path()?;
        write_file(&path, &plist(&agent, config))?;
        println!("wrote {}", path.display());

        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());
        }
        let bundle = app_bundle()?;
        if bundle.exists() {
            std::fs::remove_dir_all(&bundle)
                .with_context(|| format!("removing {}", bundle.display()))?;
            println!("removed {}", bundle.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 {}.",
            app_executable()?.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";

    /// Where kagi ≤ 0.6.0 wrote its `wscript` shim. Only swept up now.
    fn legacy_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"))
    }

    fn remove_legacy_shim() -> Result<()> {
        let shim = legacy_shim_path()?;
        if shim.exists() {
            std::fs::remove_file(&shim).with_context(|| format!("removing {}", shim.display()))?;
            println!("removed legacy {}", shim.display());
        }
        Ok(())
    }

    /// `canonicalize` yields a verbatim `\\?\C:\…` path; strip it so the
    /// command line stays one any launcher parses.
    fn plain(path: &Path) -> String {
        let s = path.display().to_string();
        match s.strip_prefix(r"\\?\") {
            Some(rest) if !rest.starts_with("UNC\\") => rest.to_owned(),
            _ => s,
        }
    }

    /// Arguments for `conhost.exe --headless`: it hosts kagi's console without
    /// ever creating a window, while kagi stays in the interactive session —
    /// which it needs, because its IME calls target the foreground window.
    /// Replaces a `wscript` shim: VBScript is being retired from Windows.
    fn conhost_args(exe: &Path, config: Option<&Path>) -> String {
        let mut args = format!("--headless \"{}\"", plain(exe));
        for a in run_args(config) {
            args.push_str(&format!(" \"{a}\""));
        }
        args
    }

    fn current_user() -> Result<String> {
        let user = std::env::var("USERNAME").context("USERNAME is not set")?;
        Ok(match std::env::var("USERDOMAIN") {
            Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
            _ => user,
        })
    }

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

    /// Logon task for `user` only, running unelevated in the interactive
    /// session. `ExecutionTimeLimit = PT0S` matters: the default would kill
    /// the daemon after 72 hours, and the battery defaults would stop it on
    /// unplug.
    fn task_xml(user: &str, args: &str) -> String {
        let user = xml_escape(user);
        let args = xml_escape(args);
        format!(
            r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <LogonTrigger><Enabled>true</Enabled><UserId>{user}</UserId></LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>{user}</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
  </Settings>
  <Actions Context="Author">
    <Exec><Command>%SystemRoot%\System32\conhost.exe</Command><Arguments>{args}</Arguments></Exec>
  </Actions>
</Task>
"#
        )
    }

    pub fn install(config: Option<&Path>) -> Result<()> {
        let args = conhost_args(&exe()?, config);

        // `/SC ONLOGON` on the command line means "at logon of any user",
        // which Task Scheduler reserves for administrators. A LogonTrigger
        // scoped to the calling user is allowed unelevated, but schtasks only
        // exposes that through `/XML`.
        let xml_file = std::env::temp_dir().join(format!("kagi-task-{}.xml", std::process::id()));
        let xml = task_xml(&current_user()?, &args);
        let mut bytes = vec![0xFF, 0xFE];
        bytes.extend(xml.encode_utf16().flat_map(u16::to_le_bytes));
        std::fs::write(&xml_file, bytes)
            .with_context(|| format!("writing {}", xml_file.display()))?;
        let xml_arg = xml_file.to_string_lossy().into_owned();
        let created = run(
            "schtasks",
            &["/Create", "/TN", TASK, "/XML", &xml_arg, "/F"],
        );
        let _ = std::fs::remove_file(&xml_file);
        created?;

        // Only now that the new task is registered is it safe to tear down
        // the old state: an earlier failure (e.g. `/Create` denied) leaves
        // whatever was already running or registered untouched instead of
        // stranding the user with neither the old nor the new task.
        let _ = kill_daemon();
        remove_legacy_shim()?;
        println!("registered logon task `{TASK}`");
        start()
    }

    pub fn uninstall() -> Result<()> {
        let _ = kill_daemon();
        run_quiet("schtasks", &["/Delete", "/TN", TASK, "/F"]);
        remove_legacy_shim()?;
        println!("removed logon task `{TASK}`");
        Ok(())
    }

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

    /// `schtasks /End` terminates only the task's own process — `conhost` —
    /// and leaves kagi running as an orphan. Kill every other `kagi.exe`
    /// too; this process is excluded by PID. The `/End` result is the one
    /// that's interesting to `stop()` — it fails when the task isn't
    /// registered or isn't running; the orphan sweep is best-effort cleanup
    /// on top of that and stays quiet either way.
    fn kill_daemon() -> Result<()> {
        let ended = run("schtasks", &["/End", "/TN", TASK]);
        let not_self = format!("PID ne {}", std::process::id());
        run_quiet("taskkill", &["/F", "/IM", "kagi.exe", "/FI", &not_self]);
        ended.map(|_| ())
    }

    pub fn stop() -> Result<()> {
        kill_daemon()?;
        println!("stopped `{TASK}`");
        Ok(())
    }

    pub fn status() -> Result<()> {
        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, set the `kagi` task to \"Run with highest privileges\"\n\
             in Task Scheduler (needs an administrator)."
        );
        Ok(())
    }
}

#[cfg(not(target_os = "windows"))]
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()
}