-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathinput.cpp
More file actions
1925 lines (1685 loc) · 67.2 KB
/
Copy pathinput.cpp
File metadata and controls
1925 lines (1685 loc) · 67.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/input.cpp
* @brief Definitions for gamepad, keyboard, and mouse input handling.
*/
#include <cstdint>
extern "C" {
#include <moonlight-common-c/src/Input.h>
#include <moonlight-common-c/src/Limelight.h>
}
// standard includes
#include <bitset>
#include <chrono>
#include <cmath>
#include <list>
#include <thread>
#include <unordered_map>
// lib includes
#include <boost/endian/buffers.hpp>
// local includes
#include "config.h"
#include "globals.h"
#include "input.h"
#include "logging.h"
#include "platform/common.h"
#include "thread_pool.h"
#include "utility.h"
// Win32 WHEEL_DELTA constant
#ifndef WHEEL_DELTA
constexpr int WHEEL_DELTA = 120; ///< Standard Windows wheel delta used to normalize scroll events.
#endif
using namespace std::literals;
namespace input {
constexpr auto MAX_GAMEPADS = std::min((std::size_t) platf::MAX_GAMEPADS, sizeof(std::int16_t) * 8); ///< Maximum gamepads representable by the active gamepad mask.
/**
* @def DISABLE_LEFT_BUTTON_DELAY
* @brief Macro for DISABLE LEFT BUTTON DELAY.
*/
#define DISABLE_LEFT_BUTTON_DELAY ((thread_pool_util::ThreadPool::task_id_t) 0x01)
/**
* @def ENABLE_LEFT_BUTTON_DELAY
* @brief Macro for ENABLE LEFT BUTTON DELAY.
*/
#define ENABLE_LEFT_BUTTON_DELAY nullptr
constexpr auto VKEY_SHIFT = 0x10; ///< Windows virtual-key code for shift.
constexpr auto VKEY_LSHIFT = 0xA0; ///< Windows virtual-key code for lshift.
constexpr auto VKEY_RSHIFT = 0xA1; ///< Windows virtual-key code for rshift.
constexpr auto VKEY_CONTROL = 0x11; ///< Windows virtual-key code for control.
constexpr auto VKEY_LCONTROL = 0xA2; ///< Windows virtual-key code for lcontrol.
constexpr auto VKEY_RCONTROL = 0xA3; ///< Windows virtual-key code for rcontrol.
constexpr auto VKEY_MENU = 0x12; ///< Windows virtual-key code for menu.
constexpr auto VKEY_LMENU = 0xA4; ///< Windows virtual-key code for lmenu.
constexpr auto VKEY_RMENU = 0xA5; ///< Windows virtual-key code for rmenu.
/**
* @brief Enumerates supported button state options.
*/
enum class button_state_e {
NONE, ///< No button state
DOWN, ///< Button is down
UP ///< Button is up
};
/**
* @brief Allocate an available input slot identifier.
*
* @param gamepad_mask Gamepad mask.
* @return Allocated ID object, or null when unavailable.
*/
template<std::size_t N>
int alloc_id(std::bitset<N> &gamepad_mask) {
for (int x = 0; x < gamepad_mask.size(); ++x) {
if (!gamepad_mask[x]) {
gamepad_mask[x] = true;
return x;
}
}
return -1;
}
/**
* @brief Release ID resources.
*
* @param gamepad_mask Gamepad mask.
* @param id Identifier for the controller, session, display, or resource.
*/
template<std::size_t N>
void free_id(std::bitset<N> &gamepad_mask, int id) {
gamepad_mask[id] = false;
}
/**
* @brief Packed identifier for a pressed key and its modifier flags.
*/
typedef uint32_t key_press_id_t;
/**
* @brief Create a key-press identifier from the virtual-key code and flags.
*
* @param vk Virtual-key code from the client input packet.
* @param flags Bit flags that modify the requested operation.
* @return Constructed kpid object.
*/
key_press_id_t make_kpid(uint16_t vk, uint8_t flags) {
return (key_press_id_t) vk << 8 | flags;
}
/**
* @brief Extract the virtual-key code from a packed key-press identifier.
*
* @param kpid Key-press identifier containing the virtual-key code and flags.
* @return Virtual-key code stored in the high byte.
*/
uint16_t vk_from_kpid(key_press_id_t kpid) {
return kpid >> 8;
}
/**
* @brief Extract the modifier flags from a packed key-press identifier.
*
* @param kpid Key-press identifier containing the virtual-key code and flags.
* @return Modifier flags stored in the low byte.
*/
uint8_t flags_from_kpid(key_press_id_t kpid) {
return kpid & 0xFF;
}
/**
* @brief Convert a little-endian netfloat to a native endianness float.
* @param f Little-endian network float bytes.
* @return Floating-point value decoded for the host CPU.
*/
float from_netfloat(netfloat f) {
return boost::endian::endian_load<float, sizeof(float), boost::endian::order::little>(f);
}
/**
* @brief Convert a little-endian netfloat to a native float and clamp it to a range.
* @param f Little-endian network float bytes.
* @param min The minimium value for clamping.
* @param max The maximum value for clamping.
* @return Decoded floating-point value clamped between min and max.
*/
float from_clamped_netfloat(netfloat f, float min, float max) {
return std::clamp(from_netfloat(f), min, max);
}
static task_pool_util::TaskPool::task_id_t key_press_repeat_id {};
static std::unordered_map<key_press_id_t, bool> key_press {};
static std::array<std::uint8_t, 5> mouse_press {};
static platf::input_t platf_input;
static std::bitset<platf::MAX_GAMEPADS> gamepadMask {};
/**
* @brief Release all platform resources associated with a virtual gamepad.
*
* @param platf_input Platf input.
* @param id Identifier for the controller, session, display, or resource.
*/
void free_gamepad(platf::input_t &platf_input, int id) {
platf::gamepad_update(platf_input, id, platf::gamepad_state_t {});
platf::free_gamepad(platf_input, id);
free_id(gamepadMask, id);
}
/**
* @brief Per-client gamepad slot and feedback state.
*/
struct gamepad_t {
gamepad_t():
gamepad_state {},
back_timeout_id {},
id {-1},
back_button_state {button_state_e::NONE} {
}
~gamepad_t() {
if (id >= 0) {
task_pool.push([id = this->id]() {
free_gamepad(platf_input, id);
});
}
}
platf::gamepad_state_t gamepad_state; ///< Gamepad state.
thread_pool_util::ThreadPool::task_id_t back_timeout_id; ///< Back timeout ID.
int id; ///< Global gamepad slot assigned to this client controller.
// When emulating the HOME button, we may need to artificially release the back button.
// Afterwards, the gamepad state on sunshine won't match the state on Moonlight.
// To prevent Sunshine from sending erroneous input data to the active application,
// Sunshine forces the button to be in a specific state until the gamepad state matches that of
// Moonlight once more.
button_state_e back_button_state; ///< Back button state.
};
/**
* @brief Input emulation settings loaded from configuration.
*/
struct input_t {
/**
* @brief Enumerates supported shortkey options.
*/
enum shortkey_e {
CTRL = 0x1, ///< Control key
ALT = 0x2, ///< Alt key
SHIFT = 0x4, ///< Shift key
SHORTCUT = CTRL | ALT | SHIFT ///< Shortcut combination
};
/**
* @brief Construct input state from the mailbox and platform backend.
*
* @param touch_port_event Event carrying the active touch port.
* @param feedback_queue Queue used for controller feedback.
*/
input_t(
safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event,
platf::feedback_queue_t feedback_queue
):
shortcutFlags {},
gamepads(MAX_GAMEPADS),
client_context {platf::allocate_client_input_context(platf_input)},
touch_port_event {std::move(touch_port_event)},
feedback_queue {std::move(feedback_queue)},
mouse_left_button_timeout {},
touch_port {{0, 0, 0, 0}, 0, 0, 1.0f, 1.0f, 0, 0},
accumulated_vscroll_delta {},
accumulated_hscroll_delta {} {
}
// Keep track of alt+ctrl+shift key combo
int shortcutFlags; ///< Shortcut flags.
bool left_alt_pressed = false; ///< Tracks whether the left Alt key is currently pressed.
bool right_alt_pressed = false; ///< Tracks whether the right Alt key is currently pressed.
std::vector<gamepad_t> gamepads; ///< Virtual gamepad slots tracked for the stream.
std::unique_ptr<platf::client_input_t> client_context; ///< Client context.
safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event; ///< Touch port event.
platf::feedback_queue_t feedback_queue; ///< Queue used to deliver controller feedback to the platform backend.
std::list<std::vector<uint8_t>> input_queue; ///< Pending raw input packets waiting for processing.
std::mutex input_queue_lock; ///< Input queue lock.
thread_pool_util::ThreadPool::task_id_t mouse_left_button_timeout; ///< Mouse left button timeout.
input::touch_port_t touch_port; ///< Touch coordinate bounds for the current stream.
int32_t accumulated_vscroll_delta; ///< Accumulated vscroll delta.
int32_t accumulated_hscroll_delta; ///< Accumulated hscroll delta.
};
/**
* @brief Apply shortcut based on VKEY
* @param keyCode The VKEY code
* @return 0 if no shortcut applied, > 0 if shortcut applied.
*/
inline int apply_shortcut(short keyCode) {
constexpr auto VK_F1 = 0x70;
constexpr auto VK_F13 = 0x7C;
BOOST_LOG(debug) << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view();
if (keyCode >= VK_F1 && keyCode <= VK_F13) {
mail::man->event<int>(mail::switch_display)->raise(keyCode - VK_F1);
return 1;
}
switch (keyCode) {
case 0x4E /* VKEY_N */:
display_cursor = !display_cursor;
return 1;
}
return 0;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_REL_MOUSE_MOVE_PACKET packet) {
BOOST_LOG(debug)
<< "--begin relative mouse move packet--"sv << std::endl
<< "deltaX ["sv << util::endian::big(packet->deltaX) << ']' << std::endl
<< "deltaY ["sv << util::endian::big(packet->deltaY) << ']' << std::endl
<< "--end relative mouse move packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_ABS_MOUSE_MOVE_PACKET packet) {
BOOST_LOG(debug)
<< "--begin absolute mouse move packet--"sv << std::endl
<< "x ["sv << util::endian::big(packet->x) << ']' << std::endl
<< "y ["sv << util::endian::big(packet->y) << ']' << std::endl
<< "width ["sv << util::endian::big(packet->width) << ']' << std::endl
<< "height ["sv << util::endian::big(packet->height) << ']' << std::endl
<< "--end absolute mouse move packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_MOUSE_BUTTON_PACKET packet) {
BOOST_LOG(debug)
<< "--begin mouse button packet--"sv << std::endl
<< "action ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl
<< "button ["sv << util::hex(packet->button).to_string_view() << ']' << std::endl
<< "--end mouse button packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_SCROLL_PACKET packet) {
BOOST_LOG(debug)
<< "--begin mouse scroll packet--"sv << std::endl
<< "scrollAmt1 ["sv << util::endian::big(packet->scrollAmt1) << ']' << std::endl
<< "--end mouse scroll packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PSS_HSCROLL_PACKET packet) {
BOOST_LOG(debug)
<< "--begin mouse hscroll packet--"sv << std::endl
<< "scrollAmount ["sv << util::endian::big(packet->scrollAmount) << ']' << std::endl
<< "--end mouse hscroll packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_KEYBOARD_PACKET packet) {
BOOST_LOG(debug)
<< "--begin keyboard packet--"sv << std::endl
<< "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl
<< "keyCode ["sv << util::hex(packet->keyCode).to_string_view() << ']' << std::endl
<< "modifiers ["sv << util::hex(packet->modifiers).to_string_view() << ']' << std::endl
<< "flags ["sv << util::hex(packet->flags).to_string_view() << ']' << std::endl
<< "--end keyboard packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_UNICODE_PACKET packet) {
std::string text(packet->text, util::endian::big(packet->header.size) - sizeof(packet->header.magic));
BOOST_LOG(debug)
<< "--begin unicode packet--"sv << std::endl
<< "text ["sv << text << ']' << std::endl
<< "--end unicode packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*
* @param packet Protocol packet being processed.
*/
void print(PNV_MULTI_CONTROLLER_PACKET packet) {
// Moonlight spams controller packet even when not necessary
BOOST_LOG(verbose)
<< "--begin controller packet--"sv << std::endl
<< "controllerNumber ["sv << packet->controllerNumber << ']' << std::endl
<< "activeGamepadMask ["sv << util::hex(packet->activeGamepadMask).to_string_view() << ']' << std::endl
<< "buttonFlags ["sv << util::hex((uint32_t) packet->buttonFlags | (packet->buttonFlags2 << 16)).to_string_view() << ']' << std::endl
<< "leftTrigger ["sv << util::hex(packet->leftTrigger).to_string_view() << ']' << std::endl
<< "rightTrigger ["sv << util::hex(packet->rightTrigger).to_string_view() << ']' << std::endl
<< "leftStickX ["sv << packet->leftStickX << ']' << std::endl
<< "leftStickY ["sv << packet->leftStickY << ']' << std::endl
<< "rightStickX ["sv << packet->rightStickX << ']' << std::endl
<< "rightStickY ["sv << packet->rightStickY << ']' << std::endl
<< "--end controller packet--"sv;
}
/**
* @brief Prints a touch packet.
* @param packet The touch packet.
*/
void print(PSS_TOUCH_PACKET packet) {
BOOST_LOG(debug)
<< "--begin touch packet--"sv << std::endl
<< "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
<< "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl
<< "x ["sv << from_netfloat(packet->x) << ']' << std::endl
<< "y ["sv << from_netfloat(packet->y) << ']' << std::endl
<< "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl
<< "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl
<< "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl
<< "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl
<< "--end touch packet--"sv;
}
/**
* @brief Prints a pen packet.
* @param packet The pen packet.
*/
void print(PSS_PEN_PACKET packet) {
BOOST_LOG(debug)
<< "--begin pen packet--"sv << std::endl
<< "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
<< "toolType ["sv << util::hex(packet->toolType).to_string_view() << ']' << std::endl
<< "penButtons ["sv << util::hex(packet->penButtons).to_string_view() << ']' << std::endl
<< "x ["sv << from_netfloat(packet->x) << ']' << std::endl
<< "y ["sv << from_netfloat(packet->y) << ']' << std::endl
<< "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl
<< "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl
<< "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl
<< "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl
<< "tilt ["sv << (uint32_t) packet->tilt << ']' << std::endl
<< "--end pen packet--"sv;
}
/**
* @brief Prints a controller arrival packet.
* @param packet The controller arrival packet.
*/
void print(PSS_CONTROLLER_ARRIVAL_PACKET packet) {
BOOST_LOG(debug)
<< "--begin controller arrival packet--"sv << std::endl
<< "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl
<< "type ["sv << util::hex(packet->type).to_string_view() << ']' << std::endl
<< "capabilities ["sv << util::hex(packet->capabilities).to_string_view() << ']' << std::endl
<< "supportedButtonFlags ["sv << util::hex(packet->supportedButtonFlags).to_string_view() << ']' << std::endl
<< "--end controller arrival packet--"sv;
}
/**
* @brief Prints a controller touch packet.
* @param packet The controller touch packet.
*/
void print(PSS_CONTROLLER_TOUCH_PACKET packet) {
BOOST_LOG(debug)
<< "--begin controller touch packet--"sv << std::endl
<< "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl
<< "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
<< "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl
<< "x ["sv << from_netfloat(packet->x) << ']' << std::endl
<< "y ["sv << from_netfloat(packet->y) << ']' << std::endl
<< "pressure ["sv << from_netfloat(packet->pressure) << ']' << std::endl
<< "--end controller touch packet--"sv;
}
/**
* @brief Prints a controller motion packet.
* @param packet The controller motion packet.
*/
void print(PSS_CONTROLLER_MOTION_PACKET packet) {
BOOST_LOG(verbose)
<< "--begin controller motion packet--"sv << std::endl
<< "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl
<< "motionType ["sv << util::hex(packet->motionType).to_string_view() << ']' << std::endl
<< "x ["sv << from_netfloat(packet->x) << ']' << std::endl
<< "y ["sv << from_netfloat(packet->y) << ']' << std::endl
<< "z ["sv << from_netfloat(packet->z) << ']' << std::endl
<< "--end controller motion packet--"sv;
}
/**
* @brief Prints a controller battery packet.
* @param packet The controller battery packet.
*/
void print(PSS_CONTROLLER_BATTERY_PACKET packet) {
BOOST_LOG(verbose)
<< "--begin controller battery packet--"sv << std::endl
<< "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl
<< "batteryState ["sv << util::hex(packet->batteryState).to_string_view() << ']' << std::endl
<< "batteryPercentage ["sv << util::hex(packet->batteryPercentage).to_string_view() << ']' << std::endl
<< "--end controller battery packet--"sv;
}
/**
* @brief Write a debug log representation of the input packet.
*/
void print(void *payload) {
auto header = (PNV_INPUT_HEADER) payload;
switch (util::endian::little(header->magic)) {
case MOUSE_MOVE_REL_MAGIC_GEN5:
print((PNV_REL_MOUSE_MOVE_PACKET) payload);
break;
case MOUSE_MOVE_ABS_MAGIC:
print((PNV_ABS_MOUSE_MOVE_PACKET) payload);
break;
case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5:
case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5:
print((PNV_MOUSE_BUTTON_PACKET) payload);
break;
case SCROLL_MAGIC_GEN5:
print((PNV_SCROLL_PACKET) payload);
break;
case SS_HSCROLL_MAGIC:
print((PSS_HSCROLL_PACKET) payload);
break;
case KEY_DOWN_EVENT_MAGIC:
case KEY_UP_EVENT_MAGIC:
print((PNV_KEYBOARD_PACKET) payload);
break;
case UTF8_TEXT_EVENT_MAGIC:
print((PNV_UNICODE_PACKET) payload);
break;
case MULTI_CONTROLLER_MAGIC_GEN5:
print((PNV_MULTI_CONTROLLER_PACKET) payload);
break;
case SS_TOUCH_MAGIC:
print((PSS_TOUCH_PACKET) payload);
break;
case SS_PEN_MAGIC:
print((PSS_PEN_PACKET) payload);
break;
case SS_CONTROLLER_ARRIVAL_MAGIC:
print((PSS_CONTROLLER_ARRIVAL_PACKET) payload);
break;
case SS_CONTROLLER_TOUCH_MAGIC:
print((PSS_CONTROLLER_TOUCH_PACKET) payload);
break;
case SS_CONTROLLER_MOTION_MAGIC:
print((PSS_CONTROLLER_MOTION_PACKET) payload);
break;
case SS_CONTROLLER_BATTERY_MAGIC:
print((PSS_CONTROLLER_BATTERY_PACKET) payload);
break;
}
}
/**
* @brief Forward a client input packet directly to the platform backend.
*
* @param input Platform input backend that receives the event.
* @param packet Protocol packet being processed.
*/
void passthrough(std::shared_ptr<input_t> &input, PNV_REL_MOUSE_MOVE_PACKET packet) {
if (!config::input.mouse) {
return;
}
input->mouse_left_button_timeout = DISABLE_LEFT_BUTTON_DELAY;
platf::move_mouse(platf_input, util::endian::big(packet->deltaX), util::endian::big(packet->deltaY));
}
/**
* @brief Converts client coordinates on the specified surface into screen coordinates.
* @param input The input context.
* @param val The cartesian coordinate pair to convert.
* @param size The size of the client's surface containing the value.
* @return The host-relative coordinate pair if a touchport is available.
*/
std::optional<std::pair<float, float>> client_to_touchport(std::shared_ptr<input_t> &input, const std::pair<float, float> &val, const std::pair<float, float> &size) {
auto &touch_port_event = input->touch_port_event;
auto &touch_port = input->touch_port;
if (touch_port_event->peek()) {
touch_port = *touch_port_event->pop();
}
if (!touch_port) {
BOOST_LOG(verbose) << "Ignoring early absolute input without a touch port"sv;
return std::nullopt;
}
auto scalarX = touch_port.width / size.first;
auto scalarY = touch_port.height / size.second;
float x = std::clamp(val.first, 0.0f, size.first) * scalarX;
float y = std::clamp(val.second, 0.0f, size.second) * scalarY;
auto offsetX = touch_port.client_offsetX;
auto offsetY = touch_port.client_offsetY;
x = std::clamp(x, offsetX, (size.first * scalarX) - offsetX);
y = std::clamp(y, offsetY, (size.second * scalarY) - offsetY);
/*
x and y here below have the coordinates of the surface of the streaming resolution,
and are dependent on how that comes configured from the client (scalar_inv is calculated
from the proportion of that and the device's **physical** size).
*/
x = (x - offsetX) * touch_port.scalar_inv;
y = (y - offsetY) * touch_port.scalar_inv;
/*
This final operation is a bit weird and has been brought about with lots of trial and error. A better
way to do this may exist.
Basically, this is what makes the touchscreen map to the coordinates inputtino expects properly.
Since inputtino's dimensions are now logical (because scaling breaks everything otherwise), using the previous
x and y coordinates would be incorrect when screens are scaled, because the touch port is smaller (or larger)
by a factor (that factor is touch_port.scalar_tpcoords), and that factor must be used to account for that difference
when moving the cursor. Otherwise, it will move either slower or faster than your finger proportionally to
scalar_tpcoords, and be offset *inversely* proportionally to scalar_tpcoords. So you must account for both differences
by multiplying and dividing.
*/
float final_x = (x + touch_port.offset_x * touch_port.scalar_tpcoords) / touch_port.scalar_tpcoords;
float final_y = (y + touch_port.offset_y * touch_port.scalar_tpcoords) / touch_port.scalar_tpcoords;
return std::pair {final_x, final_y};
}
/**
* @brief Multiply a polar coordinate pair by a cartesian scaling factor.
* @param r The radial coordinate.
* @param angle The angular coordinate (radians).
* @param scalar The scalar cartesian coordinate pair.
* @return The scaled radial coordinate.
*/
float multiply_polar_by_cartesian_scalar(float r, float angle, const std::pair<float, float> &scalar) {
// Convert polar to cartesian coordinates
float x = r * std::cos(angle);
float y = r * std::sin(angle);
// Scale the values
x *= scalar.first;
y *= scalar.second;
// Convert the result back to a polar radial coordinate
return std::sqrt(std::pow(x, 2) + std::pow(y, 2));
}
std::pair<float, float> scale_client_contact_area(const std::pair<float, float> &val, uint16_t rotation, const std::pair<float, float> &scalar) {
// If the rotation is unknown, we'll just scale both axes equally by using
// a 45-degree angle for our scaling calculations
float angle = rotation == LI_ROT_UNKNOWN ? (M_PI / 4) : (rotation * (M_PI / 180));
// If we have a major but not a minor axis, treat the touch as circular
float major = val.first;
float minor = val.second != 0.0f ? val.second : val.first;
// The minor axis is perpendicular to major axis so the angle must be rotated by 90 degrees
return {multiply_polar_by_cartesian_scalar(major, angle, scalar), multiply_polar_by_cartesian_scalar(minor, angle + (M_PI / 2), scalar)};
}
/**
* @brief Forward a client input packet directly to the platform backend.
*
* @param input Platform input backend that receives the event.
* @param packet Protocol packet being processed.
*/
void passthrough(std::shared_ptr<input_t> &input, PNV_ABS_MOUSE_MOVE_PACKET packet) {
if (!config::input.mouse) {
return;
}
if (input->mouse_left_button_timeout == DISABLE_LEFT_BUTTON_DELAY) {
input->mouse_left_button_timeout = ENABLE_LEFT_BUTTON_DELAY;
}
float x = util::endian::big(packet->x);
float y = util::endian::big(packet->y);
// Prevent divide by zero
// Don't expect it to happen, but just in case
if (!packet->width || !packet->height) {
BOOST_LOG(warning) << "Moonlight passed invalid dimensions"sv;
return;
}
auto width = (float) util::endian::big(packet->width);
auto height = (float) util::endian::big(packet->height);
auto tpcoords = client_to_touchport(input, {x, y}, {width, height});
if (!tpcoords) {
return;
}
auto &touch_port = input->touch_port;
int touch_port_dim_x;
int touch_port_dim_y;
if (touch_port.env_logical_width != 0 && touch_port.env_logical_height != 0) {
touch_port_dim_x = touch_port.env_logical_width;
touch_port_dim_y = touch_port.env_logical_height;
} else {
touch_port_dim_x = touch_port.env_width;
touch_port_dim_y = touch_port.env_height;
}
platf::touch_port_t abs_port {
touch_port.offset_x,
touch_port.offset_y,
touch_port_dim_x,
touch_port_dim_y
};
platf::abs_mouse(platf_input, abs_port, tpcoords->first, tpcoords->second);
}
/**
* @brief Called to pass a mouse button message to the platform backend.
*
* @param input The input context pointer.
* @param packet The mouse button packet.
*/
void passthrough(std::shared_ptr<input_t> &input, PNV_MOUSE_BUTTON_PACKET packet) {
if (!config::input.mouse) {
return;
}
auto release = util::endian::little(packet->header.magic) == MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5;
auto button = util::endian::big(packet->button);
if (button > 0 && button < mouse_press.size()) {
if (mouse_press[button] != release) {
// button state is already what we want
return;
}
mouse_press[button] = !release;
}
/**
* When Moonlight sends mouse input through absolute coordinates,
* it's possible that BUTTON_RIGHT is pressed down immediately after releasing BUTTON_LEFT.
* As a result, Sunshine will left-click on hyperlinks in the browser before right-clicking
*
* This can be solved by delaying BUTTON_LEFT, however, any delay on input is undesirable during gaming
* As a compromise, Sunshine will only put delays on BUTTON_LEFT when
* absolute mouse coordinates have been sent.
*
* Try to make sure BUTTON_RIGHT gets called before BUTTON_LEFT is released.
*
* input->mouse_left_button_timeout can only be nullptr
* when the last mouse coordinates were absolute
*/
if (button == BUTTON_LEFT && release && !input->mouse_left_button_timeout) {
auto f = [=]() {
auto left_released = mouse_press[BUTTON_LEFT];
if (left_released) {
// Already released left button
return;
}
platf::button_mouse(platf_input, BUTTON_LEFT, release);
mouse_press[BUTTON_LEFT] = false;
input->mouse_left_button_timeout = nullptr;
};
input->mouse_left_button_timeout = task_pool.pushDelayed(std::move(f), 10ms).task_id;
return;
}
if (
button == BUTTON_RIGHT && !release &&
input->mouse_left_button_timeout > DISABLE_LEFT_BUTTON_DELAY
) {
platf::button_mouse(platf_input, BUTTON_RIGHT, false);
platf::button_mouse(platf_input, BUTTON_RIGHT, true);
mouse_press[BUTTON_RIGHT] = false;
return;
}
platf::button_mouse(platf_input, button, release);
}
/**
* @brief Apply configured keybinding remaps to a platform keycode.
*
* @param keycode Platform keycode being translated or emitted.
* @return Remapped keycode when configured, otherwise the original keycode.
*/
short map_keycode(short keycode) {
auto it = config::input.keybindings.find(keycode);
if (it != std::end(config::input.keybindings)) {
return it->second;
}
return keycode;
}
/**
* @brief Update flags for keyboard shortcut combo's
*
* @param flags Bit flags that modify the requested operation.
* @param keyCode Moonlight keyboard packet key code.
* @param release Whether the key or button event is a release.
*/
inline void update_shortcutFlags(int *flags, short keyCode, bool release) {
switch (keyCode) {
case VKEY_SHIFT:
case VKEY_LSHIFT:
case VKEY_RSHIFT:
if (release) {
*flags &= ~input_t::SHIFT;
} else {
*flags |= input_t::SHIFT;
}
break;
case VKEY_CONTROL:
case VKEY_LCONTROL:
case VKEY_RCONTROL:
if (release) {
*flags &= ~input_t::CTRL;
} else {
*flags |= input_t::CTRL;
}
break;
case VKEY_MENU:
case VKEY_LMENU:
case VKEY_RMENU:
if (release) {
*flags &= ~input_t::ALT;
} else {
*flags |= input_t::ALT;
}
break;
}
}
/**
* @brief Check whether modifier.
*
* @param keyCode Moonlight keyboard packet key code.
* @return True when the key code is a keyboard modifier.
*/
bool is_modifier(uint16_t keyCode) {
switch (keyCode) {
case VKEY_SHIFT:
case VKEY_LSHIFT:
case VKEY_RSHIFT:
case VKEY_CONTROL:
case VKEY_LCONTROL:
case VKEY_RCONTROL:
case VKEY_MENU:
case VKEY_LMENU:
case VKEY_RMENU:
return true;
default:
return false;
}
}
/**
* @brief Send key and modifiers.
*
* @param key_code Moonlight keyboard packet key code.
* @param release Whether the key or button event is a release.
* @param flags Bit flags that modify the requested operation.
* @param synthetic_modifiers Synthetic modifiers.
*/
void send_key_and_modifiers(uint16_t key_code, bool release, uint8_t flags, uint8_t synthetic_modifiers) {
if (!release) {
// Press any synthetic modifiers required for this key
if (synthetic_modifiers & MODIFIER_SHIFT) {
platf::keyboard_update(platf_input, VKEY_SHIFT, false, flags);
}
if (synthetic_modifiers & MODIFIER_CTRL) {
platf::keyboard_update(platf_input, VKEY_CONTROL, false, flags);
}
if (synthetic_modifiers & MODIFIER_ALT) {
platf::keyboard_update(platf_input, VKEY_MENU, false, flags);
}
}
platf::keyboard_update(platf_input, map_keycode(key_code), release, flags);
if (!release) {
// Raise any synthetic modifier keys we pressed
if (synthetic_modifiers & MODIFIER_SHIFT) {
platf::keyboard_update(platf_input, VKEY_SHIFT, true, flags);
}
if (synthetic_modifiers & MODIFIER_CTRL) {
platf::keyboard_update(platf_input, VKEY_CONTROL, true, flags);
}
if (synthetic_modifiers & MODIFIER_ALT) {
platf::keyboard_update(platf_input, VKEY_MENU, true, flags);
}
}
}
/**
* @brief Re-emit a held key until its repeat task is cancelled.
*
* @param key_code Moonlight keyboard packet key code.
* @param flags Bit flags that modify the requested operation.
* @param synthetic_modifiers Synthetic modifiers.
*/
void repeat_key(uint16_t key_code, uint8_t flags, uint8_t synthetic_modifiers) {
// If key no longer pressed, stop repeating
if (!key_press[make_kpid(key_code, flags)]) {
key_press_repeat_id = nullptr;
return;
}
send_key_and_modifiers(key_code, false, flags, synthetic_modifiers);
key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_period, key_code, flags, synthetic_modifiers).task_id;
}
/**
* @brief Forward a client input packet directly to the platform backend.
*
* @param input Platform input backend that receives the event.
* @param packet Protocol packet being processed.
*/
void passthrough(std::shared_ptr<input_t> &input, PNV_KEYBOARD_PACKET packet) {
if (!config::input.keyboard) {
return;
}
auto release = util::endian::little(packet->header.magic) == KEY_UP_EVENT_MAGIC;
auto keyCode = packet->keyCode & 0x00FF;
if (keyCode == VKEY_LMENU) {
input->left_alt_pressed = !release;
} else if (keyCode == VKEY_RMENU) {
input->right_alt_pressed = !release;
}
// Right-alt maps to meta, so it must not also register as ALT
int modifiers = packet->modifiers;
if (config::input.key_rightalt_to_key_win && input->right_alt_pressed && !input->left_alt_pressed) {
modifiers &= ~MODIFIER_ALT;
}
// Set synthetic modifier flags if the keyboard packet is requesting modifier
// keys that are not current pressed.
uint8_t synthetic_modifiers = 0;
if (!release && !is_modifier(keyCode)) {
if (!(input->shortcutFlags & input_t::SHIFT) && (modifiers & MODIFIER_SHIFT)) {
synthetic_modifiers |= MODIFIER_SHIFT;
}
if (!(input->shortcutFlags & input_t::CTRL) && (modifiers & MODIFIER_CTRL)) {
synthetic_modifiers |= MODIFIER_CTRL;
}
if (!(input->shortcutFlags & input_t::ALT) && (modifiers & MODIFIER_ALT)) {
synthetic_modifiers |= MODIFIER_ALT;
}
}
auto &pressed = key_press[make_kpid(keyCode, packet->flags)];
if (!pressed) {
if (!release) {
// A new key has been pressed down, we need to check for key combo's
// If a key-combo has been pressed down, don't pass it through
if (input->shortcutFlags == input_t::SHORTCUT && apply_shortcut(keyCode) > 0) {
return;
}
if (key_press_repeat_id) {
task_pool.cancel(key_press_repeat_id);
}
if (config::input.key_repeat_delay.count() > 0) {
key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_delay, keyCode, packet->flags, synthetic_modifiers).task_id;
}
} else {
// Already released
return;
}
} else if (!release) {
// Already pressed down key
return;
}
pressed = !release;
send_key_and_modifiers(keyCode, release, packet->flags, synthetic_modifiers);
update_shortcutFlags(&input->shortcutFlags, map_keycode(keyCode), release);
}
/**
* @brief Called to pass a vertical scroll message the platform backend.
* @param input The input context pointer.
* @param packet The scroll packet.
*/
void passthrough(std::shared_ptr<input_t> &input, PNV_SCROLL_PACKET packet) {
if (!config::input.mouse) {
return;
}
if (config::input.high_resolution_scrolling) {
platf::scroll(platf_input, util::endian::big(packet->scrollAmt1));