-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathuhid_backend.cpp
More file actions
3393 lines (2980 loc) · 116 KB
/
Copy pathuhid_backend.cpp
File metadata and controls
3393 lines (2980 loc) · 116 KB
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
/**
* @file src/platform/linux/uhid_backend.cpp
* @brief Linux UHID backend definitions.
*/
// standard includes
#include <algorithm>
#include <array>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <iomanip>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <numbers>
#include <optional>
#include <set>
#include <span>
#include <sstream>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
// platform includes
#include <fcntl.h>
#ifndef __user
#define __user
#endif
#include <linux/input.h>
#include <linux/uinput.h>
#if defined(__linux__)
#include <linux/uhid.h>
#endif
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#if defined(LIBVIRTUALHID_HAVE_XTEST)
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#endif
// lib includes
#include <libevdev/libevdev-uinput.h>
#include <libevdev/libevdev.h>
// local includes
#include "core/backend.hpp"
#if defined(__linux__)
#include "shared/playstation_feature_reports.hpp"
#endif
#include <libvirtualhid/profiles.hpp>
#include <libvirtualhid/report.hpp>
namespace lvh::detail {
namespace { // NOSONAR(cpp:S1000): Linux backend internals need internal linkage; tests include this file with syscall overrides.
#if defined(__linux__)
constexpr auto uhid_path = "/dev/uhid";
#endif
#if defined(__FreeBSD__)
constexpr std::array uinput_paths {"/dev/input/uinput", "/dev/uinput"};
#else
constexpr std::array uinput_paths {"/dev/uinput"};
#endif
constexpr auto absolute_axis_max = 65535;
constexpr auto touch_axis_max_x = 19200;
constexpr auto touch_axis_max_y = 10800;
constexpr auto touch_max_contacts = 16;
constexpr auto touch_pressure_max = 253;
constexpr auto tablet_pressure_max = 4096;
constexpr auto tablet_distance_max = 1024;
constexpr auto tablet_resolution = 28;
constexpr auto poll_timeout_ms = 100;
constexpr auto uinput_feedback_startup_delay = std::chrono::milliseconds {100};
constexpr auto xbox_trigger_max = 255;
// The Bluetooth bus selects the sparse evdev mapping that matches the
// button capabilities exposed by these Xbox uinput devices.
constexpr auto xbox_sparse_uinput_bus = BUS_BLUETOOTH;
constexpr std::uint16_t xbox_wireless_uinput_product_id = 0x0B20;
constexpr std::uint16_t xbox_series_uinput_product_id = 0x0B13;
#if defined(__linux__)
namespace ps = playstation_feature_reports;
constexpr auto playstation_periodic_report_ms = 10;
constexpr auto uhid_start_timeout = std::chrono::seconds {5};
#endif
int system_access(const char *path, int mode) {
return ::access(path, mode);
}
int system_open(const char *path, int flags) {
return ::open(path, flags);
}
int system_close(int fd) {
return ::close(fd);
}
std::ptrdiff_t system_write(int fd, std::span<const std::byte> buffer) {
return static_cast<std::ptrdiff_t>(::write(fd, buffer.data(), buffer.size()));
}
int system_ioctl(int fd, unsigned long request, unsigned long argument = 0) {
return ::ioctl(fd, request, argument);
}
int system_poll(pollfd *descriptors, nfds_t descriptor_count, int timeout) {
return ::poll(descriptors, descriptor_count, timeout);
}
std::ptrdiff_t system_read(int fd, std::span<std::byte> buffer) {
return static_cast<std::ptrdiff_t>(::read(fd, buffer.data(), buffer.size()));
}
std::string errno_message(int error) {
return std::error_code(error, std::generic_category()).message();
}
OperationStatus system_error_status(ErrorCode code, const std::string &operation, int error) {
return OperationStatus::failure(code, operation + ": " + errno_message(error));
}
bool can_access_uhid() {
#if defined(__linux__)
return system_access(uhid_path, R_OK | W_OK) == 0;
#else
return false;
#endif
}
bool can_access_uinput() {
return std::ranges::any_of(uinput_paths, [](const char *path) {
return system_access(path, R_OK | W_OK) == 0;
});
}
int open_uinput(int flags) {
for (const auto *path : uinput_paths) {
const auto fd = system_open(path, flags);
if (fd >= 0) {
return fd;
}
}
return -1;
}
#if defined(__linux__)
std::array<std::uint8_t, 6> generated_mac_address(DeviceId id) {
return {
0x02,
0x00,
static_cast<std::uint8_t>((id >> 24U) & 0xFFU),
static_cast<std::uint8_t>((id >> 16U) & 0xFFU),
static_cast<std::uint8_t>((id >> 8U) & 0xFFU),
static_cast<std::uint8_t>(id & 0xFFU),
};
}
std::optional<std::array<std::uint8_t, 6>> parse_mac_address(const std::string &text) {
std::array<std::uint8_t, 6> mac {};
std::istringstream stream {text};
for (std::size_t index = 0; index < mac.size(); ++index) {
unsigned int value = 0;
stream >> std::hex >> value;
if (!stream || value > 0xFFU) {
return std::nullopt;
}
mac[index] = static_cast<std::uint8_t>(value);
if (index + 1U < mac.size()) {
char separator = 0;
stream >> separator;
if (separator != ':') {
return std::nullopt;
}
}
}
return mac;
}
std::string format_mac_address(const std::array<std::uint8_t, 6> &mac) {
std::ostringstream stream;
stream << std::hex << std::setfill('0');
for (std::size_t index = 0; index < mac.size(); ++index) {
if (index != 0) {
stream << ':';
}
stream << std::setw(2) << static_cast<unsigned int>(mac[index]);
}
return stream.str();
}
std::uint32_t crc32(std::span<const std::uint8_t> buffer, std::uint32_t seed = 0) {
auto crc = seed ^ 0xFFFFFFFFU;
for (const auto byte : buffer) {
crc ^= byte;
for (auto bit = 0; bit < 8; ++bit) {
const auto mask = 0U - (crc & 1U);
crc = (crc >> 1U) ^ (0xEDB88320U & mask);
}
}
return crc ^ 0xFFFFFFFFU;
}
std::uint32_t playstation_crc_seed(std::uint8_t seed) {
return crc32(std::span {&seed, 1U});
}
void write_u32_le(std::uint8_t *buffer, std::uint32_t value) {
buffer[0] = static_cast<std::uint8_t>(value & 0xFFU);
buffer[1] = static_cast<std::uint8_t>((value >> 8U) & 0xFFU);
buffer[2] = static_cast<std::uint8_t>((value >> 16U) & 0xFFU);
buffer[3] = static_cast<std::uint8_t>((value >> 24U) & 0xFFU);
}
#endif
#if defined(__linux__)
bool is_playstation_profile(GamepadProfileKind kind) {
return kind == GamepadProfileKind::dualshock4 || kind == GamepadProfileKind::dualsense;
}
#endif
bool uses_uinput_gamepad_profile(GamepadProfileKind kind) {
switch (kind) {
using enum GamepadProfileKind;
case generic:
case xbox_360:
case xbox_one:
case xbox_series:
case switch_pro:
return true;
case dualshock4:
case dualsense:
#if defined(__FreeBSD__)
return true;
#else
return false;
#endif
}
return false;
}
std::optional<int> uinput_misc1_button(GamepadProfileKind kind) {
switch (kind) {
using enum GamepadProfileKind;
case generic:
case xbox_series:
#if defined(__FreeBSD__)
case dualsense:
#endif
return KEY_RECORD;
case switch_pro:
return BTN_Z;
case xbox_360:
case xbox_one:
case dualshock4:
#if !defined(__FreeBSD__)
case dualsense:
#endif
return std::nullopt;
}
return std::nullopt;
}
bool uses_sparse_uinput_button_slots(GamepadProfileKind kind) {
using enum GamepadProfileKind;
return kind == xbox_360 || kind == xbox_one || kind == xbox_series;
}
std::uint16_t to_uhid_bus(BusType bus_type) {
if (bus_type == BusType::bluetooth) {
return BUS_BLUETOOTH;
}
return BUS_USB;
}
#if defined(__linux__)
std::uint16_t to_uhid_bus(const DeviceProfile &profile) {
if (profile.gamepad_kind == GamepadProfileKind::switch_pro) {
return BUS_VIRTUAL;
}
return to_uhid_bus(profile.bus_type);
}
std::string_view uhid_gamepad_name(const DeviceProfile &profile) {
// Steam's PlayStation HID path expects Sony's native product name. Keep
// consumer branding out of the Linux transport identity while preserving
// the requested descriptor, bus, and report framing.
if (is_playstation_profile(profile.gamepad_kind)) {
return "Wireless Controller";
}
return profile.name;
}
#endif
std::uint16_t to_uinput_bus(BusType bus_type) {
return to_uhid_bus(bus_type);
}
#if defined(__linux__)
template<std::size_t Size>
void copy_string(__u8 (&destination)[Size], std::string_view source) {
const auto length = std::min(source.size(), Size - 1);
std::memcpy(destination, source.data(), length);
destination[length] = 0;
}
template<std::size_t Size>
void copy_string(char (&destination)[Size], std::string_view source) {
const auto length = std::min(source.size(), Size - 1);
std::memcpy(destination, source.data(), length);
destination[length] = 0;
}
template<std::size_t Size>
void copy_string(std::array<char, Size> &destination, std::string_view source) {
const auto length = std::min(source.size(), Size - 1);
std::memcpy(destination.data(), source.data(), length);
destination[length] = 0;
}
#endif
std::optional<std::string> read_first_line(const std::filesystem::path &path) {
std::ifstream file {path};
if (!file) {
return std::nullopt;
}
std::string line;
std::getline(file, line);
return line;
}
void append_node(std::vector<DeviceNode> &nodes, DeviceNodeKind kind, const std::filesystem::path &path) {
nodes.push_back({.kind = kind, .path = path.string()});
}
#if defined(__linux__)
void append_node_if_missing(std::vector<DeviceNode> &nodes, DeviceNodeKind kind, const std::filesystem::path &path) {
const auto path_string = path.string();
const auto existing = std::ranges::find_if(nodes, [kind, &path_string](const DeviceNode &node) {
return node.kind == kind && node.path == path_string;
});
if (existing == nodes.end()) {
nodes.push_back({.kind = kind, .path = path_string});
}
}
#endif
bool hidraw_name_matches(const std::filesystem::path &uevent_path, std::string_view name) {
std::ifstream file {uevent_path};
if (!file) {
return false;
}
std::string line;
while (std::getline(file, line)) {
constexpr std::string_view key {"HID_NAME="};
if (line.starts_with(key)) {
return line.size() == key.size() + name.size() && line.ends_with(name);
}
}
return false;
}
#if defined(__linux__)
bool hidraw_metadata_matches(
const std::filesystem::path &uevent_path,
std::string_view name,
std::string_view physical_id,
std::string_view unique_id
) {
std::ifstream file {uevent_path};
if (!file) {
return false;
}
auto actual_name = std::optional<std::string> {};
auto actual_physical_id = std::optional<std::string> {};
auto actual_unique_id = std::optional<std::string> {};
std::string line;
while (std::getline(file, line)) {
if (constexpr std::string_view name_key {"HID_NAME="}; line.starts_with(name_key)) {
actual_name = line.substr(name_key.size());
continue;
}
if (constexpr std::string_view phys_key {"HID_PHYS="}; line.starts_with(phys_key)) {
actual_physical_id = line.substr(phys_key.size());
continue;
}
if (constexpr std::string_view uniq_key {"HID_UNIQ="}; line.starts_with(uniq_key)) {
actual_unique_id = line.substr(uniq_key.size());
}
}
auto matched_stable_metadata = false;
if (!physical_id.empty() && actual_physical_id.has_value()) {
matched_stable_metadata = true;
if (*actual_physical_id != physical_id) {
return false;
}
}
if (!unique_id.empty() && actual_unique_id.has_value()) {
matched_stable_metadata = true;
if (*actual_unique_id != unique_id) {
return false;
}
}
if (matched_stable_metadata) {
return true;
}
return !name.empty() && actual_name.has_value() && *actual_name == name;
}
std::vector<DeviceNode> discover_hidraw_nodes_by_metadata(
std::string_view name,
std::string_view physical_id,
std::string_view unique_id,
const std::filesystem::path &hidraw_root = "/sys/class/hidraw"
) {
using enum DeviceNodeKind;
std::vector<DeviceNode> nodes;
std::error_code error;
if (!std::filesystem::exists(hidraw_root, error)) {
return nodes;
}
for (std::filesystem::directory_iterator it {hidraw_root, error}, end; !error && it != end; it.increment(error)) {
if (!hidraw_metadata_matches(it->path() / "device" / "uevent", name, physical_id, unique_id)) {
continue;
}
append_node(nodes, hidraw, std::filesystem::path {"/dev"} / it->path().filename());
append_node(nodes, sysfs, it->path());
}
return nodes;
}
#endif
std::vector<DeviceNode> discover_input_nodes_by_name(
const std::string &name,
const std::filesystem::path &input_root,
const std::filesystem::path &hidraw_root
) {
using enum DeviceNodeKind;
std::vector<DeviceNode> nodes;
if (name.empty()) {
return nodes;
}
std::error_code error;
if (std::filesystem::exists(input_root, error)) {
for (std::filesystem::directory_iterator it {input_root, error}, end; !error && it != end; it.increment(error)) {
const auto filename = it->path().filename().string();
const auto is_event_node = filename.starts_with("event");
if (const auto is_joystick_node = filename.starts_with("js"); !is_event_node && !is_joystick_node) {
continue;
}
if (const auto sysfs_name = read_first_line(it->path() / "device" / "name"); !sysfs_name || *sysfs_name != name) {
continue;
}
append_node(
nodes,
is_event_node ? input_event : joystick,
std::filesystem::path {"/dev/input"} / it->path().filename()
);
append_node(nodes, sysfs, it->path());
}
}
if (std::filesystem::exists(hidraw_root, error)) {
for (std::filesystem::directory_iterator it {hidraw_root, error}, end; !error && it != end; it.increment(error)) {
if (!hidraw_name_matches(it->path() / "device" / "uevent", name)) {
continue;
}
append_node(nodes, hidraw, std::filesystem::path {"/dev"} / it->path().filename());
append_node(nodes, sysfs, it->path());
}
}
return nodes;
}
std::vector<DeviceNode> discover_input_nodes_by_name(const std::string &name) {
return discover_input_nodes_by_name(name, "/sys/class/input", "/sys/class/hidraw");
}
OperationStatus ioctl_status(const std::string &operation) {
return system_error_status(ErrorCode::backend_failure, operation, errno);
}
template<typename Target, std::size_t Size>
std::optional<Target> mapped_keyboard_code(
KeyboardKeyCode key_code,
const std::array<std::pair<KeyboardKeyCode, Target>, Size> &mappings
) {
const auto it = std::ranges::find_if(mappings, [key_code](const auto &mapping) {
return mapping.first == key_code;
});
if (it == mappings.end()) {
return std::nullopt;
}
return it->second;
}
int key_code_to_linux(KeyboardKeyCode key_code) {
static constexpr std::array<std::pair<KeyboardKeyCode, int>, 47> special_keys {{
{0x08, KEY_BACKSPACE},
{0x09, KEY_TAB},
{0x0D, KEY_ENTER},
{0x10, KEY_LEFTSHIFT},
{0xA0, KEY_LEFTSHIFT},
{0x11, KEY_LEFTCTRL},
{0xA2, KEY_LEFTCTRL},
{0x12, KEY_LEFTALT},
{0xA4, KEY_LEFTALT},
{0x14, KEY_CAPSLOCK},
{0x1B, KEY_ESC},
{0x20, KEY_SPACE},
{0x21, KEY_PAGEUP},
{0x22, KEY_PAGEDOWN},
{0x23, KEY_END},
{0x24, KEY_HOME},
{0x25, KEY_LEFT},
{0x26, KEY_UP},
{0x27, KEY_RIGHT},
{0x28, KEY_DOWN},
{0x2C, KEY_SYSRQ},
{0x2D, KEY_INSERT},
{0x2E, KEY_DELETE},
{0x5B, KEY_LEFTMETA},
{0x5C, KEY_RIGHTMETA},
{0x6A, KEY_KPASTERISK},
{0x6B, KEY_KPPLUS},
{0x6D, KEY_KPMINUS},
{0x6E, KEY_KPDOT},
{0x6F, KEY_KPSLASH},
{0x90, KEY_NUMLOCK},
{0x91, KEY_SCROLLLOCK},
{0xA1, KEY_RIGHTSHIFT},
{0xA3, KEY_RIGHTCTRL},
{0xA5, KEY_RIGHTALT},
{0xBA, KEY_SEMICOLON},
{0xBB, KEY_EQUAL},
{0xBC, KEY_COMMA},
{0xBD, KEY_MINUS},
{0xBE, KEY_DOT},
{0xBF, KEY_SLASH},
{0xC0, KEY_GRAVE},
{0xDB, KEY_LEFTBRACE},
{0xDC, KEY_BACKSLASH},
{0xDD, KEY_RIGHTBRACE},
{0xDE, KEY_APOSTROPHE},
{0xE2, KEY_102ND},
}};
if (const auto linux_key = mapped_keyboard_code(key_code, special_keys); linux_key.has_value()) {
return linux_key.value();
}
if (key_code >= 0x30 && key_code <= 0x39) {
static constexpr std::array digit_keys {
KEY_0,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
};
return digit_keys[key_code - 0x30];
}
if (key_code >= 0x41 && key_code <= 0x5A) {
static constexpr std::array letter_keys {
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_H,
KEY_I,
KEY_J,
KEY_K,
KEY_L,
KEY_M,
KEY_N,
KEY_O,
KEY_P,
KEY_Q,
KEY_R,
KEY_S,
KEY_T,
KEY_U,
KEY_V,
KEY_W,
KEY_X,
KEY_Y,
KEY_Z,
};
return letter_keys[key_code - 0x41];
}
if (key_code >= 0x60 && key_code <= 0x69) {
static constexpr std::array keypad_digit_keys {
KEY_KP0,
KEY_KP1,
KEY_KP2,
KEY_KP3,
KEY_KP4,
KEY_KP5,
KEY_KP6,
KEY_KP7,
KEY_KP8,
KEY_KP9,
};
return keypad_digit_keys[key_code - 0x60];
}
if (key_code >= 0x70 && key_code <= 0x87) {
static constexpr std::array function_keys {
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12,
KEY_F13,
KEY_F14,
KEY_F15,
KEY_F16,
KEY_F17,
KEY_F18,
KEY_F19,
KEY_F20,
KEY_F21,
KEY_F22,
KEY_F23,
KEY_F24,
};
return function_keys[key_code - 0x70];
}
return -1;
}
int mouse_button_to_linux(MouseButton button) {
switch (button) {
using enum MouseButton;
case left:
return BTN_LEFT;
case middle:
return BTN_MIDDLE;
case right:
return BTN_RIGHT;
case side:
return BTN_SIDE;
case extra:
return BTN_EXTRA;
}
return BTN_LEFT;
}
int scale_absolute_axis(std::int32_t value, std::int32_t limit) {
if (limit <= 0) {
return 0;
}
const auto clamped = std::clamp(value, 0, limit);
const auto numerator = static_cast<std::int64_t>(clamped) * absolute_axis_max;
return static_cast<int>(numerator / limit);
}
int scale_normalized_axis(float value, int maximum) {
return static_cast<int>(std::lround(std::clamp(value, 0.0F, 1.0F) * static_cast<float>(maximum)));
}
int clamp_degrees(std::int32_t value) {
return std::clamp(value, -90, 90);
}
int tablet_tilt_units(float degrees) {
const auto radians = std::clamp(degrees, -90.0F, 90.0F) * static_cast<float>(std::numbers::pi) / 180.0F;
return static_cast<int>(std::lround(radians * tablet_resolution));
}
std::vector<std::uint32_t> decode_utf8(std::string_view text) {
std::vector<std::uint32_t> codepoints;
const auto bytes = std::as_bytes(std::span {text.data(), text.size()});
for (std::size_t i = 0; i < text.size();) {
const auto first = bytes[i];
std::uint32_t codepoint = 0;
std::size_t length = 0;
if (const auto first_value = std::to_integer<std::uint32_t>(first); first_value <= 0x7FU) {
codepoint = first_value;
length = 1;
} else if ((first & std::byte {0xE0}) == std::byte {0xC0}) {
codepoint = std::to_integer<std::uint32_t>(first & std::byte {0x1F});
length = 2;
} else if ((first & std::byte {0xF0}) == std::byte {0xE0}) {
codepoint = std::to_integer<std::uint32_t>(first & std::byte {0x0F});
length = 3;
} else if ((first & std::byte {0xF8}) == std::byte {0xF0}) {
codepoint = std::to_integer<std::uint32_t>(first & std::byte {0x07});
length = 4;
} else {
++i;
continue;
}
if (i + length > text.size()) {
break;
}
bool valid = true;
for (std::size_t offset = 1; offset < length; ++offset) {
const auto next = bytes[i + offset];
if ((next & std::byte {0xC0}) != std::byte {0x80}) {
valid = false;
break;
}
codepoint = (codepoint << 6U) | std::to_integer<std::uint32_t>(next & std::byte {0x3F});
}
if (valid) {
codepoints.push_back(codepoint);
i += length;
} else {
++i;
}
}
return codepoints;
}
std::string uppercase_hex(std::uint32_t codepoint) {
return std::format("{:X}", codepoint);
}
KeyboardKeyCode hex_digit_key_code(char digit) {
if (digit >= '0' && digit <= '9') {
return static_cast<KeyboardKeyCode>(0x30 + (digit - '0'));
}
return static_cast<KeyboardKeyCode>(0x41 + (digit - 'A'));
}
template<std::size_t Count, class SubmitKeyEvent>
OperationStatus submit_keyboard_events(const std::array<KeyboardEvent, Count> &events, SubmitKeyEvent &submit_key_event) {
for (const auto &event : events) {
if (const auto status = submit_key_event(event); !status.ok()) {
return status;
}
}
return OperationStatus::success();
}
template<class SubmitKeyEvent>
OperationStatus type_text_with_unicode_hex(std::string_view text, SubmitKeyEvent submit_key_event) {
static constexpr std::array<KeyboardEvent, 6> unicode_hex_prefix {{
{.key_code = 0xA2, .pressed = true},
{.key_code = 0xA0, .pressed = true},
{.key_code = 0x55, .pressed = true},
{.key_code = 0x55, .pressed = false},
{.key_code = 0xA0, .pressed = false},
{.key_code = 0xA2, .pressed = false},
}};
static constexpr std::array<KeyboardEvent, 2> unicode_hex_suffix {{
{.key_code = 0x0D, .pressed = true},
{.key_code = 0x0D, .pressed = false},
}};
for (const auto codepoint : decode_utf8(text)) {
const auto hex = uppercase_hex(codepoint);
if (const auto status = submit_keyboard_events(unicode_hex_prefix, submit_key_event); !status.ok()) {
return status;
}
for (const auto digit : hex) {
const auto key_code = hex_digit_key_code(digit);
const std::array<KeyboardEvent, 2> digit_events {{
{.key_code = key_code, .pressed = true},
{.key_code = key_code, .pressed = false},
}};
if (const auto status = submit_keyboard_events(digit_events, submit_key_event); !status.ok()) {
return status;
}
}
if (const auto status = submit_keyboard_events(unicode_hex_suffix, submit_key_event); !status.ok()) {
return status;
}
}
return OperationStatus::success();
}
[[maybe_unused]] int legacy_scroll_steps(std::int32_t distance) {
if (distance == 0) {
return 0;
}
if (const auto steps = distance / 120; steps != 0) {
return steps;
}
return distance > 0 ? 1 : -1;
}
/**
* @brief Shared Linux uinput device wrapper.
*/
class UinputDevice {
public:
explicit UinputDevice(int file_descriptor):
fd_ {file_descriptor} {}
UinputDevice(const UinputDevice &) = delete;
UinputDevice &operator=(const UinputDevice &) = delete;
UinputDevice(UinputDevice &&) noexcept = delete;
UinputDevice &operator=(UinputDevice &&) noexcept = delete;
virtual ~UinputDevice() {
static_cast<void>(close_uinput("uinput device"));
}
protected:
OperationStatus create_uinput_device(const DeviceProfile &profile, DeviceId id);
std::vector<DeviceNode> uinput_device_nodes(const std::string &device_name) const;
OperationStatus emit_event(std::uint16_t type, std::uint16_t code, std::int32_t value) {
std::lock_guard lock {write_mutex_};
return emit_event_locked(type, code, value);
}
OperationStatus sync() {
return emit_event(EV_SYN, SYN_REPORT, 0);
}
OperationStatus close_uinput(const std::string &description) {
if (!open_.exchange(false)) {
return OperationStatus::success();
}
auto status = OperationStatus::success();
if (fd_ >= 0) {
if (uinput_device_ != nullptr) {
libevdev_uinput_destroy(uinput_device_);
uinput_device_ = nullptr;
} else if (system_ioctl(fd_, UI_DEV_DESTROY) < 0) {
status = ioctl_status("failed to destroy " + description);
}
if (system_close(fd_) != 0 && status.ok()) {
status = system_error_status(ErrorCode::backend_failure, "failed to close /dev/uinput", errno);
}
fd_ = -1;
}
return status;
}
bool is_open() const {
return open_;
}
int file_descriptor() const {
return fd_;
}
private:
OperationStatus emit_event_locked(std::uint16_t type, std::uint16_t code, std::int32_t value) {
if (fd_ < 0) {
return OperationStatus::failure(ErrorCode::device_closed, "uinput device is closed");
}
input_event event {};
event.type = type;
event.code = code;
event.value = value;
const auto event_buffer = std::as_bytes(std::span {&event, 1U});
const auto result = system_write(fd_, event_buffer);
if (result < 0) {
return system_error_status(ErrorCode::backend_failure, "failed to write uinput event", errno);
}
if (static_cast<std::size_t>(result) != sizeof(event)) {
return OperationStatus::failure(ErrorCode::backend_failure, "short write while sending uinput event");
}
return OperationStatus::success();
}
int fd_ = -1;
libevdev_uinput *uinput_device_ = nullptr;
std::atomic_bool open_ = true;
std::mutex write_mutex_;
};
struct LibevdevDeviceDeleter {
void operator()(libevdev *device) const {
libevdev_free(device);
}
};
using LibevdevDevice = std::unique_ptr<libevdev, LibevdevDeviceDeleter>;
struct UinputCreationResult {
OperationStatus status;
libevdev_uinput *device = nullptr;
};
input_absinfo make_absinfo(
int minimum,
int maximum,
int fuzz = 0,
int flat = 0,
int resolution = 0
) {
input_absinfo info {};
info.minimum = minimum;
info.maximum = maximum;
info.fuzz = fuzz;
info.flat = flat;
info.resolution = resolution;
return info;
}
OperationStatus libevdev_status(int result, const std::string &operation) {
if (result >= 0) {
return OperationStatus::success();
}
return OperationStatus::failure(ErrorCode::backend_failure, operation + ": " + errno_message(-result));
}
OperationStatus enable_evdev_type(libevdev *device, unsigned int type, const std::string &description) {
return libevdev_status(libevdev_enable_event_type(device, type), "failed to enable " + description);
}
OperationStatus enable_evdev_code(
libevdev *device,
unsigned int type,
unsigned int code,
const std::string &description,
const input_absinfo *absinfo = nullptr
) {
return libevdev_status(
libevdev_enable_event_code(device, type, code, absinfo),
std::format("failed to enable {} {}", description, code)
);
}
OperationStatus enable_evdev_property(libevdev *device, unsigned int property, const std::string &description) {
return libevdev_status(
libevdev_enable_property(device, property),
"failed to enable " + description + " property"
);
}