snipexpand 0.2.5

Fast, config-based text expansion for Linux and Wayland
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
use anyhow::Result;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use tokio::io::AsyncWriteExt;
use tokio::signal::unix::{signal, SignalKind};

use crate::config::Config;
use crate::expander::Expander;
use crate::injector::Injector;
use crate::ipc::{IpcCmd, IpcServer};
use crate::keyboard::{KeyboardEvent, KeyboardStream};

// evdev KEY codes (Linux input-event-codes.h)
const KEY_BACKSPACE: u16 = 14;
const KEY_TAB: u16 = 15;
const KEY_ENTER: u16 = 28;
const MODIFIER_KEYS: &[u16] = &[
    29,  // KEY_LEFTCTRL
    42,  // KEY_LEFTSHIFT
    54,  // KEY_RIGHTSHIFT
    56,  // KEY_LEFTALT
    97,  // KEY_RIGHTCTRL
    100, // KEY_RIGHTALT / AltGr
    125, // KEY_LEFTMETA
    126, // KEY_RIGHTMETA
];
const SHORTCUT_MODIFIERS: &[u16] = &[
    29,  // KEY_LEFTCTRL
    56,  // KEY_LEFTALT
    97,  // KEY_RIGHTCTRL
    125, // KEY_LEFTMETA
    126, // KEY_RIGHTMETA
];
// Keys that reset the expansion buffer (cursor movement)
const RESET_KEYS: &[u16] = &[
    105, // KEY_LEFT
    106, // KEY_RIGHT
    103, // KEY_UP
    108, // KEY_DOWN
    102, // KEY_HOME
    107, // KEY_END
    1,   // KEY_ESC
    110, // KEY_INSERT
    111, // KEY_DELETE
    104, // KEY_PAGEUP
    109, // KEY_PAGEDOWN
];

struct Undo {
    replacement_len: usize,
    original: String,
}

struct PendingExpansion {
    release_code: u16,
    key_released: bool,
    expansion: crate::expander::Expansion,
}

#[derive(Default)]
struct InputState {
    held_modifiers: HashSet<(std::path::PathBuf, u16)>,
    undo: Option<Undo>,
    pending_undo: Option<Undo>,
    pending_expansion: Option<PendingExpansion>,
}

impl InputState {
    fn update_modifier(&mut self, device: &std::path::Path, code: u16, value: i32) {
        match value {
            0 => {
                self.held_modifiers.remove(&(device.to_path_buf(), code));
            }
            1 => {
                self.held_modifiers.insert((device.to_path_buf(), code));
            }
            _ => {}
        }
    }

    fn shift_held(&self) -> bool {
        self.held_modifiers
            .iter()
            .any(|(_, code)| matches!(code, 42 | 54))
    }

    fn altgr_held(&self) -> bool {
        self.held_modifiers.iter().any(|(_, code)| *code == 100)
    }

    fn shortcut_held(&self) -> bool {
        self.held_modifiers
            .iter()
            .any(|(_, code)| SHORTCUT_MODIFIERS.contains(code))
    }

    fn disconnect_device(&mut self, device: &std::path::Path) {
        self.held_modifiers
            .retain(|(held_device, _)| held_device != device);
    }
}

pub async fn run(config: Config) -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive("snipexpand=info".parse()?),
        )
        .init();
    tracing::info!("SnipExpand daemon starting");
    log_config_warnings(&config);

    // Spawn Wayland thread (blocks until keymap received)
    let injector = Injector::spawn(
        config.settings.injection_backend,
        config.settings.injection_delay_ms,
        config.settings.wayland_injection_delay_ms,
        config.settings.uinput_injection_delay_ms,
        config.settings.injection_settle_ms,
        wayland_text_characters(&config),
    )?;
    tracing::info!("Injection keyboard ready");

    // Open evdev keyboard stream
    let mut kb_stream = KeyboardStream::new().await?;
    tracing::info!("Keyboard event stream ready");

    // IPC server
    let ipc_path = crate::ipc::socket_path()?;
    let ipc_server = IpcServer::new(&ipc_path).await?;
    tracing::info!("IPC socket at {:?}", ipc_path);

    // Config + expander
    let config = Arc::new(Mutex::new(config));
    let mut expander = {
        let cfg = config.lock().unwrap();
        Expander::new_configured(
            cfg.matches.clone(),
            cfg.settings.trigger_mode,
            cfg.settings.terminator_chars(),
        )
    };

    // Config file watcher
    let (watch_tx, mut watch_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
    let config_path = Config::dir();
    let watch_tx2 = watch_tx.clone();
    // Use std::thread::spawn (not spawn_blocking) so the tokio runtime doesn't
    // wait for this thread on shutdown, enabling fast SIGTERM handling.
    std::thread::spawn(move || {
        use notify::{Config as NConfig, RecommendedWatcher, RecursiveMode, Watcher};
        use std::sync::mpsc;
        let (tx, rx) = mpsc::channel();
        let event_tx = tx.clone();
        let mut watcher = match RecommendedWatcher::new(
            move |result: notify::Result<notify::Event>| match result {
                Ok(event) if is_config_change(&event.kind) => {
                    let _ = event_tx.send(());
                }
                Ok(_) => {}
                Err(error) => tracing::warn!("Config watcher error: {}", error),
            },
            NConfig::default(),
        ) {
            Ok(w) => w,
            Err(e) => {
                tracing::error!("Config watcher failed to start: {}", e);
                return;
            }
        };
        if let Err(e) = std::fs::create_dir_all(&config_path) {
            tracing::error!("Failed to create config directory: {}", e);
            return;
        }
        if let Err(e) = watcher.watch(&config_path, RecursiveMode::Recursive) {
            tracing::error!("Failed to watch config directory: {}", e);
            return;
        }
        while rx.recv().is_ok() {
            // Editors often save through several create, rename, and modify
            // operations. Wait for that burst to settle and reload once.
            while rx
                .recv_timeout(std::time::Duration::from_millis(50))
                .is_ok()
            {}
            let _ = watch_tx2.send(());
        }
    });

    // Signals
    let mut sig_term = signal(SignalKind::terminate())?;
    let mut sig_int = signal(SignalKind::interrupt())?;
    let mut sig_usr1 = signal(SignalKind::user_defined1())?;

    // Keep watch_tx alive so the channel stays open
    let _watch_tx = watch_tx;

    // Track physical modifier state for XKB-based input character decoding.
    let mut input = InputState::default();

    tracing::info!("SnipExpand daemon ready");

    loop {
        tokio::select! {
            event = kb_stream.next_event() => {
                match event {
                    Some(KeyboardEvent::Key(ev)) => {
                        if MODIFIER_KEYS.contains(&ev.code) {
                            input.update_modifier(&ev.device, ev.code, ev.value);
                            if SHORTCUT_MODIFIERS.contains(&ev.code) {
                                cancel_input_context(&mut expander, &mut input);
                            } else if ev.value == 0 {
                                complete_pending_expansion(&injector, &config, &mut input, ev.code);
                            }
                            continue;
                        }
                        match ev.code {
                            _ if ev.value == 0 && ev.code == KEY_BACKSPACE => {
                                if let Some(previous) = input.pending_undo.take() {
                                    complete_undo(&injector, &mut expander, previous);
                                }
                            }
                            _ if ev.value == 2 && ev.code == KEY_BACKSPACE => {
                                // A held Backspace means continuous deletion, not expansion undo.
                                input.pending_undo = None;
                                expander.reset();
                            }
                            _ if ev.value == 0 => {
                                complete_pending_expansion(&injector, &config, &mut input, ev.code);
                            }
                            _ if ev.value == 1 => {
                                // Key press only. Repeat events flood the buffer.
                                handle_key_event(&ev, &mut expander, &injector, &mut input);
                            }
                            _ => {}
                        }
                    }
                    Some(KeyboardEvent::Disconnected(device)) => {
                        input.disconnect_device(&device);
                        cancel_input_context(&mut expander, &mut input);
                    }
                    None => {
                        tracing::warn!("Keyboard stream ended");
                        break;
                    }
                }
            }

            Some(_) = watch_rx.recv() => {
                tracing::info!("Config changed, reloading");
                reload_config(&config, &mut expander, &injector);
            }

            cmd = ipc_server.accept() => {
                match cmd {
                    Ok((IpcCmd::Reload, mut stream)) => {
                        tracing::info!("Reload requested via IPC");
                        reload_config(&config, &mut expander, &injector);
                        let _ = stream.write_all(b"ok\n").await;
                    }
                    Ok((IpcCmd::Status, mut stream)) => {
                        tracing::info!("Status requested via IPC");
                        let status = {
                            let cfg = config.lock().unwrap();
                            crate::ipc::DaemonStatus {
                                running: true,
                                version: env!("CARGO_PKG_VERSION").to_string(),
                                pid: std::process::id(),
                                injection_backend: injector.backend().to_string(),
                                match_groups: cfg.matches.len(),
                                triggers: cfg.matches.iter().map(|item| item.triggers.len()).sum(),
                                files: cfg.loaded_files.len(),
                                config_valid: Config::load_default().is_ok(),
                            }
                        };
                        if let Ok(mut response) = serde_json::to_vec(&status) {
                            response.push(b'\n');
                            let _ = stream.write_all(&response).await;
                        }
                    }
                    Ok((IpcCmd::Paste(trigger), mut stream)) => {
                        cancel_input_context(&mut expander, &mut input);
                        if let Some(expansion) = expander.expansion_for_trigger(&trigger) {
                            input.undo = inject_expansion(&injector, &config, expansion);
                            let _ = stream.write_all(b"ok\n").await;
                        } else {
                            let _ = stream.write_all(b"error: trigger not found\n").await;
                        }
                    }
                    Err(e) => tracing::warn!("IPC error: {}", e),
                }
            }

            _ = sig_term.recv() => {
                tracing::info!("SIGTERM received, shutting down");
                break;
            }
            _ = sig_int.recv() => {
                tracing::info!("SIGINT received, shutting down");
                break;
            }
            _ = sig_usr1.recv() => {
                tracing::info!("SIGUSR1 received, reloading config");
                reload_config(&config, &mut expander, &injector);
            }
        }
    }

    drop(kb_stream);
    tracing::info!("SnipExpand daemon stopped");
    Ok(())
}

fn is_config_change(kind: &notify::EventKind) -> bool {
    kind.is_create() || kind.is_modify() || kind.is_remove()
}

fn handle_key_event(
    ev: &crate::keyboard::KeyEvent,
    expander: &mut Expander,
    injector: &Injector,
    input: &mut InputState,
) {
    if input.shortcut_held() {
        cancel_input_context(expander, input);
        return;
    }

    if RESET_KEYS.contains(&ev.code) {
        cancel_input_context(expander, input);
        return;
    }

    if ev.code == KEY_BACKSPACE {
        if let Some(previous) = input.undo.take() {
            input.pending_undo = Some(previous);
            return;
        }
        expander.pop_char();
        return;
    }

    if ev.code == KEY_ENTER || ev.code == KEY_TAB {
        input.undo = None;
        input.pending_undo = None;
        let character = if ev.code == KEY_ENTER { '\n' } else { '\t' };
        if let Some(expansion) = expander.push_char(character) {
            queue_expansion(input, ev.code, expansion);
        }
        return;
    }

    // Use the actual XKB keymap to decode the keypress for any keyboard layout.
    if let Some(ch) =
        injector
            .keymap()
            .decode(ev.code as u32, input.shift_held(), input.altgr_held())
    {
        input.undo = None;
        input.pending_undo = None;
        tracing::debug!(
            "key {} (shift={} altgr={}) -> {:?}",
            ev.code,
            input.shift_held(),
            input.altgr_held(),
            ch
        );
        if let Some(expansion) = expander.push_char(ch) {
            tracing::info!(
                "Trigger matched; waiting for key release ({} backspaces + {} chars)",
                expansion.delete_count,
                expansion.text.len()
            );
            queue_expansion(input, ev.code, expansion);
        }
    } else {
        cancel_input_context(expander, input);
    }
}

fn cancel_input_context(expander: &mut Expander, input: &mut InputState) {
    input.undo = None;
    input.pending_undo = None;
    input.pending_expansion = None;
    expander.reset();
}

fn queue_expansion(
    input: &mut InputState,
    release_code: u16,
    expansion: crate::expander::Expansion,
) {
    input.pending_expansion = Some(PendingExpansion {
        release_code,
        key_released: false,
        expansion,
    });
}

fn complete_pending_expansion(
    injector: &Injector,
    config: &Arc<Mutex<Config>>,
    input: &mut InputState,
    released_code: u16,
) {
    let Some(pending) = input.pending_expansion.as_mut() else {
        return;
    };
    if released_code == pending.release_code {
        pending.key_released = true;
    }
    if !pending.key_released || input.shift_held() || input.altgr_held() {
        return;
    }
    let Some(pending) = input.pending_expansion.take() else {
        return;
    };
    tracing::info!(
        "Trigger key released; expanding ({} backspaces + {} chars)",
        pending.expansion.delete_count,
        pending.expansion.text.len()
    );
    input.undo = inject_expansion(injector, config, pending.expansion);
}

fn complete_undo(injector: &Injector, expander: &mut Expander, previous: Undo) {
    if let Err(error) = injector.undo_text(
        previous.replacement_len.saturating_sub(1),
        &previous.original,
    ) {
        tracing::error!("Could not undo expansion: {}", error);
        return;
    }
    expander.reset();
    tracing::info!("Undid previous expansion");
}

fn inject_expansion(
    injector: &Injector,
    config: &Arc<Mutex<Config>>,
    expansion: crate::expander::Expansion,
) -> Option<Undo> {
    let has_exclusions = !config.lock().unwrap().settings.app_exclusions.is_empty();
    if has_exclusions {
        match crate::app::detect() {
            Ok(app) if config.lock().unwrap().excludes_app(&app) => {
                tracing::info!(
                    class = app.class.as_deref().unwrap_or("<unknown>"),
                    title = app.title.as_deref().unwrap_or("<unknown>"),
                    "Expansion suppressed by app exclusion"
                );
                return None;
            }
            Ok(_) => {}
            Err(error) => tracing::warn!(
                "Could not evaluate app exclusions; allowing expansion: {}",
                error
            ),
        }
    }
    injector.backspace(expansion.delete_count);
    type_with_fallback(injector, &expansion.text);
    injector.position_cursor(&expansion.text, expansion.cursor_back);
    if let Err(error) = injector.flush() {
        tracing::error!("Could not finish expansion injection: {}", error);
    }
    let undo_enabled = config.lock().unwrap().settings.undo_enabled;
    (undo_enabled && expansion.cursor_back == 0 && !expansion.text.contains('\n')).then(|| Undo {
        replacement_len: expansion.text.chars().count(),
        original: expansion.undo_text,
    })
}

fn type_with_fallback(injector: &Injector, text: &str) {
    if injector.backend() == "wayland" {
        match injector.type_wayland_text(text) {
            Ok(()) => return,
            Err(error) => tracing::warn!("Persistent Wayland text unavailable: {}", error),
        }
    }
    if injector.can_type(text) {
        injector.type_text(text);
    } else if let Err(error) = injector.type_unicode(text) {
        tracing::error!("Unicode fallback failed: {}", error);
    }
}

fn wayland_text_characters(config: &Config) -> String {
    let mut text = (' '..='~').collect::<String>();
    text.push('\n');
    text.push('\t');
    for item in &config.matches {
        text.push_str(&item.replace);
    }
    text
}

fn reload_config(config: &Arc<Mutex<Config>>, expander: &mut Expander, injector: &Injector) {
    match Config::load_default() {
        Ok(new_cfg) => {
            let (backend_changed, text_characters_changed) = {
                let current = config.lock().unwrap();
                (
                    new_cfg.settings.injection_backend != current.settings.injection_backend,
                    wayland_text_characters(&new_cfg) != wayland_text_characters(&current),
                )
            };
            if backend_changed {
                tracing::warn!("injection_backend changes require a daemon restart");
            }
            expander.update_configured(
                new_cfg.matches.clone(),
                new_cfg.settings.trigger_mode,
                new_cfg.settings.terminator_chars(),
            );
            injector.set_delay_ms(new_cfg.settings.injection_delay_for(injector.backend()));
            injector.set_settle_ms(new_cfg.settings.injection_settle_ms);
            if text_characters_changed {
                if let Err(error) =
                    injector.refresh_wayland_text_keymap(wayland_text_characters(&new_cfg))
                {
                    tracing::warn!("Could not refresh the Wayland Unicode keymap: {}", error);
                }
            }
            *config.lock().unwrap() = new_cfg;
            log_config_warnings(&config.lock().unwrap());
            tracing::info!("Config reloaded");
        }
        Err(e) => tracing::warn!("Failed to reload config: {}", e),
    }
}

fn log_config_warnings(config: &Config) {
    for warning in config.unreachable_triggers() {
        tracing::warn!(
            trigger = warning.trigger,
            source = %warning.source.display(),
            blocking_trigger = warning.blocking_trigger,
            blocking_source = %warning.blocking_source.display(),
            "Trigger is unreachable in immediate mode because its prefix expands first"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::TriggerMode;

    fn expander(trigger: &str) -> Expander {
        Expander::new(
            vec![(trigger.to_string(), "expanded".to_string())],
            TriggerMode::Immediate,
        )
    }

    #[test]
    fn left_and_right_shift_are_tracked_independently() {
        let mut input = InputState::default();
        let keyboard = std::path::Path::new("/dev/input/event1");
        input.update_modifier(keyboard, 42, 1);
        input.update_modifier(keyboard, 54, 1);
        input.update_modifier(keyboard, 42, 0);
        assert!(input.shift_held());
        input.update_modifier(keyboard, 54, 0);
        assert!(!input.shift_held());
    }

    #[test]
    fn modifiers_are_tracked_per_keyboard_and_cleared_on_disconnect() {
        let mut input = InputState::default();
        let first = std::path::Path::new("/dev/input/event1");
        let second = std::path::Path::new("/dev/input/event2");
        input.update_modifier(first, 42, 1);
        input.update_modifier(second, 42, 1);
        input.update_modifier(first, 42, 0);
        assert!(input.shift_held());
        input.disconnect_device(second);
        assert!(!input.shift_held());
    }

    #[test]
    fn altgr_is_text_input_not_a_shortcut_modifier() {
        let mut input = InputState::default();
        input.update_modifier(std::path::Path::new("/dev/input/event1"), 100, 1);
        assert!(input.altgr_held());
        assert!(!input.shortcut_held());
    }

    #[test]
    fn shortcut_cancels_a_partial_trigger() {
        let mut expander = expander("ac");
        let mut input = InputState::default();
        assert!(expander.push_char('a').is_none());

        let keyboard = std::path::Path::new("/dev/input/event1");
        input.update_modifier(keyboard, 29, 1);
        cancel_input_context(&mut expander, &mut input);
        input.update_modifier(keyboard, 29, 0);

        assert!(expander.push_char('c').is_none());
    }

    #[test]
    fn cancel_clears_undo_and_pending_expansion_state() {
        let mut expander = expander("x");
        let mut input = InputState {
            undo: Some(Undo {
                replacement_len: 8,
                original: ";example".to_string(),
            }),
            pending_undo: Some(Undo {
                replacement_len: 8,
                original: ";example".to_string(),
            }),
            pending_expansion: Some(PendingExpansion {
                release_code: 45,
                key_released: false,
                expansion: crate::expander::Expansion {
                    delete_count: 1,
                    text: "expanded".to_string(),
                    cursor_back: 0,
                    undo_text: "x".to_string(),
                },
            }),
            ..InputState::default()
        };

        cancel_input_context(&mut expander, &mut input);

        assert!(input.undo.is_none());
        assert!(input.pending_undo.is_none());
        assert!(input.pending_expansion.is_none());
    }

    #[test]
    fn config_watcher_ignores_reads_but_accepts_writes() {
        use notify::event::{AccessKind, CreateKind, ModifyKind, RemoveKind};

        assert!(!is_config_change(&notify::EventKind::Access(
            AccessKind::Any
        )));
        assert!(!is_config_change(&notify::EventKind::Other));
        assert!(is_config_change(&notify::EventKind::Create(
            CreateKind::Any
        )));
        assert!(is_config_change(&notify::EventKind::Modify(
            ModifyKind::Any
        )));
        assert!(is_config_change(&notify::EventKind::Remove(
            RemoveKind::Any
        )));
    }
}