-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwindows_backend.cpp
More file actions
2168 lines (1863 loc) · 73.2 KB
/
Copy pathwindows_backend.cpp
File metadata and controls
2168 lines (1863 loc) · 73.2 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/windows/windows_backend.cpp
* @brief Windows UMDF control-channel backend definitions.
*/
#ifndef DOXYGEN
#if defined(WINVER) && WINVER < 0x0A00
#undef WINVER
#endif
#ifndef WINVER
#define WINVER 0x0A00
#endif
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
#undef _WIN32_WINNT
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0A00
#endif
#if defined(NTDDI_VERSION) && NTDDI_VERSION < 0x0A000006
#undef NTDDI_VERSION
#endif
#ifndef NTDDI_VERSION
#define NTDDI_VERSION 0x0A000006
#endif
#endif
// local includes
#include "core/backend.hpp"
#include "lvh_windows_broker_protocol.h"
#include "platform/windows/control_protocol.hpp"
#include "platform/windows/keylayout.hpp"
#include "platform/windows/shared/generic_pid_rumble.hpp"
#include "platform/windows/windows_broker_client.hpp"
#include <libvirtualhid/profiles.hpp>
#include <libvirtualhid/report.hpp>
// lib includes
#include <lizardbyte/common/env.h>
// standard includes
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <numbers>
#include <optional>
#include <span>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// platform includes
// clang-format off
#include <Windows.h>
#include <SetupAPI.h>
// clang-format on
namespace lvh::detail {
namespace { // NOSONAR(cpp:S1000): Windows backend internals need internal linkage; tests include this file with the platform factory renamed.
class WindowsBackendContext;
using UniqueHandle = std::unique_ptr<void, decltype(&::CloseHandle)>;
using SendInputFunction = std::function<UINT(std::span<INPUT>)>;
using SyncThreadDesktopFunction = std::function<HDESK()>;
/**
* @brief Thread-local desktop identity used for SendInput retry decisions.
*/
struct LastKnownInputDesktop {
HDESK value = nullptr; ///< Last desktop returned by OpenInputDesktop.
};
/**
* @brief Runtime-loaded Windows synthetic pointer API entry points.
*/
struct SyntheticPointerApi {
std::function<HSYNTHETICPOINTERDEVICE(POINTER_INPUT_TYPE, ULONG, POINTER_FEEDBACK_MODE)> create; ///< Device creation entry point.
std::function<BOOL(HSYNTHETICPOINTERDEVICE, const POINTER_TYPE_INFO *, UINT32)> inject; ///< Pointer injection entry point.
std::function<void(HSYNTHETICPOINTERDEVICE)> destroy; ///< Device destroy entry point.
};
UINT send_input_with_win32(std::span<INPUT> inputs) {
return ::SendInput(
static_cast<UINT>(inputs.size()),
inputs.data(),
static_cast<int>(sizeof(INPUT))
);
}
SendInputFunction &send_input_function() {
static SendInputFunction function = send_input_with_win32;
return function;
}
HDESK sync_thread_desktop_with_win32() {
const auto desktop = ::OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, GENERIC_ALL);
if (!desktop) {
return nullptr;
}
static_cast<void>(::SetThreadDesktop(desktop));
::CloseDesktop(desktop);
return desktop;
}
SyncThreadDesktopFunction &sync_thread_desktop_function() {
static SyncThreadDesktopFunction function = sync_thread_desktop_with_win32;
return function;
}
LastKnownInputDesktop &last_known_input_desktop() {
thread_local LastKnownInputDesktop desktop;
return desktop;
}
template<typename Function>
Function load_user32_function(HMODULE user32, const char *name) {
const auto address = ::GetProcAddress(user32, name);
Function function {};
static_assert(sizeof(function) == sizeof(address));
std::memcpy(&function, &address, sizeof(function));
return function;
}
SyntheticPointerApi make_win32_synthetic_pointer_api() {
const auto user32 = ::GetModuleHandleA("user32.dll");
if (!user32) {
return {};
}
const auto create = load_user32_function<decltype(&::CreateSyntheticPointerDevice)>(user32, "CreateSyntheticPointerDevice");
const auto inject = load_user32_function<decltype(&::InjectSyntheticPointerInput)>(user32, "InjectSyntheticPointerInput");
const auto destroy = load_user32_function<decltype(&::DestroySyntheticPointerDevice)>(user32, "DestroySyntheticPointerDevice");
if (!create || !inject || !destroy) {
return {};
}
return {
.create = create,
.inject = inject,
.destroy = destroy,
};
}
SyntheticPointerApi &synthetic_pointer_api() {
static SyntheticPointerApi api = make_win32_synthetic_pointer_api();
return api;
}
bool synthetic_pointer_available(const SyntheticPointerApi &api) {
return api.create && api.inject && api.destroy;
}
OperationStatus unsupported_profile_status(std::string message) {
return OperationStatus::failure(ErrorCode::unsupported_profile, std::move(message));
}
constexpr GUID control_device_interface_guid {
0x3890af65,
0x2da0,
0x443c,
{0x84, 0xff, 0x6e, 0x70, 0xe8, 0x41, 0xba, 0x1e}
};
UniqueHandle make_unique_handle(HANDLE handle) {
return {handle, &::CloseHandle};
}
std::string windows_error_message(DWORD error_code) {
std::array<char, 1024> message_buffer {};
const auto message_size = ::FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
message_buffer.data(),
static_cast<DWORD>(message_buffer.size()),
nullptr
);
std::string message;
if (message_size > 0U) {
message.assign(message_buffer.data(), message_size);
while (!message.empty() && (message.back() == '\r' || message.back() == '\n')) {
message.pop_back();
}
} else {
std::ostringstream fallback;
fallback << "Windows error " << error_code;
message = fallback.str();
}
return message;
}
OperationStatus windows_failure(ErrorCode code, std::string_view operation, DWORD error_code) {
std::ostringstream message;
message << operation << ": " << windows_error_message(error_code);
return OperationStatus::failure(code, message.str());
}
UniqueHandle &overlapped_device_io_event() {
thread_local UniqueHandle operation_event {nullptr, &::CloseHandle};
if (!operation_event) {
operation_event = make_unique_handle(::CreateEventA(nullptr, TRUE, FALSE, nullptr));
}
return operation_event;
}
template<typename CancelOperation, typename FinishOperation>
void cancel_and_drain_overlapped_io(
OVERLAPPED &overlapped,
DWORD *bytes_returned,
CancelOperation &&cancel_operation,
FinishOperation &&finish_operation
) {
static_cast<void>(std::forward<CancelOperation>(cancel_operation)(overlapped));
static_cast<void>(std::forward<FinishOperation>(finish_operation)(overlapped, bytes_returned, TRUE));
}
template<typename StartOperation, typename FinishOperation>
OperationStatus run_overlapped_device_io(
std::string_view operation,
DWORD *bytes_returned,
StartOperation &&start_operation,
FinishOperation &&finish_operation
) {
const auto &operation_event = overlapped_device_io_event();
if (!operation_event) {
return windows_failure(ErrorCode::backend_failure, operation, ::GetLastError());
}
if (::ResetEvent(operation_event.get()) == FALSE) {
return windows_failure(ErrorCode::backend_failure, operation, ::GetLastError());
}
OVERLAPPED overlapped {};
overlapped.hEvent = operation_event.get();
if (std::forward<StartOperation>(start_operation)(overlapped, bytes_returned) != FALSE) {
return OperationStatus::success();
}
if (const auto start_error = ::GetLastError(); start_error != ERROR_IO_PENDING) {
return windows_failure(ErrorCode::backend_failure, operation, start_error);
}
if (std::forward<FinishOperation>(finish_operation)(overlapped, bytes_returned, TRUE) == FALSE) {
return windows_failure(ErrorCode::backend_failure, operation, ::GetLastError());
}
return OperationStatus::success();
}
template<typename Submit>
OperationStatus submit_with_desktop_retry(Submit submit, std::string_view operation) {
using enum ErrorCode;
if (submit()) {
return OperationStatus::success();
}
auto error_code = ::GetLastError();
auto &known_desktop = last_known_input_desktop();
if (const auto desktop = sync_thread_desktop_function()(); known_desktop.value != desktop) {
known_desktop.value = desktop;
if (submit()) {
return OperationStatus::success();
}
error_code = ::GetLastError();
}
return windows_failure(backend_failure, operation, error_code);
}
OperationStatus send_input(std::span<INPUT> inputs, std::string_view operation) {
return submit_with_desktop_retry([&inputs] {
return send_input_function()(inputs) == static_cast<UINT>(inputs.size());
},
operation);
}
OperationStatus send_input(const INPUT &input, std::string_view operation) {
std::array inputs {input};
return send_input(std::span<INPUT> {inputs}, operation);
}
OperationStatus inject_synthetic_pointer_input(
const SyntheticPointerApi &api,
HSYNTHETICPOINTERDEVICE device,
const POINTER_TYPE_INFO *pointer_info,
UINT32 count,
std::string_view operation
) {
using enum ErrorCode;
if (!synthetic_pointer_available(api)) {
return OperationStatus::failure(backend_unavailable, "Windows synthetic pointer APIs are unavailable");
}
return submit_with_desktop_retry([&api, device, pointer_info, count] {
return api.inject(device, pointer_info, count) != FALSE;
},
operation);
}
std::vector<std::string> enumerate_control_device_interface_paths() {
std::vector<std::string> paths;
const auto device_info_set = ::SetupDiGetClassDevsA(
&control_device_interface_guid,
nullptr,
nullptr,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE
);
if (device_info_set == INVALID_HANDLE_VALUE) {
return paths;
}
const auto cleanup = std::unique_ptr<void, decltype(&::SetupDiDestroyDeviceInfoList)> {
device_info_set,
&::SetupDiDestroyDeviceInfoList
};
for (DWORD index = 0;; ++index) {
SP_DEVICE_INTERFACE_DATA interface_data {};
interface_data.cbSize = sizeof(interface_data);
if (::SetupDiEnumDeviceInterfaces(device_info_set, nullptr, &control_device_interface_guid, index, &interface_data) == FALSE) {
break;
}
DWORD required_size = 0;
static_cast<void>(::SetupDiGetDeviceInterfaceDetailA(
device_info_set,
&interface_data,
nullptr,
0,
&required_size,
nullptr
));
if (required_size == 0U || ::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
continue;
}
auto buffer = std::make_unique_for_overwrite<std::byte[]>(required_size);
auto *detail_data = static_cast<SP_DEVICE_INTERFACE_DETAIL_DATA_A *>(static_cast<void *>(buffer.get()));
detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
if (::SetupDiGetDeviceInterfaceDetailA(device_info_set, &interface_data, detail_data, required_size, nullptr, nullptr) != FALSE) {
paths.emplace_back(detail_data->DevicePath);
}
}
return paths;
}
DWORD mouse_button_flags(MouseButton button, bool pressed) {
switch (button) {
using enum MouseButton;
case left:
return pressed ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
case middle:
return pressed ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
case right:
return pressed ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
case side:
case extra:
return pressed ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
}
return 0;
}
DWORD mouse_button_data(MouseButton button) {
switch (button) {
using enum MouseButton;
case side:
return XBUTTON1;
case extra:
return XBUTTON2;
case left:
case middle:
case right:
return 0;
}
return 0;
}
LONG scale_absolute_axis(float value, std::int32_t dimension) {
if (dimension <= 1) {
return 0;
}
const auto clamped = std::clamp(value, 0.0F, static_cast<float>(dimension));
const auto scaled = clamped * static_cast<float>(std::numeric_limits<std::uint16_t>::max()) / static_cast<float>(dimension);
return static_cast<LONG>(std::lround(scaled));
}
PointerViewport resolve_pointer_viewport(PointerViewport viewport) {
if (viewport.width > 0 && viewport.height > 0) {
return viewport;
}
viewport.offset_x = ::GetSystemMetrics(SM_XVIRTUALSCREEN);
viewport.offset_y = ::GetSystemMetrics(SM_YVIRTUALSCREEN);
viewport.width = std::max(1, ::GetSystemMetrics(SM_CXVIRTUALSCREEN));
viewport.height = std::max(1, ::GetSystemMetrics(SM_CYVIRTUALSCREEN));
return viewport;
}
POINT pointer_location(const PointerViewport &raw_viewport, float x, float y) {
const auto viewport = resolve_pointer_viewport(raw_viewport);
return {
.x = viewport.offset_x + static_cast<LONG>(std::lround(std::clamp(x, 0.0F, 1.0F) * static_cast<float>(viewport.width))),
.y = viewport.offset_y + static_cast<LONG>(std::lround(std::clamp(y, 0.0F, 1.0F) * static_cast<float>(viewport.height))),
};
}
void update_pointer_location(POINTER_INFO &pointer_info, const PointerViewport &viewport, float x, float y) {
pointer_info.ptPixelLocation = pointer_location(viewport, x, y);
}
bool extended_key(KeyboardKeyCode key_code) {
switch (key_code) {
case VK_LWIN:
case VK_RWIN:
case VK_RMENU:
case VK_RCONTROL:
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
case VK_PRIOR:
case VK_NEXT:
case VK_UP:
case VK_DOWN:
case VK_LEFT:
case VK_RIGHT:
case VK_DIVIDE:
case VK_APPS:
return true;
default:
return false;
}
}
/**
* @brief Whether a scan code is sent with the E0 extended prefix.
*
* @param scan_code Low byte of the scan code.
* @return True when the scan code requires `KEYEVENTF_EXTENDEDKEY`.
*/
bool extended_scan_code(WORD scan_code) {
switch (scan_code) {
case 0x1C:
case 0x35:
case 0x37:
case 0x38:
case 0x47:
case 0x48:
case 0x49:
case 0x4B:
case 0x4D:
case 0x50:
case 0x51:
case 0x52:
case 0x53:
case 0x5B:
case 0x5C:
case 0x5D:
case 0x5F:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6A:
case 0x6B:
case 0x6C:
case 0x6D:
case 0x6E:
case 0x6F:
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
case 0x78:
case 0x79:
case 0x7A:
case 0x7B:
case 0x7C:
case 0x7D:
case 0x7E:
case 0x7F:
return true;
default:
return false;
}
}
/**
* @brief Map a virtual key to a scan code using the active keyboard layout.
*
* @param key_code Windows virtual key code.
* @return Scan code and extended-prefix flag from `MapVirtualKeyW`.
*/
struct MappedScanCode {
WORD scan_code = 0;
bool extended = false;
};
MappedScanCode map_virtual_key_to_scan_code(KeyboardKeyCode key_code) {
const auto mapped = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
if (mapped == 0U) {
return {};
}
return {
.scan_code = static_cast<WORD>(mapped & 0xFFU),
.extended = (mapped & 0xFF00U) != 0U,
};
}
bool can_map_virtual_key_to_scan_code(KeyboardKeyCode key_code) {
return key_code != VK_LWIN && key_code != VK_RWIN && key_code != VK_PAUSE;
}
constexpr auto synthetic_pointer_repeat_interval = std::chrono::milliseconds {50}; ///< Active pointer refresh interval.
constexpr auto pointer_edge_triggered_flags = POINTER_FLAG_DOWN | POINTER_FLAG_UP | POINTER_FLAG_CANCELED | POINTER_FLAG_UPDATE; ///< One-frame pointer flags.
std::vector<std::string> resolve_control_device_paths() {
constexpr auto environment_name = "LIBVIRTUALHID_WINDOWS_CONTROL_DEVICE";
if (std::string override_path; lizardbyte::common::get_env(environment_name, override_path) && !override_path.empty()) {
return {override_path};
}
auto paths = enumerate_control_device_interface_paths();
paths.emplace_back(windows::default_control_device_path);
paths.emplace_back(windows::global_control_device_path);
return paths;
}
OperationStatus protocol_status(std::uint32_t status, std::string_view operation) {
using enum ErrorCode;
switch (status) {
case LVH_WINDOWS_STATUS_SUCCESS:
return OperationStatus::success();
case LVH_WINDOWS_STATUS_INVALID_ARGUMENT:
return OperationStatus::failure(invalid_argument, std::string {operation});
case LVH_WINDOWS_STATUS_UNSUPPORTED_PROFILE:
return OperationStatus::failure(unsupported_profile, std::string {operation});
case LVH_WINDOWS_STATUS_DEVICE_NOT_FOUND:
return OperationStatus::failure(device_closed, std::string {operation});
case LVH_WINDOWS_STATUS_BACKEND_FAILURE:
default:
return OperationStatus::failure(backend_failure, std::string {operation});
}
}
OperationStatus validate_windows_gamepad_profile(const DeviceProfile &profile) {
using enum ErrorCode;
if (profile.report_descriptor.size() > LVH_WINDOWS_MAX_REPORT_DESCRIPTOR_SIZE) {
return OperationStatus::failure(
invalid_argument,
"Windows gamepad HID descriptor exceeds control protocol limit"
);
}
if (profile.input_report_size > LVH_WINDOWS_MAX_INPUT_REPORT_SIZE) {
return OperationStatus::failure(
invalid_argument,
"Windows gamepad input report exceeds control protocol limit"
);
}
if (profile.output_report_size > LVH_WINDOWS_MAX_OUTPUT_REPORT_SIZE) {
return OperationStatus::failure(
invalid_argument,
"Windows gamepad output report exceeds control protocol limit"
);
}
return OperationStatus::success();
}
class WindowsControlChannel {
public:
WindowsControlChannel(const WindowsControlChannel &) = delete;
WindowsControlChannel &operator=(const WindowsControlChannel &) = delete;
WindowsControlChannel(WindowsControlChannel &&) noexcept = delete;
WindowsControlChannel &operator=(WindowsControlChannel &&) noexcept = delete;
virtual ~WindowsControlChannel() = default;
virtual const std::string &path() const = 0;
virtual HANDLE native_handle() const {
return nullptr;
}
virtual OperationStatus create_gamepad(
const LvhWindowsCreateGamepadRequest &request,
LvhWindowsCreateGamepadResponse &response
) const = 0;
virtual OperationStatus destroy_device(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token
) const = 0;
virtual OperationStatus submit_input_report(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token,
const std::vector<std::uint8_t> &report
) const = 0;
virtual std::optional<LvhWindowsOutputReportEvent> read_output_report(HANDLE stop_event) const = 0;
protected:
WindowsControlChannel() = default;
};
class Win32WindowsControlChannel final: public WindowsControlChannel {
public:
struct SharedHandle {
explicit SharedHandle(UniqueHandle value):
value {std::move(value)} {}
UniqueHandle value;
};
static std::pair<std::unique_ptr<WindowsControlChannel>, std::unique_ptr<WindowsControlChannel>> open_pair(
const std::string &path
) {
const auto handle = ::CreateFileA(
path.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
nullptr
);
if (handle == INVALID_HANDLE_VALUE) {
return {};
}
auto shared_handle = std::make_shared<SharedHandle>(make_unique_handle(handle));
return {
std::make_unique<Win32WindowsControlChannel>(path, shared_handle),
std::make_unique<Win32WindowsControlChannel>(path, std::move(shared_handle)),
};
}
const std::string &path() const override {
return path_;
}
HANDLE native_handle() const override {
return handle_->value.get();
}
OperationStatus create_gamepad(
const LvhWindowsCreateGamepadRequest &request,
LvhWindowsCreateGamepadResponse &response
) const override {
using enum ErrorCode;
auto request_copy = request;
DWORD bytes_returned = 0;
if (const auto status = device_io_control(LVH_WINDOWS_IOCTL_CREATE_GAMEPAD, request_copy, response, &bytes_returned, "create Windows gamepad"); !status.ok()) {
return status;
}
if (bytes_returned < sizeof(response)) {
return OperationStatus::failure(backend_failure, "Windows driver returned a truncated gamepad response");
}
return protocol_status(response.status, "Windows driver rejected gamepad creation");
}
OperationStatus destroy_device(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token
) const override {
auto request = windows::make_destroy_device_request(driver_device_id, session_token);
DWORD bytes_returned = 0;
return device_io_control(
LVH_WINDOWS_IOCTL_DESTROY_DEVICE,
request,
&bytes_returned,
"destroy Windows virtual HID device"
);
}
OperationStatus submit_input_report(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token,
const std::vector<std::uint8_t> &report
) const override {
using enum ErrorCode;
if (report.size() > LVH_WINDOWS_MAX_INPUT_REPORT_SIZE) {
return OperationStatus::failure(invalid_argument, "input report exceeds Windows control protocol limit");
}
auto request = windows::make_submit_input_report_request(driver_device_id, session_token, report);
DWORD bytes_returned = 0;
return device_io_control(
LVH_WINDOWS_IOCTL_SUBMIT_INPUT_REPORT,
request,
&bytes_returned,
"submit Windows input report"
);
}
std::optional<LvhWindowsOutputReportEvent> read_output_report(HANDLE stop_event) const override {
LvhWindowsOutputReportEvent event {};
event.version = LVH_WINDOWS_CONTROL_PROTOCOL_VERSION;
event.size = sizeof(event);
auto operation_event = make_unique_handle(::CreateEventA(nullptr, TRUE, FALSE, nullptr));
if (!operation_event) {
return std::nullopt;
}
OVERLAPPED overlapped {};
overlapped.hEvent = operation_event.get();
DWORD bytes_returned = 0;
const auto cancel_and_drain = [this, &overlapped, &bytes_returned] {
cancel_and_drain_overlapped_io(
overlapped,
&bytes_returned,
[this](OVERLAPPED &pending) {
return ::CancelIoEx(handle_->value.get(), &pending);
},
[this](OVERLAPPED &pending, DWORD *result_size, BOOL wait) {
return ::GetOverlappedResult(handle_->value.get(), &pending, result_size, wait);
}
);
};
if (const auto started = ::DeviceIoControl(handle_->value.get(), LVH_WINDOWS_IOCTL_READ_OUTPUT_REPORT, nullptr, 0, &event, sizeof(event), &bytes_returned, &overlapped); started == FALSE) {
if (const auto error_code = ::GetLastError(); error_code != ERROR_IO_PENDING) {
return std::nullopt;
}
std::array<HANDLE, 2> wait_handles {
operation_event.get(),
stop_event,
};
const auto wait_result = ::WaitForMultipleObjects(
static_cast<DWORD>(wait_handles.size()),
wait_handles.data(),
FALSE,
INFINITE
);
if (wait_result == WAIT_OBJECT_0 + 1U) {
cancel_and_drain();
return std::nullopt;
}
if (wait_result != WAIT_OBJECT_0) {
cancel_and_drain();
return std::nullopt;
}
}
if (::GetOverlappedResult(handle_->value.get(), &overlapped, &bytes_returned, FALSE) == FALSE) {
return std::nullopt;
}
if (constexpr auto event_header_size = sizeof(event.version) + sizeof(event.size) + sizeof(event.driver_device_id) + sizeof(event.report_size); bytes_returned < event_header_size) {
return std::nullopt;
}
event.report_size = std::min(event.report_size, static_cast<std::uint32_t>(LVH_WINDOWS_MAX_OUTPUT_REPORT_SIZE));
return event;
}
Win32WindowsControlChannel(std::string path, std::shared_ptr<SharedHandle> handle):
path_ {std::move(path)},
handle_ {std::move(handle)} {}
private:
template<typename Input, typename Output>
OperationStatus device_io_control(
DWORD control_code,
Input &input,
Output &output,
DWORD *bytes_returned,
std::string_view operation
) const {
return run_overlapped_device_io(
operation,
bytes_returned,
[this, control_code, &input, &output](OVERLAPPED &overlapped, DWORD *result_size) {
return ::DeviceIoControl(
handle_->value.get(),
control_code,
&input,
sizeof(input),
&output,
sizeof(output),
result_size,
&overlapped
);
},
[this](OVERLAPPED &overlapped, DWORD *result_size, BOOL wait) {
return ::GetOverlappedResult(handle_->value.get(), &overlapped, result_size, wait);
}
);
}
template<typename Input>
OperationStatus device_io_control(
DWORD control_code,
Input &input,
DWORD *bytes_returned,
std::string_view operation
) const {
return run_overlapped_device_io(
operation,
bytes_returned,
[this, control_code, &input](OVERLAPPED &overlapped, DWORD *result_size) {
return ::DeviceIoControl(
handle_->value.get(),
control_code,
&input,
sizeof(input),
nullptr,
0,
result_size,
&overlapped
);
},
[this](OVERLAPPED &overlapped, DWORD *result_size, BOOL wait) {
return ::GetOverlappedResult(handle_->value.get(), &overlapped, result_size, wait);
}
);
}
std::string path_;
std::shared_ptr<SharedHandle> handle_;
};
struct WindowsControlChannels {
std::unique_ptr<WindowsControlChannel> command;
std::unique_ptr<WindowsControlChannel> event;
};
WindowsControlChannels open_control_channels() {
for (const auto &path : resolve_control_device_paths()) {
auto [command, event] = Win32WindowsControlChannel::open_pair(path);
if (command && event) {
return {std::move(command), std::move(event)};
}
}
return {};
}
class BrokeredWindowsControlChannel final: public WindowsControlChannel {
public:
explicit BrokeredWindowsControlChannel(std::unique_ptr<WindowsControlChannel> direct_channel):
direct_channel_ {std::move(direct_channel)} {}
static std::unique_ptr<WindowsControlChannel> open(std::unique_ptr<WindowsControlChannel> direct_channel) {
if (!direct_channel) {
return nullptr;
}
auto brokered_channel = std::make_unique<BrokeredWindowsControlChannel>(std::move(direct_channel));
if (!brokered_channel->broker_available()) {
return nullptr;
}
return brokered_channel;
}
const std::string &path() const override {
return direct_channel_->path();
}
HANDLE native_handle() const override {
return direct_channel_->native_handle();
}
OperationStatus create_gamepad(
const LvhWindowsCreateGamepadRequest &request,
LvhWindowsCreateGamepadResponse &response
) const override {
LvhWindowsBrokerCreateGamepadRequest broker_request {};
broker_request.header = windows_broker::make_request_header(
LvhWindowsBrokerRequestType::create_gamepad,
sizeof(broker_request)
);
broker_request.client_control_handle = static_cast<std::uint64_t>(
reinterpret_cast<std::uintptr_t>(direct_channel_->native_handle())
);
broker_request.gamepad = request;
LvhWindowsBrokerCreateGamepadResponse broker_response {};
if (const auto status = windows_broker::call(broker_request, broker_response, "create Windows gamepad through broker"); !status.ok()) {
return status;
}
response = broker_response.gamepad;
return protocol_status(response.status, "Windows driver rejected gamepad creation");
}
OperationStatus destroy_device(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token
) const override {
LvhWindowsBrokerDestroyDeviceRequest broker_request {};
broker_request.header = windows_broker::make_request_header(
LvhWindowsBrokerRequestType::destroy_device,
sizeof(broker_request)
);
broker_request.device = windows::make_destroy_device_request(driver_device_id, session_token);
LvhWindowsBrokerDestroyDeviceResponse broker_response {};
return windows_broker::call(broker_request, broker_response, "destroy Windows virtual HID device through broker");
}
OperationStatus submit_input_report(
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token,
const std::vector<std::uint8_t> &report
) const override {
return direct_channel_->submit_input_report(driver_device_id, session_token, report);
}
std::optional<LvhWindowsOutputReportEvent> read_output_report(HANDLE stop_event) const override {
return direct_channel_->read_output_report(stop_event);
}
private:
bool broker_available() const {
LvhWindowsBrokerStatusRequest request {};
request.header = windows_broker::make_request_header(
LvhWindowsBrokerRequestType::status,
sizeof(request)
);
LvhWindowsBrokerStatusResponse response {};
return windows_broker::call(request, response, "query Windows broker status").ok();
}
std::unique_ptr<WindowsControlChannel> direct_channel_;
};
WindowsControlChannels open_brokered_control_channels() {
auto channels = open_control_channels();
channels.command = BrokeredWindowsControlChannel::open(std::move(channels.command));
return channels;
}
class WindowsGamepadState {
public:
WindowsGamepadState(
DeviceId client_device_id,
std::uint64_t driver_device_id,
const LvhWindowsSessionToken &session_token,
DeviceProfile device_profile,
std::string device_path
):
client_id {client_device_id},
driver_id {driver_device_id},
token {session_token},
profile {std::move(device_profile)},
path {std::move(device_path)} {