Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/evdev/evdev.cpp

raw symbols SCIP
1 // Copyright 2015 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/evdev/evdev.h"
5
6 #include <algorithm>
7 #include <cstring>
8 #include <map>
9 #include <memory>
10 #include <string>
11
12 #include <fcntl.h>
13 #include <libudev.h>
14 #include <sys/eventfd.h>
15 #include <unistd.h>
16
17 #include "Common/Assert.h"
18 #include "Common/Flag.h"
19 #include "Common/Logging/Log.h"
20 #include "Common/MathUtil.h"
21 #include "Common/ScopeGuard.h"
22 #include "Common/StringUtil.h"
23 #include "Common/Thread.h"
24 #include "Common/WorkQueueThread.h"
25 #include "InputCommon/ControllerInterface/ControllerInterface.h"
26
27 namespace ciface::evdev
28 {
29 class InputBackend final : public ciface::InputBackend
30 {
31 public:
32 InputBackend(ControllerInterface* controller_interface);
33 ~InputBackend();
34 void PopulateDevices() override;
35
36 void RemoveDevnodeObject(const std::string&);
37
38 // Linux has the strange behavior that closing file descriptors of event devices can be
39 // surprisingly slow, in the range of 20-70 milliseconds. For modern systems that have maybe 30
40 // event devices this can quickly add up, leading to visibly slow startup. So we close FDs on a
41 // separate thread *shrug*
42 void CloseDescriptor(int fd) { m_cleanup_thread.Push(fd); }
43
44 private:
45 std::shared_ptr<evdevDevice>
46 FindDeviceWithUniqueIDAndPhysicalLocation(const char* unique_id, const char* physical_location);
47
48 void AddDeviceNode(const char* devnode);
49
50 void StartHotplugThread();
51 void StopHotplugThread();
52 void HotplugThreadFunc();
53
54 std::thread m_hotplug_thread;
55 Common::Flag m_hotplug_thread_running;
56 int m_wakeup_eventfd;
57
58 // There is no easy way to get the device name from only a dev node
59 // during a device removed event, since libevdev can't work on removed devices;
60 // sysfs is not stable, so this is probably the easiest way to get a name for a node.
61 // This can, and will be modified by different thread, possibly concurrently,
62 // as devices can be destroyed by any thread at any time. As of now it's protected
63 // by ControllerInterface::m_devices_population_mutex.
64 std::map<std::string, std::weak_ptr<evdevDevice>> m_devnode_objects;
65
66 Common::WorkQueueThread<int> m_cleanup_thread;
67 };
68
69 std::unique_ptr<ciface::InputBackend> CreateInputBackend(ControllerInterface* controller_interface)
70 {
71 return std::make_unique<InputBackend>(controller_interface);
72 }
73
74 class Input : public Core::Device::Input
75 {
76 public:
77 Input(u16 code, libevdev* dev) : m_code(code), m_dev(dev) {}
78
79 protected:
80 const u16 m_code;
81 libevdev* const m_dev;
82 };
83
84 class Button : public Input
85 {
86 public:
87 Button(u8 index, u16 code, libevdev* dev) : Input(code, dev), m_index(index) {}
88
89 ControlState GetState() const final override
90 {
91 int value = 0;
92 libevdev_fetch_event_value(m_dev, EV_KEY, m_code, &value);
93 return value;
94 }
95
96 protected:
97 std::optional<std::string> GetEventCodeName() const
98 {
99 if (const char* code_name = libevdev_event_code_get_name(EV_KEY, m_code))
100 {
101 const auto name = StripWhitespace(code_name);
102
103 for (auto remove_prefix : {"BTN_", "KEY_"})
104 {
105 if (name.starts_with(remove_prefix))
106 return std::string(name.substr(std::strlen(remove_prefix)));
107 }
108
109 return std::string(name);
110 }
111 else
112 {
113 return std::nullopt;
114 }
115 }
116
117 std::string GetIndexedName() const { return "Button " + std::to_string(m_index); }
118
119 const u8 m_index;
120 };
121
122 class NumberedButton final : public Button
123 {
124 public:
125 using Button::Button;
126
127 std::string GetName() const override { return GetIndexedName(); }
128 };
129
130 class NamedButton final : public Button
131 {
132 public:
133 using Button::Button;
134
135 bool IsMatchingName(std::string_view name) const final override
136 {
137 // Match either the "START" naming provided by evdev or the "Button 0"-like naming.
138 return name == GetEventCodeName() || name == GetIndexedName();
139 }
140
141 std::string GetName() const override { return GetEventCodeName().value_or(GetIndexedName()); }
142 };
143
144 class NamedButtonWithNoBackwardsCompat final : public Button
145 {
146 public:
147 using Button::Button;
148
149 std::string GetName() const override { return GetEventCodeName().value_or(GetIndexedName()); }
150 };
151
152 class AnalogInput : public Input
153 {
154 public:
155 using Input::Input;
156
157 ControlState GetState() const final override
158 {
159 int value = 0;
160 libevdev_fetch_event_value(m_dev, EV_ABS, m_code, &value);
161
162 return (value - m_base) / m_range;
163 }
164
165 protected:
166 ControlState m_range;
167 int m_base;
168 };
169
170 class Axis : public AnalogInput
171 {
172 public:
173 Axis(u8 index, u16 code, bool upper, libevdev* dev) : AnalogInput(code, dev), m_index(index)
174 {
175 const int min = libevdev_get_abs_minimum(m_dev, m_code);
176 const int max = libevdev_get_abs_maximum(m_dev, m_code);
177
178 m_base = (max + min) / 2;
179 m_range = (upper ? max : min) - m_base;
180 }
181
182 std::string GetName() const override { return GetIndexedName(); }
183
184 protected:
185 std::string GetIndexedName() const
186 {
187 return "Axis " + std::to_string(m_index) + (m_range < 0 ? '-' : '+');
188 }
189
190 private:
191 const u8 m_index;
192 };
193
194 class MotionDataInput final : public AnalogInput
195 {
196 public:
197 MotionDataInput(u16 code, ControlState resolution_scale, libevdev* dev) : AnalogInput(code, dev)
198 {
199 auto* const info = libevdev_get_abs_info(m_dev, m_code);
200
201 // The average of the minimum and maximum value. (neutral value)
202 m_base = (info->maximum + info->minimum) / 2;
203
204 m_range = info->resolution / resolution_scale;
205 }
206
207 std::string GetName() const override
208 {
209 // Unfortunately there doesn't seem to be a "standard" orientation
210 // so we can't use "Accel Up"-like names.
211 constexpr std::array<const char*, 6> motion_data_names = {{
212 "Accel X",
213 "Accel Y",
214 "Accel Z",
215 "Gyro X",
216 "Gyro Y",
217 "Gyro Z",
218 }};
219
220 // Our name array relies on sane axis codes from 0 to 5.
221 static_assert(ABS_X == 0, "evdev axis value sanity check");
222 static_assert(ABS_RX == 3, "evdev axis value sanity check");
223
224 return std::string(motion_data_names[m_code]) + (m_range < 0 ? '-' : '+');
225 }
226
227 bool IsDetectable() const override { return false; }
228 };
229
230 class CursorInput final : public Axis
231 {
232 public:
233 using Axis::Axis;
234
235 std::string GetName() const final override
236 {
237 // "Cursor X-" naming.
238 return std::string("Cursor ") + char('X' + m_code) + (m_range < 0 ? '-' : '+');
239 }
240
241 bool IsDetectable() const override { return false; }
242 };
243
244 std::shared_ptr<evdevDevice>
245 InputBackend::FindDeviceWithUniqueIDAndPhysicalLocation(const char* unique_id,
246 const char* physical_location)
247 {
248 if (!unique_id || !physical_location)
249 return nullptr;
250
251 for (auto& [node, dev] : m_devnode_objects)
252 {
253 if (const auto device = dev.lock())
254 {
255 const auto* dev_uniq = device->GetUniqueID();
256 const auto* dev_phys = device->GetPhysicalLocation();
257
258 if (dev_uniq && dev_phys && std::strcmp(dev_uniq, unique_id) == 0 &&
259 std::strcmp(dev_phys, physical_location) == 0)
260 {
261 return device;
262 }
263 }
264 }
265
266 return nullptr;
267 }
268
269 void InputBackend::AddDeviceNode(const char* devnode)
270 {
271 // Unfortunately udev gives us no way to filter out the non event device interfaces.
272 // So we open it and see if it works with evdev ioctls or not.
273
274 // The device file will be read on one of the main threads, so we open in non-blocking mode.
275 const int fd = open(devnode, O_RDWR | O_NONBLOCK);
276 if (fd == -1)
277 {
278 return;
279 }
280
281 libevdev* dev = nullptr;
282 if (libevdev_new_from_fd(fd, &dev) != 0)
283 {
284 // This usually fails because the device node isn't an evdev device, such as /dev/input/js0
285 CloseDescriptor(fd);
286 return;
287 }
288
289 const auto uniq = libevdev_get_uniq(dev);
290 const auto phys = libevdev_get_phys(dev);
291 auto evdev_device = FindDeviceWithUniqueIDAndPhysicalLocation(uniq, phys);
292 if (evdev_device)
293 {
294 NOTICE_LOG_FMT(CONTROLLERINTERFACE,
295 "evdev combining devices with unique id: {}, physical location: {}", uniq, phys);
296
297 evdev_device->AddNode(devnode, fd, dev);
298
299 // Remove and re-add device as naming and inputs may have changed.
300 // This will also give it the correct index and invoke device change callbacks.
301 // Make sure to force the device removal immediately (as they are shared ptrs and
302 // they could be kept alive, preventing us from re-creating the device)
303 GetControllerInterface().RemoveDevice(
304 [&evdev_device](const auto* device) {
305 return static_cast<const evdevDevice*>(device) == evdev_device.get();
306 },
307 true);
308
309 GetControllerInterface().AddDevice(evdev_device);
310 }
311 else
312 {
313 evdev_device = std::make_shared<evdevDevice>(this);
314
315 const bool was_interesting = evdev_device->AddNode(devnode, fd, dev);
316
317 if (was_interesting)
318 GetControllerInterface().AddDevice(evdev_device);
319 }
320
321 // If the devices failed to be added to ControllerInterface, it will be added here but then
322 // immediately removed in its destructor due to the shared ptr not having any references left
323 m_devnode_objects.emplace(devnode, std::move(evdev_device));
324 }
325
326 void InputBackend::HotplugThreadFunc()
327 {
328 Common::SetCurrentThreadName("evdev Hotplug Thread");
329 NOTICE_LOG_FMT(CONTROLLERINTERFACE, "evdev hotplug thread started");
330
331 udev* const udev = udev_new();
332 Common::ScopeGuard udev_guard([udev] { udev_unref(udev); });
333
334 ASSERT_MSG(CONTROLLERINTERFACE, udev != nullptr, "Couldn't initialize libudev.");
335
336 // Set up monitoring
337 udev_monitor* const monitor = udev_monitor_new_from_netlink(udev, "udev");
338 Common::ScopeGuard monitor_guard([monitor] { udev_monitor_unref(monitor); });
339
340 udev_monitor_filter_add_match_subsystem_devtype(monitor, "input", nullptr);
341 udev_monitor_enable_receiving(monitor);
342 const int monitor_fd = udev_monitor_get_fd(monitor);
343
344 while (m_hotplug_thread_running.IsSet())
345 {
346 fd_set fds;
347
348 FD_ZERO(&fds);
349 FD_SET(monitor_fd, &fds);
350 FD_SET(m_wakeup_eventfd, &fds);
351
352 const int ret =
353 select(std::max(monitor_fd, m_wakeup_eventfd) + 1, &fds, nullptr, nullptr, nullptr);
354 if (ret < 1 || !FD_ISSET(monitor_fd, &fds))
355 continue;
356
357 udev_device* const dev = udev_monitor_receive_device(monitor);
358 Common::ScopeGuard dev_guard([dev] { udev_device_unref(dev); });
359
360 const char* const action = udev_device_get_action(dev);
361 const char* const devnode = udev_device_get_devnode(dev);
362 if (!devnode)
363 continue;
364
365 // Use GetControllerInterface().PlatformPopulateDevices() to protect access around
366 // m_devnode_objects. Note that even if we get these events at the same time as a
367 // a PopulateDevices() request (e.g. on start up, we might get all the add events
368 // for connected devices), this won't ever cause duplicate devices as AddDeviceNode()
369 // automatically removes the old one if it already existed
370 if (strcmp(action, "remove") == 0)
371 {
372 GetControllerInterface().PlatformPopulateDevices([&devnode, this] {
373 std::shared_ptr<evdevDevice> ptr;
374
375 const auto it = m_devnode_objects.find(devnode);
376 if (it != m_devnode_objects.end())
377 ptr = it->second.lock();
378
379 // If we don't recognize this device, ptr will be null and no device will be removed.
380
381 GetControllerInterface().RemoveDevice([&ptr](const auto* device) {
382 return static_cast<const evdevDevice*>(device) == ptr.get();
383 });
384 });
385 }
386 else if (strcmp(action, "add") == 0)
387 {
388 GetControllerInterface().PlatformPopulateDevices(
389 [&devnode, this] { AddDeviceNode(devnode); });
390 }
391 }
392 NOTICE_LOG_FMT(CONTROLLERINTERFACE, "evdev hotplug thread stopped");
393 }
394
395 void InputBackend::StartHotplugThread()
396 {
397 // Mark the thread as running.
398 if (!m_hotplug_thread_running.TestAndSet())
399 {
400 // It was already running.
401 return;
402 }
403
404 m_wakeup_eventfd = eventfd(0, 0);
405 ASSERT_MSG(CONTROLLERINTERFACE, m_wakeup_eventfd != -1, "Couldn't create eventfd.");
406 m_hotplug_thread = std::thread(&InputBackend::HotplugThreadFunc, this);
407 }
408
409 void InputBackend::StopHotplugThread()
410 {
411 // Tell the hotplug thread to stop.
412 if (!m_hotplug_thread_running.TestAndClear())
413 {
414 // It wasn't running, we're done.
415 return;
416 }
417
418 // Write something to efd so that select() stops blocking.
419 const uint64_t value = 1;
420 static_cast<void>(!write(m_wakeup_eventfd, &value, sizeof(uint64_t)));
421
422 m_hotplug_thread.join();
423 close(m_wakeup_eventfd);
424 }
425
426 InputBackend::InputBackend(ControllerInterface* controller_interface)
427 : ciface::InputBackend(controller_interface), m_cleanup_thread("evdev cleanup", close)
428 {
429 StartHotplugThread();
430 }
431
432 // Only call this when ControllerInterface::m_devices_population_mutex is locked
433 void InputBackend::PopulateDevices()
434 {
435 // Don't run if we are not initialized
436 if (!m_hotplug_thread_running.IsSet())
437 {
438 return;
439 }
440
441 // We use udev to iterate over all /dev/input/event* devices.
442 // Note: the Linux kernel is currently limited to just 32 event devices. If
443 // this ever changes, hopefully udev will take care of this.
444
445 udev* const udev = udev_new();
446 ASSERT_MSG(CONTROLLERINTERFACE, udev != nullptr, "Couldn't initialize libudev.");
447
448 // List all input devices
449 udev_enumerate* const enumerate = udev_enumerate_new(udev);
450 udev_enumerate_add_match_subsystem(enumerate, "input");
451 udev_enumerate_scan_devices(enumerate);
452 udev_list_entry* const devices = udev_enumerate_get_list_entry(enumerate);
453
454 // Iterate over all input devices
455 udev_list_entry* dev_list_entry;
456 udev_list_entry_foreach(dev_list_entry, devices)
457 {
458 const char* path = udev_list_entry_get_name(dev_list_entry);
459
460 udev_device* dev = udev_device_new_from_syspath(udev, path);
461
462 if (const char* devnode = udev_device_get_devnode(dev))
463 AddDeviceNode(devnode);
464
465 udev_device_unref(dev);
466 }
467 udev_enumerate_unref(enumerate);
468 udev_unref(udev);
469 }
470
471 InputBackend::~InputBackend()
472 {
473 StopHotplugThread();
474 }
475
476 bool evdevDevice::AddNode(std::string devnode, int fd, libevdev* dev)
477 {
478 m_nodes.emplace_back(Node{std::move(devnode), fd, dev});
479
480 // Take on the alphabetically first name.
481 const auto potential_new_name = StripWhitespace(libevdev_get_name(dev));
482 if (m_name.empty() || potential_new_name < m_name)
483 m_name = potential_new_name;
484
485 const bool is_motion_device = libevdev_has_property(dev, INPUT_PROP_ACCELEROMETER);
486 const bool is_pointing_device = libevdev_has_property(dev, INPUT_PROP_BUTTONPAD);
487
488 // If a device has BTN_JOYSTICK it probably uses event codes counting up from 0x120
489 // which have very useless and wrong names.
490 const bool has_btn_joystick = libevdev_has_event_code(dev, EV_KEY, BTN_JOYSTICK);
491 const bool has_sensible_button_names = !has_btn_joystick;
492
493 // Buttons (and keyboard keys)
494 int num_buttons = 0;
495 for (int key = 0; key != KEY_CNT; ++key)
496 {
497 if (libevdev_has_event_code(dev, EV_KEY, key))
498 {
499 if (is_pointing_device || is_motion_device)
500 {
501 // This node will probably be combined with another with regular buttons.
502 // We don't want to match "Button 0" names here as it will name clash.
503 AddInput(new NamedButtonWithNoBackwardsCompat(num_buttons, key, dev));
504 }
505 else if (has_sensible_button_names)
506 {
507 AddInput(new NamedButton(num_buttons, key, dev));
508 }
509 else
510 {
511 AddInput(new NumberedButton(num_buttons, key, dev));
512 }
513
514 ++num_buttons;
515 }
516 }
517
518 int num_axis = 0;
519
520 if (is_motion_device)
521 {
522 // If INPUT_PROP_ACCELEROMETER is set then X,Y,Z,RX,RY,RZ contain motion data.
523
524 auto add_motion_inputs = [&num_axis, dev, this](int first_code, double scale) {
525 for (int i = 0; i != 3; ++i)
526 {
527 const int code = first_code + i;
528 if (libevdev_has_event_code(dev, EV_ABS, code))
529 {
530 AddInput(new MotionDataInput(code, scale * -1, dev));
531 AddInput(new MotionDataInput(code, scale, dev));
532
533 ++num_axis;
534 }
535 }
536 };
537
538 // evdev resolution is specified in "g"s and deg/s.
539 // Convert these to m/s/s and rad/s.
540 constexpr ControlState accel_scale = MathUtil::GRAVITY_ACCELERATION;
541 constexpr ControlState gyro_scale = MathUtil::TAU / 360;
542
543 add_motion_inputs(ABS_X, accel_scale);
544 add_motion_inputs(ABS_RX, gyro_scale);
545
546 return true;
547 }
548
549 if (is_pointing_device)
550 {
551 auto add_cursor_input = [&num_axis, dev, this](int code) {
552 if (libevdev_has_event_code(dev, EV_ABS, code))
553 {
554 AddInput(new CursorInput(num_axis, code, false, dev));
555 AddInput(new CursorInput(num_axis, code, true, dev));
556
557 ++num_axis;
558 }
559 };
560
561 add_cursor_input(ABS_X);
562 add_cursor_input(ABS_Y);
563
564 return true;
565 }
566
567 // Axes beyond ABS_MISC have strange behavior (for multi-touch) which we do not handle.
568 const int abs_axis_code_count = ABS_MISC;
569
570 // Absolute axis (thumbsticks)
571 for (int axis = 0; axis != abs_axis_code_count; ++axis)
572 {
573 if (libevdev_has_event_code(dev, EV_ABS, axis))
574 {
575 AddFullAnalogSurfaceInputs(new Axis(num_axis, axis, false, dev),
576 new Axis(num_axis, axis, true, dev));
577 ++num_axis;
578 }
579 }
580
581 // Disable autocenter
582 if (libevdev_has_event_code(dev, EV_FF, FF_AUTOCENTER))
583 {
584 input_event ie = {};
585 ie.type = EV_FF;
586 ie.code = FF_AUTOCENTER;
587 ie.value = 0;
588
589 static_cast<void>(!write(fd, &ie, sizeof(ie)));
590 }
591
592 // Constant FF effect
593 if (libevdev_has_event_code(dev, EV_FF, FF_CONSTANT))
594 {
595 AddOutput(new ConstantEffect(fd));
596 }
597
598 // Periodic FF effects
599 if (libevdev_has_event_code(dev, EV_FF, FF_PERIODIC))
600 {
601 for (auto wave : {FF_SINE, FF_SQUARE, FF_TRIANGLE, FF_SAW_UP, FF_SAW_DOWN})
602 {
603 if (libevdev_has_event_code(dev, EV_FF, wave))
604 AddOutput(new PeriodicEffect(fd, wave));
605 }
606 }
607
608 // Rumble (i.e. Left/Right) (i.e. Strong/Weak) effect
609 if (libevdev_has_event_code(dev, EV_FF, FF_RUMBLE))
610 {
611 AddOutput(new RumbleEffect(fd, RumbleEffect::Motor::Strong));
612 AddOutput(new RumbleEffect(fd, RumbleEffect::Motor::Weak));
613 }
614
615 // TODO: Add leds as output devices
616
617 // Filter out interesting devices (see description below)
618 return num_axis >= 2 || num_buttons >= 8;
619
620 // On modern linux systems, there are a lot of event devices that aren't controllers.
621 // For example, the PC Speaker is an event device. Webcams sometimes show up as
622 // event devices. The power button is an event device.
623 //
624 // We don't want these showing up in the list of controllers, so we use this
625 // heuristic to filter out anything that doesn't smell like a controller:
626 //
627 // More than two analog axis:
628 // Most controllers have at least one stick. This rule will catch all such
629 // controllers, while ignoring anything with a single axis (like the mouse
630 // scroll-wheel)
631 //
632 // --- OR ---
633 //
634 // More than 8 buttons:
635 // The user might be using a digital only pad such as a NES controller.
636 // This rule caches such controllers, while eliminating any device with
637 // only a few buttons, like the power button. Sometimes laptops have devices
638 // with 5 or 6 special buttons, which is why the threshold is set to 8 to
639 // match a NES controller.
640 //
641 // This heuristic is quite loose. The user may still see weird devices showing up
642 // as controllers, but it hopefully shouldn't filter out anything they actually
643 // want to use.
644 }
645
646 const char* evdevDevice::GetUniqueID() const
647 {
648 if (m_nodes.empty())
649 return nullptr;
650
651 const auto uniq = libevdev_get_uniq(m_nodes.front().device);
652
653 // Some devices (e.g. Mayflash adapter) return an empty string which is not very unique.
654 if (uniq && std::strlen(uniq) == 0)
655 return nullptr;
656
657 return uniq;
658 }
659
660 const char* evdevDevice::GetPhysicalLocation() const
661 {
662 if (m_nodes.empty())
663 return nullptr;
664
665 return libevdev_get_phys(m_nodes.front().device);
666 }
667
668 evdevDevice::evdevDevice(InputBackend* input_backend) : m_input_backend(*input_backend)
669 {
670 }
671
672 evdevDevice::~evdevDevice()
673 {
674 for (auto& node : m_nodes)
675 {
676 m_input_backend.RemoveDevnodeObject(node.devnode);
677 libevdev_free(node.device);
678 m_input_backend.CloseDescriptor(node.fd);
679 }
680 }
681
682 void InputBackend::RemoveDevnodeObject(const std::string& node)
683 {
684 m_devnode_objects.erase(node);
685 }
686
687 Core::DeviceRemoval evdevDevice::UpdateInput()
688 {
689 // Run through all evdev events
690 // libevdev will keep track of the actual controller state internally which can be queried
691 // later with libevdev_fetch_event_value()
692 for (auto& node : m_nodes)
693 {
694 int rc = LIBEVDEV_READ_STATUS_SUCCESS;
695 while (rc >= 0)
696 {
697 input_event ev;
698 if (LIBEVDEV_READ_STATUS_SYNC == rc)
699 rc = libevdev_next_event(node.device, LIBEVDEV_READ_FLAG_SYNC, &ev);
700 else
701 rc = libevdev_next_event(node.device, LIBEVDEV_READ_FLAG_NORMAL, &ev);
702 }
703 }
704 return Core::DeviceRemoval::Keep;
705 }
706
707 bool evdevDevice::IsValid() const
708 {
709 for (auto& node : m_nodes)
710 {
711 const int current_fd = libevdev_get_fd(node.device);
712
713 if (current_fd == -1)
714 return false;
715
716 libevdev* device = nullptr;
717 if (libevdev_new_from_fd(current_fd, &device) != 0)
718 {
719 close(current_fd);
720 return false;
721 }
722
723 libevdev_free(device);
724 }
725
726 return true;
727 }
728
729 evdevDevice::Effect::Effect(int fd) : m_fd(fd)
730 {
731 m_effect.id = -1;
732 // Left (for wheels):
733 m_effect.direction = 0x4000;
734 m_effect.replay.length = RUMBLE_LENGTH_MS;
735
736 // FYI: type is set within UpdateParameters.
737 m_effect.type = DISABLED_EFFECT_TYPE;
738 }
739
740 std::string evdevDevice::ConstantEffect::GetName() const
741 {
742 return "Constant";
743 }
744
745 std::string evdevDevice::PeriodicEffect::GetName() const
746 {
747 switch (m_effect.u.periodic.waveform)
748 {
749 case FF_SQUARE:
750 return "Square";
751 case FF_TRIANGLE:
752 return "Triangle";
753 case FF_SINE:
754 return "Sine";
755 case FF_SAW_UP:
756 return "Sawtooth Up";
757 case FF_SAW_DOWN:
758 return "Sawtooth Down";
759 default:
760 return "Unknown";
761 }
762 }
763
764 std::string evdevDevice::RumbleEffect::GetName() const
765 {
766 return (Motor::Strong == m_motor) ? "Strong" : "Weak";
767 }
768
769 void evdevDevice::Effect::SetState(ControlState state)
770 {
771 if (UpdateParameters(state))
772 {
773 // Update effect if parameters changed.
774 UpdateEffect();
775 }
776 }
777
778 void evdevDevice::Effect::UpdateEffect()
779 {
780 // libevdev doesn't have nice helpers for forcefeedback
781 // we will use the file descriptors directly.
782
783 // Note: m_effect.type is set within UpdateParameters
784 // to determine if effect should be playing or not.
785 if (m_effect.type != DISABLED_EFFECT_TYPE)
786 {
787 if (-1 == m_effect.id)
788 {
789 // If effect was not uploaded (previously stopped)
790 // we upload it and start playback
791
792 ioctl(m_fd, EVIOCSFF, &m_effect);
793
794 input_event play = {};
795 play.type = EV_FF;
796 play.code = m_effect.id;
797 play.value = 1;
798
799 static_cast<void>(!write(m_fd, &play, sizeof(play)));
800 }
801 else
802 {
803 // Effect is already playing. Just update parameters.
804 ioctl(m_fd, EVIOCSFF, &m_effect);
805 }
806 }
807 else
808 {
809 // Stop and remove effect.
810 ioctl(m_fd, EVIOCRMFF, m_effect.id);
811 m_effect.id = -1;
812 }
813 }
814
815 evdevDevice::ConstantEffect::ConstantEffect(int fd) : Effect(fd)
816 {
817 m_effect.u.constant = {};
818 }
819
820 evdevDevice::PeriodicEffect::PeriodicEffect(int fd, u16 waveform) : Effect(fd)
821 {
822 m_effect.u.periodic = {};
823 m_effect.u.periodic.waveform = waveform;
824 m_effect.u.periodic.period = RUMBLE_PERIOD_MS;
825 m_effect.u.periodic.offset = 0;
826 m_effect.u.periodic.phase = 0;
827 }
828
829 evdevDevice::RumbleEffect::RumbleEffect(int fd, Motor motor) : Effect(fd), m_motor(motor)
830 {
831 m_effect.u.rumble = {};
832 }
833
834 bool evdevDevice::ConstantEffect::UpdateParameters(ControlState state)
835 {
836 s16& value = m_effect.u.constant.level;
837 const s16 old_value = value;
838
839 constexpr s16 MAX_VALUE = 0x7fff;
840 value = s16(state * MAX_VALUE);
841
842 m_effect.type = value ? FF_CONSTANT : DISABLED_EFFECT_TYPE;
843 return value != old_value;
844 }
845
846 bool evdevDevice::PeriodicEffect::UpdateParameters(ControlState state)
847 {
848 s16& value = m_effect.u.periodic.magnitude;
849 const s16 old_value = value;
850
851 constexpr s16 MAX_VALUE = 0x7fff;
852 value = s16(state * MAX_VALUE);
853
854 m_effect.type = value ? FF_PERIODIC : DISABLED_EFFECT_TYPE;
855 return value != old_value;
856 }
857
858 bool evdevDevice::RumbleEffect::UpdateParameters(ControlState state)
859 {
860 u16& value = (Motor::Strong == m_motor) ? m_effect.u.rumble.strong_magnitude :
861 m_effect.u.rumble.weak_magnitude;
862 const u16 old_value = value;
863
864 constexpr u16 MAX_VALUE = 0xffff;
865 value = u16(state * MAX_VALUE);
866
867 m_effect.type = value ? FF_RUMBLE : DISABLED_EFFECT_TYPE;
868 return value != old_value;
869 }
870
871 evdevDevice::Effect::~Effect()
872 {
873 m_effect.type = DISABLED_EFFECT_TYPE;
874 UpdateEffect();
875 }
876 } // namespace ciface::evdev