Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/WGInput/WGInput.cpp

raw symbols SCIP
1 // Copyright 2020 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/WGInput/WGInput.h"
5
6 #include <array>
7 #include <map>
8 #include <string_view>
9 #include <utility>
10
11 // For CoGetApartmentType
12 #include <objbase.h>
13 #pragma comment(lib, "ole32")
14
15 // NOTE: winrt translates com failures to c++ exceptions, so we must use try/catch in this file to
16 // prevent possible errors from escaping and terminating Dolphin.
17 #include <winrt/base.h>
18 #include <winrt/windows.devices.haptics.h>
19 #include <winrt/windows.devices.power.h>
20 #include <winrt/windows.foundation.collections.h>
21 #include <winrt/windows.gaming.input.h>
22 #include <winrt/windows.system.power.h>
23 #pragma comment(lib, "windowsapp")
24
25 #include <fmt/format.h>
26
27 #include "Common/HRWrap.h"
28 #include "Common/Logging/Log.h"
29 #include "Common/ScopeGuard.h"
30 #include "Common/StringUtil.h"
31 #include "Common/WorkQueueThread.h"
32 #include "InputCommon/ControllerInterface/ControllerInterface.h"
33
34 namespace WGI = winrt::Windows::Gaming::Input;
35 namespace Haptics = winrt::Windows::Devices::Haptics;
36 using winrt::Windows::Foundation::Collections::IVectorView;
37
38 namespace ciface::WGInput
39 {
40 static constexpr std::string_view SOURCE_NAME = "WGInput";
41
42 // These names correspond to the values of the GameControllerButtonLabel enum.
43 // "None" is not used.
44 // There are some overlapping names assuming no device exposes both
45 // GameControllerButtonLabel::XboxLeftBumper and GameControllerButtonLabel::LeftBumper.
46 // If needed we can prepend "Xbox" to relevant input names on conflict in the future.
47 static constexpr std::array wgi_button_names = {
48 "None", "Back", "Start", "Menu", "View", "Pad N",
49 "Pad S", "Pad W", "Pad E", "Button A", "Button B", "Button X",
50 "Button Y", "Bumper L", "Trigger L", "Thumb L", "Bumper R", "Trigger R",
51 "Thumb R", "Paddle 1", "Paddle 2", "Paddle 3", "Paddle 4", "Mode",
52 "Select", "Menu", "View", "Back", "Start", "Options",
53 "Share", "Pad N", "Pad S", "Pad W", "Pad E", "Letter A",
54 "Letter B", "Letter C", "Letter L", "Letter R", "Letter X", "Letter Y",
55 "Letter Z", "Cross", "Circle", "Square", "Triangle", "Bumper L",
56 "Trigger L", "Thumb L", "Left 1", "Left 2", "Left 3", "Bumper R",
57 "Trigger R", "Thumb R", "Right 1", "Right 2", "Right 3", "Paddle 1",
58 "Paddle 2", "Paddle 3", "Paddle 4", "Plus", "Minus", "Down Left Arrow",
59 "Dial L", "Dial R", "Suspension",
60 };
61
62 template <typename T, typename M>
63 struct MemberName
64 {
65 M T::* ptr;
66 const char* name;
67 };
68
69 static constexpr MemberName<WGI::GamepadReading, double> gamepad_trigger_names[] = {
70 {&WGI::GamepadReading::LeftTrigger, "Trigger L"},
71 {&WGI::GamepadReading::RightTrigger, "Trigger R"}};
72
73 static constexpr MemberName<WGI::GamepadReading, double> gamepad_axis_names[] = {
74 {&WGI::GamepadReading::LeftThumbstickX, "Left X"},
75 {&WGI::GamepadReading::LeftThumbstickY, "Left Y"},
76 {&WGI::GamepadReading::RightThumbstickX, "Right X"},
77 {&WGI::GamepadReading::RightThumbstickY, "Right Y"}};
78
79 static constexpr MemberName<WGI::GamepadVibration, double> gamepad_motor_names[] = {
80 {&WGI::GamepadVibration::LeftMotor, "Motor L"},
81 {&WGI::GamepadVibration::RightMotor, "Motor R"},
82 {&WGI::GamepadVibration::LeftTrigger, "Trigger L"},
83 {&WGI::GamepadVibration::RightTrigger, "Trigger R"}};
84
85 class Device : public Core::Device
86 {
87 public:
88 Device(std::string name, WGI::RawGameController raw_controller, WGI::Gamepad gamepad)
89 : m_name(std::move(name)), m_raw_controller(raw_controller), m_gamepad(gamepad)
90 {
91 // Buttons:
92 PopulateButtons();
93
94 // Add inputs for IGamepad interface if available.
95 if (m_gamepad)
96 {
97 // Axes:
98 for (auto& axis : gamepad_axis_names)
99 {
100 AddInput(new NamedAxis(&(m_gamepad_reading.*axis.ptr), 0.0, -1.0, axis.name));
101 AddInput(new NamedAxis(&(m_gamepad_reading.*axis.ptr), 0.0, +1.0, axis.name));
102 }
103
104 // Triggers:
105 for (auto& trigger : gamepad_trigger_names)
106 AddInput(new NamedTrigger(&(m_gamepad_reading.*trigger.ptr), trigger.name));
107
108 // Motors:
109 for (auto& motor : gamepad_motor_names)
110 AddOutput(new NamedMotor(&(m_state_out.*motor.ptr), motor.name, this));
111 }
112
113 // Add IRawGameController's axes if IGamepad is not available.
114 // This may need to change if some devices expose additional axes.
115 // Maybe we can determine which additional axes are not in IGamepad's collection.
116 const bool use_raw_controller_axes = !m_gamepad;
117
118 if (use_raw_controller_axes)
119 {
120 try
121 {
122 // Axes:
123 m_axes.resize(m_raw_controller.AxisCount());
124
125 u32 i = 0;
126 for (auto& axis : m_axes)
127 {
128 AddFullAnalogSurfaceInputs(new IndexedAxis(&axis, 0.5, +0.5, i),
129 new IndexedAxis(&axis, 0.5, -0.5, i));
130 ++i;
131 }
132 }
133 catch (winrt::hresult_error)
134 {
135 // If AxisCount failed, m_axes will remain zero-sized; nothing to do.
136 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating axes");
137 }
138 }
139
140 // Apparently some devices (e.g. DS4) provide the IGameController interface
141 // but expose the dpad only on a switch (IRawGameController interface).
142 // We'll need to add switches regardless of available interfaces.
143 constexpr bool use_raw_controller_switches = true;
144
145 // Switches (Hats):
146 if (use_raw_controller_switches)
147 {
148 try
149 {
150 m_switches.resize(m_raw_controller.SwitchCount());
151 // Accumulate switch kinds first, to ensure no inputs are added if there is any error.
152 std::vector<WGI::GameControllerSwitchKind> switch_kinds;
153 for (u32 i = 0; i < m_switches.size(); i++)
154 switch_kinds.push_back(m_raw_controller.GetSwitchKind(i));
155
156 u32 i = 0;
157 for (auto& swtch : m_switches)
158 {
159 using gcsp = WGI::GameControllerSwitchPosition;
160
161 AddInput(new IndexedSwitch(&swtch, i, gcsp::Up));
162 AddInput(new IndexedSwitch(&swtch, i, gcsp::Down));
163
164 if (switch_kinds[i] != WGI::GameControllerSwitchKind::TwoWay)
165 {
166 // If it's not a "two-way" switch (up/down only) then add the left/right inputs.
167 AddInput(new IndexedSwitch(&swtch, i, gcsp::Left));
168 AddInput(new IndexedSwitch(&swtch, i, gcsp::Right));
169 }
170
171 ++i;
172 }
173 }
174 catch (winrt::hresult_error)
175 {
176 // Safe as no inputs will have been added.
177 m_switches.clear();
178 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating switches");
179 }
180 }
181
182 // Haptics:
183 PopulateHaptics();
184
185 // Battery:
186 if (UpdateBatteryLevel())
187 AddInput(new Battery(&m_battery_level));
188 }
189
190 int GetSortPriority() const override { return -1; }
191
192 const WGI::RawGameController GetRawGameController() const { return m_raw_controller; }
193
194 private:
195 using ButtonValueType = u8;
196
197 class Button : public Input
198 {
199 public:
200 explicit Button(const ButtonValueType* button) : m_button(*button) {}
201 ControlState GetState() const override { return ControlState(m_button != 0); }
202
203 private:
204 const ButtonValueType& m_button;
205 };
206
207 // A button with one of the "labels" that WGI provides.
208 class NamedButton final : public Button
209 {
210 public:
211 NamedButton(const ButtonValueType* button, std::string_view name) : Button(button), m_name(name)
212 {
213 }
214 std::string GetName() const override { return std::string(m_name); }
215
216 private:
217 const std::string_view m_name;
218 };
219
220 // A button with no label so we name it by its index.
221 class IndexedButton final : public Button
222 {
223 public:
224 IndexedButton(const ButtonValueType* button, u32 index) : Button(button), m_index(index) {}
225 std::string GetName() const override { return fmt::format("Button {}", m_index); }
226
227 private:
228 u32 m_index;
229 };
230
231 class Axis : public Input
232 {
233 public:
234 Axis(const double* axis, double base, double range)
235 : m_base(base), m_range(range), m_axis(*axis)
236 {
237 }
238
239 ControlState GetState() const override { return ControlState(m_axis - m_base) / m_range; }
240
241 protected:
242 const double m_base;
243 const double m_range;
244
245 private:
246 const double& m_axis;
247 };
248
249 class NamedAxis final : public Axis
250 {
251 public:
252 NamedAxis(const double* axis, double base, double range, std::string_view name)
253 : Axis(axis, base, range), m_name(name)
254 {
255 }
256 std::string GetName() const override
257 {
258 return fmt::format("{}{}", m_name, m_range < 0 ? '-' : '+');
259 }
260
261 private:
262 const std::string_view m_name;
263 };
264
265 class NamedTrigger final : public Axis
266 {
267 public:
268 NamedTrigger(const double* axis, std::string_view name) : Axis(axis, 0.0, 1.0), m_name(name) {}
269 std::string GetName() const override { return std::string(m_name); }
270
271 private:
272 const std::string_view m_name;
273 };
274
275 class NamedMotor final : public Output
276 {
277 public:
278 NamedMotor(double* motor, std::string_view name, Device* parent)
279 : m_motor(*motor), m_name(name), m_parent(*parent)
280 {
281 }
282 std::string GetName() const override { return std::string(m_name); }
283 void SetState(ControlState state) override
284 {
285 if (m_motor == state)
286 return;
287
288 m_motor = state;
289 m_parent.UpdateMotors();
290 }
291
292 private:
293 double& m_motor;
294 const std::string_view m_name;
295 Device& m_parent;
296 };
297
298 class IndexedAxis final : public Axis
299 {
300 public:
301 IndexedAxis(const double* axis, double base, double range, u32 index)
302 : Axis(axis, base, range), m_index(index)
303 {
304 }
305 std::string GetName() const override
306 {
307 return fmt::format("Axis {}{}", m_index, m_range < 0 ? '-' : '+');
308 }
309
310 private:
311 const u32 m_index;
312 };
313
314 class IndexedSwitch final : public Input
315 {
316 public:
317 IndexedSwitch(const WGI::GameControllerSwitchPosition* swtch, u32 index,
318 WGI::GameControllerSwitchPosition direction)
319 : m_switch(*swtch), m_index(index), m_direction(static_cast<int32_t>(direction))
320 {
321 }
322 std::string GetName() const override
323 {
324 return fmt::format("Switch {} {}", m_index, "NESW"[m_direction / 2]);
325 }
326 ControlState GetState() const override
327 {
328 if (m_switch == WGI::GameControllerSwitchPosition::Center)
329 return 0.0;
330
331 // All of the "in between" states (e.g. Up-Right) are one-off from the four cardinal
332 // directions. This tests that the current switch state value is within 1 of the desired
333 // state.
334 const auto direction_diff = std::abs(static_cast<int32_t>(m_switch) - m_direction);
335 return ControlState(direction_diff <= 1 || direction_diff == 7);
336 }
337
338 private:
339 const WGI::GameControllerSwitchPosition& m_switch;
340 const u32 m_index;
341 const int32_t m_direction;
342 };
343
344 class Battery : public Input
345 {
346 public:
347 Battery(const double* level) : m_level(*level) {}
348
349 bool IsDetectable() const override { return false; }
350
351 ControlState GetState() const override { return m_level; }
352
353 std::string GetName() const override { return "Battery"; }
354
355 private:
356 const double& m_level;
357 };
358
359 class SimpleHaptics : public Output
360 {
361 public:
362 SimpleHaptics(Haptics::SimpleHapticsController haptics,
363 Haptics::SimpleHapticsControllerFeedback feedback, u32 haptics_index)
364 : m_haptics(haptics), m_feedback(feedback), m_haptics_index(haptics_index)
365 {
366 }
367
368 void SetState(ControlState state) override
369 {
370 if (m_current_state == state)
371 return;
372
373 m_current_state = state;
374
375 try
376 {
377 if (state)
378 m_haptics.SendHapticFeedback(m_feedback, state);
379 else
380 m_haptics.StopFeedback();
381 }
382 catch (winrt::hresult_error)
383 {
384 // Ignore
385 }
386 }
387
388 protected:
389 u32 GetHapticsIndex() const { return m_haptics_index; }
390
391 private:
392 Haptics::SimpleHapticsController m_haptics;
393 Haptics::SimpleHapticsControllerFeedback m_feedback;
394 const u32 m_haptics_index;
395 ControlState m_current_state = 0;
396 };
397
398 class NamedFeedback final : public SimpleHaptics
399 {
400 public:
401 NamedFeedback(Haptics::SimpleHapticsController haptics,
402 Haptics::SimpleHapticsControllerFeedback feedback, u32 haptics_index,
403 std::string_view feedback_name)
404 : SimpleHaptics(haptics, feedback, haptics_index), m_feedback_name(feedback_name)
405 {
406 }
407 std::string GetName() const override
408 {
409 return fmt::format("{} {}", m_feedback_name, GetHapticsIndex());
410 }
411
412 private:
413 const std::string_view m_feedback_name;
414 };
415
416 void PopulateButtons()
417 {
418 try
419 {
420 // Using RawGameController for buttons because it gives us a nice array instead of a bitmask.
421 m_buttons.resize(m_raw_controller.ButtonCount());
422
423 u32 i = 0;
424 for (const auto& button : m_buttons)
425 {
426 WGI::GameControllerButtonLabel lbl{WGI::GameControllerButtonLabel::None};
427 try
428 {
429 lbl = m_raw_controller.GetButtonLabel(i);
430 }
431 catch (winrt::hresult_error)
432 {
433 lbl = WGI::GameControllerButtonLabel::None;
434 }
435
436 const int32_t button_name_idx = static_cast<int32_t>(lbl);
437 if (lbl != WGI::GameControllerButtonLabel::None &&
438 button_name_idx < wgi_button_names.size())
439 AddInput(new NamedButton(&button, wgi_button_names[button_name_idx]));
440 else
441 AddInput(new IndexedButton(&button, i));
442
443 ++i;
444 }
445 }
446 catch (winrt::hresult_error)
447 {
448 // If ButtonCount failed, m_buttons will be zero-sized.
449 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating buttons");
450 }
451 }
452
453 void PopulateHaptics()
454 {
455 static const std::map<uint16_t, std::string> waveform_name_map{
456 {Haptics::KnownSimpleHapticsControllerWaveforms::Click(), "Click"},
457 {Haptics::KnownSimpleHapticsControllerWaveforms::BuzzContinuous(), "Buzz"},
458 {Haptics::KnownSimpleHapticsControllerWaveforms::RumbleContinuous(), "Rumble"},
459 };
460
461 try
462 {
463 // SimpleHapticsControllers is available from Windows 1709.
464 u32 haptics_index = 0;
465 for (auto haptics_controller : m_raw_controller.SimpleHapticsControllers())
466 {
467 for (Haptics::SimpleHapticsControllerFeedback feedback :
468 haptics_controller.SupportedFeedback())
469 {
470 const uint16_t waveform = feedback.Waveform();
471 auto waveform_name_it = waveform_name_map.find(waveform);
472 if (waveform_name_it == waveform_name_map.end())
473 {
474 WARN_LOG_FMT(CONTROLLERINTERFACE,
475 "WGInput: Unhandled haptics feedback waveform: 0x{:04x}.", waveform);
476 continue;
477 }
478 AddOutput(new NamedFeedback(haptics_controller, feedback, haptics_index,
479 waveform_name_it->second));
480 }
481 ++haptics_index;
482 }
483 }
484 catch (winrt::hresult_error)
485 {
486 // Don't need to cleanup any state. It's OK if some outputs were added.
487 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating haptics");
488 }
489 }
490
491 std::string GetName() const override { return m_name; }
492
493 std::string GetSource() const override { return std::string(SOURCE_NAME); }
494
495 Core::DeviceRemoval UpdateInput() override
496 {
497 // IRawGameController:
498 static_assert(sizeof(bool) == sizeof(ButtonValueType));
499 // This cludge is needed to workaround GetCurrentReading wanting array_view<bool>, while
500 // using std::vector<bool> would create a bit-packed array, which isn't wanted. So, we keep
501 // vector<u8> and view it as array<bool>.
502 auto buttons =
503 winrt::array_view<bool>(reinterpret_cast<winrt::array_view<bool>::pointer>(&m_buttons[0]),
504 static_cast<winrt::array_view<bool>::size_type>(m_buttons.size()));
505 try
506 {
507 m_raw_controller.GetCurrentReading(buttons, m_switches, m_axes);
508 }
509 catch (winrt::hresult_error error)
510 {
511 ERROR_LOG_FMT(CONTROLLERINTERFACE,
512 "WGInput: IRawGameController::GetCurrentReading failed: {}", error.code());
513 }
514
515 // IGamepad:
516 if (m_gamepad)
517 {
518 try
519 {
520 m_gamepad_reading = m_gamepad.GetCurrentReading();
521 }
522 catch (winrt::hresult_error error)
523 {
524 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: IGamepad::GetCurrentReading failed: {}",
525 error.code());
526 }
527 }
528
529 // IGameControllerBatteryInfo:
530 if (!UpdateBatteryLevel())
531 DEBUG_LOG_FMT(CONTROLLERINTERFACE, "WGInput: UpdateBatteryLevel failed.");
532
533 return Core::DeviceRemoval::Keep;
534 }
535
536 void UpdateMotors()
537 {
538 try
539 {
540 m_gamepad.Vibration(m_state_out);
541 }
542 catch (winrt::hresult_error)
543 {
544 // Ignore
545 }
546 }
547
548 bool UpdateBatteryLevel()
549 {
550 try
551 {
552 // Workaround for Steam. If Steam's GameOverlayRenderer64.dll is loaded, battery_info is null.
553 auto battery_info = m_raw_controller.try_as<WGI::IGameControllerBatteryInfo>();
554 if (!battery_info)
555 return false;
556 const winrt::Windows::Devices::Power::BatteryReport report =
557 battery_info.TryGetBatteryReport();
558 if (!report)
559 return false;
560
561 // TryGetBatteryReport causes a memleak of 0x58 bytes each time it is called, up to at
562 // least Windows 21H2. A hack to fix the memleak is recorded here for posterity.
563 // auto report_ = *(uintptr_t***)&report;
564 // auto rc = &report_[0x40 / 8][0x30 / 8];
565 // if (*rc == 2)
566 // (*rc)--;
567
568 using winrt::Windows::System::Power::BatteryStatus;
569 const BatteryStatus status = report.Status();
570 switch (status)
571 {
572 case BatteryStatus::NotPresent:
573 m_battery_level = 0;
574 return true;
575
576 case BatteryStatus::Idle:
577 case BatteryStatus::Charging:
578 m_battery_level = BATTERY_INPUT_MAX_VALUE;
579 return true;
580
581 default:
582 break;
583 }
584
585 const int32_t full_value = report.FullChargeCapacityInMilliwattHours().GetInt32();
586 const int32_t remaining_value = report.RemainingCapacityInMilliwattHours().GetInt32();
587 m_battery_level = BATTERY_INPUT_MAX_VALUE * remaining_value / full_value;
588 return true;
589 }
590 catch (winrt::hresult_error)
591 {
592 return false;
593 }
594 }
595
596 const std::string m_name;
597
598 const WGI::RawGameController m_raw_controller;
599 std::vector<ButtonValueType> m_buttons;
600 std::vector<WGI::GameControllerSwitchPosition> m_switches;
601 std::vector<double> m_axes;
602
603 WGI::Gamepad m_gamepad = nullptr;
604 WGI::GamepadReading m_gamepad_reading{};
605 WGI::GamepadVibration m_state_out{};
606
607 ControlState m_battery_level = 0;
608 };
609
610 enum class AddRemoveEventType
611 {
612 AddOrReplace,
613 Remove,
614 };
615
616 struct AddRemoveEvent
617 {
618 AddRemoveEventType type;
619 WGI::RawGameController raw_game_controller;
620 };
621
622 static thread_local bool s_initialized_winrt;
623 static winrt::event_token s_event_added, s_event_removed;
624 static Common::WorkQueueThread<AddRemoveEvent> s_device_add_remove_queue;
625
626 static bool COMIsInitialized()
627 {
628 APTTYPE apt_type{};
629 APTTYPEQUALIFIER apt_qualifier{};
630 return CoGetApartmentType(&apt_type, &apt_qualifier) == S_OK;
631 }
632
633 static void AddDevice(const WGI::RawGameController& raw_game_controller)
634 {
635 // Get user-facing device name if available. Otherwise generate a name from vid/pid.
636 std::string device_name;
637 try
638 {
639 device_name = StripWhitespace(WStringToUTF8(raw_game_controller.DisplayName().c_str()));
640 if (device_name.empty())
641 {
642 const u16 vid = raw_game_controller.HardwareVendorId();
643 const u16 pid = raw_game_controller.HardwareProductId();
644 device_name = fmt::format("Device_{:04x}:{:04x}", vid, pid);
645 INFO_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Empty device name, using {}", device_name);
646 }
647 }
648 catch (winrt::hresult_error)
649 {
650 device_name = "Device";
651 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to get device name, using {}", device_name);
652 }
653
654 try
655 {
656 WGI::Gamepad gamepad = WGI::Gamepad::FromGameController(raw_game_controller);
657 // Note that gamepad may be nullptr here. The Device class will deal with this.
658 auto dev = std::make_shared<Device>(std::move(device_name), raw_game_controller, gamepad);
659
660 // Only add if it has some inputs/outputs.
661 if (dev->Inputs().size() || dev->Outputs().size())
662 g_controller_interface.AddDevice(std::move(dev));
663 }
664 catch (winrt::hresult_error)
665 {
666 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to add device {}", device_name);
667 }
668 }
669
670 static void RemoveDevice(const WGI::RawGameController& raw_game_controller)
671 {
672 g_controller_interface.RemoveDevice([&](const auto* dev) {
673 if (dev->GetSource() != SOURCE_NAME)
674 return false;
675 return static_cast<const Device*>(dev)->GetRawGameController() == raw_game_controller;
676 });
677 }
678
679 #pragma warning(push)
680 // 'winrt::impl::implements_delegate<winrt::Windows::Foundation::EventHandler<winrt::Windows::Gaming::Input::RawGameController>,H>':
681 // class has virtual functions, but its non-trivial destructor is not virtual; instances of this
682 // class may not be destructed correctly
683 // (H is the lambda)
684 #pragma warning(disable : 4265)
685
686 static void HandleAddRemoveEvent(AddRemoveEvent evt)
687 {
688 try
689 {
690 winrt::init_apartment();
691 }
692 catch (const winrt::hresult_error& ex)
693 {
694 ERROR_LOG_FMT(CONTROLLERINTERFACE,
695 "WGInput: Failed to CoInitialize for add/remove controller event: {}",
696 WStringToUTF8(ex.message()));
697 return;
698 }
699 Common::ScopeGuard coinit_guard([] { winrt::uninit_apartment(); });
700
701 switch (evt.type)
702 {
703 case AddRemoveEventType::AddOrReplace:
704 RemoveDevice(evt.raw_game_controller);
705 AddDevice(evt.raw_game_controller);
706 break;
707 case AddRemoveEventType::Remove:
708 RemoveDevice(evt.raw_game_controller);
709 break;
710 default:
711 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Invalid add/remove controller event: {}",
712 std::to_underlying(evt.type));
713 }
714 }
715
716 void Init()
717 {
718 if (!COMIsInitialized())
719 {
720 // NOTE: Devices in g_controller_interface should only be accessed by threads that have had
721 // winrt (com) initialized.
722 winrt::init_apartment();
723 s_initialized_winrt = true;
724 }
725
726 s_device_add_remove_queue.Reset("WGInput Add/Remove Device Thread", HandleAddRemoveEvent);
727
728 try
729 {
730 // These events will be invoked from WGI-managed threadpool.
731 s_event_added = WGI::RawGameController::RawGameControllerAdded(
732 [](auto&&, WGI::RawGameController raw_game_controller) {
733 s_device_add_remove_queue.EmplaceItem(
734 AddRemoveEvent{AddRemoveEventType::AddOrReplace, std::move(raw_game_controller)});
735 });
736
737 s_event_removed = WGI::RawGameController::RawGameControllerRemoved(
738 [](auto&&, WGI::RawGameController raw_game_controller) {
739 s_device_add_remove_queue.EmplaceItem(
740 AddRemoveEvent{AddRemoveEventType::Remove, std::move(raw_game_controller)});
741 });
742 }
743 catch (winrt::hresult_error)
744 {
745 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to register event handlers");
746 }
747 }
748
749 #pragma warning(pop)
750
751 void DeInit()
752 {
753 s_device_add_remove_queue.Shutdown();
754
755 WGI::RawGameController::RawGameControllerAdded(s_event_added);
756 WGI::RawGameController::RawGameControllerRemoved(s_event_removed);
757
758 if (s_initialized_winrt)
759 {
760 winrt::uninit_apartment();
761 s_initialized_winrt = false;
762 }
763 }
764
765 void PopulateDevices()
766 {
767 // WGI Interfaces to potentially use:
768 // Gamepad: Buttons, 2x Sticks and 2x Triggers, 4x Vibration Motors
769 // RawGameController: Buttons, Switches (Hats), Axes, Haptics
770 // The following are not implemented:
771 // ArcadeStick: Buttons (probably no need to specialize, literally just buttons)
772 // FlightStick: Buttons, HatSwitch, Pitch, Roll, Throttle, Yaw
773 // RacingWheel: Buttons, Clutch, Handbrake, PatternShifterGear, Throttle, Wheel, WheelMotor
774 // UINavigationController: Directions, Scrolling, etc.
775
776 // RawGameController available from Windows 15063.
777 // properties added in 1709: DisplayName, NonRoamableId, SimpleHapticsControllers
778
779 try
780 {
781 for (const WGI::RawGameController& raw_game_controller :
782 WGI::RawGameController::RawGameControllers())
783 {
784 RemoveDevice(raw_game_controller);
785 AddDevice(raw_game_controller);
786 }
787 }
788 catch (winrt::hresult_error)
789 {
790 // Only reach here if RawGameControllers() failed
791 ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: PopulateDevices failed");
792 }
793 }
794
795 } // namespace ciface::WGInput