From fa5c465f7418fd1774f74a0d5adef5ac2f432e31 Mon Sep 17 00:00:00 2001 From: Russell Luther Date: Sat, 21 Nov 2026 04:42:35 -0500 Subject: [PATCH 1/3] fix(windows): apply settings while all initial devices are unavailable A persisted state whose initial devices are all gone (e.g. displays behind a KVM switch after an unclean shutdown) made every applySettings() call fail until the persistence was reset by hand. Use the current topology as the base in that case. The cached initial state is still persisted, so the original layout is restored once the devices return. --- src/windows/settings_manager_apply.cpp | 30 ++++++++++++- .../windows/test_settings_manager_apply.cpp | 43 +++++++++++++++++++ .../windows/test_settings_manager_undock.cpp | 35 +++++++++++++++ 3 files changed, 107 insertions(+), 1 deletion(-) diff --git a/src/windows/settings_manager_apply.cpp b/src/windows/settings_manager_apply.cpp index d68d2b0..cc65668 100644 --- a/src/windows/settings_manager_apply.cpp +++ b/src/windows/settings_manager_apply.cpp @@ -43,6 +43,19 @@ namespace display_device { }); return inactive; } + + /** + * @brief Check whether all the devices of a topology are unavailable. + * @param topology Topology to check. + * @param devices Currently enumerated devices. + * @return True if none of the topology's devices are available. + */ + bool isTopologyUnavailable(const ActiveTopology &topology, const EnumeratedDeviceList &devices) { + const auto available {win_utils::getDeviceIds(devices)}; + return std::ranges::none_of(win_utils::flattenTopology(topology), [&available](const auto &device_id) { + return available.contains(device_id); + }); + } } // namespace SettingsManager::ApplyResult SettingsManager::applySettings(const SingleDisplayConfiguration &config) { @@ -167,9 +180,24 @@ namespace display_device { } SingleDisplayConfigState new_state {*new_initial_state}; + // The cached initial state cannot be used as a base when all of its devices are gone (e.g. the original displays + // are behind a KVM switch or powered off). It is still kept for the revert once they return, but until then + // the current topology has to be the base, the same as if there was no cached state. + auto base_initial_state {std::make_optional(new_state.m_initial)}; + if (cached_state && isTopologyUnavailable(new_state.m_initial.m_topology, devices)) { + DD_LOG(warning) << "None of the devices from the initial topology are available. Will use the current topology as a base until they return:\n" + << " - initial topology: " << toJson(new_state.m_initial.m_topology, JSON_COMPACT) << "\n" + << " - current topology: " << toJson(topology_before_changes, JSON_COMPACT); + base_initial_state = win_utils::computeInitialState(std::nullopt, topology_before_changes, devices); + if (!base_initial_state) { + // Error already logged + return std::nullopt; + } + } + // In case some devices are no longer available in the system, we could try to strip them from the initial state // and hope that we are still "safe" to make further changes (to be determined by computeNewTopologyAndMetadata call below). - const auto stripped_initial_state {win_utils::stripInitialState(new_state.m_initial, devices)}; + const auto stripped_initial_state {win_utils::stripInitialState(*base_initial_state, devices)}; if (!stripped_initial_state) { // Error already logged return std::nullopt; diff --git a/tests/unit/windows/test_settings_manager_apply.cpp b/tests/unit/windows/test_settings_manager_apply.cpp index 624b5bc..9582976 100644 --- a/tests/unit/windows/test_settings_manager_apply.cpp +++ b/tests/unit/windows/test_settings_manager_apply.cpp @@ -450,6 +450,49 @@ TEST_F_S_MOCKED(PrepareTopology, FailedToStripInitialState) { EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4"}), display_device::SettingsManager::ApplyResult::DevicePrepFailed); } +TEST_F_S_MOCKED(PrepareTopology, InitialDevicesUnavailable) { + using DevicePrep = display_device::SingleDisplayConfiguration::DevicePreparation; + const display_device::ActiveTopology current_topology {{"DeviceId4"}}; + const display_device::EnumeratedDeviceList devices {{.m_device_id = "DeviceId4", .m_info = display_device::EnumeratedDevice::Info {.m_primary = true}}}; + const display_device::DeviceDisplayModeMap current_modes {{"DeviceId4", {{2560, 1440}, {60, 1}}}}; + const display_device::DeviceDisplayModeMap new_modes {{"DeviceId4", {{1920, 1080}, {60, 1}}}}; + + // A leftover state from a session that was never reverted, with all the original devices gone since then + auto initial_state {DEFAULT_PERSISTENCE_INPUT_BASE}; + initial_state.m_modified = {current_topology}; + auto persistence_input {initial_state}; + persistence_input.m_modified.m_original_modes = current_modes; + + InSequence sequence; + expectedDefaultCallsUntilTopologyPrep(sequence, current_topology, initial_state); + expectedIsCapturedCall(sequence, false); + expectedDeviceEnumCall(sequence, devices); + expectedIsTopologyTheSameCall(sequence, current_topology, current_topology); + expectedGetCurrentDisplayModesCall(sequence, {"DeviceId4"}, current_modes); + expectedSetDisplayModesCall(sequence, new_modes); + expectedGetCurrentDisplayModesCall(sequence, {"DeviceId4"}, new_modes); + expectedPersistenceCall(sequence, persistence_input); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4", .m_device_prep = DevicePrep::EnsureOnlyDisplay, .m_resolution = {{1920, 1080}}}), display_device::SettingsManager::ApplyResult::Ok); +} + +TEST_F_S_MOCKED(PrepareTopology, InitialDevicesUnavailable, FailedToComputeBaseState) { + const display_device::ActiveTopology current_topology {{"DeviceId4"}}; + auto initial_state {DEFAULT_PERSISTENCE_INPUT_BASE}; + initial_state.m_modified = {current_topology}; + + InSequence sequence; + expectedDefaultCallsUntilTopologyPrep(sequence, current_topology, initial_state); + expectedIsCapturedCall(sequence, false); + expectedDeviceEnumCall(sequence, {{.m_device_id = "DeviceId4", .m_info = display_device::EnumeratedDevice::Info {.m_primary = false}}}); + + expectedTopologyGuardTopologyCall(sequence, current_topology); + expectedTopologyGuardNewlyCapturedContextCall(sequence, false); + + EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4"}), display_device::SettingsManager::ApplyResult::DevicePrepFailed); +} + TEST_F_S_MOCKED(PrepareTopology, DeviceNotFoundInNewTopology) { InSequence sequence; expectedDefaultCallsUntilTopologyPrep(sequence); diff --git a/tests/unit/windows/test_settings_manager_undock.cpp b/tests/unit/windows/test_settings_manager_undock.cpp index dd71ddc..4f31288 100644 --- a/tests/unit/windows/test_settings_manager_undock.cpp +++ b/tests/unit/windows/test_settings_manager_undock.cpp @@ -376,3 +376,38 @@ TEST_F(UndockRecovery, StagingKeepsSurvivingCloneGroup) { ASSERT_GE(writes.size(), 3u); EXPECT_EQ(writes[writes.size() - 2], (ActiveTopology {{"stream"}, {"left", "right"}})); } + +TEST_F(UndockRecovery, StreamCanBeConfiguredWhileRecoveryIsPending) { + // Neither the original display nor a panel is available, e.g. a desktop with its monitors behind a KVM switch. + const DeviceDisplayModeMap idle_modes {{"stream", {{2560, 1440}, {60, 1}}}}; + const DeviceDisplayModeMap stream_modes {{"stream", {{1920, 1080}, {60, 1}}}}; + auto modes {idle_modes}; + devices = {{.m_device_id = "stream", .m_info = EnumeratedDevice::Info {.m_primary = true}}}; + init(); + ON_CALL(*api, getCurrentDisplayModes(_)).WillByDefault([&modes](const auto &) { + return modes; + }); + ON_CALL(*api, setDisplayModes(_)).WillByDefault([&modes](const DeviceDisplayModeMap &new_modes) { + modes = new_modes; + return true; + }); + + SingleDisplayConfiguration config; + config.m_device_id = "stream"; + config.m_device_prep = SingleDisplayConfiguration::DevicePreparation::EnsureOnlyDisplay; + config.m_resolution = Resolution {1920, 1080}; + EXPECT_EQ(manager->applySettings(config), SettingsManager::ApplyResult::Ok); + EXPECT_EQ(modes, stream_modes); + EXPECT_EQ(active, (ActiveTopology {{"stream"}})); + + // The stream ends with the dock still away. Its mode is restored and the recovery stays pending. + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::SwitchingTopologyFailed); + EXPECT_EQ(modes, idle_modes); + EXPECT_EQ(clears, 0); + + // The dock returns and the original layout comes back. + devices.push_back({.m_device_id = "dock"}); + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"dock"}})); + EXPECT_EQ(clears, 1); +} From 47d289ba2dfdde94d073d4c89779ebb0b9841340 Mon Sep 17 00:00:00 2001 From: Russell Luther Date: Sat, 21 Nov 2026 05:09:19 -0500 Subject: [PATCH 2/3] Move the base state selection out of prepareTopology Keeps prepareTopology under the cognitive complexity limit (S3776). --- src/windows/settings_manager_apply.cpp | 46 ++++++++++++++++---------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/src/windows/settings_manager_apply.cpp b/src/windows/settings_manager_apply.cpp index cc65668..dacec97 100644 --- a/src/windows/settings_manager_apply.cpp +++ b/src/windows/settings_manager_apply.cpp @@ -56,6 +56,32 @@ namespace display_device { return available.contains(device_id); }); } + + /** + * @brief Get the initial state to use as a base for the new topology, without the unavailable devices. + * + * The cached initial state cannot be used as a base when all of its devices are gone (e.g. the original displays + * are behind a KVM switch or powered off). It is still kept for the revert once they return, but until then + * the current topology has to be the base, the same as if there was no cached state. + * @param initial_state Initial state that will be persisted. + * @param is_cached Whether the initial state comes from a previous session. + * @param topology_before_changes Currently active topology. + * @param devices Currently enumerated devices. + * @return Stripped initial state to base the new topology on, or empty optional if there is nothing to base it on. + */ + std::optional computeBaseInitialState(const SingleDisplayConfigState::Initial &initial_state, const bool is_cached, const ActiveTopology &topology_before_changes, const EnumeratedDeviceList &devices) { + if (!is_cached || !isTopologyUnavailable(initial_state.m_topology, devices)) { + // In case some devices are no longer available in the system, we could try to strip them from the initial state + // and hope that we are still "safe" to make further changes (to be determined by computeNewTopologyAndMetadata call). + return win_utils::stripInitialState(initial_state, devices); + } + + DD_LOG(warning) << "None of the devices from the initial topology are available. Will use the current topology as a base until they return:\n" + << " - initial topology: " << toJson(initial_state.m_topology, JSON_COMPACT) << "\n" + << " - current topology: " << toJson(topology_before_changes, JSON_COMPACT); + const auto current_state {win_utils::computeInitialState(std::nullopt, topology_before_changes, devices)}; + return current_state ? win_utils::stripInitialState(*current_state, devices) : std::nullopt; + } } // namespace SettingsManager::ApplyResult SettingsManager::applySettings(const SingleDisplayConfiguration &config) { @@ -180,24 +206,8 @@ namespace display_device { } SingleDisplayConfigState new_state {*new_initial_state}; - // The cached initial state cannot be used as a base when all of its devices are gone (e.g. the original displays - // are behind a KVM switch or powered off). It is still kept for the revert once they return, but until then - // the current topology has to be the base, the same as if there was no cached state. - auto base_initial_state {std::make_optional(new_state.m_initial)}; - if (cached_state && isTopologyUnavailable(new_state.m_initial.m_topology, devices)) { - DD_LOG(warning) << "None of the devices from the initial topology are available. Will use the current topology as a base until they return:\n" - << " - initial topology: " << toJson(new_state.m_initial.m_topology, JSON_COMPACT) << "\n" - << " - current topology: " << toJson(topology_before_changes, JSON_COMPACT); - base_initial_state = win_utils::computeInitialState(std::nullopt, topology_before_changes, devices); - if (!base_initial_state) { - // Error already logged - return std::nullopt; - } - } - - // In case some devices are no longer available in the system, we could try to strip them from the initial state - // and hope that we are still "safe" to make further changes (to be determined by computeNewTopologyAndMetadata call below). - const auto stripped_initial_state {win_utils::stripInitialState(*base_initial_state, devices)}; + // The new topology is based on the initial state, which is the current topology if the cached one is of no use. + const auto stripped_initial_state {computeBaseInitialState(new_state.m_initial, cached_state.has_value(), topology_before_changes, devices)}; if (!stripped_initial_state) { // Error already logged return std::nullopt; From 013e7f034cb738c8706a358e6077053e5345dbdc Mon Sep 17 00:00:00 2001 From: Russell Luther Date: Sat, 21 Nov 2026 11:16:44 -0500 Subject: [PATCH 3/3] Refuse a topology change while all initial devices are unavailable The cached initial state still describes the absent layout, so the active topology could not be restored after changing it. Mode and HDR changes within the active topology are still applied. --- src/windows/settings_manager_apply.cpp | 20 +++++++++++++++++++ .../windows/test_settings_manager_undock.cpp | 18 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/windows/settings_manager_apply.cpp b/src/windows/settings_manager_apply.cpp index dacec97..3f9a6b5 100644 --- a/src/windows/settings_manager_apply.cpp +++ b/src/windows/settings_manager_apply.cpp @@ -82,6 +82,21 @@ namespace display_device { const auto current_state {win_utils::computeInitialState(std::nullopt, topology_before_changes, devices)}; return current_state ? win_utils::stripInitialState(*current_state, devices) : std::nullopt; } + + /** + * @brief Check whether a topology change has to be refused because the original devices are away. + * + * The cached initial state still describes the absent layout, so there would be nothing to restore + * the currently active topology from once it is changed. + * @param change_is_needed Whether the new topology differs from the active one. + * @param is_cached Whether the initial state comes from a previous session. + * @param initial_topology Topology of the initial state that will be persisted. + * @param devices Currently enumerated devices. + * @return True if the topology must not be changed. + */ + bool isTopologyChangeBlocked(const bool change_is_needed, const bool is_cached, const ActiveTopology &initial_topology, const EnumeratedDeviceList &devices) { + return change_is_needed && is_cached && isTopologyUnavailable(initial_topology, devices); + } } // namespace SettingsManager::ApplyResult SettingsManager::applySettings(const SingleDisplayConfiguration &config) { @@ -227,6 +242,11 @@ namespace display_device { return std::nullopt; } + if (isTopologyChangeBlocked(change_is_needed, cached_state.has_value(), new_state.m_initial.m_topology, devices)) { + DD_LOG(error) << "Cannot switch display topology while all original devices are unavailable!"; + return std::nullopt; + } + if (change_is_needed) { if (cached_state && !m_dd_api->isTopologyTheSame(cached_state->m_modified.m_topology, new_topology)) { DD_LOG(warning) << "To apply new display device settings, previous modifications must be undone! Trying to undo them now."; diff --git a/tests/unit/windows/test_settings_manager_undock.cpp b/tests/unit/windows/test_settings_manager_undock.cpp index 4f31288..327e45e 100644 --- a/tests/unit/windows/test_settings_manager_undock.cpp +++ b/tests/unit/windows/test_settings_manager_undock.cpp @@ -411,3 +411,21 @@ TEST_F(UndockRecovery, StreamCanBeConfiguredWhileRecoveryIsPending) { EXPECT_EQ(active, (ActiveTopology {{"dock"}})); EXPECT_EQ(clears, 1); } + +TEST_F(UndockRecovery, TopologyIsNotSwitchedWhileRecoveryIsPending) { + // The saved initial state still describes the absent layout, so a split clone group could not be put back together. + active = {{"stream", "clone"}}; + devices = { + {.m_device_id = "stream", .m_info = EnumeratedDevice::Info {.m_primary = true}}, + {.m_device_id = "clone", .m_info = EnumeratedDevice::Info {.m_primary = true}}, + {.m_device_id = "inactive"} + }; + init(); + + SingleDisplayConfiguration config; + config.m_device_id = "stream"; + config.m_device_prep = SingleDisplayConfiguration::DevicePreparation::EnsureOnlyDisplay; + EXPECT_EQ(manager->applySettings(config), SettingsManager::ApplyResult::DevicePrepFailed); + EXPECT_EQ(active, (ActiveTopology {{"stream", "clone"}})); + EXPECT_EQ(clears, 0); +}