WGInput: implement error handling

This commit is contained in:
Shawn Hoffman 2022-08-27 02:11:27 -07:00
parent 6bc8ab7001
commit cd407abe34

View File

@ -7,10 +7,13 @@
#include <map> #include <map>
#include <string_view> #include <string_view>
#include <fmt/format.h> // For CoGetApartmentType
#include <objbase.h>
#pragma comment(lib, "ole32")
// TODO winrt translates com failures to c++ exceptions, so we must use try/catch in this file to // NOTE: winrt translates com failures to c++ exceptions, so we must use try/catch in this file to
// prevent possible errors from terminating Dolphin. // prevent possible errors from escaping and terminating Dolphin.
#include <winrt/base.h>
#include <winrt/windows.devices.haptics.h> #include <winrt/windows.devices.haptics.h>
#include <winrt/windows.devices.power.h> #include <winrt/windows.devices.power.h>
#include <winrt/windows.foundation.collections.h> #include <winrt/windows.foundation.collections.h>
@ -18,6 +21,8 @@
#include <winrt/windows.system.power.h> #include <winrt/windows.system.power.h>
#pragma comment(lib, "windowsapp") #pragma comment(lib, "windowsapp")
#include <fmt/format.h>
#include "Common/Logging/Log.h" #include "Common/Logging/Log.h"
#include "Common/StringUtil.h" #include "Common/StringUtil.h"
#include "InputCommon/ControllerInterface/ControllerInterface.h" #include "InputCommon/ControllerInterface/ControllerInterface.h"
@ -107,6 +112,8 @@ public:
const bool use_raw_controller_axes = !m_gamepad; const bool use_raw_controller_axes = !m_gamepad;
if (use_raw_controller_axes) if (use_raw_controller_axes)
{
try
{ {
// Axes: // Axes:
m_axes.resize(m_raw_controller.AxisCount()); m_axes.resize(m_raw_controller.AxisCount());
@ -115,10 +122,17 @@ public:
for (auto& axis : m_axes) for (auto& axis : m_axes)
{ {
// AddAnalogInputs adds additional "FullAnalogSurface" Inputs. // AddAnalogInputs adds additional "FullAnalogSurface" Inputs.
AddAnalogInputs(new IndexedAxis(&axis, 0.5, +0.5, i), new IndexedAxis(&axis, 0.5, -0.5, i)); AddAnalogInputs(new IndexedAxis(&axis, 0.5, +0.5, i),
new IndexedAxis(&axis, 0.5, -0.5, i));
++i; ++i;
} }
} }
catch (winrt::hresult_error)
{
// If AxisCount failed, m_axes will remain zero-sized; nothing to do.
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating axes");
}
}
// Apparently some devices (e.g. DS4) provide the IGameController interface // Apparently some devices (e.g. DS4) provide the IGameController interface
// but expose the dpad only on a switch (IRawGameController interface). // but expose the dpad only on a switch (IRawGameController interface).
@ -127,20 +141,24 @@ public:
// Switches (Hats): // Switches (Hats):
if (use_raw_controller_switches) if (use_raw_controller_switches)
{
try
{ {
m_switches.resize(m_raw_controller.SwitchCount()); m_switches.resize(m_raw_controller.SwitchCount());
// Accumulate switch kinds first, to ensure no inputs are added if there is any error.
std::vector<WGI::GameControllerSwitchKind> switch_kinds;
for (u32 i = 0; i < m_switches.size(); i++)
switch_kinds.push_back(m_raw_controller.GetSwitchKind(i));
u32 i = 0; u32 i = 0;
for (auto& swtch : m_switches) for (auto& swtch : m_switches)
{ {
using gcsp = WGI::GameControllerSwitchPosition; using gcsp = WGI::GameControllerSwitchPosition;
WGI::GameControllerSwitchKind switch_kind = m_raw_controller.GetSwitchKind(i);
AddInput(new IndexedSwitch(&swtch, i, gcsp::Up)); AddInput(new IndexedSwitch(&swtch, i, gcsp::Up));
AddInput(new IndexedSwitch(&swtch, i, gcsp::Down)); AddInput(new IndexedSwitch(&swtch, i, gcsp::Down));
if (switch_kind != WGI::GameControllerSwitchKind::TwoWay) if (switch_kinds[i] != WGI::GameControllerSwitchKind::TwoWay)
{ {
// If it's not a "two-way" switch (up/down only) then add the left/right inputs. // If it's not a "two-way" switch (up/down only) then add the left/right inputs.
AddInput(new IndexedSwitch(&swtch, i, gcsp::Left)); AddInput(new IndexedSwitch(&swtch, i, gcsp::Left));
@ -150,6 +168,13 @@ public:
++i; ++i;
} }
} }
catch (winrt::hresult_error)
{
// Safe as no inputs will have been added.
m_switches.clear();
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating switches");
}
}
// Haptics: // Haptics:
PopulateHaptics(); PopulateHaptics();
@ -344,11 +369,18 @@ private:
m_current_state = state; m_current_state = state;
try
{
if (state) if (state)
m_haptics.SendHapticFeedback(m_feedback, state); m_haptics.SendHapticFeedback(m_feedback, state);
else else
m_haptics.StopFeedback(); m_haptics.StopFeedback();
} }
catch (winrt::hresult_error)
{
// Ignore
}
}
protected: protected:
u32 GetHapticsIndex() const { return m_haptics_index; } u32 GetHapticsIndex() const { return m_haptics_index; }
@ -379,6 +411,8 @@ private:
}; };
void PopulateButtons() void PopulateButtons()
{
try
{ {
// Using RawGameController for buttons because it gives us a nice array instead of a bitmask. // Using RawGameController for buttons because it gives us a nice array instead of a bitmask.
m_buttons.resize(m_raw_controller.ButtonCount()); m_buttons.resize(m_raw_controller.ButtonCount());
@ -386,9 +420,19 @@ private:
u32 i = 0; u32 i = 0;
for (const auto& button : m_buttons) for (const auto& button : m_buttons)
{ {
const WGI::GameControllerButtonLabel lbl = m_raw_controller.GetButtonLabel(i); WGI::GameControllerButtonLabel lbl{WGI::GameControllerButtonLabel::None};
try
{
lbl = m_raw_controller.GetButtonLabel(i);
}
catch (winrt::hresult_error)
{
lbl = WGI::GameControllerButtonLabel::None;
}
const int32_t button_name_idx = static_cast<int32_t>(lbl); const int32_t button_name_idx = static_cast<int32_t>(lbl);
if (lbl != WGI::GameControllerButtonLabel::None && button_name_idx < wgi_button_names.size()) if (lbl != WGI::GameControllerButtonLabel::None &&
button_name_idx < wgi_button_names.size())
AddInput(new NamedButton(&button, wgi_button_names[button_name_idx])); AddInput(new NamedButton(&button, wgi_button_names[button_name_idx]));
else else
AddInput(new IndexedButton(&button, i)); AddInput(new IndexedButton(&button, i));
@ -396,6 +440,12 @@ private:
++i; ++i;
} }
} }
catch (winrt::hresult_error)
{
// If ButtonCount failed, m_buttons will be zero-sized.
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating buttons");
}
}
void PopulateHaptics() void PopulateHaptics()
{ {
@ -405,6 +455,8 @@ private:
{Haptics::KnownSimpleHapticsControllerWaveforms::RumbleContinuous(), "Rumble"}, {Haptics::KnownSimpleHapticsControllerWaveforms::RumbleContinuous(), "Rumble"},
}; };
try
{
// SimpleHapticsControllers is available from Windows 1709. // SimpleHapticsControllers is available from Windows 1709.
u32 haptics_index = 0; u32 haptics_index = 0;
for (auto haptics_controller : m_raw_controller.SimpleHapticsControllers()) for (auto haptics_controller : m_raw_controller.SimpleHapticsControllers())
@ -426,6 +478,12 @@ private:
++haptics_index; ++haptics_index;
} }
} }
catch (winrt::hresult_error)
{
// Don't need to cleanup any state. It's OK if some outputs were added.
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Error populating haptics");
}
}
std::string GetName() const override { return m_name; } std::string GetName() const override { return m_name; }
@ -441,20 +499,50 @@ private:
auto buttons = auto buttons =
winrt::array_view<bool>(reinterpret_cast<winrt::array_view<bool>::pointer>(&m_buttons[0]), winrt::array_view<bool>(reinterpret_cast<winrt::array_view<bool>::pointer>(&m_buttons[0]),
static_cast<winrt::array_view<bool>::size_type>(m_buttons.size())); static_cast<winrt::array_view<bool>::size_type>(m_buttons.size()));
try
{
m_raw_controller.GetCurrentReading(buttons, m_switches, m_axes); m_raw_controller.GetCurrentReading(buttons, m_switches, m_axes);
}
catch (winrt::hresult_error error)
{
ERROR_LOG_FMT(CONTROLLERINTERFACE,
"WGInput: IRawGameController::GetCurrentReading failed: {:x}", error.code());
}
// IGamepad: // IGamepad:
if (m_gamepad) if (m_gamepad)
{
try
{
m_gamepad_reading = m_gamepad.GetCurrentReading(); m_gamepad_reading = m_gamepad.GetCurrentReading();
}
catch (winrt::hresult_error error)
{
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: IGamepad::GetCurrentReading failed: {:x}",
error.code());
}
}
// IGameControllerBatteryInfo: // IGameControllerBatteryInfo:
if (!UpdateBatteryLevel()) if (!UpdateBatteryLevel())
DEBUG_LOG_FMT(CONTROLLERINTERFACE, "WGInput: UpdateBatteryLevel failed."); DEBUG_LOG_FMT(CONTROLLERINTERFACE, "WGInput: UpdateBatteryLevel failed.");
} }
void UpdateMotors() { m_gamepad.Vibration(m_state_out); } void UpdateMotors()
{
try
{
m_gamepad.Vibration(m_state_out);
}
catch (winrt::hresult_error)
{
// Ignore
}
}
bool UpdateBatteryLevel() bool UpdateBatteryLevel()
{
try
{ {
const winrt::Windows::Devices::Power::BatteryReport report = const winrt::Windows::Devices::Power::BatteryReport report =
m_raw_controller.TryGetBatteryReport(); m_raw_controller.TryGetBatteryReport();
@ -462,11 +550,11 @@ private:
return false; return false;
// TryGetBatteryReport causes a memleak of 0x58 bytes each time it is called, up to at // TryGetBatteryReport causes a memleak of 0x58 bytes each time it is called, up to at
// least Windows 21H2. This is a big hack to "fix" the refcount. // least Windows 21H2. A hack to fix the memleak is recorded here for posterity.
auto report_ = *(uintptr_t***)&report; // auto report_ = *(uintptr_t***)&report;
auto rc = &report_[0x40 / 8][0x30 / 8]; // auto rc = &report_[0x40 / 8][0x30 / 8];
if (*rc == 2) // if (*rc == 2)
(*rc)--; // (*rc)--;
using winrt::Windows::System::Power::BatteryStatus; using winrt::Windows::System::Power::BatteryStatus;
const BatteryStatus status = report.Status(); const BatteryStatus status = report.Status();
@ -490,6 +578,11 @@ private:
m_battery_level = BATTERY_INPUT_MAX_VALUE * remaining_value / full_value; m_battery_level = BATTERY_INPUT_MAX_VALUE * remaining_value / full_value;
return true; return true;
} }
catch (winrt::hresult_error)
{
return false;
}
}
const std::string m_name; const std::string m_name;
@ -508,19 +601,36 @@ private:
static thread_local bool s_initialized_winrt; static thread_local bool s_initialized_winrt;
static winrt::event_token s_event_added, s_event_removed; static winrt::event_token s_event_added, s_event_removed;
static bool COMIsInitialized()
{
APTTYPE apt_type{};
APTTYPEQUALIFIER apt_qualifier{};
return CoGetApartmentType(&apt_type, &apt_qualifier) == S_OK;
}
static void AddDevice(const WGI::RawGameController& raw_game_controller) static void AddDevice(const WGI::RawGameController& raw_game_controller)
{ {
// Get user-facing device name if available. Otherwise generate a name from vid/pid. // Get user-facing device name if available. Otherwise generate a name from vid/pid.
auto device_name = std::string device_name;
std::string(StripWhitespace(WStringToUTF8(raw_game_controller.DisplayName().c_str()))); try
{
device_name = StripWhitespace(WStringToUTF8(raw_game_controller.DisplayName().c_str()));
if (device_name.empty()) if (device_name.empty())
{ {
const u16 vid = raw_game_controller.HardwareVendorId(); const u16 vid = raw_game_controller.HardwareVendorId();
const u16 pid = raw_game_controller.HardwareProductId(); const u16 pid = raw_game_controller.HardwareProductId();
device_name = fmt::format("Device_{:04x}:{:04x}", vid, pid); device_name = fmt::format("Device_{:04x}:{:04x}", vid, pid);
INFO_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Empty device name, using {}", device_name);
}
}
catch (winrt::hresult_error)
{
device_name = "Device";
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to get device name, using {}", device_name); ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to get device name, using {}", device_name);
} }
try
{
WGI::Gamepad gamepad = WGI::Gamepad::FromGameController(raw_game_controller); WGI::Gamepad gamepad = WGI::Gamepad::FromGameController(raw_game_controller);
// Note that gamepad may be nullptr here. The Device class will deal with this. // Note that gamepad may be nullptr here. The Device class will deal with this.
auto dev = std::make_shared<Device>(std::move(device_name), raw_game_controller, gamepad); auto dev = std::make_shared<Device>(std::move(device_name), raw_game_controller, gamepad);
@ -528,6 +638,11 @@ static void AddDevice(const WGI::RawGameController& raw_game_controller)
// Only add if it has some inputs/outputs. // Only add if it has some inputs/outputs.
if (dev->Inputs().size() || dev->Outputs().size()) if (dev->Inputs().size() || dev->Outputs().size())
g_controller_interface.AddDevice(std::move(dev)); g_controller_interface.AddDevice(std::move(dev));
}
catch (winrt::hresult_error)
{
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to add device {}", device_name);
}
} }
static void RemoveDevice(const WGI::RawGameController& raw_game_controller) static void RemoveDevice(const WGI::RawGameController& raw_game_controller)
@ -548,21 +663,16 @@ static void RemoveDevice(const WGI::RawGameController& raw_game_controller)
void Init() void Init()
{ {
if (!COMIsInitialized())
{
// NOTE: Devices in g_controller_interface should only be accessed by threads that have had
// winrt (com) initialized.
winrt::init_apartment();
s_initialized_winrt = true;
}
try try
{ {
// TODO currently, com gets initialized in STA previously on the thread that calls this
// function. need to ensure Devices in g_controller_interface only get accessed by threads that
// have had com initialized.
// winrt::init_apartment();
// s_initialized_winrt = true;
}
catch (...)
{
s_initialized_winrt = false;
}
// XXX If SDL is enabled, these get broken after the first one is fired.
// These events will be invoked from WGI-managed threadpool. // These events will be invoked from WGI-managed threadpool.
s_event_added = WGI::RawGameController::RawGameControllerAdded( s_event_added = WGI::RawGameController::RawGameControllerAdded(
[](auto&&, const WGI::RawGameController raw_game_controller) { [](auto&&, const WGI::RawGameController raw_game_controller) {
@ -574,6 +684,11 @@ void Init()
[](auto&&, const WGI::RawGameController raw_game_controller) { [](auto&&, const WGI::RawGameController raw_game_controller) {
RemoveDevice(raw_game_controller); RemoveDevice(raw_game_controller);
}); });
}
catch (winrt::hresult_error)
{
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: Failed to register event handlers");
}
} }
#pragma warning(pop) #pragma warning(pop)
@ -604,12 +719,20 @@ void PopulateDevices()
// RawGameController available from Windows 15063. // RawGameController available from Windows 15063.
// properties added in 1709: DisplayName, NonRoamableId, SimpleHapticsControllers // properties added in 1709: DisplayName, NonRoamableId, SimpleHapticsControllers
try
{
for (const WGI::RawGameController& raw_game_controller : for (const WGI::RawGameController& raw_game_controller :
WGI::RawGameController::RawGameControllers()) WGI::RawGameController::RawGameControllers())
{ {
RemoveDevice(raw_game_controller); RemoveDevice(raw_game_controller);
AddDevice(raw_game_controller); AddDevice(raw_game_controller);
} }
}
catch (winrt::hresult_error)
{
// Only reach here if RawGameControllers() failed
ERROR_LOG_FMT(CONTROLLERINTERFACE, "WGInput: PopulateDevices failed");
}
} }
} // namespace ciface::WGInput } // namespace ciface::WGInput