| 1 | // Copyright 2010 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "InputCommon/ControllerInterface/ControllerInterface.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | |
| 8 | #include "Common/Assert.h" |
| 9 | #include "Common/Logging/Log.h" |
| 10 | #include "Core/HW/WiimoteReal/WiimoteReal.h" |
| 11 | |
| 12 | #ifdef CIFACE_USE_WIN32 |
| 13 | #include "InputCommon/ControllerInterface/Win32/Win32.h" |
| 14 | #endif |
| 15 | #ifdef CIFACE_USE_XLIB |
| 16 | #include "InputCommon/ControllerInterface/Xlib/XInput2.h" |
| 17 | #endif |
| 18 | #ifdef CIFACE_USE_OSX |
| 19 | #include "InputCommon/ControllerInterface/Quartz/Quartz.h" |
| 20 | #endif |
| 21 | #ifdef CIFACE_USE_SDL |
| 22 | #include "InputCommon/ControllerInterface/SDL/SDL.h" |
| 23 | #endif |
| 24 | #ifdef CIFACE_USE_ANDROID |
| 25 | #include "InputCommon/ControllerInterface/Android/Android.h" |
| 26 | #endif |
| 27 | #ifdef CIFACE_USE_EVDEV |
| 28 | #include "InputCommon/ControllerInterface/evdev/evdev.h" |
| 29 | #endif |
| 30 | #ifdef CIFACE_USE_PIPES |
| 31 | #include "InputCommon/ControllerInterface/Pipes/Pipes.h" |
| 32 | #endif |
| 33 | #ifdef CIFACE_USE_DUALSHOCKUDPCLIENT |
| 34 | #include "InputCommon/ControllerInterface/DualShockUDPClient/DualShockUDPClient.h" |
| 35 | #endif |
| 36 | #ifdef CIFACE_USE_STEAMDECK |
| 37 | #include "InputCommon/ControllerInterface/SteamDeck/SteamDeck.h" |
| 38 | #endif |
| 39 | |
| 40 | ControllerInterface g_controller_interface; |
| 41 | |
| 42 | // We need to save which input channel we are in by thread, so we can access the correct input |
| 43 | // update values in different threads by input channel. We start from InputChannel::Host on all |
| 44 | // threads as hotkeys are updated from a worker thread, but UI can read from the main thread. This |
| 45 | // will never interfere with game threads. |
| 46 | static thread_local ciface::InputChannel tls_input_channel = ciface::InputChannel::Host; |
| 47 | |
| 48 | static thread_local bool tls_is_updating_devices = false; |
| 49 | |
| 50 | void ControllerInterface::Initialize(const WindowSystemInfo& wsi) |
| 51 | { |
| 52 | if (m_is_init) |
| 53 | return; |
| 54 | |
| 55 | std::lock_guard lk_population(m_devices_population_mutex); |
| 56 | |
| 57 | m_wsi = wsi; |
| 58 | |
| 59 | m_populating_devices_counter = 1; |
| 60 | |
| 61 | #ifdef CIFACE_USE_WIN32 |
| 62 | m_input_backends.emplace_back(ciface::Win32::CreateInputBackend(this)); |
| 63 | #endif |
| 64 | #ifdef CIFACE_USE_XLIB |
| 65 | m_input_backends.emplace_back(ciface::XInput2::CreateInputBackend(this)); |
| 66 | #endif |
| 67 | #ifdef CIFACE_USE_OSX |
| 68 | m_input_backends.emplace_back(ciface::Quartz::CreateInputBackend(this)); |
| 69 | #endif |
| 70 | #ifdef CIFACE_USE_SDL |
| 71 | m_input_backends.emplace_back(ciface::SDL::CreateInputBackend(this)); |
| 72 | #endif |
| 73 | #ifdef CIFACE_USE_ANDROID |
| 74 | m_input_backends.emplace_back(ciface::Android::CreateInputBackend(this)); |
| 75 | #endif |
| 76 | #ifdef CIFACE_USE_EVDEV |
| 77 | m_input_backends.emplace_back(ciface::evdev::CreateInputBackend(this)); |
| 78 | #endif |
| 79 | #ifdef CIFACE_USE_PIPES |
| 80 | m_input_backends.emplace_back(ciface::Pipes::CreateInputBackend(this)); |
| 81 | #endif |
| 82 | #ifdef CIFACE_USE_DUALSHOCKUDPCLIENT |
| 83 | m_input_backends.emplace_back(ciface::DualShockUDPClient::CreateInputBackend(this)); |
| 84 | #endif |
| 85 | #ifdef CIFACE_USE_STEAMDECK |
| 86 | m_input_backends.emplace_back(ciface::SteamDeck::CreateInputBackend(this)); |
| 87 | #endif |
| 88 | |
| 89 | // Don't allow backends to add devices before the first RefreshDevices() as they will be cleaned |
| 90 | // there. Or they'd end up waiting on the devices mutex if populated from another thread. |
| 91 | m_is_init = true; |
| 92 | |
| 93 | RefreshDevices(); |
| 94 | |
| 95 | // Devices writes are already protected by m_devices_population_mutex but this won't hurt |
| 96 | m_devices_mutex.lock(); |
| 97 | const bool devices_empty = m_devices.empty(); |
| 98 | m_devices_mutex.unlock(); |
| 99 | |
| 100 | if (m_populating_devices_counter.fetch_sub(1) == 1 && !devices_empty) |
| 101 | InvokeDevicesChangedCallbacks(); |
| 102 | } |
| 103 | |
| 104 | void ControllerInterface::ChangeWindow(void* hwnd, WindowChangeReason reason) |
| 105 | { |
| 106 | if (!m_is_init) |
| 107 | return; |
| 108 | |
| 109 | // This shouldn't use render_surface so no need to update it. |
| 110 | m_wsi.render_window = hwnd; |
| 111 | |
| 112 | // No need to re-add devices if this is an application exit request |
| 113 | if (reason == WindowChangeReason::Exit) |
| 114 | ClearDevices(); |
| 115 | else |
| 116 | RefreshDevices(RefreshReason::WindowChangeOnly); |
| 117 | } |
| 118 | |
| 119 | void ControllerInterface::RefreshDevices(RefreshReason reason) |
| 120 | { |
| 121 | if (!m_is_init) |
| 122 | return; |
| 123 | |
| 124 | // We lock m_devices_population_mutex here to make everything simpler. |
| 125 | // Multiple devices classes have their own "hotplug" thread, and can add/remove devices at any |
| 126 | // time, while actual writes to "m_devices" are safe, the order in which they happen is not. That |
| 127 | // means a thread could be adding devices while we are removing them from a different thread, |
| 128 | // or removing them as we are populating them (causing missing or duplicate devices). |
| 129 | std::lock_guard lk_population(m_devices_population_mutex); |
| 130 | |
| 131 | // If only the window changed, avoid removing and re-adding all devices. |
| 132 | // Instead only refresh devices that require the window handle. |
| 133 | if (reason == RefreshReason::WindowChangeOnly) |
| 134 | { |
| 135 | m_populating_devices_counter.fetch_add(1); |
| 136 | |
| 137 | for (auto& backend : m_input_backends) |
| 138 | backend->HandleWindowChange(); |
| 139 | |
| 140 | if (m_populating_devices_counter.fetch_sub(1) == 1) |
| 141 | InvokeDevicesChangedCallbacks(); |
| 142 | |
| 143 | return; |
| 144 | } |
| 145 | |
| 146 | m_populating_devices_counter.fetch_add(1); |
| 147 | |
| 148 | // Make sure shared_ptr<Device> objects are released before repopulating. |
| 149 | ClearDevices(); |
| 150 | |
| 151 | // Some of these calls won't immediately populate devices, but will do it async |
| 152 | // with their own PlatformPopulateDevices(). |
| 153 | // This means that devices might end up in different order, unless we override their priority. |
| 154 | // It also means they might appear as "disconnected" in the Qt UI for a tiny bit of time. |
| 155 | // This helps the emulation and host thread to not stall when repopulating devices for any reason. |
| 156 | // Every platform that adds a device that is meant to be used as default device should try to not |
| 157 | // do it async, to not risk the emulated controllers default config loading not finding a default |
| 158 | // device. |
| 159 | |
| 160 | for (auto& backend : m_input_backends) |
| 161 | backend->PopulateDevices(); |
| 162 | |
| 163 | WiimoteReal::PopulateDevices(); |
| 164 | |
| 165 | if (m_populating_devices_counter.fetch_sub(1) == 1) |
| 166 | InvokeDevicesChangedCallbacks(); |
| 167 | } |
| 168 | |
| 169 | void ControllerInterface::PlatformPopulateDevices(const std::function<void()>& callback) |
| 170 | { |
| 171 | if (!m_is_init) |
| 172 | return; |
| 173 | |
| 174 | std::lock_guard lk_population(m_devices_population_mutex); |
| 175 | |
| 176 | m_populating_devices_counter.fetch_add(1); |
| 177 | |
| 178 | callback(); |
| 179 | |
| 180 | if (m_populating_devices_counter.fetch_sub(1) == 1) |
| 181 | InvokeDevicesChangedCallbacks(); |
| 182 | } |
| 183 | |
| 184 | // Remove all devices and call library cleanup functions |
| 185 | void ControllerInterface::Shutdown() |
| 186 | { |
| 187 | if (!m_is_init) |
| 188 | return; |
| 189 | |
| 190 | // Prevent additional devices from being added during shutdown. |
| 191 | m_is_init = false; |
| 192 | // Additional safety measure to avoid InvokeDevicesChangedCallbacks() |
| 193 | m_populating_devices_counter = 1; |
| 194 | |
| 195 | // Update control references so shared_ptr<Device>s are freed up BEFORE we shutdown the backends. |
| 196 | ClearDevices(); |
| 197 | |
| 198 | // Empty the container of input backends to deconstruct and deinitialize them. |
| 199 | m_input_backends.clear(); |
| 200 | |
| 201 | // Make sure no devices had been added within Shutdown() in the time |
| 202 | // between checking they checked atomic m_is_init bool and we changed it. |
| 203 | // We couldn't have locked m_devices_population_mutex for the whole Shutdown() |
| 204 | // as it could cause deadlocks. Note that this is still not 100% safe as some backends are |
| 205 | // shut down in other places, possibly adding devices after we have shut down, but the chances of |
| 206 | // that happening are basically zero. |
| 207 | ClearDevices(); |
| 208 | } |
| 209 | |
| 210 | void ControllerInterface::ClearDevices() |
| 211 | { |
| 212 | std::lock_guard lk_population(m_devices_population_mutex); |
| 213 | |
| 214 | { |
| 215 | std::lock_guard lk(m_devices_mutex); |
| 216 | |
| 217 | if (m_devices.empty()) |
| 218 | return; |
| 219 | |
| 220 | for (const auto& d : m_devices) |
| 221 | { |
| 222 | // Set outputs to ZERO before destroying device |
| 223 | for (ciface::Core::Device::Output* o : d->Outputs()) |
| 224 | o->SetState(0); |
| 225 | } |
| 226 | |
| 227 | // Devices could still be alive after this as there might be shared ptrs around holding them. |
| 228 | // The InvokeDevicesChangedCallbacks() underneath should always clean all of them (it needs to). |
| 229 | m_devices.clear(); |
| 230 | } |
| 231 | |
| 232 | InvokeDevicesChangedCallbacks(); |
| 233 | } |
| 234 | |
| 235 | bool ControllerInterface::AddDevice(std::shared_ptr<ciface::Core::Device> device) |
| 236 | { |
| 237 | // If we are shutdown (or in process of shutting down) ignore this request: |
| 238 | if (!m_is_init) |
| 239 | return false; |
| 240 | |
| 241 | ASSERT_MSG(CONTROLLERINTERFACE, !tls_is_updating_devices, |
| 242 | "Devices shouldn't be added within input update calls, there is a risk of deadlock " |
| 243 | "if another thread was already here"); |
| 244 | |
| 245 | std::lock_guard lk_population(m_devices_population_mutex); |
| 246 | |
| 247 | { |
| 248 | std::lock_guard lk(m_devices_mutex); |
| 249 | |
| 250 | const auto is_id_in_use = [&device, this](int id) { |
| 251 | return std::ranges::any_of(m_devices, [&device, &id](const auto& d) { |
| 252 | return d->GetSource() == device->GetSource() && d->GetName() == device->GetName() && |
| 253 | d->GetId() == id; |
| 254 | }); |
| 255 | }; |
| 256 | |
| 257 | const auto preferred_id = device->GetPreferredId(); |
| 258 | if (preferred_id.has_value() && !is_id_in_use(*preferred_id)) |
| 259 | { |
| 260 | // Use the device's preferred ID if available. |
| 261 | device->SetId(*preferred_id); |
| 262 | } |
| 263 | else |
| 264 | { |
| 265 | // Find the first available ID to use. |
| 266 | int id = 0; |
| 267 | while (is_id_in_use(id)) |
| 268 | ++id; |
| 269 | |
| 270 | device->SetId(id); |
| 271 | } |
| 272 | |
| 273 | NOTICE_LOG_FMT(CONTROLLERINTERFACE, "Added device: {}", device->GetQualifiedName()); |
| 274 | m_devices.emplace_back(std::move(device)); |
| 275 | |
| 276 | // We can't (and don't want) to control the order in which devices are added, but we need |
| 277 | // their order to be consistent, and we need the same one to always be the first, where present |
| 278 | // (the keyboard and mouse device usually). This is because when defaulting a controller |
| 279 | // profile, it will automatically select the first device in the list as its default. It would |
| 280 | // be nice to sort devices by Source then Name then ID, but it's better to leave them sorted by |
| 281 | // the add order. This also avoids breaking the order on other platforms that are less tested. |
| 282 | std::ranges::stable_sort(m_devices, std::ranges::greater{}, |
| 283 | &ciface::Core::Device::GetSortPriority); |
| 284 | } |
| 285 | |
| 286 | if (!m_populating_devices_counter) |
| 287 | InvokeDevicesChangedCallbacks(); |
| 288 | return true; |
| 289 | } |
| 290 | |
| 291 | void ControllerInterface::RemoveDevice(std::function<bool(const ciface::Core::Device*)> callback, |
| 292 | bool force_devices_release) |
| 293 | { |
| 294 | // If we are shutdown (or in process of shutting down) ignore this request: |
| 295 | if (!m_is_init) |
| 296 | return; |
| 297 | |
| 298 | ASSERT_MSG(CONTROLLERINTERFACE, !tls_is_updating_devices, |
| 299 | "Devices shouldn't be removed within input update calls, there is a risk of deadlock " |
| 300 | "if another thread was already here"); |
| 301 | |
| 302 | std::lock_guard lk_population(m_devices_population_mutex); |
| 303 | |
| 304 | bool any_removed; |
| 305 | { |
| 306 | std::lock_guard lk(m_devices_mutex); |
| 307 | const size_t erased = std::erase_if(m_devices, [&callback](const auto& dev) { |
| 308 | if (callback(dev.get())) |
| 309 | { |
| 310 | NOTICE_LOG_FMT(CONTROLLERINTERFACE, "Removed device: {}", dev->GetQualifiedName()); |
| 311 | return true; |
| 312 | } |
| 313 | return false; |
| 314 | }); |
| 315 | any_removed = erased != 0; |
| 316 | } |
| 317 | |
| 318 | if (any_removed && (!m_populating_devices_counter || force_devices_release)) |
| 319 | InvokeDevicesChangedCallbacks(); |
| 320 | } |
| 321 | |
| 322 | // Update input for all devices. |
| 323 | void ControllerInterface::UpdateInput() |
| 324 | { |
| 325 | // This should never happen |
| 326 | ASSERT(m_is_init); |
| 327 | if (!m_is_init) |
| 328 | return; |
| 329 | |
| 330 | // We add the devices to remove while we still have the "m_devices_mutex" locked. |
| 331 | // This guarantees that: |
| 332 | // -We won't try to lock "m_devices_population_mutex" while it was already locked and waiting |
| 333 | // for "m_devices_mutex", which would result in dead lock. |
| 334 | // -We don't keep shared ptrs on devices and thus unwillingly keep them alive even if somebody |
| 335 | // is currently trying to remove them (and needs them destroyed on the spot). |
| 336 | // -If somebody else destroyed them in the meantime, we'll know which ones have been destroyed. |
| 337 | std::vector<std::weak_ptr<ciface::Core::Device>> devices_to_remove; |
| 338 | |
| 339 | { |
| 340 | std::lock_guard lk_devices(m_devices_mutex); |
| 341 | |
| 342 | tls_is_updating_devices = true; |
| 343 | |
| 344 | for (auto& backend : m_input_backends) |
| 345 | backend->UpdateInput(devices_to_remove); |
| 346 | |
| 347 | for (const auto& d : m_devices) |
| 348 | { |
| 349 | // Theoretically we could avoid updating input on devices that don't have any references to |
| 350 | // them, but in practice a few devices types could break in different ways, so we don't |
| 351 | if (d->UpdateInput() == ciface::Core::DeviceRemoval::Remove) |
| 352 | devices_to_remove.push_back(d); |
| 353 | } |
| 354 | |
| 355 | tls_is_updating_devices = false; |
| 356 | } |
| 357 | |
| 358 | if (devices_to_remove.size() > 0) |
| 359 | { |
| 360 | RemoveDevice([&](const ciface::Core::Device* device) { |
| 361 | return std::ranges::any_of(devices_to_remove, |
| 362 | [device](const auto& d) { return d.lock().get() == device; }); |
| 363 | }); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | void ControllerInterface::SetCurrentInputChannel(ciface::InputChannel input_channel) |
| 368 | { |
| 369 | tls_input_channel = input_channel; |
| 370 | } |
| 371 | |
| 372 | ciface::InputChannel ControllerInterface::GetCurrentInputChannel() |
| 373 | { |
| 374 | return tls_input_channel; |
| 375 | } |
| 376 | |
| 377 | WindowSystemInfo ControllerInterface::GetWindowSystemInfo() const |
| 378 | { |
| 379 | return m_wsi; |
| 380 | } |
| 381 | |
| 382 | void ControllerInterface::SetAspectRatioAdjustment(float value) |
| 383 | { |
| 384 | m_aspect_ratio_adjustment = value; |
| 385 | } |
| 386 | |
| 387 | Common::Vec2 ControllerInterface::GetWindowInputScale() const |
| 388 | { |
| 389 | const auto ar = m_aspect_ratio_adjustment.load(); |
| 390 | |
| 391 | if (ar > 1) |
| 392 | return {1.f, ar}; |
| 393 | else |
| 394 | return {1 / ar, 1.f}; |
| 395 | } |
| 396 | |
| 397 | void ControllerInterface::SetMouseCenteringRequested(bool center) |
| 398 | { |
| 399 | m_requested_mouse_centering = center; |
| 400 | } |
| 401 | |
| 402 | bool ControllerInterface::IsMouseCenteringRequested() const |
| 403 | { |
| 404 | return m_requested_mouse_centering.load(); |
| 405 | } |
| 406 | |
| 407 | // Register a callback to be called when a device is added or removed (as from the input backends' |
| 408 | // hotplug thread), or when devices are refreshed |
| 409 | // Returns a handle for later removing the callback. |
| 410 | |
| 411 | Common::EventHook |
| 412 | ControllerInterface::RegisterDevicesChangedCallback(Common::HookableEvent<>::CallbackType callback) |
| 413 | { |
| 414 | return m_devices_changed_event.Register(std::move(callback)); |
| 415 | } |
| 416 | |
| 417 | // Invoke all callbacks that were registered |
| 418 | void ControllerInterface::InvokeDevicesChangedCallbacks() |
| 419 | { |
| 420 | m_devices_changed_event.Trigger(); |
| 421 | } |