ControllerInterface/Win32: Prevent devcies from losing their "id" on a hotplug event.

This commit is contained in:
Jordan Woyak 2019-03-09 09:57:37 -06:00
parent d26c1ce24d
commit eadbdd6bc3
10 changed files with 121 additions and 39 deletions

View file

@ -93,6 +93,9 @@ void ControllerInterface::RefreshDevices()
m_is_populating_devices = true;
// Make sure shared_ptr<Device> objects are released before repopulating.
InvokeDevicesChangedCallbacks();
#ifdef CIFACE_USE_WIN32
ciface::Win32::PopulateDevices(m_wsi.render_surface);
#endif
@ -179,21 +182,29 @@ void ControllerInterface::AddDevice(std::shared_ptr<ciface::Core::Device> device
{
std::lock_guard<std::mutex> lk(m_devices_mutex);
// Try to find an ID for this device
int id = 0;
while (true)
const auto is_id_in_use = [&device, this](int id) {
return std::any_of(m_devices.begin(), m_devices.end(), [&device, &id](const auto& d) {
return d->GetSource() == device->GetSource() && d->GetName() == device->GetName() &&
d->GetId() == id;
});
};
const auto preferred_id = device->GetPreferredId();
if (preferred_id.has_value() && !is_id_in_use(*preferred_id))
{
const auto it =
std::find_if(m_devices.begin(), m_devices.end(), [&device, &id](const auto& d) {
return d->GetSource() == device->GetSource() && d->GetName() == device->GetName() &&
d->GetId() == id;
});
if (it == m_devices.end()) // no device with the same name with this ID, so we can use it
break;
else
id++;
// Use the device's preferred ID if available.
device->SetId(*preferred_id);
}
else
{
// Find the first available ID to use.
int id = 0;
while (is_id_in_use(id))
++id;
device->SetId(id);
}
device->SetId(id);
NOTICE_LOG(SERIALINTERFACE, "Added device: %s", device->GetQualifiedName().c_str());
m_devices.emplace_back(std::move(device));