Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
input.cpp
Go to the documentation of this file.
1
5#include <cstdint>
6extern "C" {
7#include <moonlight-common-c/src/Input.h>
8#include <moonlight-common-c/src/Limelight.h>
9}
10
11// standard includes
12#include <bitset>
13#include <chrono>
14#include <cmath>
15#include <list>
16#include <stdexcept>
17#include <thread>
18#include <unordered_map>
19
20// lib includes
21#include <boost/endian/buffers.hpp>
22
23// local includes
24#include "config.h"
25#include "globals.h"
26#include "input.h"
27#include "logging.h"
28#include "platform/common.h"
29#include "thread_pool.h"
30#include "utility.h"
31
32// Win32 WHEEL_DELTA constant
33#ifndef WHEEL_DELTA
34 #define WHEEL_DELTA 120
35#endif
36
37using namespace std::literals;
38
39namespace input {
40
41 constexpr auto MAX_GAMEPADS = std::min((std::size_t) platf::MAX_GAMEPADS, sizeof(std::int16_t) * 8);
42#define DISABLE_LEFT_BUTTON_DELAY ((thread_pool_util::ThreadPool::task_id_t) 0x01)
43#define ENABLE_LEFT_BUTTON_DELAY nullptr
44
45 constexpr auto VKEY_SHIFT = 0x10;
46 constexpr auto VKEY_LSHIFT = 0xA0;
47 constexpr auto VKEY_RSHIFT = 0xA1;
48 constexpr auto VKEY_CONTROL = 0x11;
49 constexpr auto VKEY_LCONTROL = 0xA2;
50 constexpr auto VKEY_RCONTROL = 0xA3;
51 constexpr auto VKEY_MENU = 0x12;
52 constexpr auto VKEY_LMENU = 0xA4;
53 constexpr auto VKEY_RMENU = 0xA5;
54
55 enum class button_state_e {
59 };
60
61 template<std::size_t N>
62 int alloc_id(std::bitset<N> &gamepad_mask) {
63 for (int x = 0; x < gamepad_mask.size(); ++x) {
64 if (!gamepad_mask[x]) {
65 gamepad_mask[x] = true;
66 return x;
67 }
68 }
69
70 return -1;
71 }
72
73 template<std::size_t N>
74 void free_id(std::bitset<N> &gamepad_mask, int id) {
75 gamepad_mask[id] = false;
76 }
77
78 typedef uint32_t key_press_id_t;
79
80 key_press_id_t make_kpid(uint16_t vk, uint8_t flags) {
81 return (key_press_id_t) vk << 8 | flags;
82 }
83
84 uint16_t vk_from_kpid(key_press_id_t kpid) {
85 return kpid >> 8;
86 }
87
88 uint8_t flags_from_kpid(key_press_id_t kpid) {
89 return kpid & 0xFF;
90 }
91
97 float from_netfloat(netfloat f) {
98 return boost::endian::endian_load<float, sizeof(float), boost::endian::order::little>(f);
99 }
100
108 float from_clamped_netfloat(netfloat f, float min, float max) {
109 return std::clamp(from_netfloat(f), min, max);
110 }
111
112 // Preserve the legacy single host input device set for normal streams.
113 // Isolated sessions get their own platform input below, keyed by session_tag.
114 static std::shared_ptr<platf::input_t> shared_platform_input;
115 static std::bitset<platf::MAX_GAMEPADS> gamepadMask {};
116
117 void free_gamepad(platf::input_t &platf_input, int id) {
118 platf::gamepad_update(platf_input, id, platf::gamepad_state_t {});
119 platf::free_gamepad(platf_input, id);
120
121 free_id(gamepadMask, id);
122 }
123
124 // The stream ended, but the client did not remove the gamepad.
125 void release_gamepad(platf::input_t &platf_input, int id) {
126 platf::gamepad_update(platf_input, id, platf::gamepad_state_t {});
127 platf::release_gamepad(platf_input, id);
128
129 free_id(gamepadMask, id);
130 }
131
132 struct gamepad_t {
133 explicit gamepad_t(std::shared_ptr<platf::input_t> platform_input):
134 gamepad_state {},
135 back_timeout_id {},
136 id {-1},
137 platform_input {std::move(platform_input)},
138 back_button_state {button_state_e::NONE} {
139 }
140
141 gamepad_t(gamepad_t &&other) noexcept:
142 gamepad_state {other.gamepad_state},
143 back_timeout_id {other.back_timeout_id},
144 id {std::exchange(other.id, -1)},
145 platform_input {std::move(other.platform_input)},
146 back_button_state {other.back_button_state} {
147 }
148 gamepad_t &operator=(gamepad_t &&) = delete;
149 gamepad_t(const gamepad_t &) = delete;
150 gamepad_t &operator=(const gamepad_t &) = delete;
151
152 ~gamepad_t() {
153 if (id >= 0) {
154 task_pool.push([id = this->id, platform_input = this->platform_input]() {
155 release_gamepad(*platform_input, id);
156 });
157 }
158 }
159
160 platf::gamepad_state_t gamepad_state;
161
162 thread_pool_util::ThreadPool::task_id_t back_timeout_id;
163
164 int id;
165 std::shared_ptr<platf::input_t> platform_input;
166
167 // When emulating the HOME button, we may need to artificially release the back button.
168 // Afterwards, the gamepad state on Hermes won't match the client state.
169 // To prevent Sunshine from sending erroneous input data to the active application,
170 // Sunshine forces the button to be in a specific state until the gamepad state matches that of
171 // Moonlight once more.
172 button_state_e back_button_state;
173 };
174
175 static std::shared_ptr<platf::input_t> platform_input_for(const std::string &tag, const std::string &socket) {
176 if (!socket.empty()) {
177#ifdef HERMES_BUILD_KWIN_TRANSPORT
178 return std::make_shared<platf::input_t>(platf::input_private_kwin(socket, tag));
179#else
180 throw std::runtime_error("Private KWin input support was not built");
181#endif
182 }
183 return tag.empty() ? shared_platform_input : std::make_shared<platf::input_t>(platf::input(tag));
184 }
185
186 struct input_t {
188 CTRL = 0x1,
189 ALT = 0x2,
190 SHIFT = 0x4,
192 };
193
194 input_t(
195 safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event,
196 platf::feedback_queue_t feedback_queue,
197 const std::string &session_tag,
198 const std::string &wayland_socket,
199 std::shared_ptr<platf::input_t> injected_platform = {},
200 std::unique_ptr<platf::client_input_t> injected_client = {}
201 ):
202 platform_input {
203 injected_platform ? std::move(injected_platform) : platform_input_for(session_tag, wayland_socket)
204 },
205 shortcutFlags {},
206 client_context {injected_client ? std::move(injected_client) : platf::allocate_client_input_context(*platform_input)},
207 touch_port_event {std::move(touch_port_event)},
208 feedback_queue {std::move(feedback_queue)},
209 mouse_left_button_timeout {},
210 touch_port {{0, 0, 0, 0}, 0, 0, {0, 0, 0, 0}, 0, 0, 1.0f},
211 accumulated_vscroll_delta {},
212 accumulated_hscroll_delta {} {
213 gamepads.reserve(MAX_GAMEPADS);
214 for (size_t index = 0; index < MAX_GAMEPADS; ++index) {
215 gamepads.emplace_back(platform_input);
216 }
217 }
218
219 std::shared_ptr<platf::input_t> platform_input;
220 task_pool_util::TaskPool::task_id_t key_press_repeat_id {};
221 std::unordered_map<key_press_id_t, bool> key_press {};
222 // Protocol mouse buttons are one-based, including BUTTON_X2 == 5.
223 std::array<std::uint8_t, 6> mouse_press {};
224
225 // Keep track of alt+ctrl+shift key combo
226 int shortcutFlags;
227
228 std::vector<gamepad_t> gamepads;
229 std::unique_ptr<platf::client_input_t> client_context;
230 std::string client_id;
231
232 safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event;
233 platf::feedback_queue_t feedback_queue;
234
235 std::list<std::vector<uint8_t>> input_queue;
236 std::mutex input_queue_lock;
237
238 thread_pool_util::ThreadPool::task_id_t mouse_left_button_timeout;
239
240 input::touch_port_t touch_port;
241
242 int32_t accumulated_vscroll_delta;
243 int32_t accumulated_hscroll_delta;
244
245 // Moves of the client's connect-time wiggle still to drop (isolated only).
246 int wake_wiggle_left = 0;
247 };
248
254 inline int apply_shortcut(short keyCode) {
255 constexpr auto VK_F1 = 0x70;
256 constexpr auto VK_F13 = 0x7C;
257
258 BOOST_LOG(debug) << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view();
259
260 if (keyCode >= VK_F1 && keyCode <= VK_F13) {
261 mail::man->event<int>(mail::switch_display)->raise(keyCode - VK_F1);
262 return 1;
263 }
264
265 switch (keyCode) {
266 case 0x4E /* VKEY_N */:
268 return 1;
269 }
270
271 return 0;
272 }
273
274 void print(PNV_REL_MOUSE_MOVE_PACKET packet) {
275 BOOST_LOG(debug)
276 << "--begin relative mouse move packet--"sv << std::endl
277 << "deltaX ["sv << util::endian::big(packet->deltaX) << ']' << std::endl
278 << "deltaY ["sv << util::endian::big(packet->deltaY) << ']' << std::endl
279 << "--end relative mouse move packet--"sv;
280 }
281
282 void print(PNV_ABS_MOUSE_MOVE_PACKET packet) {
283 BOOST_LOG(debug)
284 << "--begin absolute mouse move packet--"sv << std::endl
285 << "x ["sv << util::endian::big(packet->x) << ']' << std::endl
286 << "y ["sv << util::endian::big(packet->y) << ']' << std::endl
287 << "width ["sv << util::endian::big(packet->width) << ']' << std::endl
288 << "height ["sv << util::endian::big(packet->height) << ']' << std::endl
289 << "--end absolute mouse move packet--"sv;
290 }
291
292 void print(PNV_MOUSE_BUTTON_PACKET packet) {
293 BOOST_LOG(debug)
294 << "--begin mouse button packet--"sv << std::endl
295 << "action ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl
296 << "button ["sv << util::hex(packet->button).to_string_view() << ']' << std::endl
297 << "--end mouse button packet--"sv;
298 }
299
300 void print(PNV_SCROLL_PACKET packet) {
301 BOOST_LOG(debug)
302 << "--begin mouse scroll packet--"sv << std::endl
303 << "scrollAmt1 ["sv << util::endian::big(packet->scrollAmt1) << ']' << std::endl
304 << "--end mouse scroll packet--"sv;
305 }
306
307 void print(PSS_HSCROLL_PACKET packet) {
308 BOOST_LOG(debug)
309 << "--begin mouse hscroll packet--"sv << std::endl
310 << "scrollAmount ["sv << util::endian::big(packet->scrollAmount) << ']' << std::endl
311 << "--end mouse hscroll packet--"sv;
312 }
313
314 void print(PNV_KEYBOARD_PACKET packet) {
315 BOOST_LOG(debug)
316 << "--begin keyboard packet--"sv << std::endl
317 << "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl
318 << "keyCode ["sv << util::hex(packet->keyCode).to_string_view() << ']' << std::endl
319 << "modifiers ["sv << util::hex(packet->modifiers).to_string_view() << ']' << std::endl
320 << "flags ["sv << util::hex(packet->flags).to_string_view() << ']' << std::endl
321 << "--end keyboard packet--"sv;
322 }
323
324 void print(PNV_UNICODE_PACKET packet) {
325 std::string text(packet->text, util::endian::big(packet->header.size) - sizeof(packet->header.magic));
326 BOOST_LOG(debug)
327 << "--begin unicode packet--"sv << std::endl
328 << "text ["sv << text << ']' << std::endl
329 << "--end unicode packet--"sv;
330 }
331
332 void print(PNV_MULTI_CONTROLLER_PACKET packet) {
333 // Moonlight spams controller packet even when not necessary
334 BOOST_LOG(verbose)
335 << "--begin controller packet--"sv << std::endl
336 << "controllerNumber ["sv << packet->controllerNumber << ']' << std::endl
337 << "activeGamepadMask ["sv << util::hex(packet->activeGamepadMask).to_string_view() << ']' << std::endl
338 << "buttonFlags ["sv << util::hex((uint32_t) packet->buttonFlags | (packet->buttonFlags2 << 16)).to_string_view() << ']' << std::endl
339 << "leftTrigger ["sv << util::hex(packet->leftTrigger).to_string_view() << ']' << std::endl
340 << "rightTrigger ["sv << util::hex(packet->rightTrigger).to_string_view() << ']' << std::endl
341 << "leftStickX ["sv << packet->leftStickX << ']' << std::endl
342 << "leftStickY ["sv << packet->leftStickY << ']' << std::endl
343 << "rightStickX ["sv << packet->rightStickX << ']' << std::endl
344 << "rightStickY ["sv << packet->rightStickY << ']' << std::endl
345 << "--end controller packet--"sv;
346 }
347
352 void print(PSS_TOUCH_PACKET packet) {
353 BOOST_LOG(debug)
354 << "--begin touch packet--"sv << std::endl
355 << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
356 << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl
357 << "x ["sv << from_netfloat(packet->x) << ']' << std::endl
358 << "y ["sv << from_netfloat(packet->y) << ']' << std::endl
359 << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl
360 << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl
361 << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl
362 << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl
363 << "--end touch packet--"sv;
364 }
365
370 void print(PSS_PEN_PACKET packet) {
371 BOOST_LOG(debug)
372 << "--begin pen packet--"sv << std::endl
373 << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
374 << "toolType ["sv << util::hex(packet->toolType).to_string_view() << ']' << std::endl
375 << "penButtons ["sv << util::hex(packet->penButtons).to_string_view() << ']' << std::endl
376 << "x ["sv << from_netfloat(packet->x) << ']' << std::endl
377 << "y ["sv << from_netfloat(packet->y) << ']' << std::endl
378 << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl
379 << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl
380 << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl
381 << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl
382 << "tilt ["sv << (uint32_t) packet->tilt << ']' << std::endl
383 << "--end pen packet--"sv;
384 }
385
390 void print(PSS_CONTROLLER_ARRIVAL_PACKET packet) {
391 BOOST_LOG(debug)
392 << "--begin controller arrival packet--"sv << std::endl
393 << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl
394 << "type ["sv << util::hex(packet->type).to_string_view() << ']' << std::endl
395 << "capabilities ["sv << util::hex(packet->capabilities).to_string_view() << ']' << std::endl
396 << "supportedButtonFlags ["sv << util::hex(packet->supportedButtonFlags).to_string_view() << ']' << std::endl
397 << "--end controller arrival packet--"sv;
398 }
399
404 void print(PSS_CONTROLLER_TOUCH_PACKET packet) {
405 BOOST_LOG(debug)
406 << "--begin controller touch packet--"sv << std::endl
407 << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl
408 << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl
409 << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl
410 << "x ["sv << from_netfloat(packet->x) << ']' << std::endl
411 << "y ["sv << from_netfloat(packet->y) << ']' << std::endl
412 << "pressure ["sv << from_netfloat(packet->pressure) << ']' << std::endl
413 << "--end controller touch packet--"sv;
414 }
415
420 void print(PSS_CONTROLLER_MOTION_PACKET packet) {
421 BOOST_LOG(verbose)
422 << "--begin controller motion packet--"sv << std::endl
423 << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl
424 << "motionType ["sv << util::hex(packet->motionType).to_string_view() << ']' << std::endl
425 << "x ["sv << from_netfloat(packet->x) << ']' << std::endl
426 << "y ["sv << from_netfloat(packet->y) << ']' << std::endl
427 << "z ["sv << from_netfloat(packet->z) << ']' << std::endl
428 << "--end controller motion packet--"sv;
429 }
430
435 void print(PSS_CONTROLLER_BATTERY_PACKET packet) {
436 BOOST_LOG(verbose)
437 << "--begin controller battery packet--"sv << std::endl
438 << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl
439 << "batteryState ["sv << util::hex(packet->batteryState).to_string_view() << ']' << std::endl
440 << "batteryPercentage ["sv << util::hex(packet->batteryPercentage).to_string_view() << ']' << std::endl
441 << "--end controller battery packet--"sv;
442 }
443
444 void print(void *payload) {
445 auto header = (PNV_INPUT_HEADER) payload;
446
447 switch (util::endian::little(header->magic)) {
448 case MOUSE_MOVE_REL_MAGIC_GEN5:
449 print((PNV_REL_MOUSE_MOVE_PACKET) payload);
450 break;
451 case MOUSE_MOVE_ABS_MAGIC:
452 print((PNV_ABS_MOUSE_MOVE_PACKET) payload);
453 break;
454 case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5:
455 case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5:
456 print((PNV_MOUSE_BUTTON_PACKET) payload);
457 break;
458 case SCROLL_MAGIC_GEN5:
459 print((PNV_SCROLL_PACKET) payload);
460 break;
461 case SS_HSCROLL_MAGIC:
462 print((PSS_HSCROLL_PACKET) payload);
463 break;
464 case KEY_DOWN_EVENT_MAGIC:
465 case KEY_UP_EVENT_MAGIC:
466 print((PNV_KEYBOARD_PACKET) payload);
467 break;
468 case UTF8_TEXT_EVENT_MAGIC:
469 print((PNV_UNICODE_PACKET) payload);
470 break;
471 case MULTI_CONTROLLER_MAGIC_GEN5:
472 print((PNV_MULTI_CONTROLLER_PACKET) payload);
473 break;
474 case SS_TOUCH_MAGIC:
475 print((PSS_TOUCH_PACKET) payload);
476 break;
477 case SS_PEN_MAGIC:
478 print((PSS_PEN_PACKET) payload);
479 break;
480 case SS_CONTROLLER_ARRIVAL_MAGIC:
481 print((PSS_CONTROLLER_ARRIVAL_PACKET) payload);
482 break;
483 case SS_CONTROLLER_TOUCH_MAGIC:
484 print((PSS_CONTROLLER_TOUCH_PACKET) payload);
485 break;
486 case SS_CONTROLLER_MOTION_MAGIC:
487 print((PSS_CONTROLLER_MOTION_PACKET) payload);
488 break;
489 case SS_CONTROLLER_BATTERY_MAGIC:
490 print((PSS_CONTROLLER_BATTERY_PACKET) payload);
491 break;
492 }
493 }
494
495 void passthrough(std::shared_ptr<input_t> &input, PNV_REL_MOUSE_MOVE_PACKET packet) {
496 if (!config::input.mouse) {
497 return;
498 }
499
500 const auto dx = util::endian::big(packet->deltaX);
501 const auto dy = util::endian::big(packet->deltaY);
502
503 // moonlight-common-c wiggles the mouse (+1,+1 then -1,-1) right after
504 // connecting to wake the display. In gamescope that shows the cursor.
505 if (input->wake_wiggle_left) {
506 const int step = input->wake_wiggle_left == 2 ? 1 : -1;
507 if (dx == step && dy == step) {
508 --input->wake_wiggle_left;
509 return;
510 }
511 input->wake_wiggle_left = 0;
512 }
513
514 input->mouse_left_button_timeout = DISABLE_LEFT_BUTTON_DELAY;
515 platf::move_mouse(*input->platform_input, dx, dy);
516 }
517
525 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) {
526 auto &touch_port_event = input->touch_port_event;
527 auto &touch_port = input->touch_port;
528 if (touch_port_event->peek()) {
529 touch_port = *touch_port_event->pop();
530 }
531 if (!touch_port) {
532 BOOST_LOG(verbose) << "Ignoring early absolute input without a touch port"sv;
533 return std::nullopt;
534 }
535
536 auto scalarX = touch_port.width / size.first;
537 auto scalarY = touch_port.height / size.second;
538
539 float x = std::clamp(val.first, 0.0f, size.first) * scalarX;
540 float y = std::clamp(val.second, 0.0f, size.second) * scalarY;
541
542 auto offsetX = touch_port.client_offsetX;
543 auto offsetY = touch_port.client_offsetY;
544
545 x = std::clamp(x, offsetX, (size.first * scalarX) - offsetX);
546 y = std::clamp(y, offsetY, (size.second * scalarY) - offsetY);
547
548 return std::pair {(x - offsetX) * touch_port.scalar_inv, (y - offsetY) * touch_port.scalar_inv};
549 }
550
558 float multiply_polar_by_cartesian_scalar(float r, float angle, const std::pair<float, float> &scalar) {
559 // Convert polar to cartesian coordinates
560 float x = r * std::cos(angle);
561 float y = r * std::sin(angle);
562
563 // Scale the values
564 x *= scalar.first;
565 y *= scalar.second;
566
567 // Convert the result back to a polar radial coordinate
568 return std::sqrt(std::pow(x, 2) + std::pow(y, 2));
569 }
570
571 std::pair<float, float> scale_client_contact_area(const std::pair<float, float> &val, uint16_t rotation, const std::pair<float, float> &scalar) {
572 // If the rotation is unknown, we'll just scale both axes equally by using
573 // a 45-degree angle for our scaling calculations
574 float angle = rotation == LI_ROT_UNKNOWN ? (M_PI / 4) : (rotation * (M_PI / 180));
575
576 // If we have a major but not a minor axis, treat the touch as circular
577 float major = val.first;
578 float minor = val.second != 0.0f ? val.second : val.first;
579
580 // The minor axis is perpendicular to major axis so the angle must be rotated by 90 degrees
581 return {multiply_polar_by_cartesian_scalar(major, angle, scalar), multiply_polar_by_cartesian_scalar(minor, angle + (M_PI / 2), scalar)};
582 }
583
584 void passthrough(std::shared_ptr<input_t> &input, PNV_ABS_MOUSE_MOVE_PACKET packet) {
585 if (!config::input.mouse) {
586 return;
587 }
588
589 if (input->mouse_left_button_timeout == DISABLE_LEFT_BUTTON_DELAY) {
590 input->mouse_left_button_timeout = ENABLE_LEFT_BUTTON_DELAY;
591 }
592
593 float x = util::endian::big(packet->x);
594 float y = util::endian::big(packet->y);
595
596 // Prevent divide by zero
597 // Don't expect it to happen, but just in case
598 if (!packet->width || !packet->height) {
599 BOOST_LOG(warning) << "Client sent invalid touch dimensions"sv;
600
601 return;
602 }
603
604 auto width = (float) util::endian::big(packet->width);
605 auto height = (float) util::endian::big(packet->height);
606
607 auto tpcoords = client_to_touchport(input, {x, y}, {width, height});
608 if (!tpcoords) {
609 return;
610 }
611
612 auto &touch_port = input->touch_port;
613 platf::touch_port_t abs_port {
614 touch_port.offset_x,
615 touch_port.offset_y,
616 touch_port.env_width,
617 touch_port.env_height
618 };
619
620 platf::abs_mouse(*input->platform_input, abs_port, tpcoords->first, tpcoords->second);
621 }
622
623 void passthrough(std::shared_ptr<input_t> &input, PNV_MOUSE_BUTTON_PACKET packet) {
624 if (!config::input.mouse) {
625 return;
626 }
627
628 auto release = util::endian::little(packet->header.magic) == MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5;
629 auto button = util::endian::big(packet->button);
630 if (button > 0 && button < input->mouse_press.size()) {
631 if (input->mouse_press[button] != release) {
632 // button state is already what we want
633 return;
634 }
635
636 input->mouse_press[button] = !release;
637 }
652 if (button == BUTTON_LEFT && release && !input->mouse_left_button_timeout) {
653 auto f = [=]() {
654 auto left_released = input->mouse_press[BUTTON_LEFT];
655 if (left_released) {
656 // Already released left button
657 return;
658 }
659 platf::button_mouse(*input->platform_input, BUTTON_LEFT, release);
660
661 input->mouse_press[BUTTON_LEFT] = false;
662 input->mouse_left_button_timeout = nullptr;
663 };
664
665 input->mouse_left_button_timeout = task_pool.pushDelayed(std::move(f), 10ms).task_id;
666
667 return;
668 }
669 if (
670 button == BUTTON_RIGHT && !release &&
671 input->mouse_left_button_timeout > DISABLE_LEFT_BUTTON_DELAY
672 ) {
673 platf::button_mouse(*input->platform_input, BUTTON_RIGHT, false);
674 platf::button_mouse(*input->platform_input, BUTTON_RIGHT, true);
675
676 input->mouse_press[BUTTON_RIGHT] = false;
677
678 return;
679 }
680
681 platf::button_mouse(*input->platform_input, button, release);
682 }
683
684 short map_keycode(short keycode) {
685 auto it = config::input.keybindings.find(keycode);
686 if (it != std::end(config::input.keybindings)) {
687 return it->second;
688 }
689
690 return keycode;
691 }
692
696 inline void update_shortcutFlags(int *flags, short keyCode, bool release) {
697 switch (keyCode) {
698 case VKEY_SHIFT:
699 case VKEY_LSHIFT:
700 case VKEY_RSHIFT:
701 if (release) {
702 *flags &= ~input_t::SHIFT;
703 } else {
704 *flags |= input_t::SHIFT;
705 }
706 break;
707 case VKEY_CONTROL:
708 case VKEY_LCONTROL:
709 case VKEY_RCONTROL:
710 if (release) {
711 *flags &= ~input_t::CTRL;
712 } else {
713 *flags |= input_t::CTRL;
714 }
715 break;
716 case VKEY_MENU:
717 case VKEY_LMENU:
718 case VKEY_RMENU:
719 if (release) {
720 *flags &= ~input_t::ALT;
721 } else {
722 *flags |= input_t::ALT;
723 }
724 break;
725 }
726 }
727
728 bool is_modifier(uint16_t keyCode) {
729 switch (keyCode) {
730 case VKEY_SHIFT:
731 case VKEY_LSHIFT:
732 case VKEY_RSHIFT:
733 case VKEY_CONTROL:
734 case VKEY_LCONTROL:
735 case VKEY_RCONTROL:
736 case VKEY_MENU:
737 case VKEY_LMENU:
738 case VKEY_RMENU:
739 return true;
740 default:
741 return false;
742 }
743 }
744
745 void send_key_and_modifiers(
746 const std::shared_ptr<input_t> &input,
747 uint16_t key_code,
748 bool release,
749 uint8_t flags,
750 uint8_t synthetic_modifiers
751 ) {
752 if (!release) {
753 // Press any synthetic modifiers required for this key
754 if (synthetic_modifiers & MODIFIER_SHIFT) {
755 platf::keyboard_update(*input->platform_input, VKEY_SHIFT, false, flags);
756 }
757 if (synthetic_modifiers & MODIFIER_CTRL) {
758 platf::keyboard_update(*input->platform_input, VKEY_CONTROL, false, flags);
759 }
760 if (synthetic_modifiers & MODIFIER_ALT) {
761 platf::keyboard_update(*input->platform_input, VKEY_MENU, false, flags);
762 }
763 }
764
765 platf::keyboard_update(*input->platform_input, map_keycode(key_code), release, flags);
766
767 if (!release) {
768 // Raise any synthetic modifier keys we pressed
769 if (synthetic_modifiers & MODIFIER_SHIFT) {
770 platf::keyboard_update(*input->platform_input, VKEY_SHIFT, true, flags);
771 }
772 if (synthetic_modifiers & MODIFIER_CTRL) {
773 platf::keyboard_update(*input->platform_input, VKEY_CONTROL, true, flags);
774 }
775 if (synthetic_modifiers & MODIFIER_ALT) {
776 platf::keyboard_update(*input->platform_input, VKEY_MENU, true, flags);
777 }
778 }
779 }
780
781 void repeat_key(
782 std::shared_ptr<input_t> input,
783 uint16_t key_code,
784 uint8_t flags,
785 uint8_t synthetic_modifiers
786 ) {
787 // If key no longer pressed, stop repeating
788 if (!input->key_press[make_kpid(key_code, flags)]) {
789 input->key_press_repeat_id = nullptr;
790 return;
791 }
792
793 send_key_and_modifiers(input, key_code, false, flags, synthetic_modifiers);
794
795 input->key_press_repeat_id = task_pool.pushDelayed(
796 repeat_key,
797 config::input.key_repeat_period,
798 input,
799 key_code,
800 flags,
801 synthetic_modifiers
802 ).task_id;
803 }
804
805 void passthrough(std::shared_ptr<input_t> &input, PNV_KEYBOARD_PACKET packet) {
806 if (!config::input.keyboard) {
807 return;
808 }
809
810 auto release = util::endian::little(packet->header.magic) == KEY_UP_EVENT_MAGIC;
811 auto keyCode = packet->keyCode & 0x00FF;
812
813 // Set synthetic modifier flags if the keyboard packet is requesting modifier
814 // keys that are not current pressed.
815 uint8_t synthetic_modifiers = 0;
816 if (!release && !is_modifier(keyCode)) {
817 if (!(input->shortcutFlags & input_t::SHIFT) && (packet->modifiers & MODIFIER_SHIFT)) {
818 synthetic_modifiers |= MODIFIER_SHIFT;
819 }
820 if (!(input->shortcutFlags & input_t::CTRL) && (packet->modifiers & MODIFIER_CTRL)) {
821 synthetic_modifiers |= MODIFIER_CTRL;
822 }
823 if (!(input->shortcutFlags & input_t::ALT) && (packet->modifiers & MODIFIER_ALT)) {
824 synthetic_modifiers |= MODIFIER_ALT;
825 }
826 }
827
828 auto &pressed = input->key_press[make_kpid(keyCode, packet->flags)];
829 if (!pressed) {
830 if (!release) {
831 // A new key has been pressed down, we need to check for key combo's
832 // If a key-combo has been pressed down, don't pass it through
833 if (input->shortcutFlags == input_t::SHORTCUT && apply_shortcut(keyCode) > 0) {
834 return;
835 }
836
837 if (input->key_press_repeat_id) {
838 task_pool.cancel(input->key_press_repeat_id);
839 }
840
841 if (config::input.key_repeat_delay.count() > 0) {
842 input->key_press_repeat_id = task_pool.pushDelayed(
843 repeat_key,
844 config::input.key_repeat_delay,
845 input,
846 keyCode,
847 packet->flags,
848 synthetic_modifiers
849 ).task_id;
850 }
851 } else {
852 // Already released
853 return;
854 }
855 } else if (!release) {
856 // Already pressed down key
857 return;
858 }
859
860 pressed = !release;
861
862 send_key_and_modifiers(input, keyCode, release, packet->flags, synthetic_modifiers);
863
864 update_shortcutFlags(&input->shortcutFlags, map_keycode(keyCode), release);
865 }
866
872 void passthrough(std::shared_ptr<input_t> &input, PNV_SCROLL_PACKET packet) {
873 if (!config::input.mouse) {
874 return;
875 }
876
877 if (config::input.high_resolution_scrolling) {
878 platf::scroll(*input->platform_input, util::endian::big(packet->scrollAmt1));
879 } else {
880 input->accumulated_vscroll_delta += util::endian::big(packet->scrollAmt1);
881 auto full_ticks = input->accumulated_vscroll_delta / WHEEL_DELTA;
882 if (full_ticks) {
883 // Send any full ticks that have accumulated and store the rest
884 platf::scroll(*input->platform_input, full_ticks * WHEEL_DELTA);
885 input->accumulated_vscroll_delta -= full_ticks * WHEEL_DELTA;
886 }
887 }
888 }
889
895 void passthrough(std::shared_ptr<input_t> &input, PSS_HSCROLL_PACKET packet) {
896 if (!config::input.mouse) {
897 return;
898 }
899
900 if (config::input.high_resolution_scrolling) {
901 platf::hscroll(*input->platform_input, util::endian::big(packet->scrollAmount));
902 } else {
903 input->accumulated_hscroll_delta += util::endian::big(packet->scrollAmount);
904 auto full_ticks = input->accumulated_hscroll_delta / WHEEL_DELTA;
905 if (full_ticks) {
906 // Send any full ticks that have accumulated and store the rest
907 platf::hscroll(*input->platform_input, full_ticks * WHEEL_DELTA);
908 input->accumulated_hscroll_delta -= full_ticks * WHEEL_DELTA;
909 }
910 }
911 }
912
913 void passthrough(std::shared_ptr<input_t> &input, PNV_UNICODE_PACKET packet) {
914 if (!config::input.keyboard) {
915 return;
916 }
917
918 auto size = util::endian::big(packet->header.size) - sizeof(packet->header.magic);
919 platf::unicode(*input->platform_input, packet->text, size);
920 }
921
927 void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_ARRIVAL_PACKET packet) {
928 if (!config::input.controller) {
929 return;
930 }
931
932 if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) {
933 BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']';
934 return;
935 }
936
937 if (input->gamepads[packet->controllerNumber].id >= 0) {
938 BOOST_LOG(warning) << "ControllerNumber already allocated ["sv << packet->controllerNumber << ']';
939 return;
940 }
941
943 packet->type,
944 util::endian::little(packet->capabilities),
945 util::endian::little(packet->supportedButtonFlags),
946 input->client_id,
947 };
948
949 auto id = alloc_id(gamepadMask);
950 if (id < 0) {
951 return;
952 }
953
954 // Allocate a new gamepad
955 if (platf::alloc_gamepad(*input->platform_input, {id, packet->controllerNumber}, arrival, input->feedback_queue)) {
956 free_id(gamepadMask, id);
957 return;
958 }
959
960 input->gamepads[packet->controllerNumber].id = id;
961 }
962
964 int output_width,
965 int output_height,
966 int offset_x,
967 int offset_y,
968 int env_width,
969 int env_height,
970 bool binds_to_output
971 ) {
972 // Bound to one output, the device's surface *is* that output: a touch in
973 // the middle of the client's picture is the middle of the device, whatever
974 // else the desktop holds. Measured against the desktop instead, every
975 // touch fell short of where it belonged by the ratio between the two - on
976 // a 2560-wide output inside a 6000-wide desktop, the middle landed a fifth
977 // of the way across.
978 if (binds_to_output && output_width > 0 && output_height > 0) {
979 return {0, 0, output_width, output_height};
980 }
981 return {offset_x, offset_y, env_width, env_height};
982 }
983
989 void passthrough(std::shared_ptr<input_t> &input, PSS_TOUCH_PACKET packet) {
990 if (!config::input.mouse) {
991 return;
992 }
993
994 // Convert the client normalized coordinates to touchport coordinates
995 auto coords = client_to_touchport(input, {from_clamped_netfloat(packet->x, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->y, 0.0f, 1.0f) * 65535.f}, {65535.f, 65535.f});
996 if (!coords) {
997 return;
998 }
999
1000 auto &touch_port = input->touch_port;
1001 // A touchscreen or a pen is measured against the surface the session
1002 // maps it onto, which is not always the whole desktop.
1003 const auto &abs_port = touch_port.device_port;
1004
1005 // Renormalize the coordinates
1006 coords->first /= abs_port.width;
1007 coords->second /= abs_port.height;
1008
1009 // Normalize rotation value to 0-359 degree range
1010 auto rotation = util::endian::little(packet->rotation);
1011 if (rotation != LI_ROT_UNKNOWN) {
1012 rotation %= 360;
1013 }
1014
1015 // Normalize the contact area based on the touchport
1016 auto contact_area = scale_client_contact_area(
1017 {from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f,
1018 from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f},
1019 rotation,
1020 {abs_port.width / 65535.f, abs_port.height / 65535.f}
1021 );
1022
1023 platf::touch_input_t touch {
1024 packet->eventType,
1025 rotation,
1026 util::endian::little(packet->pointerId),
1027 coords->first,
1028 coords->second,
1029 from_clamped_netfloat(packet->pressureOrDistance, 0.0f, 1.0f),
1030 contact_area.first,
1031 contact_area.second,
1032 };
1033
1034 platf::touch_update(input->client_context.get(), abs_port, touch);
1035 }
1036
1042 void passthrough(std::shared_ptr<input_t> &input, PSS_PEN_PACKET packet) {
1043 if (!config::input.mouse) {
1044 return;
1045 }
1046
1047 // Convert the client normalized coordinates to touchport coordinates
1048 auto coords = client_to_touchport(input, {from_clamped_netfloat(packet->x, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->y, 0.0f, 1.0f) * 65535.f}, {65535.f, 65535.f});
1049 if (!coords) {
1050 return;
1051 }
1052
1053 auto &touch_port = input->touch_port;
1054 // A touchscreen or a pen is measured against the surface the session
1055 // maps it onto, which is not always the whole desktop.
1056 const auto &abs_port = touch_port.device_port;
1057
1058 // Renormalize the coordinates
1059 coords->first /= abs_port.width;
1060 coords->second /= abs_port.height;
1061
1062 // Normalize rotation value to 0-359 degree range
1063 auto rotation = util::endian::little(packet->rotation);
1064 if (rotation != LI_ROT_UNKNOWN) {
1065 rotation %= 360;
1066 }
1067
1068 // Normalize the contact area based on the touchport
1069 auto contact_area = scale_client_contact_area(
1070 {from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f,
1071 from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f},
1072 rotation,
1073 {abs_port.width / 65535.f, abs_port.height / 65535.f}
1074 );
1075
1076 platf::pen_input_t pen {
1077 packet->eventType,
1078 packet->toolType,
1079 packet->penButtons,
1080 packet->tilt,
1081 rotation,
1082 coords->first,
1083 coords->second,
1084 from_clamped_netfloat(packet->pressureOrDistance, 0.0f, 1.0f),
1085 contact_area.first,
1086 contact_area.second,
1087 };
1088
1089 platf::pen_update(input->client_context.get(), abs_port, pen);
1090 }
1091
1097 void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_TOUCH_PACKET packet) {
1098 if (!config::input.controller) {
1099 return;
1100 }
1101
1102 if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) {
1103 BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']';
1104 return;
1105 }
1106
1107 auto &gamepad = input->gamepads[packet->controllerNumber];
1108 if (gamepad.id < 0) {
1109 BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv;
1110 return;
1111 }
1112
1114 {gamepad.id, packet->controllerNumber},
1115 packet->eventType,
1116 util::endian::little(packet->pointerId),
1117 from_clamped_netfloat(packet->x, 0.0f, 1.0f),
1118 from_clamped_netfloat(packet->y, 0.0f, 1.0f),
1119 from_clamped_netfloat(packet->pressure, 0.0f, 1.0f),
1120 };
1121
1122 platf::gamepad_touch(*input->platform_input, touch);
1123 }
1124
1130 void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_MOTION_PACKET packet) {
1131 if (!config::input.controller) {
1132 return;
1133 }
1134
1135 if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) {
1136 BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']';
1137 return;
1138 }
1139
1140 auto &gamepad = input->gamepads[packet->controllerNumber];
1141 if (gamepad.id < 0) {
1142 BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv;
1143 return;
1144 }
1145
1147 {gamepad.id, packet->controllerNumber},
1148 packet->motionType,
1149 from_netfloat(packet->x),
1150 from_netfloat(packet->y),
1151 from_netfloat(packet->z),
1152 };
1153
1154 platf::gamepad_motion(*input->platform_input, motion);
1155 }
1156
1162 void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_BATTERY_PACKET packet) {
1163 if (!config::input.controller) {
1164 return;
1165 }
1166
1167 if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) {
1168 BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']';
1169 return;
1170 }
1171
1172 auto &gamepad = input->gamepads[packet->controllerNumber];
1173 if (gamepad.id < 0) {
1174 BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv;
1175 return;
1176 }
1177
1178 platf::gamepad_battery_t battery {
1179 {gamepad.id, packet->controllerNumber},
1180 packet->batteryState,
1181 packet->batteryPercentage
1182 };
1183
1184 platf::gamepad_battery(*input->platform_input, battery);
1185 }
1186
1187 void passthrough(std::shared_ptr<input_t> &input, PNV_MULTI_CONTROLLER_PACKET packet) {
1188 if (!config::input.controller) {
1189 return;
1190 }
1191
1192 if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) {
1193 BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']';
1194
1195 return;
1196 }
1197
1198 auto &gamepad = input->gamepads[packet->controllerNumber];
1199
1200 // If this is an event for a new gamepad, create the gamepad now. Ideally, the client would
1201 // send a controller arrival instead of this but it's still supported for legacy clients.
1202 if ((packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id < 0) {
1203 auto id = alloc_id(gamepadMask);
1204 if (id < 0) {
1205 return;
1206 }
1207
1208 if (platf::alloc_gamepad(*input->platform_input, {id, (uint8_t) packet->controllerNumber}, {.client_id = input->client_id}, input->feedback_queue)) {
1209 free_id(gamepadMask, id);
1210 return;
1211 }
1212
1213 gamepad.id = id;
1214 } else if (!(packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id >= 0) {
1215 // If this is the final event for a gamepad being removed, free the gamepad and return.
1216 free_gamepad(*input->platform_input, gamepad.id);
1217 gamepad.id = -1;
1218 return;
1219 }
1220
1221 // If this gamepad has not been initialized, ignore it.
1222 // This could happen when platf::alloc_gamepad fails
1223 if (gamepad.id < 0) {
1224 BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv;
1225 return;
1226 }
1227
1228 std::uint16_t bf = packet->buttonFlags;
1229 std::uint32_t bf2 = packet->buttonFlags2;
1230 platf::gamepad_state_t gamepad_state {
1231 bf | (bf2 << 16),
1232 packet->leftTrigger,
1233 packet->rightTrigger,
1234 packet->leftStickX,
1235 packet->leftStickY,
1236 packet->rightStickX,
1237 packet->rightStickY
1238 };
1239
1240 auto bf_new = gamepad_state.buttonFlags;
1241 switch (gamepad.back_button_state) {
1242 case button_state_e::UP:
1243 if (!(platf::BACK & bf_new)) {
1244 gamepad.back_button_state = button_state_e::NONE;
1245 }
1246 gamepad_state.buttonFlags &= ~platf::BACK;
1247 break;
1248 case button_state_e::DOWN:
1249 if (platf::BACK & bf_new) {
1250 gamepad.back_button_state = button_state_e::NONE;
1251 }
1252 gamepad_state.buttonFlags |= platf::BACK;
1253 break;
1254 case button_state_e::NONE:
1255 break;
1256 }
1257
1258 bf = gamepad_state.buttonFlags ^ gamepad.gamepad_state.buttonFlags;
1259 bf_new = gamepad_state.buttonFlags;
1260
1261 if (platf::BACK & bf) {
1262 if (platf::BACK & bf_new) {
1263 // Don't emulate home button if timeout < 0
1264 if (config::input.back_button_timeout >= 0ms) {
1265 auto f = [input, controller = packet->controllerNumber]() {
1266 auto &gamepad = input->gamepads[controller];
1267
1268 auto &state = gamepad.gamepad_state;
1269
1270 // Force the back button up
1271 gamepad.back_button_state = button_state_e::UP;
1272 state.buttonFlags &= ~platf::BACK;
1273 platf::gamepad_update(*input->platform_input, gamepad.id, state);
1274
1275 // Press Home button
1276 state.buttonFlags |= platf::HOME;
1277 platf::gamepad_update(*input->platform_input, gamepad.id, state);
1278
1279 // Sleep for a short time to allow the input to be detected
1280 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1281
1282 // Release Home button
1283 state.buttonFlags &= ~platf::HOME;
1284 platf::gamepad_update(*input->platform_input, gamepad.id, state);
1285
1286 gamepad.back_timeout_id = nullptr;
1287 };
1288
1289 gamepad.back_timeout_id = task_pool.pushDelayed(std::move(f), config::input.back_button_timeout).task_id;
1290 }
1291 } else if (gamepad.back_timeout_id) {
1292 task_pool.cancel(gamepad.back_timeout_id);
1293 gamepad.back_timeout_id = nullptr;
1294 }
1295 }
1296
1297 platf::gamepad_update(*input->platform_input, gamepad.id, gamepad_state);
1298
1299 gamepad.gamepad_state = gamepad_state;
1300 }
1301
1307
1314 batch_result_e batch(PNV_REL_MOUSE_MOVE_PACKET dest, PNV_REL_MOUSE_MOVE_PACKET src) {
1315 short deltaX, deltaY;
1316
1317 // Batching is safe as long as the result doesn't overflow a 16-bit integer
1318 if (!__builtin_add_overflow(util::endian::big(dest->deltaX), util::endian::big(src->deltaX), &deltaX)) {
1320 }
1321 if (!__builtin_add_overflow(util::endian::big(dest->deltaY), util::endian::big(src->deltaY), &deltaY)) {
1323 }
1324
1325 // Take the sum of deltas
1326 dest->deltaX = util::endian::big(deltaX);
1327 dest->deltaY = util::endian::big(deltaY);
1329 }
1330
1337 batch_result_e batch(PNV_ABS_MOUSE_MOVE_PACKET dest, PNV_ABS_MOUSE_MOVE_PACKET src) {
1338 // Batching must only happen if the reference width and height don't change
1339 if (dest->width != src->width || dest->height != src->height) {
1341 }
1342
1343 // Take the latest absolute position
1344 *dest = *src;
1346 }
1347
1354 batch_result_e batch(PNV_SCROLL_PACKET dest, PNV_SCROLL_PACKET src) {
1355 short scrollAmt;
1356
1357 // Batching is safe as long as the result doesn't overflow a 16-bit integer
1358 if (!__builtin_add_overflow(util::endian::big(dest->scrollAmt1), util::endian::big(src->scrollAmt1), &scrollAmt)) {
1360 }
1361
1362 // Take the sum of delta
1363 dest->scrollAmt1 = util::endian::big(scrollAmt);
1364 dest->scrollAmt2 = util::endian::big(scrollAmt);
1366 }
1367
1374 batch_result_e batch(PSS_HSCROLL_PACKET dest, PSS_HSCROLL_PACKET src) {
1375 short scrollAmt;
1376
1377 // Batching is safe as long as the result doesn't overflow a 16-bit integer
1378 if (!__builtin_add_overflow(util::endian::big(dest->scrollAmount), util::endian::big(src->scrollAmount), &scrollAmt)) {
1380 }
1381
1382 // Take the sum of delta
1383 dest->scrollAmount = util::endian::big(scrollAmt);
1385 }
1386
1393 batch_result_e batch(PNV_MULTI_CONTROLLER_PACKET dest, PNV_MULTI_CONTROLLER_PACKET src) {
1394 // Do not allow batching if the active controllers change
1395 if (dest->activeGamepadMask != src->activeGamepadMask) {
1397 }
1398
1399 // We can only batch entries for the same controller, but allow batching attempts to continue
1400 // in case we have more packets for this controller later in the queue.
1401 if (dest->controllerNumber != src->controllerNumber) {
1403 }
1404
1405 // Do not allow batching if the button state changes on this controller
1406 if (dest->buttonFlags != src->buttonFlags || dest->buttonFlags2 != src->buttonFlags2) {
1408 }
1409
1410 // Take the latest state
1411 *dest = *src;
1413 }
1414
1421 batch_result_e batch(PSS_TOUCH_PACKET dest, PSS_TOUCH_PACKET src) {
1422 // Only batch hover or move events
1423 if (dest->eventType != LI_TOUCH_EVENT_MOVE &&
1424 dest->eventType != LI_TOUCH_EVENT_HOVER) {
1426 }
1427
1428 // Don't batch beyond state changing events
1429 if (src->eventType != LI_TOUCH_EVENT_MOVE &&
1430 src->eventType != LI_TOUCH_EVENT_HOVER) {
1432 }
1433
1434 // Batched events must be the same pointer ID
1435 if (dest->pointerId != src->pointerId) {
1437 }
1438
1439 // The pointer must be in the same state
1440 if (dest->eventType != src->eventType) {
1442 }
1443
1444 // Take the latest state
1445 *dest = *src;
1447 }
1448
1455 batch_result_e batch(PSS_PEN_PACKET dest, PSS_PEN_PACKET src) {
1456 // Only batch hover or move events
1457 if (dest->eventType != LI_TOUCH_EVENT_MOVE &&
1458 dest->eventType != LI_TOUCH_EVENT_HOVER) {
1460 }
1461
1462 // Batched events must be the same type
1463 if (dest->eventType != src->eventType) {
1465 }
1466
1467 // Do not allow batching if the button state changes
1468 if (dest->penButtons != src->penButtons) {
1470 }
1471
1472 // Do not batch beyond tool changes
1473 if (dest->toolType != src->toolType) {
1475 }
1476
1477 // Take the latest state
1478 *dest = *src;
1480 }
1481
1488 batch_result_e batch(PSS_CONTROLLER_TOUCH_PACKET dest, PSS_CONTROLLER_TOUCH_PACKET src) {
1489 // Only batch hover or move events
1490 if (dest->eventType != LI_TOUCH_EVENT_MOVE &&
1491 dest->eventType != LI_TOUCH_EVENT_HOVER) {
1493 }
1494
1495 // We can only batch entries for the same controller, but allow batching attempts to continue
1496 // in case we have more packets for this controller later in the queue.
1497 if (dest->controllerNumber != src->controllerNumber) {
1499 }
1500
1501 // Don't batch beyond state changing events
1502 if (src->eventType != LI_TOUCH_EVENT_MOVE &&
1503 src->eventType != LI_TOUCH_EVENT_HOVER) {
1505 }
1506
1507 // Batched events must be the same pointer ID
1508 if (dest->pointerId != src->pointerId) {
1510 }
1511
1512 // The pointer must be in the same state
1513 if (dest->eventType != src->eventType) {
1515 }
1516
1517 // Take the latest state
1518 *dest = *src;
1520 }
1521
1528 batch_result_e batch(PSS_CONTROLLER_MOTION_PACKET dest, PSS_CONTROLLER_MOTION_PACKET src) {
1529 // We can only batch entries for the same controller, but allow batching attempts to continue
1530 // in case we have more packets for this controller later in the queue.
1531 if (dest->controllerNumber != src->controllerNumber) {
1533 }
1534
1535 // Batched events must be the same sensor
1536 if (dest->motionType != src->motionType) {
1538 }
1539
1540 // Take the latest state
1541 *dest = *src;
1543 }
1544
1551 batch_result_e batch(PNV_INPUT_HEADER dest, PNV_INPUT_HEADER src) {
1552 // We can only batch if the packet types are the same
1553 if (dest->magic != src->magic) {
1555 }
1556
1557 // We can only batch certain message types
1558 switch (util::endian::little(dest->magic)) {
1559 case MOUSE_MOVE_REL_MAGIC_GEN5:
1560 return batch((PNV_REL_MOUSE_MOVE_PACKET) dest, (PNV_REL_MOUSE_MOVE_PACKET) src);
1561 case MOUSE_MOVE_ABS_MAGIC:
1562 return batch((PNV_ABS_MOUSE_MOVE_PACKET) dest, (PNV_ABS_MOUSE_MOVE_PACKET) src);
1563 case SCROLL_MAGIC_GEN5:
1564 return batch((PNV_SCROLL_PACKET) dest, (PNV_SCROLL_PACKET) src);
1565 case SS_HSCROLL_MAGIC:
1566 return batch((PSS_HSCROLL_PACKET) dest, (PSS_HSCROLL_PACKET) src);
1567 case MULTI_CONTROLLER_MAGIC_GEN5:
1568 return batch((PNV_MULTI_CONTROLLER_PACKET) dest, (PNV_MULTI_CONTROLLER_PACKET) src);
1569 case SS_TOUCH_MAGIC:
1570 return batch((PSS_TOUCH_PACKET) dest, (PSS_TOUCH_PACKET) src);
1571 case SS_PEN_MAGIC:
1572 return batch((PSS_PEN_PACKET) dest, (PSS_PEN_PACKET) src);
1573 case SS_CONTROLLER_TOUCH_MAGIC:
1574 return batch((PSS_CONTROLLER_TOUCH_PACKET) dest, (PSS_CONTROLLER_TOUCH_PACKET) src);
1575 case SS_CONTROLLER_MOTION_MAGIC:
1576 return batch((PSS_CONTROLLER_MOTION_PACKET) dest, (PSS_CONTROLLER_MOTION_PACKET) src);
1577 default:
1578 // Not a batchable message type
1580 }
1581 }
1582
1587 void passthrough_next_message(std::shared_ptr<input_t> input) {
1588 // 'entry' backs the 'payload' pointer, so they must remain in scope together
1589 std::vector<uint8_t> entry;
1590 PNV_INPUT_HEADER payload;
1591
1592 // Lock the input queue while batching, but release it before sending
1593 // the input to the OS. This avoids potentially lengthy lock contention
1594 // in the control stream thread while input is being processed by the OS.
1595 {
1596 std::lock_guard<std::mutex> lg(input->input_queue_lock);
1597
1598 // If all entries have already been processed, nothing to do
1599 if (input->input_queue.empty()) {
1600 return;
1601 }
1602
1603 // Pop off the first entry, which we will send
1604 entry = input->input_queue.front();
1605 payload = (PNV_INPUT_HEADER) entry.data();
1606 input->input_queue.pop_front();
1607
1608 // Try to batch with remaining items on the queue
1609 auto i = input->input_queue.begin();
1610 while (i != input->input_queue.end()) {
1611 auto batchable_entry = *i;
1612 auto batchable_payload = (PNV_INPUT_HEADER) batchable_entry.data();
1613
1614 auto batch_result = batch(payload, batchable_payload);
1615 if (batch_result == batch_result_e::terminate_batch) {
1616 // Stop batching
1617 break;
1618 } else if (batch_result == batch_result_e::batched) {
1619 // Erase this entry since it was batched
1620 i = input->input_queue.erase(i);
1621 } else {
1622 // We couldn't batch this entry, but try to batch later entries.
1623 i++;
1624 }
1625 }
1626 }
1627
1628 // Print the final input packet
1629 input::print((void *) payload);
1630
1631 // Send the batched input to the OS
1632 switch (util::endian::little(payload->magic)) {
1633 case MOUSE_MOVE_REL_MAGIC_GEN5:
1634 passthrough(input, (PNV_REL_MOUSE_MOVE_PACKET) payload);
1635 break;
1636 case MOUSE_MOVE_ABS_MAGIC:
1637 passthrough(input, (PNV_ABS_MOUSE_MOVE_PACKET) payload);
1638 break;
1639 case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5:
1640 case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5:
1641 passthrough(input, (PNV_MOUSE_BUTTON_PACKET) payload);
1642 break;
1643 case SCROLL_MAGIC_GEN5:
1644 passthrough(input, (PNV_SCROLL_PACKET) payload);
1645 break;
1646 case SS_HSCROLL_MAGIC:
1647 passthrough(input, (PSS_HSCROLL_PACKET) payload);
1648 break;
1649 case KEY_DOWN_EVENT_MAGIC:
1650 case KEY_UP_EVENT_MAGIC:
1651 passthrough(input, (PNV_KEYBOARD_PACKET) payload);
1652 break;
1653 case UTF8_TEXT_EVENT_MAGIC:
1654 passthrough(input, (PNV_UNICODE_PACKET) payload);
1655 break;
1656 case MULTI_CONTROLLER_MAGIC_GEN5:
1657 passthrough(input, (PNV_MULTI_CONTROLLER_PACKET) payload);
1658 break;
1659 case SS_TOUCH_MAGIC:
1660 passthrough(input, (PSS_TOUCH_PACKET) payload);
1661 break;
1662 case SS_PEN_MAGIC:
1663 passthrough(input, (PSS_PEN_PACKET) payload);
1664 break;
1665 case SS_CONTROLLER_ARRIVAL_MAGIC:
1666 passthrough(input, (PSS_CONTROLLER_ARRIVAL_PACKET) payload);
1667 break;
1668 case SS_CONTROLLER_TOUCH_MAGIC:
1669 passthrough(input, (PSS_CONTROLLER_TOUCH_PACKET) payload);
1670 break;
1671 case SS_CONTROLLER_MOTION_MAGIC:
1672 passthrough(input, (PSS_CONTROLLER_MOTION_PACKET) payload);
1673 break;
1674 case SS_CONTROLLER_BATTERY_MAGIC:
1675 passthrough(input, (PSS_CONTROLLER_BATTERY_PACKET) payload);
1676 break;
1677 }
1678 }
1679
1685 void passthrough(std::shared_ptr<input_t> &input, std::vector<std::uint8_t> &&input_data, const crypto::PERM& permission) {
1686 // No input permissions at all
1687 if (!(permission & crypto::PERM::_all_inputs)) {
1688 return;
1689 }
1690
1691 // Have some input permission
1692 // Otherwise have all input permission
1693 if ((permission & crypto::PERM::_all_inputs) != crypto::PERM::_all_inputs) {
1694 PNV_INPUT_HEADER payload = (PNV_INPUT_HEADER)input_data.data();
1695
1696 // Check permission
1697 switch (util::endian::little(payload->magic)) {
1698 case MULTI_CONTROLLER_MAGIC_GEN5:
1699 case SS_CONTROLLER_ARRIVAL_MAGIC:
1700 case SS_CONTROLLER_TOUCH_MAGIC:
1701 case SS_CONTROLLER_MOTION_MAGIC:
1702 case SS_CONTROLLER_BATTERY_MAGIC:
1703 if (!(permission & crypto::PERM::input_controller)) {
1704 return;
1705 } else {
1706 break;
1707 }
1708 case MOUSE_MOVE_REL_MAGIC_GEN5:
1709 case MOUSE_MOVE_ABS_MAGIC:
1710 case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5:
1711 case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5:
1712 case SCROLL_MAGIC_GEN5:
1713 case SS_HSCROLL_MAGIC:
1714 if (!(permission & crypto::PERM::input_mouse)) {
1715 return;
1716 } else {
1717 break;
1718 }
1719 case KEY_DOWN_EVENT_MAGIC:
1720 case KEY_UP_EVENT_MAGIC:
1721 case UTF8_TEXT_EVENT_MAGIC:
1722 if (!(permission & crypto::PERM::input_kbd)) {
1723 return;
1724 } else {
1725 break;
1726 }
1727 case SS_TOUCH_MAGIC:
1728 if (!(permission & crypto::PERM::input_touch)) {
1729 return;
1730 } else {
1731 break;
1732 }
1733 case SS_PEN_MAGIC:
1734 if (!(permission & crypto::PERM::input_pen)) {
1735 return;
1736 } else {
1737 break;
1738 }
1739 default:
1740 // Unknown input event
1741 return;
1742 }
1743 }
1744
1745 {
1746 std::lock_guard<std::mutex> lg(input->input_queue_lock);
1747 input->input_queue.push_back(std::move(input_data));
1748 }
1750 }
1751
1752 void reset(std::shared_ptr<input_t> &input) {
1753 task_pool.cancel(input->key_press_repeat_id);
1754 task_pool.cancel(input->mouse_left_button_timeout);
1755
1756 // Ensure input is synchronous, by using the task_pool
1757 task_pool.push([input]() {
1758 for (int x = 0; x < input->mouse_press.size(); ++x) {
1759 if (input->mouse_press[x]) {
1760 platf::button_mouse(*input->platform_input, x, true);
1761 input->mouse_press[x] = false;
1762 }
1763 }
1764
1765 for (auto &kp : input->key_press) {
1766 if (!kp.second) {
1767 // already released
1768 continue;
1769 }
1770 platf::keyboard_update(*input->platform_input, map_keycode(vk_from_kpid(kp.first) & 0x00FF), true, flags_from_kpid(kp.first));
1771 input->key_press[kp.first] = false;
1772 }
1773
1774 for (auto &gamepad : input->gamepads) {
1775 if (gamepad.back_timeout_id) {
1776 task_pool.cancel(gamepad.back_timeout_id);
1777 gamepad.back_timeout_id = nullptr;
1778 }
1779 if (gamepad.id >= 0) {
1780 platf::gamepad_update(*input->platform_input, gamepad.id, {});
1781 platf::gamepad_touch(*input->platform_input, {{gamepad.id, 0}, LI_TOUCH_EVENT_CANCEL_ALL});
1782 }
1783 gamepad.gamepad_state = {};
1784 gamepad.back_button_state = button_state_e::NONE;
1785 }
1786 const auto &port = input->touch_port.device_port;
1787 platf::touch_update(input->client_context.get(), port, {.eventType = LI_TOUCH_EVENT_CANCEL_ALL});
1788 platf::pen_update(input->client_context.get(), port, {.eventType = LI_TOUCH_EVENT_CANCEL_ALL});
1789 input->shortcutFlags = 0;
1790 input->key_press_repeat_id = nullptr;
1791 input->mouse_left_button_timeout = nullptr;
1792 });
1793 }
1794
1796 public:
1797 ~deinit_t() override {
1798 shared_platform_input.reset();
1799 }
1800 };
1801
1802 [[nodiscard]] std::unique_ptr<platf::deinit_t> init() {
1803 shared_platform_input = std::make_shared<platf::input_t>(platf::input());
1804
1805 return std::make_unique<deinit_t>();
1806 }
1807
1808 bool probe_gamepads() {
1809 if (!shared_platform_input) {
1810 return true;
1811 }
1812 // supported_gamepads expects the owning handle, not its backend payload.
1813 const auto gamepads = platf::supported_gamepads(shared_platform_input.get());
1814 for (auto &gamepad : gamepads) {
1815 if (gamepad.is_enabled && gamepad.name != "auto") {
1816 return false;
1817 }
1818 }
1819 return true;
1820 }
1821
1829 void attach_launch_gamepads(std::shared_ptr<input_t> &input, int mask) {
1830 if (!config::input.controller || config::input.gamepad == "auto"sv) {
1831 return;
1832 }
1833
1834 for (int nr = 0; nr < (int) input->gamepads.size(); ++nr) {
1835 auto &gamepad = input->gamepads[nr];
1836 if (!(mask & (1 << nr)) || gamepad.id >= 0) {
1837 continue;
1838 }
1839
1840 auto id = alloc_id(gamepadMask);
1841 if (id < 0) {
1842 return;
1843 }
1844
1845 if (platf::alloc_gamepad(*input->platform_input, {id, (uint8_t) nr}, {.client_id = input->client_id}, input->feedback_queue)) {
1846 free_id(gamepadMask, id);
1847 return;
1848 }
1849
1850 gamepad.id = id;
1851 }
1852 }
1853
1854 std::shared_ptr<input_t> alloc(
1855 safe::mail_t mail,
1856 const std::string &session_tag,
1857 int launch_gamepads,
1858 const std::string &wayland_socket,
1859 const std::string &client_id
1860 ) {
1861 auto input = std::make_shared<input_t>(
1862 mail->event<input::touch_port_t>(mail::touch_port),
1863 mail->queue<platf::gamepad_feedback_msg_t>(mail::gamepad_feedback),
1864 session_tag,
1865 wayland_socket
1866 );
1867 input->client_id = client_id;
1868
1869 if (launch_gamepads) {
1870 task_pool.push([input, launch_gamepads]() mutable {
1871 attach_launch_gamepads(input, launch_gamepads);
1872 });
1873 }
1874
1875 // Workaround to ensure new frames will be captured when a client connects.
1876 //
1877 // Not for an isolated session. Its capture reads the framebuffer the
1878 // session's Hermes-KMS card holds and repeats the last image when nothing
1879 // changes, so there is nothing to wake. And the nudge is real input on the
1880 // session's own seat, which Gamescope answers by showing its cursor in the
1881 // middle of Steam's gamepad UI before the client has moved anything (#57).
1882 // The client's own connect-time wiggle is dropped for the same reason.
1883 if (!session_tag.empty()) {
1884 input->wake_wiggle_left = config::input.isolated_ignore_mouse_wiggle ? 2 : 0;
1885 } else {
1886 task_pool.pushDelayed([input]() {
1887 platf::move_mouse(*input->platform_input, 1, 1);
1888 platf::move_mouse(*input->platform_input, -1, -1);
1889 },
1890 100ms);
1891 }
1892
1893 return input;
1894 }
1895
1896#ifdef HERMES_TESTS
1897 std::shared_ptr<input_t> alloc_for_testing(
1898 safe::mail_t mail,
1899 std::shared_ptr<platf::input_t> platform,
1900 std::unique_ptr<platf::client_input_t> client
1901 ) {
1902 return std::make_shared<input_t>(
1903 mail->event<input::touch_port_t>(mail::touch_port),
1904 mail->queue<platf::gamepad_feedback_msg_t>(mail::gamepad_feedback),
1905 std::string {},
1906 std::string {},
1907 std::move(platform),
1908 std::move(client)
1909 );
1910 }
1911#endif
1912} // namespace input
Declarations for common platform specific utilities.
std::vector< supported_gamepad_t > & supported_gamepads(input_t *input)
Gets the supported gamepads for this platform backend.
int alloc_gamepad(input_t &input, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue)
Create a new virtual gamepad.
std::unique_ptr< client_input_t > allocate_client_input_context(input_t &input)
Allocate a context to store per-client input data.
void pen_update(client_input_t *input, const touch_port_t &touch_port, const pen_input_t &pen)
Send a pen event to the OS.
void gamepad_motion(input_t &input, const gamepad_motion_t &motion)
Send a gamepad motion event to the OS.
void gamepad_battery(input_t &input, const gamepad_battery_t &battery)
Send a gamepad battery event to the OS.
void release_gamepad(input_t &input, int nr)
Release a gamepad because its stream ended, not because the client removed it. A detached desktop kee...
void gamepad_touch(input_t &input, const gamepad_touch_t &touch)
Send a gamepad touch event to the OS.
input_t input(const std::string &session_tag={})
void touch_update(client_input_t *input, const touch_port_t &touch_port, const touch_input_t &touch)
Send a touch event to the OS.
Declarations for the configuration of Sunshine.
PERM
The permissions of a client.
Definition crypto.h:45
thread_pool_util::ThreadPool task_pool
A thread pool for processing tasks.
Definition globals.cpp:9
bool display_cursor
A boolean flag to indicate whether the cursor should be displayed.
Definition globals.cpp:10
Declarations for globally accessible variables and functions.
float multiply_polar_by_cartesian_scalar(float r, float angle, const std::pair< float, float > &scalar)
Multiply a polar coordinate pair by a cartesian scaling factor.
Definition input.cpp:558
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)
Converts client coordinates on the specified surface into screen coordinates.
Definition input.cpp:525
void attach_launch_gamepads(std::shared_ptr< input_t > &input, int mask)
Plug in the gamepads the client reported at launch.
Definition input.cpp:1829
float from_clamped_netfloat(netfloat f, float min, float max)
Convert a little-endian netfloat to a native endianness float and clamps it.
Definition input.cpp:108
platf::touch_port_t direct_device_port(int output_width, int output_height, int offset_x, int offset_y, int env_width, int env_height, bool binds_to_output)
The rectangle a touchscreen or a pen is addressed in.
Definition input.cpp:963
float from_netfloat(netfloat f)
Convert a little-endian netfloat to a native endianness float.
Definition input.cpp:97
void update_shortcutFlags(int *flags, short keyCode, bool release)
Update flags for keyboard shortcut combo's.
Definition input.cpp:696
std::pair< float, float > scale_client_contact_area(const std::pair< float, float > &val, uint16_t rotation, const std::pair< float, float > &scalar)
Scale the ellipse axes according to the provided size.
Definition input.cpp:571
batch_result_e batch(PNV_REL_MOUSE_MOVE_PACKET dest, PNV_REL_MOUSE_MOVE_PACKET src)
Batch two relative mouse messages.
Definition input.cpp:1314
button_state_e
Definition input.cpp:55
@ NONE
No button state.
Definition input.cpp:56
@ DOWN
Button is down.
Definition input.cpp:57
@ UP
Button is up.
Definition input.cpp:58
std::shared_ptr< input_t > alloc(safe::mail_t mail, const std::string &session_tag, int launch_gamepads, const std::string &wayland_socket, const std::string &client_id)
Definition input.cpp:1854
void passthrough_next_message(std::shared_ptr< input_t > input)
Called on a thread pool thread to process an input message.
Definition input.cpp:1587
batch_result_e
Definition input.cpp:1302
@ terminate_batch
Stop trying to batch with this entry.
Definition input.cpp:1305
@ not_batchable
Not eligible to batch but continue attempts to batch.
Definition input.cpp:1304
@ batched
This entry was batched with the source entry.
Definition input.cpp:1303
int apply_shortcut(short keyCode)
Apply shortcut based on VKEY.
Definition input.cpp:254
Declarations for gamepad, keyboard, and mouse input handling.
Declarations for logging related functions.
Handles process-wide communication.
Definition globals.h:25
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
std::optional< std::string > wayland_socket(const std::string &client_uuid)
The name of the Wayland socket the session's compositor created.
@ CTRL
Control key.
Definition input.cpp:188
@ ALT
Alt key.
Definition input.cpp:189
@ SHORTCUT
Shortcut combination.
Definition input.cpp:191
@ SHIFT
Shift key.
Definition input.cpp:190
Declarations for the thread pool system.
Declarations for utility functions.
void release(input_raw_t *raw, int index)
Free a gamepad whose stream ended; a detached desktop keeps it.