WGInput.cpp 24 KB

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