libinput-rs 0.2.2

Fail-open Rust touchpad companion and drop-in libinput ABI replacement
Documentation
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
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Default)]
struct Section {
    matches: Vec<(String, String)>,
    event_codes: Vec<String>,
    input_props: Vec<String>,
    size_hint: Option<(f64, f64)>,
    resolution_hint: Option<(f64, f64)>,
    is_virtual: bool,
    model_lenovo_scrollpoint: bool,
    model_alps_serial_touchpad: bool,
    model_dell_canvas_totem: bool,
    model_apple_touchpad: bool,
    model_apple_touchpad_onebutton: bool,
    model_clickfinger_default: bool,
    model_wacom_touchpad: bool,
    tpkb_combo_layout_below: bool,
    keyboard_integration: Option<KeyboardIntegration>,
    palm_pressure_threshold: Option<u32>,
    palm_size_threshold: Option<u32>,
}

struct DeviceIdentity<'a> {
    name: &'a str,
    bus: u16,
    vendor: u16,
    product: u16,
    version: u16,
    udev_types: &'a [&'a str],
}

/// How a keyboard is physically integrated with the system.  This is a
/// quirk-derived property: bus type alone is not enough to decide whether a
/// keyboard should participate in a touchpad's disable-while-typing state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyboardIntegration {
    Internal,
    External,
}

#[derive(Default)]
pub struct AppliedQuirks {
    pub messages: Vec<String>,
    pub size_hint: Option<(f64, f64)>,
    pub resolution_hint: Option<(f64, f64)>,
    pub disable_hi_res_wheel_vertical: bool,
    pub disable_hi_res_wheel_horizontal: bool,
    pub disable_tablet_tilt_x: bool,
    pub disable_tablet_tilt_y: bool,
    pub is_virtual: bool,
    pub model_lenovo_scrollpoint: bool,
    pub model_alps_serial_touchpad: bool,
    pub model_dell_canvas_totem: bool,
    pub model_apple_touchpad: bool,
    pub model_apple_touchpad_onebutton: bool,
    pub model_clickfinger_default: bool,
    pub model_wacom_touchpad: bool,
    pub tpkb_combo_layout_below: bool,
    pub keyboard_integration: Option<KeyboardIntegration>,
    pub palm_pressure_threshold: Option<u32>,
    pub palm_size_threshold: Option<u32>,
}

pub fn apply_quirks(
    name: &str,
    bus: u16,
    vendor: u16,
    product: u16,
    version: u16,
    udev_types: &[&str],
    event_codes: &mut Vec<u16>,
) -> AppliedQuirks {
    let mut applied = AppliedQuirks::default();
    let directory = std::env::var_os("LIBINPUT_QUIRKS_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/usr/share/libinput"));
    let Ok(entries) = fs::read_dir(directory) else {
        return applied;
    };
    let mut files: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .is_some_and(|extension| extension == "quirks")
        })
        .collect();
    files.sort();

    let identity = DeviceIdentity {
        name,
        bus,
        vendor,
        product,
        version,
        udev_types,
    };
    for path in files {
        apply_file(&path, &identity, event_codes, &mut applied);
    }
    applied
}

fn apply_file(
    path: &Path,
    identity: &DeviceIdentity<'_>,
    event_codes: &mut Vec<u16>,
    applied: &mut AppliedQuirks,
) {
    let Ok(contents) = fs::read_to_string(path) else {
        return;
    };
    let mut section = Section::default();
    let mut in_section = false;
    for raw_line in contents.lines() {
        let line = raw_line.trim();
        if line.starts_with('[') && line.ends_with(']') {
            if in_section {
                apply_section(&section, identity, event_codes, applied);
            }
            section = Section::default();
            in_section = true;
            continue;
        }
        if !in_section || line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        if key.starts_with("Match") {
            section
                .matches
                .push((key.trim().to_string(), value.trim().to_string()));
        } else if key.trim() == "AttrEventCode" {
            section.event_codes.push(value.trim().to_string());
        } else if key.trim() == "AttrInputProp" {
            section.input_props.push(value.trim().to_string());
        } else if key.trim() == "AttrSizeHint" {
            section.size_hint = parse_dimensions(value);
        } else if key.trim() == "AttrResolutionHint" {
            section.resolution_hint = parse_dimensions(value);
        } else if key.trim() == "AttrTPKComboLayout" {
            section.tpkb_combo_layout_below = value.trim().eq_ignore_ascii_case("below");
        } else if key.trim() == "AttrKeyboardIntegration" {
            section.keyboard_integration = match value.trim().to_ascii_lowercase().as_str() {
                "internal" => Some(KeyboardIntegration::Internal),
                "external" => Some(KeyboardIntegration::External),
                _ => None,
            };
        } else if key.trim() == "AttrPalmPressureThreshold" {
            section.palm_pressure_threshold = value.trim().parse().ok();
        } else if key.trim() == "AttrPalmSizeThreshold" {
            section.palm_size_threshold = value.trim().parse().ok();
        } else if key.trim() == "AttrIsVirtual" {
            section.is_virtual = value.trim() == "1";
        } else if key.trim() == "ModelLenovoScrollPoint" {
            section.model_lenovo_scrollpoint = value.trim() == "1";
        } else if key.trim() == "ModelALPSSerialTouchpad" {
            section.model_alps_serial_touchpad = value.trim() == "1";
        } else if key.trim() == "ModelDellCanvasTotem" {
            section.model_dell_canvas_totem = value.trim() == "1";
        } else if key.trim() == "ModelAppleTouchpad" {
            section.model_apple_touchpad = value.trim() == "1";
        } else if key.trim() == "ModelAppleTouchpadOneButton" {
            section.model_apple_touchpad_onebutton = value.trim() == "1";
        } else if key.trim() == "ModelWacomTouchpad" {
            section.model_wacom_touchpad = value.trim() == "1";
        } else if matches!(
            key.trim(),
            "ModelChromebook"
                | "ModelSystem76Bonobo"
                | "ModelSystem76Galago"
                | "ModelSystem76Kudu"
                | "ModelClevoW740SU"
        ) {
            section.model_clickfinger_default = value.trim() == "1";
        }
    }
    if in_section {
        apply_section(&section, identity, event_codes, applied);
    }
}

fn apply_section(
    section: &Section,
    identity: &DeviceIdentity<'_>,
    event_codes: &mut Vec<u16>,
    applied: &mut AppliedQuirks,
) {
    if !section
        .matches
        .iter()
        .all(|(key, value)| match_property(key, value, identity))
    {
        return;
    }
    for expression in &section.event_codes {
        for token in expression
            .split(';')
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            let (enable, code_name) = match token.as_bytes().first() {
                Some(b'+') => (true, &token[1..]),
                Some(b'-') => (false, &token[1..]),
                _ => continue,
            };
            let relative_code = code_name.strip_prefix("EV_REL:").unwrap_or(code_name);
            if relative_code == "REL_WHEEL_HI_RES" {
                applied.disable_hi_res_wheel_vertical = !enable;
                continue;
            }
            if relative_code == "REL_HWHEEL_HI_RES" {
                applied.disable_hi_res_wheel_horizontal = !enable;
                continue;
            }
            let absolute_code = code_name.strip_prefix("EV_ABS:").unwrap_or(code_name);
            if absolute_code == "ABS_TILT_X" {
                applied.disable_tablet_tilt_x = !enable;
                continue;
            }
            if absolute_code == "ABS_TILT_Y" {
                applied.disable_tablet_tilt_y = !enable;
                continue;
            }
            let Some(code) = parse_key_code(code_name) else {
                continue;
            };
            let action = if enable { "enabling" } else { "disabling" };
            applied.messages.push(format!(
                "{action} EV_KEY {}",
                key_code_name(code).unwrap_or(code_name)
            ));
            if enable {
                if !event_codes.contains(&code) {
                    event_codes.push(code);
                }
            } else {
                event_codes.retain(|existing| *existing != code);
            }
        }
    }
    for expression in &section.input_props {
        for token in expression
            .split(';')
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            let (action, property) = match token.as_bytes().first() {
                Some(b'+') => ("enabling", &token[1..]),
                Some(b'-') => ("disabling", &token[1..]),
                _ => continue,
            };
            applied.messages.push(format!("{action} {property}"));
        }
    }
    if let Some(size) = section.size_hint {
        applied.size_hint = Some(size);
    }
    if let Some(resolution) = section.resolution_hint {
        applied.resolution_hint = Some(resolution);
    }
    applied.is_virtual |= section.is_virtual;
    applied.model_lenovo_scrollpoint |= section.model_lenovo_scrollpoint;
    applied.model_alps_serial_touchpad |= section.model_alps_serial_touchpad;
    applied.model_dell_canvas_totem |= section.model_dell_canvas_totem;
    applied.model_apple_touchpad |= section.model_apple_touchpad;
    applied.model_apple_touchpad_onebutton |= section.model_apple_touchpad_onebutton;
    applied.model_clickfinger_default |= section.model_clickfinger_default;
    applied.model_wacom_touchpad |= section.model_wacom_touchpad;
    applied.tpkb_combo_layout_below |= section.tpkb_combo_layout_below;
    if let Some(integration) = section.keyboard_integration {
        // Quirk files are applied in lexical order, matching the precedence
        // model of the upstream quirk database. A later matching rule is
        // therefore allowed to replace an earlier integration classification.
        applied.keyboard_integration = Some(integration);
    }
    if let Some(threshold) = section.palm_pressure_threshold {
        applied.palm_pressure_threshold = Some(threshold);
    }
    if let Some(threshold) = section.palm_size_threshold {
        applied.palm_size_threshold = Some(threshold);
    }
}

fn match_property(key: &str, value: &str, identity: &DeviceIdentity<'_>) -> bool {
    match key {
        "MatchName" => glob_matches(value, identity.name),
        "MatchBus" => match value.to_ascii_lowercase().as_str() {
            "usb" => identity.bus == 0x03,
            "bluetooth" => identity.bus == 0x05,
            "ps2" | "i8042" => identity.bus == 0x11,
            "i2c" => identity.bus == 0x18,
            "spi" => identity.bus == 0x1c,
            "rmi" => identity.bus == 0x1d,
            _ => false,
        },
        "MatchVendor" => parse_number(value).is_some_and(|number| number == identity.vendor),
        "MatchProduct" => parse_number(value).is_some_and(|number| number == identity.product),
        "MatchVersion" => parse_number(value).is_some_and(|number| number == identity.version),
        "MatchUdevType" => identity
            .udev_types
            .iter()
            .any(|udev_type| value.eq_ignore_ascii_case(udev_type)),
        // A match constraint we cannot establish must not broaden a quirk.
        _ => false,
    }
}

fn parse_dimensions(value: &str) -> Option<(f64, f64)> {
    let (x, y) = value.trim().split_once('x')?;
    let x: f64 = x.parse().ok()?;
    let y: f64 = y.parse().ok()?;
    (x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0).then_some((x, y))
}

fn parse_number(value: &str) -> Option<u16> {
    let value = value.trim();
    if let Some(hex) = value
        .strip_prefix("0x")
        .or_else(|| value.strip_prefix("0X"))
    {
        u16::from_str_radix(hex, 16).ok()
    } else {
        value.parse().ok()
    }
}

fn parse_key_code(name: &str) -> Option<u16> {
    if let Some(code) = name.strip_prefix("EV_KEY:") {
        return parse_number(code);
    }
    Some(match name {
        "BTN_LEFT" => 0x110,
        "BTN_RIGHT" => 0x111,
        "BTN_MIDDLE" => 0x112,
        "BTN_SIDE" => 0x113,
        "BTN_EXTRA" => 0x114,
        "BTN_FORWARD" => 0x115,
        "BTN_BACK" => 0x116,
        "BTN_TASK" => 0x117,
        "BTN_0" => 0x100,
        "KEY_F1" => 59,
        "KEY_F2" => 60,
        "KEY_F3" => 61,
        _ => return None,
    })
}

fn key_code_name(code: u16) -> Option<&'static str> {
    Some(match code {
        0x110 => "BTN_LEFT",
        0x111 => "BTN_RIGHT",
        0x112 => "BTN_MIDDLE",
        0x113 => "BTN_SIDE",
        0x114 => "BTN_EXTRA",
        0x115 => "BTN_FORWARD",
        0x116 => "BTN_BACK",
        0x117 => "BTN_TASK",
        59 => "KEY_F1",
        60 => "KEY_F2",
        61 => "KEY_F3",
        _ => return None,
    })
}

fn glob_matches(pattern: &str, value: &str) -> bool {
    let pattern = pattern.as_bytes();
    let value = value.as_bytes();
    let (mut p, mut v, mut star, mut retry) = (0, 0, None, 0);
    while v < value.len() {
        if p < pattern.len() && (pattern[p] == b'?' || pattern[p] == value[v]) {
            p += 1;
            v += 1;
        } else if p < pattern.len() && pattern[p] == b'*' {
            star = Some(p);
            p += 1;
            retry = v;
        } else if let Some(star_position) = star {
            p = star_position + 1;
            retry += 1;
            v = retry;
        } else {
            return false;
        }
    }
    while p < pattern.len() && pattern[p] == b'*' {
        p += 1;
    }
    p == pattern.len()
}

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

    #[test]
    fn glob_supports_quirk_name_patterns() {
        assert!(glob_matches(
            "*Logitech*Marble*",
            "Logitech USB Marble Mouse"
        ));
        assert!(!glob_matches(
            "*Logitech*M575*",
            "Logitech USB Marble Mouse"
        ));
    }

    #[test]
    fn parses_numeric_and_named_key_codes() {
        assert_eq!(parse_key_code("EV_KEY:0x118"), Some(0x118));
        assert_eq!(parse_key_code("BTN_MIDDLE"), Some(0x112));
        assert_eq!(parse_key_code("EV_ABS:0x00"), None);
    }

    #[test]
    fn parses_positive_dimensions() {
        assert_eq!(parse_dimensions("100x55"), Some((100.0, 55.0)));
        assert_eq!(parse_dimensions("0x55"), None);
        assert_eq!(parse_dimensions("invalid"), None);
    }

    #[test]
    fn applies_apple_touchpad_onebutton_quirk_by_identity() {
        std::env::set_var(
            "LIBINPUT_QUIRKS_DIR",
            concat!(env!("CARGO_MANIFEST_DIR"), "/tests/quirks"),
        );
        let mut event_codes = Vec::new();
        let applied = apply_quirks(
            "litest appletouch",
            0x03,
            0x05ac,
            0x021a,
            0x00,
            &["touchpad"],
            &mut event_codes,
        );
        assert!(applied.model_apple_touchpad_onebutton);
    }
}