DInputKeyboardMouse.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Copyright 2010 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "InputCommon/ControllerInterface/DInput/DInputKeyboardMouse.h"
  4. #include <algorithm>
  5. #include "Common/Logging/Log.h"
  6. #include "Core/Core.h"
  7. #include "Core/Host.h"
  8. #include "InputCommon/ControllerInterface/ControllerInterface.h"
  9. #include "InputCommon/ControllerInterface/DInput/DInput.h"
  10. // (lower would be more sensitive) user can lower sensitivity by setting range
  11. // seems decent here ( at 8 ), I don't think anyone would need more sensitive than this
  12. // and user can lower it much farther than they would want to with the range
  13. #define MOUSE_AXIS_SENSITIVITY 8
  14. // if input hasn't been received for this many ms, mouse input will be skipped
  15. // otherwise it is just some crazy value
  16. #define DROP_INPUT_TIME 250
  17. namespace ciface::DInput
  18. {
  19. class RelativeMouseAxis final : public Core::Device::RelativeInput
  20. {
  21. public:
  22. std::string GetName() const override
  23. {
  24. return fmt::format("RelativeMouse {}{}", char('X' + m_index), (m_scale > 0) ? '+' : '-');
  25. }
  26. RelativeMouseAxis(u8 index, bool positive, const RelativeMouseState* state)
  27. : m_state(*state), m_index(index), m_scale(positive * 2 - 1)
  28. {
  29. }
  30. ControlState GetState() const override
  31. {
  32. return ControlState(m_state.GetValue().data[m_index] * m_scale);
  33. }
  34. private:
  35. const RelativeMouseState& m_state;
  36. const u8 m_index;
  37. const s8 m_scale;
  38. };
  39. static const struct
  40. {
  41. const BYTE code;
  42. const char* const name;
  43. } named_keys[] = {
  44. #include "InputCommon/ControllerInterface/DInput/NamedKeys.h" // NOLINT
  45. };
  46. // Prevent duplicate keyboard/mouse devices. Modified by more threads.
  47. static bool s_keyboard_mouse_exists;
  48. static HWND s_hwnd;
  49. void InitKeyboardMouse(IDirectInput8* const idi8, HWND hwnd)
  50. {
  51. if (s_keyboard_mouse_exists)
  52. return;
  53. s_hwnd = hwnd;
  54. // Mouse and keyboard are a combined device, to allow shift+click and stuff
  55. // if that's dumb, I will make a VirtualDevice class that just uses ranges of inputs/outputs from
  56. // other devices
  57. // so there can be a separated Keyboard and mouse, as well as combined KeyboardMouse
  58. LPDIRECTINPUTDEVICE8 kb_device = nullptr;
  59. LPDIRECTINPUTDEVICE8 mo_device = nullptr;
  60. // These are "virtual" system devices, so they are always there even if we have no physical
  61. // mouse and keyboard plugged into the computer
  62. if (SUCCEEDED(idi8->CreateDevice(GUID_SysKeyboard, &kb_device, nullptr)) &&
  63. SUCCEEDED(kb_device->SetDataFormat(&c_dfDIKeyboard)) &&
  64. SUCCEEDED(kb_device->SetCooperativeLevel(nullptr, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)) &&
  65. SUCCEEDED(idi8->CreateDevice(GUID_SysMouse, &mo_device, nullptr)) &&
  66. SUCCEEDED(mo_device->SetDataFormat(&c_dfDIMouse2)) &&
  67. SUCCEEDED(mo_device->SetCooperativeLevel(nullptr, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
  68. {
  69. g_controller_interface.AddDevice(std::make_shared<KeyboardMouse>(kb_device, mo_device));
  70. return;
  71. }
  72. ERROR_LOG_FMT(CONTROLLERINTERFACE, "KeyboardMouse device failed to be created");
  73. if (kb_device)
  74. kb_device->Release();
  75. if (mo_device)
  76. mo_device->Release();
  77. }
  78. void SetKeyboardMouseWindow(HWND hwnd)
  79. {
  80. s_hwnd = hwnd;
  81. }
  82. KeyboardMouse::~KeyboardMouse()
  83. {
  84. s_keyboard_mouse_exists = false;
  85. // Independently of the order in which we do these, if we put a breakpoint on Unacquire() (or in
  86. // any place in the call stack before this), when refreshing devices from the UI, on the second
  87. // attempt, it will get stuck in an infinite (while) loop inside dinput8.dll. Given that it can't
  88. // be otherwise be reproduced (not even with sleeps), we can just ignore the problem.
  89. // kb
  90. m_kb_device->Unacquire();
  91. m_kb_device->Release();
  92. // mouse
  93. m_mo_device->Unacquire();
  94. m_mo_device->Release();
  95. }
  96. KeyboardMouse::KeyboardMouse(const LPDIRECTINPUTDEVICE8 kb_device,
  97. const LPDIRECTINPUTDEVICE8 mo_device)
  98. : m_kb_device(kb_device), m_mo_device(mo_device), m_last_update(GetTickCount()), m_state_in()
  99. {
  100. s_keyboard_mouse_exists = true;
  101. if (FAILED(m_kb_device->Acquire()))
  102. WARN_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to acquire. We'll retry later");
  103. if (FAILED(m_mo_device->Acquire()))
  104. WARN_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to acquire. We'll retry later");
  105. // KEYBOARD
  106. // add keys
  107. for (u8 i = 0; i < sizeof(named_keys) / sizeof(*named_keys); ++i)
  108. AddInput(new Key(i, m_state_in.keyboard[named_keys[i].code]));
  109. // Add combined left/right modifiers with consistent naming across platforms.
  110. AddCombinedInput("Alt", {"LMENU", "RMENU"});
  111. AddCombinedInput("Shift", {"LSHIFT", "RSHIFT"});
  112. AddCombinedInput("Ctrl", {"LCONTROL", "RCONTROL"});
  113. // MOUSE
  114. DIDEVCAPS mouse_caps = {};
  115. mouse_caps.dwSize = sizeof(mouse_caps);
  116. m_mo_device->GetCapabilities(&mouse_caps);
  117. // mouse buttons
  118. for (u8 i = 0; i < mouse_caps.dwButtons; ++i)
  119. AddInput(new Button(i, m_state_in.mouse.rgbButtons[i]));
  120. // mouse axes
  121. for (unsigned int i = 0; i < mouse_caps.dwAxes; ++i)
  122. {
  123. const LONG& ax = (&m_state_in.mouse.lX)[i];
  124. // each axis gets a negative and a positive input instance associated with it
  125. AddInput(new Axis(i, ax, (2 == i) ? -1 : -MOUSE_AXIS_SENSITIVITY));
  126. AddInput(new Axis(i, ax, -(2 == i) ? 1 : MOUSE_AXIS_SENSITIVITY));
  127. }
  128. // cursor, with a hax for-loop
  129. for (unsigned int i = 0; i < 4; ++i)
  130. AddInput(new Cursor(!!(i & 2), (&m_state_in.cursor.x)[i / 2], !!(i & 1)));
  131. // Raw relative mouse movement.
  132. for (unsigned int i = 0; i != mouse_caps.dwAxes; ++i)
  133. {
  134. AddInput(new RelativeMouseAxis(i, false, &m_state_in.relative_mouse));
  135. AddInput(new RelativeMouseAxis(i, true, &m_state_in.relative_mouse));
  136. }
  137. }
  138. void KeyboardMouse::UpdateCursorInput()
  139. {
  140. // Get the size of the current window (in my case Rect.top and Rect.left was zero).
  141. RECT rect;
  142. GetClientRect(s_hwnd, &rect);
  143. // Width and height are the size of the rendering window. They could be 0
  144. const auto win_width = std::max(rect.right - rect.left, 1l);
  145. const auto win_height = std::max(rect.bottom - rect.top, 1l);
  146. POINT point = {};
  147. if (g_controller_interface.IsMouseCenteringRequested() &&
  148. (Host_RendererHasFocus() || Host_TASInputHasFocus()))
  149. {
  150. point.x = win_width / 2;
  151. point.y = win_height / 2;
  152. POINT screen_point = point;
  153. ClientToScreen(s_hwnd, &screen_point);
  154. SetCursorPos(screen_point.x, screen_point.y);
  155. g_controller_interface.SetMouseCenteringRequested(false);
  156. }
  157. else if (Host_TASInputHasFocus())
  158. {
  159. // When a TAS Input window has focus and "Enable Controller Input" is checked most types of
  160. // input should be read normally as if the render window had focus instead. The cursor is an
  161. // exception, as otherwise using the mouse to set any control in the TAS Input window will also
  162. // update the Wii IR value (or any other input controlled by the cursor).
  163. return;
  164. }
  165. else
  166. {
  167. GetCursorPos(&point);
  168. // Get the cursor position relative to the upper left corner of the current window
  169. // (separate or render to main)
  170. ScreenToClient(s_hwnd, &point);
  171. }
  172. const auto window_scale = g_controller_interface.GetWindowInputScale();
  173. // Convert the cursor position to a range from -1 to 1.
  174. m_state_in.cursor.x = (ControlState(point.x) / win_width * 2 - 1) * window_scale.x;
  175. m_state_in.cursor.y = (ControlState(point.y) / win_height * 2 - 1) * window_scale.y;
  176. }
  177. Core::DeviceRemoval KeyboardMouse::UpdateInput()
  178. {
  179. UpdateCursorInput();
  180. DIMOUSESTATE2 tmp_mouse;
  181. // if mouse position hasn't been updated in a short while, skip a dev state
  182. DWORD cur_time = GetTickCount();
  183. if (cur_time - m_last_update > DROP_INPUT_TIME)
  184. {
  185. // set axes to zero
  186. m_state_in.mouse = {};
  187. m_state_in.relative_mouse = {};
  188. // skip this input state
  189. m_mo_device->GetDeviceState(sizeof(tmp_mouse), &tmp_mouse);
  190. }
  191. m_last_update = cur_time;
  192. HRESULT mo_hr = m_mo_device->GetDeviceState(sizeof(tmp_mouse), &tmp_mouse);
  193. if (DIERR_INPUTLOST == mo_hr || DIERR_NOTACQUIRED == mo_hr)
  194. {
  195. INFO_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to get state");
  196. if (FAILED(m_mo_device->Acquire()))
  197. INFO_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to re-acquire, we'll retry later");
  198. }
  199. else if (SUCCEEDED(mo_hr))
  200. {
  201. m_state_in.relative_mouse.Move({tmp_mouse.lX, tmp_mouse.lY, tmp_mouse.lZ});
  202. m_state_in.relative_mouse.Update();
  203. // need to smooth out the axes, otherwise it doesn't work for shit
  204. for (unsigned int i = 0; i < 3; ++i)
  205. ((&m_state_in.mouse.lX)[i] += (&tmp_mouse.lX)[i]) /= 2;
  206. // copy over the buttons
  207. std::copy_n(tmp_mouse.rgbButtons, std::size(tmp_mouse.rgbButtons), m_state_in.mouse.rgbButtons);
  208. }
  209. HRESULT kb_hr = m_kb_device->GetDeviceState(sizeof(m_state_in.keyboard), &m_state_in.keyboard);
  210. if (kb_hr == DIERR_INPUTLOST || kb_hr == DIERR_NOTACQUIRED)
  211. {
  212. INFO_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to get state");
  213. if (SUCCEEDED(m_kb_device->Acquire()))
  214. m_kb_device->GetDeviceState(sizeof(m_state_in.keyboard), &m_state_in.keyboard);
  215. else
  216. INFO_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to re-acquire, we'll retry later");
  217. }
  218. return Core::DeviceRemoval::Keep;
  219. }
  220. std::string KeyboardMouse::GetName() const
  221. {
  222. return "Keyboard Mouse";
  223. }
  224. std::string KeyboardMouse::GetSource() const
  225. {
  226. return DINPUT_SOURCE_NAME;
  227. }
  228. // Give this device a higher priority to make sure it shows first
  229. int KeyboardMouse::GetSortPriority() const
  230. {
  231. return DEFAULT_DEVICE_SORT_PRIORITY;
  232. }
  233. bool KeyboardMouse::IsVirtualDevice() const
  234. {
  235. return true;
  236. }
  237. // names
  238. std::string KeyboardMouse::Key::GetName() const
  239. {
  240. return named_keys[m_index].name;
  241. }
  242. std::string KeyboardMouse::Button::GetName() const
  243. {
  244. return std::string("Click ") + char('0' + m_index);
  245. }
  246. std::string KeyboardMouse::Axis::GetName() const
  247. {
  248. char tmpstr[] = "Axis ..";
  249. tmpstr[5] = (char)('X' + m_index);
  250. tmpstr[6] = (m_range < 0 ? '-' : '+');
  251. return tmpstr;
  252. }
  253. std::string KeyboardMouse::Cursor::GetName() const
  254. {
  255. char tmpstr[] = "Cursor ..";
  256. tmpstr[7] = (char)('X' + m_index);
  257. tmpstr[8] = (m_positive ? '+' : '-');
  258. return tmpstr;
  259. }
  260. // get/set state
  261. ControlState KeyboardMouse::Key::GetState() const
  262. {
  263. return (m_key != 0);
  264. }
  265. ControlState KeyboardMouse::Button::GetState() const
  266. {
  267. return (m_button != 0);
  268. }
  269. ControlState KeyboardMouse::Axis::GetState() const
  270. {
  271. return ControlState(m_axis) / m_range;
  272. }
  273. ControlState KeyboardMouse::Cursor::GetState() const
  274. {
  275. return m_axis / (m_positive ? 1.0 : -1.0);
  276. }
  277. } // namespace ciface::DInput