tabletdb 0.1.1

A database of auxiliary information about graphics tablets
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
// SPDX-License-Identifier: MIT
//! A database of information about graphics tablets.
//!
//! This crate provides **static** information about graphics tablets (Wacom, Huion, XP-Pen, Ugee,
//! etc.) that cannot be obtained from the kernel device itself such as:
//! - is the given tablet integrated into a display or a system (i.e. a laptop display)
//! - which axes and buttons are available on a given tool. The kernel exports *all possible*
//!   axes across *all possible* tools on a tablet.
//! - which tools are available on a given tablet
//! - obtaining a detailed (SVG) and rough (top/bottom/left/right) layout of the button positions
//!
//! A physical tablet is not required for querying information about tablet.
//! This crate does not affect the functionality of a tablet. It's a wrapper around a set of text
//! files that describe a tablet and never actually looks at the device itself beyond (maybe)
//! extracting the device's name and ids from `/sys`.
//!
//! This crate is tablet-vendor-agnostic and (in theory) platform-agnostic. Support for platforms
//! other than Linux is untested.
//!
//! ## Tablets, Styli, Buttons, Rings, Dials, Strips
//!
//! A tablet as seen by this crate refers to the physical tablet that is connected to the host via
//! one of the supported [BusTypes](BusType).
//!
//! Many tablets have [Buttons](Button) and almost all tablets support [Styli](Stylus), the notable
//! exception being those resembling a [Remote](FormFactor::Remote), e.g. the Wacom
//! ExpressKey Remote.
//!
//! A tablet may also have additional [Features](Feature):
//! - a [Ring] is a ring-shaped feature providing absolute finger position, see e.g. the Wacom
//!   Intuos Pro series
//! - a [Dial] is a dial or wheel-shaped feature providing relative input data, see
//!   e.g. the Huion Inspiroy 2S or the Huion Inspiroy Dial 2
//! - a touch [Strip] strip providing absolute finger position, see e.g. the Wacom Intuos 3.
//!
//! A tablet may have more than one feature (e.g. two rings) and more than one feature type (e.g. a
//! ring and two strips).
//!
//! ## Modes and Mode Toggles
//!
//! Features may be logically associated with a [Button]. For example the Wacom Intuos Pro
//! series has one button inside the [Ring]. This button is physically independent
//! of the ring but often associated with the "modes" of the ring (and other buttons).
//! This button is referred to as "mode toggle button".
//!
//! Such a mode may allow assigning different actions to the feature depending on the current mode.
//! This crate only provides information about which button is logically associated
//! with the feature (see [Feature::buttons()]) and the number of modes expected on this tablet
//! ([Feature::num_modes()]).
//!
//! On Linux, the modes are typically tied to the LEDs on the device and pressing the
//! button associated with the feature will iterate and/or toggle the respective LED.
//!
//! Some tablets have more than one mode toggle button - on those tablets each button
//! is expected to switch to one specific mode. On tablets with one mode switch button
//! the button is typically expected to cycle modes.
//!
//! ## Examples
//!
//! The most common use is to query information about a tablet that exists locally:
//! ```
//! # use tabletdb::{Error, TabletInfo, Cache};
//! # use std::path::PathBuf;
//! # fn load()  -> Result<(), Error> {
//! // A cache with default include paths
//! let cache = Cache::new()?;
//! for entry in std::fs::read_dir("/dev/input").unwrap().flatten() {
//!     // Extract the information from a local tablet
//!     let info = TabletInfo::new_from_path(&entry.path())?;
//!     // Find that tablet in the cache
//!     for tablet in cache.iter().filter(|t| *t == &info) {
//!         println!("{:?}: {}", entry.path(), tablet.name());
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//! But it's also possible to simply filter on other information if no device is present:
//! ```
//! # use tabletdb::{Error, BusType, TabletInfo, Cache};
//! # use std::path::PathBuf;
//! # fn load()  -> Result<(), Error> {
//! // A cache with default include paths
//! let cache = Cache::new()?;
//! for tablet in cache.iter().filter(|t| t.bustype() == BusType::Bluetooth) {
//!         println!("{} is a supported Bluetooth tablet", tablet.name());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! See the [CacheBuilder] for cases where non-default include paths are needed.
//!
//! ## Relationship to libwacom
//! This crate aims to be equivalent to [libwacom](https://github.com/linuxwacom/libwacom).
//! Some of libwacom's deprecated APIs are not present here, others
//! provide a different structure but the set of information is the same.
//!
//! <div class="warning">
//! This crate currently uses the libwacom data files as data source.  Note that these data files
//! are <em>not</em> stable API and updating libwacom may cause this crate to stop working. We aim
//! to remove this dependency in future versions.
//! </div>

use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use thiserror::Error;

pub(crate) mod parser;

/// Crate-specific errors
#[derive(Error, Debug)]
pub enum Error {
    #[error("Invalid Argument: {message}")]
    InvalidArgument { message: String },

    #[error("Parsing failed: {message}")]
    ParserError { message: String },

    /// Failed to load required files for the cache.
    ///
    /// This error is raised if all files failed. The [Cache]'s include
    /// paths are optional and empty include directories are
    /// not a cause for failure.
    #[error("Failed to load DB: {message}")]
    IO { message: String },
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::IO {
            message: format!("{e}"),
        }
    }
}

pub(crate) type Result<T> = std::result::Result<T, Error>;

/// Builder struct for a tablet [Cache].
///
/// This builder is only required for adding non-default include paths,
/// use [Cache::new()] for a tablet cache that uses the defaults.
pub struct CacheBuilder {
    paths: Vec<PathBuf>,
}

impl CacheBuilder {
    /// Create a new, empty, [CacheBuilder] without any include paths.
    /// This info is only needed where include paths need to be
    /// modified, for standard invocations use [Cache::new()].
    ///
    /// The typical invocation is
    /// ```
    /// # use tabletdb::*;
    /// # fn build() -> Result<(), tabletdb::Error> {
    /// let cache = CacheBuilder::new()
    ///                 .add_default_includes()
    ///                 .build()?;
    /// # Ok(())
    /// # }
    /// ```
    /// The above example is equivalent to [Cache::new()].
    pub fn new() -> Self {
        CacheBuilder { paths: Vec::new() }
    }

    /// Add the default set of include paths as compiled in, typically:
    /// - `/usr/share/libwacom`,
    /// - `/etc/libwacom`
    /// - `$XDG_CONFIG_HOME/libwacom`.
    pub fn add_default_includes(mut self) -> Self {
        // FIXME: this should come from libwacom-data.pc or something
        // except libwacom explicitly has those tablet files as "not API"
        self.paths.push("/usr/share/libwacom".into());
        self.paths.push("/etc/libwacom".into());
        let xdg_dirs = xdg::BaseDirectories::with_prefix("libwacom").unwrap();
        self.paths.push(xdg_dirs.get_config_home());
        self
    }

    /// Add an include path at the current position. Include paths are
    /// processed in-order with a file in most recent path obscuring
    /// a file with the same name in an earlier include path.
    ///
    /// Include paths to not need to exist, empty or non-existing include
    /// paths are ignored.
    pub fn add_include(mut self, path: &Path) -> Self {
        self.paths.push(path.into());
        self
    }

    fn find_files(&self, suffix: &str) -> Result<Vec<PathBuf>> {
        let mut files: HashMap<String, PathBuf> = HashMap::new();
        for path in &self.paths {
            std::fs::read_dir(path)?
                .filter_map(|f| f.ok())
                .filter(|f| f.file_type().map(|f| f.is_file()).is_ok())
                .filter(|f| f.file_name().to_string_lossy().ends_with(suffix))
                .for_each(|f| {
                    files.insert(f.file_name().to_string_lossy().to_string(), f.path());
                });
        }

        let files: Vec<PathBuf> = files.into_values().collect();
        Ok(files)
    }

    fn build_tablets(&self) -> Result<Vec<parser::TabletEntry>> {
        let tablets = self
            .find_files(".tablet")?
            .iter()
            .map(|path| parser::TabletFile::new(path))
            .inspect(|res| match res {
                Ok(_) => {}
                Err(e) => log::warn!("{e}"),
            })
            .filter_map(|res| res.ok())
            .flat_map(|tf| tf.entries)
            .collect::<Vec<parser::TabletEntry>>();

        Ok(tablets)
    }

    fn build_styli(&self) -> Result<Vec<parser::StylusEntry>> {
        let styli = self
            .find_files(".stylus")?
            .iter()
            .map(|path| parser::StylusFile::new(path))
            .inspect(|res| match res {
                Ok(_) => {}
                Err(e) => log::warn!("{e}"),
            })
            .filter_map(|res| res.ok())
            .flat_map(|sf| sf.styli)
            .collect::<Vec<parser::StylusEntry>>();

        Ok(styli)
    }

    /// Create a tablet [Cache] from the current include paths.
    pub fn build(self) -> Result<Cache> {
        let mut tablet_entries = self.build_tablets()?;
        let stylus_entries = self.build_styli()?;

        let mut groups: HashMap<String, Vec<StylusId>> = HashMap::new();
        for stylus in &stylus_entries {
            if let Some(stylus_group) = &stylus.group {
                groups
                    .entry(stylus_group.clone())
                    .or_default()
                    .push(stylus.id);
            }
        }

        // Resolve the groups into actual ids
        for tablet in &mut tablet_entries {
            tablet.styli = tablet
                .styli
                .iter_mut()
                .flat_map(|r| match r {
                    StylusRef::ID(id) => vec![StylusRef::ID(*id)],
                    StylusRef::Group(group) => groups
                        .get(group)
                        .unwrap_or(&Vec::<StylusId>::new())
                        .iter()
                        .map(|id: &StylusId| StylusRef::ID(*id))
                        .collect(),
                })
                .collect();
        }

        let tools: Vec<Tool> = stylus_entries
            .iter()
            .enumerate()
            // Filter out any tools with non-existing paired ids
            .filter(|(_, entry)| {
                entry
                    .paired_ids
                    .map(|id| stylus_entries.iter().any(|p| p.id == id))
                    .unwrap_or(true)
            })
            // Filter any invert erasers, we map those directl
            .filter(|(_, entry)| entry.eraser_type != Some(EraserType::Invert))
            .map(|(idx, s)| {
                if s.tool_type == parser::ToolType::Puck {
                    Ok(Tool::Mouse(Mouse {
                        idx,
                        id: s.id,
                        axes: s.axes.clone(),
                        name: s.name.clone(),
                        buttons: (0..s.num_buttons).map(|_| ToolButton {}).collect(),
                        has_lens: s.has_lens,
                    }))
                } else {
                    let st = match s.tool_type {
                        parser::ToolType::General => StylusType::General,
                        parser::ToolType::Inking => StylusType::Inking,
                        parser::ToolType::Airbrush => StylusType::Airbrush,
                        parser::ToolType::Classic => StylusType::Classic,
                        parser::ToolType::Marker => StylusType::Marker,
                        parser::ToolType::Stroke => StylusType::Stroke,
                        parser::ToolType::Pen3D => StylusType::Pen3D,
                        parser::ToolType::Mobile => StylusType::Mobile,
                        _ => {
                            return Err(Error::ParserError {
                                message: format!("Unsupported tool type {:?}", s.tool_type),
                            })
                        }
                    };
                    let stylus = Stylus {
                        idx,
                        id: s.id,
                        stylus_type: st,
                        eraser_type: s.eraser_type,
                        axes: s.axes.clone(),
                        name: s.name.clone(),
                        buttons: (0..s.num_buttons).map(|_| ToolButton {}).collect(),
                    };
                    // This is really bad in the data files. A tool
                    // without a paired ID is always a stylus or an
                    // eraser but only the eraser has the EraserType
                    // set.
                    if s.eraser_type.is_none_or(|t| t == EraserType::Button) {
                        Ok(Tool::Stylus(stylus))
                    } else {
                        let paired_id = s.paired_ids.unwrap();
                        let eraser: Eraser = stylus_entries
                            .iter()
                            .filter(|e| e.id == paired_id)
                            .map(|e| Eraser {
                                idx,
                                id: e.id,
                                eraser_type: e.eraser_type.unwrap(),
                                axes: e.axes.clone(),
                                name: e.name.clone(),
                                buttons: Vec::new(),
                            })
                            .take(1)
                            .next()
                            .unwrap();
                        Ok(Tool::StylusWithEraser(stylus, eraser))
                    }
                }
            })
            .collect::<Result<Vec<Tool>>>()?;

        let tablets = tablet_entries
            .into_iter()
            .enumerate()
            .map(|(idx, t)| Tablet {
                idx,
                name: t.name,
                model_name: t.model_name,
                kernel_name: t.device_match.name,
                fw_version: t.device_match.fw,
                layout: t.layout,

                width: Length { inches: t.width },
                height: Length { inches: t.height },

                form_factor: FormFactor::from_flags(&t.integrated_in),

                paired_id: t.paired_id.map(|m| m.to_device_id()),

                bustype: t.device_match.bustype,
                vid: t.device_match.vid,
                pid: t.device_match.pid,

                is_reversible: t.reversible,
                has_touch: t.touch,
                has_touchswitch: t.touchswitch,
                has_stylus: t.stylus,

                buttons: t
                    .buttons
                    .iter()
                    .map(|b| crate::Button {
                        index: crate::ButtonIndex(b.index.0),
                        location: b.location,
                        evdev_code: crate::EvdevCode(b.evdev_code.0),
                    })
                    .collect(),
                rings: t.rings,
                strips: t.strips,
                dials: t.dials,

                tools: tools
                    .iter()
                    .filter(|tool| {
                        t.styli.iter().any(|id| match id {
                            StylusRef::ID(id) => {
                                tool.vendor_id() == id.vendor_id() && tool.tool_id() == id.tool_id()
                            }
                            _ => false,
                        })
                    })
                    .cloned()
                    .collect::<Vec<Tool>>(),
            })
            .collect();

        Ok(Cache { tablets, tools })
    }
}

impl Default for CacheBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// The bustype of this device
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub enum BusType {
    USB,
    Bluetooth,
    Serial,
    I2C,
}

impl std::fmt::Display for BusType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                BusType::USB => "usb",
                BusType::Bluetooth => "bluetooth",
                BusType::Serial => "serial",
                BusType::I2C => "i2c",
            }
        )
    }
}

/// A 16-bit Vendor ID
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct VendorId(u16);

impl std::ops::Deref for VendorId {
    type Target = u16;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::LowerHex for VendorId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::LowerHex::fmt(&val, f)
    }
}

impl std::fmt::UpperHex for VendorId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::UpperHex::fmt(&val, f)
    }
}

impl From<VendorId> for u16 {
    fn from(vid: VendorId) -> u16 {
        vid.0
    }
}

impl From<&VendorId> for u16 {
    fn from(vid: &VendorId) -> u16 {
        vid.0
    }
}

impl From<u16> for VendorId {
    fn from(vid: u16) -> VendorId {
        VendorId(vid)
    }
}

/// A 16-bit Product ID
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct ProductId(pub u16);

impl std::ops::Deref for ProductId {
    type Target = u16;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::LowerHex for ProductId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::LowerHex::fmt(&val, f)
    }
}

impl std::fmt::UpperHex for ProductId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::UpperHex::fmt(&val, f)
    }
}

impl From<ProductId> for u16 {
    fn from(pid: ProductId) -> u16 {
        pid.0
    }
}

impl From<&ProductId> for u16 {
    fn from(pid: &ProductId) -> u16 {
        pid.0
    }
}

impl From<u16> for ProductId {
    fn from(pid: u16) -> ProductId {
        ProductId(pid)
    }
}

/// A 32-bit Stylus ID.
///
/// This ID can identify the type of a stylus but
/// is only supported by some tablets.
///
/// Typically styli that support a [ToolId] are also
/// uniquely identifiable at runtime via a unique serial number.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct ToolId(pub u32);

impl std::ops::Deref for ToolId {
    type Target = u32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::LowerHex for ToolId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::LowerHex::fmt(&val, f)
    }
}

impl std::fmt::UpperHex for ToolId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let val = self.0;
        std::fmt::UpperHex::fmt(&val, f)
    }
}

impl From<ToolId> for u32 {
    fn from(pid: ToolId) -> u32 {
        pid.0
    }
}

impl From<&ToolId> for u32 {
    fn from(pid: &ToolId) -> u32 {
        pid.0
    }
}

/// A USB device ID comprising a bus type, vendor id and product id
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct DeviceId {
    bustype: BusType,
    vid: VendorId,
    pid: ProductId,
}

impl DeviceId {
    pub fn bus_type(&self) -> BusType {
        self.bustype
    }

    pub fn vendor_id(&self) -> VendorId {
        self.vid
    }

    pub fn product_id(&self) -> ProductId {
        self.pid
    }
}

/// A stylus ID comprising a vendor and tool id
///
/// Unlike a [DeviceId] a stylus ID may have a 32-bit
/// [ToolId].
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct StylusId {
    vid: VendorId,
    pid: ToolId,
}

impl StylusId {
    pub fn vendor_id(&self) -> VendorId {
        self.vid
    }

    pub fn tool_id(&self) -> ToolId {
        self.pid
    }
}

/// Helper trait to convert between crazy units and
/// sensible ones.
pub trait Units {
    fn inches(&self) -> f32;

    fn cm(&self) -> f32 {
        self.inches() * 2.54
    }
    fn mm(&self) -> f32 {
        self.inches() * 25.4
    }
}

/// A physical length, e.g. the Tablet's [width](Tablet::width) or [height](Tablet::height).
///
/// See the [Units] trait to access the length.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub struct Length {
    inches: usize,
}

impl Units for Length {
    fn inches(&self) -> f32 {
        self.inches as f32
    }
}

/// Specifies how the tablet is integrated.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub enum FormFactor {
    /// The tablet is integrated into a display, e.g.
    /// a Wacom Cintiq.
    ExternalDisplay,
    /// The tablet is integrated into the display of a system, e.g.
    /// a built-in tablet in a laptop.
    InternalDisplay,
    /// The tablet is an external remote like the
    /// Wacom ExpressKey Remote.
    Remote,
}

impl FormFactor {
    fn from_flags(flags: &[parser::IntegrationFlags]) -> Option<FormFactor> {
        let ff = flags.iter().fold(None, |acc, f| match (acc, f) {
            (_, parser::IntegrationFlags::Remote) => Some(FormFactor::Remote),
            (_, parser::IntegrationFlags::System) => Some(FormFactor::InternalDisplay),
            (Some(FormFactor::InternalDisplay), parser::IntegrationFlags::Display) => {
                Some(FormFactor::InternalDisplay)
            }
            (_, parser::IntegrationFlags::Display) => Some(FormFactor::ExternalDisplay),
        });
        ff
    }
}

/// A cache of all tablets known to this crate at the
/// time of building the cache.
///
/// The overwhelmingly vast majority of users do
/// not have a tablet and of the remaining portion the
/// overwhelmingly vast majority of users only have one
/// tablet that is plugged in once and hardly ever removed.
/// Keeping the tablet cache around is not always necessary. It may
/// be more efficient to simply get the tablet and drop the
/// rest of the cache when a new device is detected.
///
/// ```
/// # use tabletdb::{Error, Tablet, TabletInfo, Cache};
/// # use std::path::Path;
/// # fn load(device_path: &Path)  -> Result<(), Error> {
/// // A cache with default include paths
/// let cache = Cache::new()?;
/// let info = TabletInfo::new_from_path(device_path)?;
/// let tablets: Vec<Tablet> = cache
///     .into_iter()
///     .filter(|t| t == &info)
///     .collect::<Vec<Tablet>>();
/// let tablet: &Tablet = tablets.first().unwrap();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Cache {
    tablets: Vec<Tablet>,
    tools: Vec<Tool>,
}

impl Cache {
    /// Create a new tablet cache with default include paths.
    /// This is a shortcut to avoid using the [CacheBuilder]
    /// for cases where modifying the include paths is not required.
    pub fn new() -> Result<Self> {
        CacheBuilder::new().add_default_includes().build()
    }

    /// Returns an iterator over all known tablets.
    ///
    /// Identical to [tablets()](Self::tablets).
    pub fn iter(&self) -> impl Iterator<Item = &Tablet> {
        self.tablets()
    }

    /// Returns an iterator over all known tablets.
    ///
    /// Identical to [iter()](Self::iter).
    pub fn tablets(&self) -> impl Iterator<Item = &Tablet> {
        self.tablets.iter()
    }

    /// Returns an iterator over all known styli.
    pub fn tools(&self) -> impl Iterator<Item = &Tool> {
        self.tools.iter()
    }
}

impl IntoIterator for Cache {
    type Item = Tablet;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.tablets.into_iter()
    }
}

/// Info about a tablet.
///
/// This struct simplifies matching against a tablet in the [Cache].
/// The most convenient way to match an existing physical device is to use
/// [TabletInfo::new_from_path()].
#[derive(Debug)]
pub struct TabletInfo {
    bustype: Option<BusType>,
    vid: Option<VendorId>,
    pid: Option<ProductId>,
    name: Option<String>,
    kernel_name: Option<String>,
    uniq: Option<String>,
}

impl TabletInfo {
    pub fn new() -> TabletInfo {
        TabletInfo {
            bustype: None,
            pid: None,
            vid: None,
            name: None,
            kernel_name: None,
            uniq: None,
        }
    }

    /// Build a [TabletInfo] from the device at the given path. Supports:
    /// - `/dev/input/event0` evdev event nodes
    /// - `/sys/devices/.../input/input0` sysfs input paths
    pub fn new_from_path(path: &Path) -> Result<TabletInfo> {
        let sysfs = if path.starts_with("/dev/input")
            && path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .starts_with("event")
        {
            let node = path.file_name().ok_or(Error::InvalidArgument {
                message: format!("Invalid path {path:?}"),
            })?;
            PathBuf::from("/sys/class/input")
                .join(node)
                .join(String::from("device"))
        } else if path.starts_with("/sys") && path.is_dir() {
            let pathbuf = PathBuf::from(path);
            if pathbuf.join("id").as_path().is_dir() {
                pathbuf
            } else {
                pathbuf.join("device")
            }
        } else {
            return Err(Error::InvalidArgument {
                message: format!("Don't know how to handle {path:?}"),
            });
        };

        let mut bustype = String::new();
        std::fs::File::open(sysfs.join("id").join("bustype"))?.read_to_string(&mut bustype)?;
        let mut vid = String::new();
        std::fs::File::open(sysfs.join("id").join("vendor"))?.read_to_string(&mut vid)?;
        let mut pid = String::new();
        std::fs::File::open(sysfs.join("id").join("product"))?.read_to_string(&mut pid)?;
        let mut name = String::new();
        std::fs::File::open(sysfs.join("name"))?.read_to_string(&mut name)?;
        let mut uniq = String::new();
        std::fs::File::open(sysfs.join("uniq"))?.read_to_string(&mut uniq)?;

        let bustype: BusType = u16::from_str_radix(bustype.as_str().trim(), 16)
            .map_err(|_| Error::IO {
                message: format!("Failed to parse bustype {bustype}"),
            })
            .map(|b| match b {
                0x3 => Ok(BusType::USB),
                0x5 => Ok(BusType::Bluetooth),
                0x11 => Ok(BusType::Serial),
                0x18 => Ok(BusType::I2C),
                _ => Err(Error::InvalidArgument {
                    message: format!("Unsupported bus type {b}"),
                }),
            })??;
        let vid = u16::from_str_radix(vid.as_str().trim(), 16).map_err(|_| Error::IO {
            message: format!("Failed to parse vendor {vid}"),
        })?;
        let pid = u16::from_str_radix(pid.as_str().trim(), 16).map_err(|_| Error::IO {
            message: format!("Failed to parse pid {pid}"),
        })?;

        Ok(TabletInfo::new()
            .bustype(bustype)
            .vid(vid.into())
            .pid(pid.into())
            .kernel_name(name.trim().into())
            .uniq(uniq.trim().into()))
    }

    /// The tablet must match this bustype
    pub fn bustype(mut self, bustype: BusType) -> Self {
        self.bustype = Some(bustype);
        self
    }
    /// The tablet must match this VID
    pub fn vid(mut self, vid: VendorId) -> Self {
        self.vid = Some(vid);
        self
    }
    /// The tablet must match this PID
    pub fn pid(mut self, pid: ProductId) -> Self {
        self.pid = Some(pid);
        self
    }
    /// The tablet must match this name given by the vendor.
    ///
    /// <div class="warning">
    /// This is almost never the name to use, use <em>kernel_name</em> instead.
    /// </div>
    ///
    /// Many Huion, XP-Pen, etc. devices differ in the official name
    /// and the name announced by the firmware to the kernel, e.g.
    /// XP-Pen devices are typically sold as "XP-Pen Foo" but the
    /// firmware (and thus the kernel) labels them as "UGEE Bar".
    ///
    /// The [name()](Self::name) is the one specified in the tablet data
    /// files. There is rarely a need to specify this name unless you want
    /// to load a specific data file. Use [kernel_name()](Self::kernel_name)
    /// instead.
    ///
    /// Even where the device announces itself correctly,
    /// do not use this together with [kernel_name()](Self::kernel_name),
    /// the kernel's name usually has the type appended (e.g. "Pen")
    /// and specifying both the name and match name typically
    /// results in no match.
    pub fn name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }
    /// The tablet must match this kernel name.
    ///
    /// Do not use this together with [name()](Self::name),
    /// the kernel's name usually has the type appended (e.g. "Pen")
    /// and specifying both the name and match name typically
    /// results in no match.
    pub fn kernel_name(mut self, name: String) -> Self {
        self.kernel_name = Some(name);
        self
    }
    /// The tablet must match the UNIQ string given
    pub fn uniq(mut self, uniq: String) -> Self {
        if !uniq.is_empty() {
            self.uniq = Some(uniq);
        }
        self
    }
}

impl Default for TabletInfo {
    fn default() -> Self {
        Self::new()
    }
}

/// An evdev code of `EV_KEY` type (e.g. `BTN_0`, etc.)
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct EvdevCode(u16);

impl EvdevCode {
    pub fn code(&self) -> u16 {
        self.0
    }
}

impl From<&EvdevCode> for u16 {
    fn from(e: &EvdevCode) -> u16 {
        e.0
    }
}

/// A zero-based button index on a tablet
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ButtonIndex(usize);

impl ButtonIndex {
    pub fn number(&self) -> usize {
        self.0
    }
}

/// A button on a tablet.
///
/// This is a button on the "pad" portion
/// of the tablet, not a button on a stylus.
#[derive(Debug, Clone, PartialEq)]
pub struct Button {
    index: ButtonIndex,
    location: Location,
    evdev_code: EvdevCode,
}

impl Button {
    /// The zero-based index of this button
    pub fn index(&self) -> ButtonIndex {
        self.index
    }

    /// An approximate location of this button. This location may be used to
    /// group buttons together in a UI or group buttons together
    /// with one button is the mode switch button.
    pub fn location(&self) -> Location {
        self.location
    }

    /// The code for this button
    pub fn evdev_code(&self) -> EvdevCode {
        self.evdev_code
    }
}

/// The physical location of a button relative to the
/// input area.
///
/// This location is only an approximate guide and may be used to provide some
/// grouping of buttons in a UI.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Location {
    Left,
    Right,
    Top,
    Bottom,
}

/// The type of an extra feature
#[derive(Debug, Clone, PartialEq)]
pub enum FeatureType {
    /// A ring providing absolute finger position, see e.g. the Wacom Intuos Pro series
    Ring,
    /// A touch strip, see e.g. the Wacom Intuos 3
    Strip,
    /// A relative dial, may physically be mouse-wheel-like or ring-like, see
    /// e.g. the Huion Inspiroy 2S or the Huion Inspiroy Dial 2
    Dial,
}

pub trait Feature {
    /// The number of hardware modes expected by this feature.
    ///
    /// This is usually tied to the number of LEDs that will cycle
    /// as the feature cycles through modes but some devices
    /// expect modes but do not have LEDs to represent the current mode.
    ///
    /// Devices that do not require modes return 0, it is up
    /// to the implementation to implement modes anyway.
    fn num_modes(&self) -> usize;

    fn feature_type(&self) -> FeatureType;

    /// 0 for the first ring/strip/dial, 1 for the second one, etc.
    fn index(&self) -> usize;

    /// `true` if this feature has a status LED indicating the current mode
    /// it is in. For devices where this returns false but [num_modes()](Self::num_modes)
    /// returns nonzero a virtual display of the current mode is required.
    fn has_status_led(&self) -> bool;

    /// The buttons associated with this feature, e.g. the button in
    /// the center of a ring. This button is the mode-switch button
    /// and pressing it should change into the next mode (if one button)
    /// or a specific mode (if multiple buttons). If this returns
    /// an empty iterator, no button is directly associated with
    /// this feature.
    fn buttons(&self) -> impl Iterator<Item = &ButtonIndex>;
}

/// A ring providing absolute finger position, see e.g. the Wacom Intuos Pro series
#[derive(Debug, Clone, PartialEq)]
pub struct Ring {
    index: usize,
    num_modes: usize,
    has_status_led: bool,
    buttons: Vec<ButtonIndex>,
}

impl Feature for Ring {
    fn feature_type(&self) -> FeatureType {
        FeatureType::Ring
    }

    fn num_modes(&self) -> usize {
        self.num_modes
    }

    fn index(&self) -> usize {
        self.index
    }

    fn has_status_led(&self) -> bool {
        self.has_status_led
    }

    fn buttons(&self) -> impl Iterator<Item = &ButtonIndex> {
        self.buttons.iter()
    }
}

/// A relative dial
///
/// A relative dial may physically be mouse-wheel-like or ring-like, see
/// e.g. the Huion Inspiroy 2S or the Huion Inspiroy Dial 2
#[derive(Debug, Clone, PartialEq)]
pub struct Dial {
    index: usize,
    num_modes: usize,
    has_status_led: bool,
    buttons: Vec<ButtonIndex>,
}

impl Feature for Dial {
    fn feature_type(&self) -> FeatureType {
        FeatureType::Dial
    }

    fn num_modes(&self) -> usize {
        self.num_modes
    }

    fn index(&self) -> usize {
        self.index
    }

    fn has_status_led(&self) -> bool {
        self.has_status_led
    }

    fn buttons(&self) -> impl Iterator<Item = &ButtonIndex> {
        self.buttons.iter()
    }
}

/// A touch strip, see e.g. the Wacom Intuos 3
#[derive(Debug, Clone, PartialEq)]
pub struct Strip {
    index: usize,
    num_modes: usize,
    has_status_led: bool,
    buttons: Vec<ButtonIndex>,
}

impl Feature for Strip {
    fn feature_type(&self) -> FeatureType {
        FeatureType::Strip
    }

    fn num_modes(&self) -> usize {
        self.num_modes
    }

    fn index(&self) -> usize {
        self.index
    }

    fn has_status_led(&self) -> bool {
        self.has_status_led
    }

    fn buttons(&self) -> impl Iterator<Item = &ButtonIndex> {
        self.buttons.iter()
    }
}

#[derive(Debug, Clone)]
enum StylusRef {
    Group(String),
    ID(StylusId),
}

/// Static information about a tablet.
#[derive(Debug, Clone, PartialEq)]
// pub struct Tablet<O: TabletOwnership> {
pub struct Tablet {
    idx: usize,
    bustype: BusType,
    vid: VendorId,
    pid: ProductId,
    name: String,
    model_name: Option<String>,

    // As used in the DeviceMatch
    kernel_name: Option<String>,
    fw_version: Option<String>,
    layout: Option<PathBuf>,

    paired_id: Option<DeviceId>,

    width: Length,
    height: Length,

    is_reversible: bool,
    has_stylus: bool,
    has_touch: bool,
    has_touchswitch: bool,

    form_factor: Option<FormFactor>,

    buttons: Vec<Button>,
    rings: Vec<Ring>,
    dials: Vec<Dial>,
    strips: Vec<Strip>,

    tools: Vec<Tool>,
}

impl Tablet {
    /// The "official" name of the device.
    /// This is the name given to the device by the
    /// vendor's marketing material and is
    /// suitable for presentation. This name may not
    /// be the name that the tablet's firmware uses and
    /// thus differ from the [kernel_name()](Self::kernel_name()).
    ///
    /// For example, the "Huion Inspiroy 2S" has a [kernel_name()](Self::kernel_name()) of
    /// "HUION Huion Tablet_H641P"
    pub fn name(&self) -> &str {
        self.name.as_str()
    }
    /// A (typically) alpha-numeric model name that serves
    /// to identify a model where the [name()](Self::name) is ambiguous
    /// and used across multiple generations of devices.
    ///
    /// For example, the "Wacom Intuos Pro M" has a model name of
    /// "PTH-660".
    pub fn model_name(&self) -> Option<&str> {
        self.model_name.as_deref()
    }
    /// The kernel name used by this device, if any.
    /// This name may differ from [name()](Self::name) and
    /// is used to identify the device in the system.
    ///
    /// For example, the "Huion Inspiroy 2S" has a [kernel_name()](Self::kernel_name()) of
    /// "HUION Huion Tablet_H641P"
    pub fn kernel_name(&self) -> Option<&str> {
        self.kernel_name.as_deref()
    }

    /// The firmware version string prefix, if any.
    ///
    /// This prefix is used to identify the a device further
    /// where [vendor_id()](Self::vendor_id), [product_id()](Self::product_id)
    /// and the device's [kernel_name()](Self::kernel_name) are not
    /// sufficient to identify the tablet. This is the case for
    /// e.g. many (most?) Huion devices. The firmware string is
    /// a prefix only, e.g. the real firmware version on Huion devices
    /// is typically suffixed with a date.
    ///
    /// This is **not** the tablet's current firmware version, this
    /// data is not queried from the device.
    pub fn firmware_version(&self) -> Option<&str> {
        self.fw_version.as_deref()
    }

    /// An optional path to an SVG file that represents the
    /// layout for this device.
    pub fn layout(&self) -> Option<&Path> {
        self.layout.as_deref()
    }
    pub fn bustype(&self) -> BusType {
        self.bustype
    }
    pub fn vendor_id(&self) -> VendorId {
        self.vid
    }
    pub fn product_id(&self) -> ProductId {
        self.pid
    }
    /// The physical width of the device as advertised on
    /// its marketing material.
    ///
    /// This may refer to the input
    /// area or the whole device, depending on the vendor.
    /// This value should only be used for presentation or
    /// identification, not calculation of input data.
    pub fn width(&self) -> Length {
        self.width
    }
    /// The physical height of the device as advertised on
    /// its marketing material.
    ///
    /// This may refer to the input
    /// area or the whole device, depending on the vendor.
    /// This value should only be used for presentation or
    /// identification, not calculation of input data.
    pub fn height(&self) -> Length {
        self.height
    }

    /// The [DeviceId] of the paired device, if any.
    ///
    /// The paired device is a device that shares the same physical
    /// device with the tablet, e.g. a touchscreen integrated into
    /// a graphics tablet.
    pub fn paired_id(&self) -> Option<DeviceId> {
        self.paired_id
    }

    /// `true` if the device is reversible, i.e. rotating the physical tablet
    /// by 180 degrees moves the button layout to the respective other side.
    /// This flag is typically used to determine if the tablet may be used
    /// in left-handed or right-handed mode.
    ///
    /// Tablets with the buttons at the top are typically **not** reversible,
    /// the button layout in the tablet's natural rotation is equally accessible for left- and for
    /// right-handed users.
    pub fn is_reversible(&self) -> bool {
        self.is_reversible
    }
    /// Returns the special form factor that applies to this tablet, if any.
    ///
    /// The default form factor is an extern tablet (e.g. Wacom Intuos series). Tablets
    /// may be integrated into [a laptop display](FormFactor::InternalDisplay) or
    /// an [external display](FormFactor::ExternalDisplay) or be a
    /// [remote-like](FormFactor::Remote) device.
    pub fn form_factor(&self) -> Option<FormFactor> {
        self.form_factor
    }
    pub fn supports_stylus(&self) -> bool {
        self.has_stylus
    }
    pub fn supports_touch(&self) -> bool {
        self.has_touch
    }
    /// The tablet has a switch to disable touch.
    pub fn has_touchswitch(&self) -> bool {
        self.has_touchswitch
    }
    pub fn buttons(&self) -> impl Iterator<Item = &Button> {
        self.buttons.iter()
    }

    //pub fn find_button(&self, index: &ButtonIndex) -> Option<&Button> {
    //    self.buttons.iter().find(|b| b.index == *index)
    //}

    pub fn rings(&self) -> impl Iterator<Item = &Ring> {
        self.rings.iter()
    }

    pub fn dials(&self) -> impl Iterator<Item = &Dial> {
        self.dials.iter()
    }

    pub fn strips(&self) -> impl Iterator<Item = &Strip> {
        self.strips.iter()
    }

    /// Returns an iterator over the styli available on this tablet.
    pub fn tools(&self) -> impl Iterator<Item = &Tool> {
        self.tools.iter()
    }

    /// Match a tablet against the info.
    ///
    /// Any field set in the [TabletInfo] is matched against the
    /// respective field in the [Tablet] - fields unset are ignored.
    /// The caller is required to set sufficient fields to get a
    /// unique match, e.g. only setting the [TabletInfo::bustype()] will
    /// match against any device with that bustype.
    pub fn matches(&self, info: &TabletInfo) -> bool {
        info.bustype.map(|b| b == self.bustype).unwrap_or(true)
            && info.vid.map(|v| v == self.vid).unwrap_or(true)
            && info.pid.map(|p| p == self.pid).unwrap_or(true)
            && info.name.as_ref().map(|n| n == &self.name).unwrap_or(true)
            && info
                .kernel_name
                .as_ref()
                .map(|n| self.kernel_name.as_ref().map(|kn| n == kn).unwrap_or(true))
                .unwrap_or(true)
    }
}

impl PartialEq<TabletInfo> for Tablet {
    fn eq(&self, other: &TabletInfo) -> bool {
        self.matches(other)
    }
}

/// An approximate description of the stylus type
///
/// This type may be used to e.g. present differnent icons
/// of a stylus depending on a type.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum StylusType {
    /// A standard pen-like stylus
    General,
    Inking,
    /// A tool that is used like an airbrush (i.e. it may
    /// never touch the surface). Airbrush tools may have a
    /// slider.
    Airbrush,
    Classic,
    Marker,
    Stroke,
    /// A pen that supports rotation axes in addition
    /// to the typical x/y and tilt
    Pen3D,
    Mobile,
}

impl std::fmt::Display for StylusType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                StylusType::General => "General",
                StylusType::Inking => "Inking",
                StylusType::Airbrush => "Airbrush",
                StylusType::Classic => "Classic",
                StylusType::Marker => "Marker",
                StylusType::Stroke => "Stroke",
                StylusType::Pen3D => "Pen3D",
                StylusType::Mobile => "Mobile",
            }
        )
    }
}

/// Type of eraser on a stylus
#[derive(Debug, Copy, Clone, PartialEq)]
enum EraserType {
    /// Eraser is a separate tool on the opposite end of the stylus
    Invert,
    /// Eraser is a button alongside any other stylus buttons
    Button,
}

/// A supported axis type
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Axis {
    Pressure,
    Tilt,
    Distance,
    Slider,
    RotationZ,
    Wheel,
}

/// A button on a tool
///
/// This is currently a placeholder struct only but it may
/// get fields and methods in the future.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolButton {}

pub trait ToolFeatures {
    /// The name of this tool given by the manufacturer,
    /// e.g. "Grip Pen". This name is suitable for presentation.
    ///
    /// This name may not be unique.
    fn name(&self) -> &str;
    fn vendor_id(&self) -> VendorId;
    fn tool_id(&self) -> ToolId;
    fn buttons(&self) -> &[ToolButton];
    fn axes(&self) -> &[Axis];
}

/// A physical tool that may be used on a device.
///
/// This is a rough grouping only, more information about each tool may be available
/// in the contained struct.
#[derive(Debug, Clone, PartialEq)]
pub enum Tool {
    /// A stylus-like tool without an eraser at the other entry.
    ///
    /// Such a stylus may have an eraser button, see [Stylus::has_eraser_button()],
    /// and *behave* like an eraser when that button is pressed. However, that
    /// eraser does not appear as separate tool in the system.
    Stylus(Stylus),
    /// A stylus-like tool with an eraser at the back.
    ///
    /// Such a stylus must not have an [eraser button](Stylus::has_eraser_button())
    /// and inverting the stylus will present the [Eraser] tool. This tool may
    /// have a different [VendorId] and [ToolId] to the [Stylus].
    StylusWithEraser(Stylus, Eraser),
    /// A mouse-like device
    ///
    /// These tools are of primarily historical interest, they are no longer
    /// for sale.
    Mouse(Mouse),
}

// A convenience implementation that returns the corresponding
// items from the [Stylus] or [Mouse], ignoring the [Eraser], if any.
impl ToolFeatures for Tool {
    /// A convenience method wrapping [Stylus::name()] for this tool,
    /// ignoring the eraser (if any)
    fn name(&self) -> &str {
        match self {
            Tool::Stylus(s) => s.name(),
            Tool::StylusWithEraser(s, _) => s.name(),
            Tool::Mouse(m) => m.name(),
        }
    }

    /// A convenience method wrapping [Stylus::vendor_id()] for this tool,
    /// ignoring the eraser (if any)
    fn vendor_id(&self) -> VendorId {
        match self {
            Tool::Stylus(s) => s.vendor_id(),
            Tool::StylusWithEraser(s, _) => s.vendor_id(),
            Tool::Mouse(m) => m.vendor_id(),
        }
    }
    /// A convenience method wrapping [Stylus::tool_id()] for this tool,
    /// ignoring the eraser (if any)
    fn tool_id(&self) -> ToolId {
        match self {
            Tool::Stylus(s) => s.tool_id(),
            Tool::StylusWithEraser(s, _) => s.tool_id(),
            Tool::Mouse(m) => m.tool_id(),
        }
    }

    fn axes(&self) -> &[Axis] {
        match self {
            Tool::Stylus(s) => s.axes(),
            Tool::StylusWithEraser(s, _) => s.axes(),
            Tool::Mouse(m) => m.axes(),
        }
    }

    /// A convenience method wrapping [Stylus::buttons()] for this tool,
    /// ignoring the eraser (if any)
    fn buttons(&self) -> &[ToolButton] {
        match self {
            Tool::Stylus(s) => s.buttons(),
            Tool::StylusWithEraser(s, _) => s.buttons(),
            Tool::Mouse(m) => m.buttons(),
        }
    }
}

/// A mouse-like device
///
/// These tools are of primarily historical interest, they are no longer
/// for sale.
#[derive(Debug, Clone, PartialEq)]
pub struct Mouse {
    idx: usize,
    name: String,
    id: StylusId,
    axes: Vec<Axis>,
    buttons: Vec<ToolButton>,
    has_lens: bool,
}

impl ToolFeatures for Mouse {
    /// The name of this eraser given by the manufacturer,
    /// e.g. "Grip Pen". This name is suitable for presentation.
    ///
    /// This name may not be unique. Using this name is not
    /// usually required, the eraser does not live without
    /// its corresponding stylus and the stylus name is a better
    /// option for presentation.
    fn name(&self) -> &str {
        &self.name
    }
    /// The vendor ID of the eraser. Theoretically this may
    /// be different to the [Stylus::vendor_id()] but no
    /// such devices have been observed in the wild yet.
    fn vendor_id(&self) -> VendorId {
        self.id.vid
    }
    /// The tool ID of the eraser.
    fn tool_id(&self) -> ToolId {
        self.id.pid
    }
    fn axes(&self) -> &[Axis] {
        &self.axes
    }
    /// The buttons on this Mouse
    fn buttons(&self) -> &[ToolButton] {
        &self.buttons
    }
}

impl Mouse {
    pub fn has_lens(&self) -> bool {
        self.has_lens
    }
}

/// An eraser is a tool intended for erasing.
///
/// This is represented in the *physical* design of the tool.
/// Typically an eraser is on the back end of a [Stylus] to
/// emulate a traditional pencil + eraser setup.
///
/// Erasers never exist on their own, they are part of
/// a [Tool::StylusWithEraser] and always coupled with
/// a corresponding [Stylus].
#[derive(Debug, Clone, PartialEq)]
pub struct Eraser {
    idx: usize,
    name: String,
    id: StylusId,
    eraser_type: EraserType,
    axes: Vec<Axis>,
    buttons: Vec<ToolButton>,
}

impl ToolFeatures for Eraser {
    /// The name of this eraser given by the manufacturer,
    /// e.g. "Grip Pen". This name is suitable for presentation.
    ///
    /// This name may not be unique. Using this name is not
    /// usually required, the eraser does not live without
    /// its corresponding stylus and the stylus name is a better
    /// option for presentation.
    fn name(&self) -> &str {
        &self.name
    }
    /// The vendor ID of the eraser. Theoretically this may
    /// be different to the [Stylus::vendor_id()] but no
    /// such devices have been observed in the wild yet.
    fn vendor_id(&self) -> VendorId {
        self.id.vid
    }
    /// The tool ID of the eraser.
    fn tool_id(&self) -> ToolId {
        self.id.pid
    }
    fn axes(&self) -> &[Axis] {
        &self.axes
    }
    /// The buttons on this Eraser, if any
    fn buttons(&self) -> &[ToolButton] {
        &self.buttons
    }
}

/// A stylus describes one stylus-like tool available on a tablet.
#[derive(Debug, Clone, PartialEq)]
pub struct Stylus {
    idx: usize,
    name: String,
    id: StylusId,
    stylus_type: StylusType,
    eraser_type: Option<EraserType>,
    buttons: Vec<ToolButton>,
    axes: Vec<Axis>,
}

impl ToolFeatures for Stylus {
    /// The name of this stylus given by the manufacturer,
    /// e.g. "Grip Pen". This name is suitable for presentation.
    ///
    /// This name may not be unique.
    fn name(&self) -> &str {
        &self.name
    }
    fn vendor_id(&self) -> VendorId {
        self.id.vid
    }
    fn tool_id(&self) -> ToolId {
        self.id.pid
    }
    fn axes(&self) -> &[Axis] {
        &self.axes
    }
    /// The buttons on this Stylus
    ///
    /// Note that many styli have an [eraser button](Stylus::has_eraser_button)
    /// that the firmware enforces eraser-like behavior for,
    /// see the
    /// [Windows Pen States](https://learn.microsoft.com/en-us/windows-hardware/design/component-guidelines/windows-pen-states)
    /// for details.
    /// This button is excluded from the number of buttons.
    fn buttons(&self) -> &[ToolButton] {
        &self.buttons
    }
}

impl Stylus {
    /// Returns true if one of the physical buttons on the stylus triggers
    /// eraser behaviour. See the
    /// [Windows Pen States](https://learn.microsoft.com/en-us/windows-hardware/design/component-guidelines/windows-pen-states)
    /// for details.
    pub fn has_eraser_button(&self) -> bool {
        !self.eraser_type.is_none_or(|t| t != EraserType::Button)
    }

    pub fn stylus_type(&self) -> StylusType {
        self.stylus_type
    }
}

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

    #[test]
    fn hex_format() {
        let vid = VendorId(0x12ab);
        assert_eq!(format!("{vid:x}"), "12ab");
        assert_eq!(format!("{vid:X}"), "12AB");
        let pid = ProductId(0xbc12);
        assert_eq!(format!("{pid:x}"), "bc12");
        assert_eq!(format!("{pid:X}"), "BC12");
        let tid = ToolId(0xd12e);
        assert_eq!(format!("{tid:x}"), "d12e");
        assert_eq!(format!("{tid:X}"), "D12E");
    }
}