diff --git a/src/windows/settings_manager_apply.cpp b/src/windows/settings_manager_apply.cpp index d68d2b0..3f9a6b5 100644 --- a/src/windows/settings_manager_apply.cpp +++ b/src/windows/settings_manager_apply.cpp @@ -43,6 +43,60 @@ 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); + }); + } + + /** + * @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; + } + + /** + * @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) { @@ -167,9 +221,8 @@ namespace display_device { } SingleDisplayConfigState new_state {*new_initial_state}; - // 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)}; + // 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; @@ -189,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_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..327e45e 100644 --- a/tests/unit/windows/test_settings_manager_undock.cpp +++ b/tests/unit/windows/test_settings_manager_undock.cpp @@ -376,3 +376,56 @@ 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); +} + +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); +}