diff --git a/src/core/runtime.cpp b/src/core/runtime.cpp index 3bf362f3..ca480666 100644 --- a/src/core/runtime.cpp +++ b/src/core/runtime.cpp @@ -1186,7 +1186,13 @@ namespace lvh { state_ {std::make_shared(options)} {} Runtime::Runtime(Runtime &&) noexcept = default; - Runtime &Runtime::operator=(Runtime &&) noexcept = default; + + Runtime &Runtime::operator=(Runtime &&other) noexcept { + Runtime replacement {std::move(other)}; + // The temporary closes the replaced runtime's devices when it is destroyed. + state_.swap(replacement.state_); + return *this; + } Runtime::~Runtime() { if (state_) { diff --git a/src/include/libvirtualhid/runtime.hpp b/src/include/libvirtualhid/runtime.hpp index efdda3f8..179fbcab 100644 --- a/src/include/libvirtualhid/runtime.hpp +++ b/src/include/libvirtualhid/runtime.hpp @@ -988,7 +988,7 @@ namespace lvh { Runtime(Runtime &&other) noexcept; /** - * @brief Move assign a runtime. + * @brief Move assign a runtime and close the devices owned by the replaced runtime. * * @param other Runtime to move from. * @return This runtime. diff --git a/tests/unit/test_runtime.cpp b/tests/unit/test_runtime.cpp index d87221c2..a6203a4e 100644 --- a/tests/unit/test_runtime.cpp +++ b/tests/unit/test_runtime.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include // local includes @@ -38,6 +39,43 @@ TEST(RuntimeTest, FakeBackendReportsCapabilities) { EXPECT_FALSE(runtime->capabilities().requires_installed_driver); } +TEST(RuntimeTest, MoveAssignmentClosesReplacedDevices) { + auto runtime = lvh::Runtime::create(); + auto old_gamepad = runtime->create_gamepad(lvh::profiles::xbox_360()); + auto old_keyboard = runtime->create_keyboard(); + ASSERT_TRUE(old_gamepad); + ASSERT_TRUE(old_keyboard); + + auto replacement = lvh::Runtime::create(); + auto new_gamepad = replacement->create_gamepad(lvh::profiles::xbox_360()); + ASSERT_TRUE(new_gamepad); + + *runtime = std::move(*replacement); + + EXPECT_FALSE(old_gamepad.gamepad->is_open()); + EXPECT_FALSE(old_keyboard.keyboard->is_open()); + EXPECT_EQ(old_gamepad.gamepad->submit({}).code(), lvh::ErrorCode::device_closed); + EXPECT_EQ(runtime->active_device_count(), 1U); + EXPECT_TRUE(new_gamepad.gamepad->submit({}).ok()); + + *replacement = std::move(*runtime); + EXPECT_EQ(replacement->active_device_count(), 1U); + replacement.reset(); + EXPECT_FALSE(new_gamepad.gamepad->is_open()); +} + +TEST(RuntimeTest, SelfMoveAssignmentKeepsDevicesOpen) { + auto runtime = lvh::Runtime::create(); + auto created = runtime->create_gamepad(lvh::profiles::xbox_360()); + ASSERT_TRUE(created); + + auto &same_runtime = *runtime; + *runtime = std::move(same_runtime); + + EXPECT_EQ(runtime->active_device_count(), 1U); + EXPECT_TRUE(created.gamepad->submit({}).ok()); +} + TEST(RuntimeTest, RoutesDiagnosticsToConsumerCallback) { struct Diagnostic { lvh::LogLevel level;