Skip to main content

efude_input/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// SPDX-FileCopyrightText: 2026 Hakoniwa
3#![allow(unsafe_code)]
4use crossbeam_queue::ArrayQueue;
5use efude_core::InkPoint;
6use serde::{Deserialize, Serialize};
7use std::sync::Arc;
8
9#[derive(Clone, Copy, Debug)]
10pub struct PenPacket {
11    pub x: f32,
12    pub y: f32,
13    pub pressure: f32,
14    pub tilt_x: f32,
15    pub tilt_y: f32,
16    pub rotation: f32,
17    pub time_ms: u64,
18    pub received_at: std::time::Instant,
19}
20
21/// Estimates a short-lived preview point from actual input samples.
22///
23/// This fallback is for rendering guidance only. Do not enqueue its result or
24/// append it to stroke samples; an OS prediction provider can replace it.
25pub fn estimate_preview_point(
26    points: &[InkPoint],
27    horizon_ms: f32,
28    max_offset: f32,
29) -> Option<InkPoint> {
30    if !horizon_ms.is_finite() || horizon_ms <= 0.0 || !max_offset.is_finite() || max_offset <= 0.0
31    {
32        return None;
33    }
34    let current = *points.last()?;
35    let previous = *points.get(points.len().checked_sub(2)?)?;
36    let elapsed_ms = current.time_ms.saturating_sub(previous.time_ms).max(1) as f32;
37    let offset = ((current.position - previous.position) / elapsed_ms * horizon_ms)
38        .clamp_length_max(max_offset);
39    if !offset.is_finite() || offset.length() < 0.1 {
40        return None;
41    }
42    let pressure_delta = current.pressure - previous.pressure;
43    Some(InkPoint {
44        position: current.position + offset,
45        pressure: (current.pressure + pressure_delta / elapsed_ms * horizon_ms).clamp(0.0, 1.0),
46        time_ms: current.time_ms.saturating_add(horizon_ms as u64),
47        ..current
48    })
49}
50
51pub struct PenInputQueue(Arc<ArrayQueue<PenPacket>>);
52impl PenInputQueue {
53    pub fn new(capacity: usize) -> Self {
54        Self(Arc::new(ArrayQueue::new(capacity.max(8))))
55    }
56    pub fn push(&self, packet: PenPacket) {
57        if self.0.push(packet).is_err() {
58            let _ = self.0.pop();
59            let _ = self.0.push(packet);
60        }
61    }
62    pub fn pop(&self) -> Option<PenPacket> {
63        self.0.pop()
64    }
65    pub fn clear(&self) {
66        while self.0.pop().is_some() {}
67    }
68    pub fn drain_into(&self, output: &mut Vec<PenPacket>, limit: usize) -> bool {
69        output.clear();
70        while output.len() < limit.max(1)
71            && let Some(packet) = self.0.pop()
72        {
73            output.push(packet);
74        }
75        !self.0.is_empty()
76    }
77    pub fn shared(&self) -> Arc<ArrayQueue<PenPacket>> {
78        Arc::clone(&self.0)
79    }
80}
81impl Default for PenInputQueue {
82    fn default() -> Self {
83        Self::new(16_384)
84    }
85}
86
87#[cfg(target_os = "windows")]
88mod windows_ink {
89    use super::{Arc, ArrayQueue, PenPacket};
90    use std::ffi::c_void;
91    use windows::Win32::{
92        Foundation::{HWND, LPARAM, LRESULT, WPARAM},
93        Graphics::Gdi::ScreenToClient,
94        UI::{
95            HiDpi::GetDpiForWindow,
96            Input::Pointer::{GetPointerPenInfo, GetPointerPenInfoHistory, POINTER_PEN_INFO},
97            Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
98            WindowsAndMessaging::{
99                PEN_MASK_PRESSURE, PEN_MASK_TILT_X, PEN_MASK_TILT_Y, WM_POINTERDOWN, WM_POINTERUP,
100                WM_POINTERUPDATE,
101            },
102        },
103    };
104
105    struct HookState {
106        queue: Arc<ArrayQueue<PenPacket>>,
107    }
108    const SUBCLASS_ID: usize = 0x4546554445;
109
110    fn push_info(hwnd: HWND, state: &HookState, info: &POINTER_PEN_INFO) {
111        let mut point = info.pointerInfo.ptPixelLocation;
112        if unsafe { ScreenToClient(hwnd, &mut point) }.as_bool() {
113            let dpi = unsafe { GetDpiForWindow(hwnd) }.max(1) as f32 / 96.;
114            let packet = PenPacket {
115                x: point.x as f32 / dpi,
116                y: point.y as f32 / dpi,
117                pressure: if info.penMask & PEN_MASK_PRESSURE != 0 {
118                    info.pressure as f32 / 1024.
119                } else {
120                    1.
121                },
122                tilt_x: if info.penMask & PEN_MASK_TILT_X != 0 {
123                    info.tiltX as f32 / 90.
124                } else {
125                    0.
126                },
127                tilt_y: if info.penMask & PEN_MASK_TILT_Y != 0 {
128                    info.tiltY as f32 / 90.
129                } else {
130                    0.
131                },
132                rotation: (info.rotation as f32).to_radians(),
133                time_ms: info.pointerInfo.dwTime as u64,
134                received_at: std::time::Instant::now(),
135            };
136            let _ = state.queue.push(packet);
137        }
138    }
139
140    unsafe extern "system" fn window_proc(
141        hwnd: HWND,
142        msg: u32,
143        wparam: WPARAM,
144        lparam: LPARAM,
145        _id: usize,
146        data: usize,
147    ) -> LRESULT {
148        if matches!(msg, WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERUP) {
149            let pointer_id = (wparam.0 & 0xffff) as u32;
150            let state = unsafe { &*(data as *const HookState) };
151            let mut history_count = 0u32;
152            if msg == WM_POINTERUPDATE
153                && unsafe { GetPointerPenInfoHistory(pointer_id, &mut history_count, None) }.is_ok()
154                && history_count > 0
155            {
156                // Keep a bounded recent history, then reverse the API's
157                // newest-first ordering before feeding the stroke queue.
158                let capacity = history_count.min(256) as usize;
159                let mut history = vec![POINTER_PEN_INFO::default(); capacity];
160                let mut available = capacity as u32;
161                if unsafe {
162                    GetPointerPenInfoHistory(pointer_id, &mut available, Some(history.as_mut_ptr()))
163                }
164                .is_ok()
165                {
166                    history.truncate(available.min(capacity as u32) as usize);
167                    for info in history.iter().rev() {
168                        push_info(hwnd, state, info);
169                    }
170                    return unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
171                }
172            }
173            let mut info = POINTER_PEN_INFO::default();
174            if unsafe { GetPointerPenInfo(pointer_id, &mut info) }.is_ok() {
175                push_info(hwnd, state, &info);
176            }
177        }
178        unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) }
179    }
180
181    pub struct WindowsInkHook {
182        hwnd: HWND,
183        state: Box<HookState>,
184    }
185    impl WindowsInkHook {
186        pub fn install(
187            hwnd: *mut c_void,
188            queue: Arc<ArrayQueue<PenPacket>>,
189        ) -> Result<Self, windows::core::Error> {
190            let hwnd = HWND(hwnd);
191            let state = Box::new(HookState { queue });
192            let data = (&*state as *const HookState) as usize;
193            if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), SUBCLASS_ID, data) }.as_bool() {
194                return Err(windows::core::Error::from_win32());
195            }
196            Ok(Self { hwnd, state })
197        }
198    }
199    impl Drop for WindowsInkHook {
200        fn drop(&mut self) {
201            let _keep_state_alive = &self.state;
202            unsafe {
203                let _ = RemoveWindowSubclass(self.hwnd, Some(window_proc), SUBCLASS_ID);
204            }
205        }
206    }
207}
208
209use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
210#[cfg(target_os = "windows")]
211pub use windows_ink::WindowsInkHook;
212
213/// Copies an RGBA image to the Windows clipboard using a DIBV5 bitmap.
214/// Whether Ctrl and the key with virtual-key code `key` (an upper-case
215/// letter or digit) are both held down right now. The window system turns
216/// Ctrl+V into a text paste and drops the key when the clipboard holds an
217/// image, so the paste shortcut is also watched here.
218#[cfg(target_os = "windows")]
219pub fn ctrl_key_down(key: u8) -> bool {
220    use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_CONTROL};
221    // SAFETY: GetAsyncKeyState only reads the keyboard state.
222    unsafe { GetAsyncKeyState(VK_CONTROL.0 as i32) < 0 && GetAsyncKeyState(key as i32) < 0 }
223}
224
225#[cfg(target_os = "windows")]
226pub fn set_clipboard_image(width: u32, height: u32, rgba: &[u8]) -> windows::core::Result<()> {
227    use windows::Win32::{
228        Foundation::{GlobalFree, HANDLE, HWND},
229        System::{
230            DataExchange::{CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData},
231            Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock},
232        },
233    };
234
235    const MAX_PIXELS: usize = 100_000_000;
236    const HEADER_SIZE: usize = 124;
237    const CF_DIBV5: u32 = 17;
238
239    let pixels = (width as usize)
240        .checked_mul(height as usize)
241        .filter(|count| *count > 0 && *count <= MAX_PIXELS)
242        .ok_or_else(windows::core::Error::from_win32)?;
243    if rgba.len() != pixels.saturating_mul(4) {
244        return Err(windows::core::Error::from_win32());
245    }
246    let data_size = pixels * 4;
247    let mut dib = vec![0; HEADER_SIZE + data_size];
248    dib[0..4].copy_from_slice(&(HEADER_SIZE as u32).to_le_bytes());
249    dib[4..8].copy_from_slice(&(width as i32).to_le_bytes());
250    dib[8..12].copy_from_slice(&(-(height as i32)).to_le_bytes());
251    dib[12..14].copy_from_slice(&1u16.to_le_bytes());
252    dib[14..16].copy_from_slice(&32u16.to_le_bytes());
253    dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
254    dib[20..24].copy_from_slice(&(data_size as u32).to_le_bytes());
255    for (offset, mask) in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff, 0xff00_0000]
256        .into_iter()
257        .enumerate()
258    {
259        let start = 40 + offset * 4;
260        dib[start..start + 4].copy_from_slice(&mask.to_le_bytes());
261    }
262    dib[56..60].copy_from_slice(&0x7352_4742u32.to_le_bytes()); // LCS_sRGB
263    for (source, target) in rgba
264        .chunks_exact(4)
265        .zip(dib[HEADER_SIZE..].chunks_exact_mut(4))
266    {
267        target.copy_from_slice(&[source[2], source[1], source[0], source[3]]);
268    }
269
270    unsafe { OpenClipboard(HWND(std::ptr::null_mut()))? };
271    let result = (|| unsafe {
272        EmptyClipboard()?;
273        let memory = GlobalAlloc(GMEM_MOVEABLE, dib.len())?;
274        let destination = GlobalLock(memory);
275        if destination.is_null() {
276            let _ = GlobalFree(memory);
277            return Err(windows::core::Error::from_win32());
278        }
279        std::ptr::copy_nonoverlapping(dib.as_ptr(), destination.cast::<u8>(), dib.len());
280        let _ = GlobalUnlock(memory);
281        match SetClipboardData(CF_DIBV5, HANDLE(memory.0)) {
282            Ok(_) => Ok(()),
283            Err(error) => {
284                let _ = GlobalFree(memory);
285                Err(error)
286            }
287        }
288    })();
289    let _ = unsafe { CloseClipboard() };
290    result
291}
292
293/// Reads a Windows DIB/DIBV5 image and converts it to RGBA8.
294#[cfg(target_os = "windows")]
295pub fn get_clipboard_image() -> windows::core::Result<Option<(u32, u32, Vec<u8>)>> {
296    use windows::Win32::{
297        Foundation::HWND,
298        System::{
299            DataExchange::{
300                CloseClipboard, GetClipboardData, IsClipboardFormatAvailable, OpenClipboard,
301            },
302            Memory::{GlobalLock, GlobalSize, GlobalUnlock},
303        },
304    };
305
306    const MAX_PIXELS: usize = 100_000_000;
307    unsafe { OpenClipboard(HWND(std::ptr::null_mut()))? };
308    let result = (|| unsafe {
309        let format = if IsClipboardFormatAvailable(17).is_ok() {
310            17 // CF_DIBV5
311        } else if IsClipboardFormatAvailable(8).is_ok() {
312            8 // CF_DIB
313        } else {
314            return Ok(None);
315        };
316        let handle = GetClipboardData(format)?;
317        let memory = windows::Win32::Foundation::HGLOBAL(handle.0);
318        let size = GlobalSize(memory);
319        if size < 40 || size > MAX_PIXELS.saturating_mul(8).saturating_add(4096) {
320            return Ok(None);
321        }
322        let source = GlobalLock(memory);
323        if source.is_null() {
324            return Ok(None);
325        }
326        let bytes = std::slice::from_raw_parts(source.cast::<u8>(), size);
327        let header_size = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
328        let width = i32::from_le_bytes(bytes[4..8].try_into().unwrap());
329        let signed_height = i32::from_le_bytes(bytes[8..12].try_into().unwrap());
330        let planes = u16::from_le_bytes(bytes[12..14].try_into().unwrap());
331        let bits_per_pixel = u16::from_le_bytes(bytes[14..16].try_into().unwrap());
332        let compression = u32::from_le_bytes(bytes[16..20].try_into().unwrap());
333        let parsed = (|| {
334            if header_size < 40
335                || header_size > size
336                || planes != 1
337                || width <= 0
338                || signed_height == 0
339                || signed_height == i32::MIN
340                || !matches!(bits_per_pixel, 24 | 32)
341                || !matches!(compression, 0 | 3)
342            {
343                return None;
344            }
345            let width = width as usize;
346            let height = signed_height.unsigned_abs() as usize;
347            let pixel_count = width.checked_mul(height)?;
348            if pixel_count == 0 || pixel_count > MAX_PIXELS {
349                return None;
350            }
351            let bytes_per_pixel = (bits_per_pixel / 8) as usize;
352            let row_stride = width.checked_mul(bytes_per_pixel)?.checked_add(3)? & !3;
353            let image_size = row_stride.checked_mul(height)?;
354            let data_offset = if compression == 3 && header_size == 40 {
355                header_size.checked_add(12)?
356            } else {
357                header_size
358            };
359            if data_offset.checked_add(image_size)? > size {
360                return None;
361            }
362            let top_down = signed_height < 0;
363            let mut rgba = vec![0; pixel_count * 4];
364            for y in 0..height {
365                let source_y = if top_down { y } else { height - 1 - y };
366                let row = data_offset + source_y * row_stride;
367                for x in 0..width {
368                    let src = row + x * bytes_per_pixel;
369                    let dst = (y * width + x) * 4;
370                    rgba[dst..dst + 4].copy_from_slice(&[
371                        bytes[src + 2],
372                        bytes[src + 1],
373                        bytes[src],
374                        if bits_per_pixel == 32 {
375                            bytes[src + 3]
376                        } else {
377                            255
378                        },
379                    ]);
380                }
381            }
382            Some((width as u32, height as u32, rgba))
383        })();
384        let _ = GlobalUnlock(memory);
385        Ok(parsed)
386    })();
387    let _ = unsafe { CloseClipboard() };
388    result
389}
390
391/// Optional Wintab backend loaded from the tablet driver's `wintab32.dll`.
392/// The driver API is resolved at runtime so systems without a Wintab driver
393/// continue to use Windows Ink or the normal window input path.
394#[cfg(target_os = "windows")]
395mod wintab {
396    use super::{Arc, ArrayQueue, PenPacket};
397    use std::ffi::{c_char, c_void};
398    use windows::Win32::{
399        Foundation::{HWND, LPARAM, LRESULT, WPARAM},
400        Graphics::Gdi::ScreenToClient,
401        UI::{
402            HiDpi::GetDpiForWindow,
403            Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
404        },
405    };
406
407    const WTI_DEFSYSCTX: u32 = 4;
408    const WTI_DEVICES: u32 = 100;
409    const DVC_PKTDATA: u32 = 6;
410    const DVC_NPRESSURE: u32 = 15;
411    const DVC_ORIENTATION: u32 = 17;
412    const CXO_SYSTEM: u32 = 0x0001;
413    const CXO_MESSAGES: u32 = 0x0004;
414    const PK_TIME: u32 = 0x0004;
415    const PK_BUTTONS: u32 = 0x0040;
416    const PK_X: u32 = 0x0080;
417    const PK_Y: u32 = 0x0100;
418    const PK_NORMAL_PRESSURE: u32 = 0x0400;
419    const PK_ORIENTATION: u32 = 0x1000;
420    const WT_PACKET_OFFSET: u32 = 0;
421    const SUBCLASS_ID: usize = 0x454655445746;
422    const PACKET_WORDS: usize = 16;
423
424    #[repr(C)]
425    #[derive(Clone, Copy)]
426    struct LogContextA {
427        name: [c_char; 40],
428        options: u32,
429        status: u32,
430        locks: u32,
431        message_base: u32,
432        device: u32,
433        packet_rate: u32,
434        packet_data: u32,
435        packet_mode: u32,
436        move_mask: u32,
437        button_down_mask: u32,
438        button_up_mask: u32,
439        input_origin: [i32; 3],
440        input_extent: [i32; 3],
441        output_origin: [i32; 3],
442        output_extent: [i32; 3],
443        sensitivity: [i32; 3],
444        system_mode: i32,
445        system_origin: [i32; 2],
446        system_extent: [i32; 2],
447        system_sensitivity: [i32; 2],
448    }
449    impl Default for LogContextA {
450        fn default() -> Self {
451            unsafe { std::mem::zeroed() }
452        }
453    }
454
455    #[repr(C)]
456    #[derive(Clone, Copy, Default)]
457    struct Axis {
458        min: i32,
459        max: i32,
460        units: u32,
461        resolution: i32,
462    }
463
464    type WtInfoA = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32;
465    type WtOpenA = unsafe extern "system" fn(HWND, *mut LogContextA, i32) -> *mut c_void;
466    type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut u32) -> i32;
467    type WtClose = unsafe extern "system" fn(*mut c_void) -> i32;
468
469    #[link(name = "kernel32")]
470    unsafe extern "system" {
471        fn LoadLibraryA(name: *const c_char) -> *mut c_void;
472        fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *mut c_void;
473        fn FreeLibrary(module: *mut c_void) -> i32;
474    }
475
476    unsafe fn load_proc<T: Copy>(module: *mut c_void, name: &'static [u8]) -> Option<T> {
477        let address = unsafe { GetProcAddress(module, name.as_ptr().cast()) };
478        if address.is_null() {
479            None
480        } else {
481            Some(unsafe { std::mem::transmute_copy(&address) })
482        }
483    }
484
485    #[derive(Clone, Copy, Default)]
486    struct AxisRange {
487        min: i32,
488        max: i32,
489    }
490
491    struct HookState {
492        queue: Arc<ArrayQueue<PenPacket>>,
493        module: *mut c_void,
494        context: *mut c_void,
495        packet_fn: WtPacket,
496        close_fn: WtClose,
497        message: u32,
498        packet_mask: u32,
499        pressure_range: AxisRange,
500        /// Largest raw pressure seen, to correct a wrong reported range.
501        pressure_seen_max: std::cell::Cell<i32>,
502        orientation: [AxisRange; 3],
503    }
504
505    fn field_offset(mask: u32, target: u32) -> Option<usize> {
506        let mut offset = 0;
507        for bit_index in 0..32 {
508            let bit = 1u32 << bit_index;
509            if mask & bit == 0 {
510                continue;
511            }
512            if bit == target {
513                return Some(offset);
514            }
515            let size = match bit {
516                PK_TIME | PK_BUTTONS | PK_X | PK_Y | PK_NORMAL_PRESSURE => 4,
517                PK_ORIENTATION => 12,
518                _ => return None,
519            };
520            offset += size;
521        }
522        None
523    }
524
525    fn packet_u32(words: &[u32; PACKET_WORDS], offset: usize) -> u32 {
526        words[offset / 4]
527    }
528    fn packet_i32(words: &[u32; PACKET_WORDS], offset: usize) -> i32 {
529        words[offset / 4] as i32
530    }
531    fn normalized(value: i32, range: AxisRange) -> f32 {
532        let span = range.max.saturating_sub(range.min);
533        if span <= 0 {
534            0.0
535        } else {
536            (value.saturating_sub(range.min) as f32 / span as f32).clamp(0.0, 1.0)
537        }
538    }
539
540    fn push_packet(hwnd: HWND, state: &HookState, serial: u32) {
541        let mut words = [0u32; PACKET_WORDS];
542        if unsafe { (state.packet_fn)(state.context, serial, words.as_mut_ptr()) } == 0 {
543            return;
544        }
545        let (Some(time_offset), Some(x_offset), Some(y_offset)) = (
546            field_offset(state.packet_mask, PK_TIME),
547            field_offset(state.packet_mask, PK_X),
548            field_offset(state.packet_mask, PK_Y),
549        ) else {
550            return;
551        };
552        let mut screen = windows::Win32::Foundation::POINT {
553            x: packet_i32(&words, x_offset),
554            y: packet_i32(&words, y_offset),
555        };
556        if !unsafe { ScreenToClient(hwnd, &mut screen) }.as_bool() {
557            return;
558        }
559        let dpi = unsafe { GetDpiForWindow(hwnd) }.max(1) as f32 / 96.0;
560        let pressure = field_offset(state.packet_mask, PK_NORMAL_PRESSURE)
561            .map(|offset| {
562                let raw = packet_u32(&words, offset) as i32;
563                if raw > state.pressure_seen_max.get() {
564                    state.pressure_seen_max.set(raw);
565                }
566                let range = AxisRange {
567                    min: state.pressure_range.min,
568                    max: state.pressure_range.max.max(state.pressure_seen_max.get()),
569                };
570                normalized(raw, range)
571            })
572            .unwrap_or(1.0);
573        let (tilt_x, tilt_y, rotation) =
574            if let Some(offset) = field_offset(state.packet_mask, PK_ORIENTATION) {
575                let azimuth = normalized(packet_i32(&words, offset), state.orientation[0]);
576                let altitude = normalized(packet_i32(&words, offset + 4), state.orientation[1]);
577                let theta = azimuth * std::f32::consts::TAU;
578                // Wintab altitude is 0 at the tablet plane and 90 degrees
579                // when the pen is perpendicular to it. Windows Ink expresses
580                // tilt as degrees away from perpendicular, so convert the
581                // altitude to the same 0..1 tilt magnitude here.
582                let altitude_radians = altitude * std::f32::consts::FRAC_PI_2;
583                let tilt = altitude_radians.cos().max(0.0);
584                let twist = normalized(packet_i32(&words, offset + 8), state.orientation[2]);
585                (
586                    theta.cos() * tilt,
587                    theta.sin() * tilt,
588                    twist * std::f32::consts::TAU,
589                )
590            } else {
591                (0.0, 0.0, 0.0)
592            };
593        let _buttons =
594            field_offset(state.packet_mask, PK_BUTTONS).map(|offset| packet_u32(&words, offset));
595        let packet = PenPacket {
596            x: screen.x as f32 / dpi,
597            y: screen.y as f32 / dpi,
598            pressure,
599            tilt_x,
600            tilt_y,
601            rotation,
602            time_ms: packet_u32(&words, time_offset) as u64,
603            received_at: std::time::Instant::now(),
604        };
605        if state.queue.push(packet).is_err() {
606            let _ = state.queue.pop();
607            let _ = state.queue.push(packet);
608        }
609    }
610
611    unsafe extern "system" fn window_proc(
612        hwnd: HWND,
613        msg: u32,
614        wparam: WPARAM,
615        lparam: LPARAM,
616        _id: usize,
617        data: usize,
618    ) -> LRESULT {
619        let state = unsafe { &*(data as *const HookState) };
620        if msg == state.message && lparam.0 as *mut c_void == state.context {
621            push_packet(hwnd, state, wparam.0 as u32);
622        }
623        unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) }
624    }
625
626    pub struct WintabHook {
627        hwnd: HWND,
628        state: Box<HookState>,
629    }
630
631    impl WintabHook {
632        pub fn install(
633            hwnd: *mut c_void,
634            queue: Arc<ArrayQueue<PenPacket>>,
635        ) -> Result<Self, String> {
636            let module = unsafe { LoadLibraryA(c"wintab32.dll".as_ptr()) };
637            if module.is_null() {
638                return Err("Wintab driver (wintab32.dll) is unavailable".into());
639            }
640            let result = (|| unsafe {
641                let wt_info: WtInfoA = load_proc(module, b"WTInfoA\0")
642                    .ok_or_else(|| "Wintab WTInfoA export is unavailable".to_string())?;
643                let wt_open: WtOpenA = load_proc(module, b"WTOpenA\0")
644                    .ok_or_else(|| "Wintab WTOpenA export is unavailable".to_string())?;
645                let packet_fn: WtPacket = load_proc(module, b"WTPacket\0")
646                    .ok_or_else(|| "Wintab WTPacket export is unavailable".to_string())?;
647                let close_fn: WtClose = load_proc(module, b"WTClose\0")
648                    .ok_or_else(|| "Wintab WTClose export is unavailable".to_string())?;
649                if wt_info(0, 0, std::ptr::null_mut()) == 0 {
650                    return Err("Wintab driver did not respond to WTInfo".into());
651                }
652                let mut context = LogContextA::default();
653                if wt_info(WTI_DEFSYSCTX, 0, (&mut context as *mut LogContextA).cast()) == 0 {
654                    return Err("Wintab system context is unavailable".into());
655                }
656                let device_category = WTI_DEVICES.saturating_add(if context.device == u32::MAX {
657                    0
658                } else {
659                    context.device
660                });
661                let mut device_packet_mask = 0u32;
662                let _ = wt_info(
663                    device_category,
664                    DVC_PKTDATA,
665                    (&mut device_packet_mask as *mut u32).cast(),
666                );
667                let mut pressure_axis = Axis::default();
668                let pressure_supported = wt_info(
669                    device_category,
670                    DVC_NPRESSURE,
671                    (&mut pressure_axis as *mut Axis).cast(),
672                ) != 0;
673                let mut orientation_axes = [Axis::default(); 3];
674                let orientation_supported = wt_info(
675                    device_category,
676                    DVC_ORIENTATION,
677                    orientation_axes.as_mut_ptr().cast(),
678                ) != 0;
679
680                // Always ask for pressure. Some drivers leave it out of the
681                // DVC_PKTDATA mask even though they deliver it, and without
682                // it every packet would read as full pressure.
683                let _ = device_packet_mask;
684                let mut packet_mask = PK_TIME | PK_BUTTONS | PK_X | PK_Y | PK_NORMAL_PRESSURE;
685                if orientation_supported {
686                    packet_mask |= PK_ORIENTATION;
687                }
688                context.options |= CXO_SYSTEM | CXO_MESSAGES;
689                // Report positions in virtual-screen pixels with the origin at
690                // the top left. The default system context may report tablet
691                // counts (and Wintab's Y axis points up), which would place
692                // every packet outside the canvas and silently fall back to
693                // pressure-less window input.
694                context.output_origin[0] = context.system_origin[0];
695                context.output_origin[1] = context.system_origin[1];
696                context.output_extent[0] = context.system_extent[0];
697                context.output_extent[1] = -context.system_extent[1];
698                context.packet_data = packet_mask;
699                context.packet_mode = 0;
700                context.move_mask =
701                    packet_mask & (PK_X | PK_Y | PK_NORMAL_PRESSURE | PK_ORIENTATION);
702                context.name[..6].copy_from_slice(&b"Efude\0".map(|byte| byte as c_char));
703                let hwnd = HWND(hwnd);
704                let context_handle = wt_open(hwnd, &mut context, 1);
705                if context_handle.is_null() {
706                    return Err("Wintab could not open a tablet context".into());
707                }
708                let state = Box::new(HookState {
709                    queue,
710                    module,
711                    context: context_handle,
712                    packet_fn,
713                    close_fn,
714                    message: context.message_base + WT_PACKET_OFFSET,
715                    packet_mask,
716                    pressure_range: if pressure_supported && pressure_axis.max > pressure_axis.min {
717                        AxisRange {
718                            min: pressure_axis.min,
719                            max: pressure_axis.max,
720                        }
721                    } else {
722                        // Unknown range: assume the common 1024 levels;
723                        // `push_packet` widens it if larger values appear.
724                        AxisRange { min: 0, max: 1023 }
725                    },
726                    pressure_seen_max: std::cell::Cell::new(0),
727                    orientation: orientation_axes.map(|axis| AxisRange {
728                        min: axis.min,
729                        max: axis.max,
730                    }),
731                });
732                let data = (&*state as *const HookState) as usize;
733                if !SetWindowSubclass(hwnd, Some(window_proc), SUBCLASS_ID, data).as_bool() {
734                    let _ = (state.close_fn)(state.context);
735                    return Err("Could not attach Wintab messages to the application window".into());
736                }
737                Ok(Self { hwnd, state })
738            })();
739            if result.is_err() {
740                unsafe { FreeLibrary(module) };
741            }
742            result
743        }
744    }
745
746    impl Drop for WintabHook {
747        fn drop(&mut self) {
748            unsafe {
749                let _ = RemoveWindowSubclass(self.hwnd, Some(window_proc), SUBCLASS_ID);
750                let _ = (self.state.close_fn)(self.state.context);
751                let _ = FreeLibrary(self.state.module);
752            }
753        }
754    }
755}
756
757#[cfg(target_os = "windows")]
758pub use wintab::WintabHook;
759#[derive(Default)]
760pub struct InputNormalizer {
761    started_at: Option<std::time::Instant>,
762}
763impl InputNormalizer {
764    pub fn begin(&mut self) {
765        self.started_at = Some(std::time::Instant::now());
766    }
767    pub fn point(&self, x: f32, y: f32, pressure: f32) -> InkPoint {
768        InkPoint::new(
769            x,
770            y,
771            pressure,
772            self.started_at
773                .map_or(0, |t| t.elapsed().as_millis() as u64),
774        )
775    }
776    /// Build a complete pen point for platform backends that expose tilt and barrel rotation.
777    pub fn pen_point(
778        &self,
779        x: f32,
780        y: f32,
781        pressure: f32,
782        tilt_x: f32,
783        tilt_y: f32,
784        rotation_radians: f32,
785    ) -> InkPoint {
786        let mut point = self.point(x, y, pressure);
787        point.tilt = glam::Vec2::new(tilt_x.clamp(-1., 1.), tilt_y.clamp(-1., 1.));
788        point.rotation = rotation_radians;
789        point
790    }
791}
792
793pub struct InputQueue {
794    pub sender: SyncSender<InkPoint>,
795    pub receiver: Receiver<InkPoint>,
796}
797impl InputQueue {
798    pub fn bounded(capacity: usize) -> Self {
799        let (sender, receiver) = sync_channel(capacity.max(1));
800        Self { sender, receiver }
801    }
802}
803
804#[cfg(target_os = "windows")]
805pub fn pointer_pressure(raw_pressure: u32) -> f32 {
806    (raw_pressure as f32 / 1024.).clamp(0., 1.)
807}
808
809#[cfg(test)]
810mod tests {
811    use super::*;
812
813    #[test]
814    fn recorded_stroke_replays_all_input_channels() {
815        let mut original = InkPoint::new(12.5, 30.0, 0.42, 14);
816        original.tilt = glam::Vec2::new(-0.3, 0.7);
817        original.rotation = 1.2;
818        let mut log = StrokeLog::default();
819        log.push(&[original]);
820        let replayed = log.replay(0).unwrap();
821        assert_eq!(replayed, vec![original]);
822    }
823}
824
825#[derive(Clone, Debug, Serialize, Deserialize)]
826pub struct RecordedPoint {
827    pub x: f32,
828    pub y: f32,
829    pub pressure: f32,
830    pub tilt_x: f32,
831    pub tilt_y: f32,
832    #[serde(default)]
833    pub rotation: f32,
834    pub time_ms: u64,
835}
836#[derive(Clone, Debug, Default, Serialize, Deserialize)]
837pub struct StrokeLog {
838    pub version: u32,
839    pub strokes: Vec<Vec<RecordedPoint>>,
840}
841impl StrokeLog {
842    pub fn push(&mut self, points: &[InkPoint]) {
843        self.strokes.push(
844            points
845                .iter()
846                .map(|p| RecordedPoint {
847                    x: p.position.x,
848                    y: p.position.y,
849                    pressure: p.pressure,
850                    tilt_x: p.tilt.x,
851                    tilt_y: p.tilt.y,
852                    rotation: p.rotation,
853                    time_ms: p.time_ms,
854                })
855                .collect(),
856        );
857        if self.strokes.len() > 128 {
858            self.strokes.remove(0);
859        }
860        self.version = 2;
861    }
862    pub fn replay(&self, index: usize) -> Option<Vec<InkPoint>> {
863        self.strokes.get(index).map(|stroke| {
864            stroke
865                .iter()
866                .map(|p| InkPoint {
867                    position: glam::Vec2::new(p.x, p.y),
868                    pressure: p.pressure,
869                    taper: 1.0,
870                    tilt: glam::Vec2::new(p.tilt_x, p.tilt_y),
871                    rotation: p.rotation,
872                    time_ms: p.time_ms,
873                })
874                .collect()
875        })
876    }
877    pub fn save(&self, path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
878        std::fs::write(path, serde_json::to_vec_pretty(self)?)?;
879        Ok(())
880    }
881    pub fn load(path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
882        Ok(serde_json::from_slice(&std::fs::read(path)?)?)
883    }
884}
885#[cfg(not(target_os = "windows"))]
886pub fn pointer_pressure(raw_pressure: u32) -> f32 {
887    (raw_pressure as f32 / 1024.).clamp(0., 1.)
888}