greentic-redbutton 0.4.2

Cross-platform Greentic red-button CLI scaffold with embedded i18n and release automation
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
use anyhow::Result;

use crate::event::DeviceMatcher;

pub trait InputSuppressor: Send {
    fn notify_button_press(&self);
}

pub fn log_startup_permission_status(matcher: &DeviceMatcher) {
    platform::log_permission_status(matcher);
}

pub fn ensure_startup_permissions(matcher: &DeviceMatcher) -> Result<()> {
    platform::ensure_permissions(matcher)
}

pub fn activate_input_suppressor(matcher: &DeviceMatcher) -> Result<Box<dyn InputSuppressor>> {
    platform::activate(matcher)
}

#[cfg(target_os = "linux")]
mod platform {
    use anyhow::{Context, Result, anyhow, bail};
    use std::fs::{File, OpenOptions, read_dir};
    use std::mem::size_of;
    use std::os::fd::AsRawFd;

    use crate::event::DeviceMatcher;
    use crate::suppress::InputSuppressor;

    const IOC_NRBITS: u32 = 8;
    const IOC_TYPEBITS: u32 = 8;
    const IOC_SIZEBITS: u32 = 14;

    const IOC_NRSHIFT: u32 = 0;
    const IOC_TYPESHIFT: u32 = IOC_NRSHIFT + IOC_NRBITS;
    const IOC_SIZESHIFT: u32 = IOC_TYPESHIFT + IOC_TYPEBITS;
    const IOC_DIRSHIFT: u32 = IOC_SIZESHIFT + IOC_SIZEBITS;

    const IOC_WRITE: u32 = 1;
    const IOC_READ: u32 = 2;

    const fn ioc(dir: u32, ty: u32, nr: u32, size: u32) -> libc::c_ulong {
        ((dir << IOC_DIRSHIFT)
            | (ty << IOC_TYPESHIFT)
            | (nr << IOC_NRSHIFT)
            | (size << IOC_SIZESHIFT)) as libc::c_ulong
    }

    const fn ior<T>(ty: u32, nr: u32) -> libc::c_ulong {
        ioc(IOC_READ, ty, nr, size_of::<T>() as u32)
    }

    const fn iow<T>(ty: u32, nr: u32) -> libc::c_ulong {
        ioc(IOC_WRITE, ty, nr, size_of::<T>() as u32)
    }

    const EVIOCGID: libc::c_ulong = ior::<InputId>(b'E' as u32, 0x02);
    const EVIOCGRAB: libc::c_ulong = iow::<libc::c_int>(b'E' as u32, 0x90);

    #[repr(C)]
    #[derive(Clone, Copy, Default)]
    struct InputId {
        bustype: u16,
        vendor: u16,
        product: u16,
        version: u16,
    }

    pub fn activate(matcher: &DeviceMatcher) -> Result<Box<dyn InputSuppressor>> {
        let grabs = grab_matching_event_devices(matcher)?;
        if grabs.is_empty() {
            bail!(
                "failed to enable Enter suppression: no /dev/input event device matched {:04x}:{:04x}",
                matcher.vendor_id,
                matcher.product_id
            );
        }
        Ok(Box::new(LinuxSuppressor { _grabs: grabs }))
    }

    pub fn ensure_permissions(matcher: &DeviceMatcher) -> Result<()> {
        let mut saw_match = false;
        for entry in read_dir("/dev/input").context("failed to read /dev/input")? {
            let entry = entry?;
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            if !name.starts_with("event") {
                continue;
            }
            let file = match OpenOptions::new().read(true).open(&path) {
                Ok(file) => file,
                Err(_) => continue,
            };
            let id = match query_input_id(&file) {
                Ok(id) => id,
                Err(_) => continue,
            };
            if id.vendor == matcher.vendor_id && id.product == matcher.product_id {
                saw_match = true;
                break;
            }
        }

        if !saw_match {
            bail!(
                "no readable /dev/input event device matched {:04x}:{:04x}; run with access to /dev/input (for example root or the input group)",
                matcher.vendor_id,
                matcher.product_id
            );
        }
        Ok(())
    }

    pub fn log_permission_status(matcher: &DeviceMatcher) {
        println!(
            "Linux input access check for {:04x}:{:04x} will require readable /dev/input/event* access.",
            matcher.vendor_id, matcher.product_id
        );
    }

    struct LinuxSuppressor {
        _grabs: Vec<GrabbedDevice>,
    }

    impl InputSuppressor for LinuxSuppressor {
        fn notify_button_press(&self) {}
    }

    struct GrabbedDevice {
        file: File,
    }

    impl Drop for GrabbedDevice {
        fn drop(&mut self) {
            let release: libc::c_int = 0;
            unsafe {
                libc::ioctl(self.file.as_raw_fd(), EVIOCGRAB, release);
            }
        }
    }

    fn grab_matching_event_devices(matcher: &DeviceMatcher) -> Result<Vec<GrabbedDevice>> {
        let mut grabs = Vec::new();
        for entry in read_dir("/dev/input").context("failed to read /dev/input")? {
            let entry = entry?;
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            if !name.starts_with("event") {
                continue;
            }

            let file = match OpenOptions::new().read(true).open(&path) {
                Ok(file) => file,
                Err(_) => continue,
            };
            let id = match query_input_id(&file) {
                Ok(id) => id,
                Err(_) => continue,
            };

            if id.vendor != matcher.vendor_id || id.product != matcher.product_id {
                continue;
            }

            grab_device(&file).with_context(|| {
                format!(
                    "failed to grab Linux input device {} for {:04x}:{:04x}",
                    path.display(),
                    matcher.vendor_id,
                    matcher.product_id
                )
            })?;
            grabs.push(GrabbedDevice { file });
        }
        Ok(grabs)
    }

    fn query_input_id(file: &File) -> Result<InputId> {
        let mut id = InputId::default();
        let rc = unsafe { libc::ioctl(file.as_raw_fd(), EVIOCGID, &mut id) };
        if rc < 0 {
            return Err(anyhow!(std::io::Error::last_os_error()));
        }
        Ok(id)
    }

    fn grab_device(file: &File) -> Result<()> {
        let enable: libc::c_int = 1;
        let rc = unsafe { libc::ioctl(file.as_raw_fd(), EVIOCGRAB, enable) };
        if rc < 0 {
            return Err(anyhow!(std::io::Error::last_os_error()));
        }
        Ok(())
    }
}

#[cfg(target_os = "macos")]
mod platform {
    use std::ffi::c_void;
    use std::ptr;
    use std::sync::OnceLock;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::mpsc;
    use std::thread;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use anyhow::{Result, bail};
    use core_foundation_sys::base::{CFAllocatorRef, CFRelease, CFTypeRef, kCFAllocatorDefault};
    use core_foundation_sys::dictionary::{
        CFDictionaryCreate, CFDictionaryRef, kCFTypeDictionaryKeyCallBacks,
        kCFTypeDictionaryValueCallBacks,
    };
    use core_foundation_sys::mach_port::CFMachPortRef;
    use core_foundation_sys::number::kCFBooleanTrue;
    use core_foundation_sys::runloop::{
        CFRunLoopAddSource, CFRunLoopGetCurrent, CFRunLoopRun, CFRunLoopSourceRef,
        kCFRunLoopCommonModes,
    };
    use core_foundation_sys::string::{CFStringCreateWithCString, kCFStringEncodingUTF8};

    use crate::event::DeviceMatcher;
    use crate::suppress::InputSuppressor;

    type CGEventMask = u64;
    type CGEventRef = *mut c_void;
    type CGEventTapProxy = *mut c_void;
    type CFMachPortCallBack = unsafe extern "C" fn(
        proxy: CGEventTapProxy,
        type_: u32,
        event: CGEventRef,
        user_info: *mut c_void,
    ) -> CGEventRef;

    const KCG_EVENT_KEY_DOWN: u32 = 10;
    const KCG_EVENT_KEY_UP: u32 = 11;
    const KCG_HEAD_INSERT_EVENT_TAP: u32 = 0;
    const KCG_SESSION_EVENT_TAP: u32 = 1;
    const KCG_EVENT_TAP_OPTION_DEFAULT: u32 = 0;
    const KCG_KEYBOARD_EVENT_KEYCODE: u32 = 9;
    const RETURN_KEYCODE: i64 = 36;
    const AX_PROMPT_KEY: &[u8] = b"AXTrustedCheckOptionPrompt\0";
    const SUPPRESSION_WINDOW: Duration = Duration::from_millis(250);

    static SUPPRESS_UNTIL_MS: AtomicU64 = AtomicU64::new(0);
    static START_RESULT: OnceLock<std::result::Result<(), String>> = OnceLock::new();

    #[link(name = "ApplicationServices", kind = "framework")]
    unsafe extern "C" {
        fn AXIsProcessTrusted() -> bool;
        fn AXIsProcessTrustedWithOptions(options: CFDictionaryRef) -> bool;
        fn CGEventTapCreate(
            tap: u32,
            place: u32,
            options: u32,
            events_of_interest: CGEventMask,
            callback: CFMachPortCallBack,
            user_info: *mut c_void,
        ) -> CFMachPortRef;
        fn CFMachPortCreateRunLoopSource(
            allocator: CFAllocatorRef,
            port: CFMachPortRef,
            order: isize,
        ) -> CFRunLoopSourceRef;
        fn CGEventGetIntegerValueField(event: CGEventRef, field: u32) -> i64;
    }

    pub fn ensure_permissions(_matcher: &DeviceMatcher) -> Result<()> {
        unsafe {
            if AXIsProcessTrusted() {
                return Ok(());
            }

            let prompt_key = CFStringCreateWithCString(
                kCFAllocatorDefault,
                AX_PROMPT_KEY.as_ptr().cast(),
                kCFStringEncodingUTF8,
            );
            if prompt_key.is_null() {
                bail!("failed to create macOS Accessibility permission prompt");
            }

            let keys = [prompt_key as *const c_void];
            let values = [kCFBooleanTrue as *const c_void];
            let options = CFDictionaryCreate(
                kCFAllocatorDefault,
                keys.as_ptr(),
                values.as_ptr(),
                1,
                &kCFTypeDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks,
            );
            if options.is_null() {
                CFRelease(prompt_key as CFTypeRef);
                bail!("failed to build macOS Accessibility permission request");
            }

            let trusted = AXIsProcessTrustedWithOptions(options);
            CFRelease(options as CFTypeRef);
            CFRelease(prompt_key as CFTypeRef);

            if trusted {
                Ok(())
            } else {
                bail!(
                    "macOS Accessibility permission is required to suppress Return; approve the prompt in System Settings and restart the app"
                )
            }
        }
    }

    pub fn log_permission_status(_matcher: &DeviceMatcher) {
        let trusted = unsafe { AXIsProcessTrusted() };
        println!(
            "macOS Accessibility permission trusted: {}",
            if trusted { "yes" } else { "no" }
        );
    }

    pub fn activate(_matcher: &DeviceMatcher) -> Result<Box<dyn InputSuppressor>> {
        let startup = START_RESULT.get_or_init(start_event_tap_thread);
        if let Err(error) = startup {
            bail!("failed to enable Enter suppression on macOS: {error}");
        }
        Ok(Box::new(MacSuppressor))
    }

    struct MacSuppressor;

    impl InputSuppressor for MacSuppressor {
        fn notify_button_press(&self) {
            let now = current_time_ms();
            let deadline = now.saturating_add(SUPPRESSION_WINDOW.as_millis() as u64);
            SUPPRESS_UNTIL_MS.store(deadline, Ordering::SeqCst);
        }
    }

    fn start_event_tap_thread() -> std::result::Result<(), String> {
        let (sender, receiver) = mpsc::channel();
        thread::spawn(move || unsafe {
            let mask = (1_u64 << KCG_EVENT_KEY_DOWN) | (1_u64 << KCG_EVENT_KEY_UP);
            let tap = CGEventTapCreate(
                KCG_SESSION_EVENT_TAP,
                KCG_HEAD_INSERT_EVENT_TAP,
                KCG_EVENT_TAP_OPTION_DEFAULT,
                mask,
                event_tap_callback,
                ptr::null_mut(),
            );
            if tap.is_null() {
                let _ = sender.send(Err(
                    "CGEventTapCreate returned null; grant Accessibility permission to this app/terminal"
                        .to_string(),
                ));
                return;
            }

            let source = CFMachPortCreateRunLoopSource(ptr::null(), tap, 0);
            if source.is_null() {
                let _ = sender.send(Err("failed to create macOS run-loop source".to_string()));
                return;
            }

            let run_loop = CFRunLoopGetCurrent();
            CFRunLoopAddSource(run_loop, source, kCFRunLoopCommonModes);
            let _ = sender.send(Ok(()));
            CFRunLoopRun();
        });

        receiver
            .recv()
            .map_err(|_| "macOS event-tap startup channel closed".to_string())?
    }

    unsafe extern "C" fn event_tap_callback(
        _proxy: CGEventTapProxy,
        type_: u32,
        event: CGEventRef,
        _user_info: *mut c_void,
    ) -> CGEventRef {
        if (type_ == KCG_EVENT_KEY_DOWN || type_ == KCG_EVENT_KEY_UP)
            && current_time_ms() <= SUPPRESS_UNTIL_MS.load(Ordering::SeqCst)
            && unsafe { CGEventGetIntegerValueField(event, KCG_KEYBOARD_EVENT_KEYCODE) }
                == RETURN_KEYCODE
        {
            return ptr::null_mut();
        }

        event
    }

    fn current_time_ms() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
}

#[cfg(target_os = "windows")]
mod platform {
    use std::ptr;
    use std::sync::OnceLock;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::mpsc;
    use std::thread;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use anyhow::{Result, bail};
    use windows_sys::Win32::Foundation::{LPARAM, LRESULT, WPARAM};
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_RETURN;
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        CallNextHookEx, DispatchMessageW, GetMessageW, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT, MSG,
        SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, WH_KEYBOARD_LL,
    };

    use crate::event::DeviceMatcher;
    use crate::suppress::InputSuppressor;

    static SUPPRESS_UNTIL_MS: AtomicU64 = AtomicU64::new(0);
    static START_RESULT: OnceLock<std::result::Result<(), String>> = OnceLock::new();

    const SUPPRESSION_WINDOW: Duration = Duration::from_millis(250);

    pub fn activate(_matcher: &DeviceMatcher) -> Result<Box<dyn InputSuppressor>> {
        let startup = START_RESULT.get_or_init(start_hook_thread);
        if let Err(error) = startup {
            bail!("failed to enable Enter suppression on Windows: {error}");
        }
        Ok(Box::new(WindowsSuppressor))
    }

    pub fn ensure_permissions(_matcher: &DeviceMatcher) -> Result<()> {
        Ok(())
    }

    pub fn log_permission_status(_matcher: &DeviceMatcher) {
        println!("Windows keyboard suppression active: no OS permission prompt is required.");
    }

    struct WindowsSuppressor;

    impl InputSuppressor for WindowsSuppressor {
        fn notify_button_press(&self) {
            let now = current_time_ms();
            let deadline = now.saturating_add(SUPPRESSION_WINDOW.as_millis() as u64);
            SUPPRESS_UNTIL_MS.store(deadline, Ordering::SeqCst);
        }
    }

    fn start_hook_thread() -> std::result::Result<(), String> {
        let (sender, receiver) = mpsc::channel();
        thread::spawn(move || unsafe {
            let hook = SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook), ptr::null_mut(), 0);
            if hook.is_null() {
                let _ = sender.send(Err(std::io::Error::last_os_error().to_string()));
                return;
            }

            let _ = sender.send(Ok(()));
            let mut message = MSG::default();
            loop {
                let status = GetMessageW(&mut message, ptr::null_mut(), 0, 0);
                if status == -1 {
                    break;
                }
                if status == 0 {
                    break;
                }
                TranslateMessage(&message);
                DispatchMessageW(&message);
            }

            UnhookWindowsHookEx(hook);
        });

        receiver
            .recv()
            .map_err(|_| "keyboard hook startup channel closed".to_string())?
    }

    unsafe extern "system" fn keyboard_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
        if code == HC_ACTION as i32 {
            let data = unsafe { &*(lparam as *const KBDLLHOOKSTRUCT) };
            let _ = wparam;
            if data.vkCode == VK_RETURN as u32
                && current_time_ms() <= SUPPRESS_UNTIL_MS.load(Ordering::SeqCst)
            {
                return 1;
            }
        }

        unsafe { CallNextHookEx(ptr::null_mut() as HHOOK, code, wparam, lparam) }
    }

    fn current_time_ms() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
mod platform {
    use anyhow::Result;

    use crate::event::DeviceMatcher;
    use crate::suppress::InputSuppressor;

    pub fn ensure_permissions(_matcher: &DeviceMatcher) -> Result<()> {
        Ok(())
    }

    pub fn log_permission_status(_matcher: &DeviceMatcher) {}

    pub fn activate(_matcher: &DeviceMatcher) -> Result<Box<dyn InputSuppressor>> {
        Ok(Box::new(NoopSuppressor))
    }

    struct NoopSuppressor;

    impl InputSuppressor for NoopSuppressor {
        fn notify_button_press(&self) {}
    }
}