From 2e97ea27476df1726350c7fcc1114c5c5575dd29 Mon Sep 17 00:00:00 2001 From: Preston Peranich Date: Wed, 25 Nov 2026 19:30:29 -0500 Subject: [PATCH 1/3] fix(windows): harden revert on inactive stream displays and preserve database-backed redock recovery Guard empty HDR and display mode queries during revert, prune stream-only devices that become inactive externally before or during revert, and preserve an already-restored initial topology in topology_prep_guard instead of force-enabling all displays into Extended mode. Also expose WinDisplayDeviceInterface::savesToDatabase() and persist optional pending topology and activated stream-only device metadata so database-backed CCD writes keep missing original displays pending until redock. --- .../display_device/windows/settings_manager.h | 6 +- .../include/display_device/windows/types.h | 2 + .../windows/win_display_device.h | 5 + .../windows/win_display_device_interface.h | 8 + src/windows/json_serializer.cpp | 12 +- src/windows/settings_manager_apply.cpp | 4 + src/windows/settings_manager_revert.cpp | 291 ++++++++++++++--- src/windows/win_display_device_general.cpp | 4 + tests/unit/windows/test_json_converter.cpp | 1 + .../windows/test_settings_manager_revert.cpp | 309 ++++++++++++++++++ .../windows/test_settings_manager_undock.cpp | 99 +++++- .../test_win_display_device_general.cpp | 6 + .../windows/utils/mock_win_display_device.h | 1 + 13 files changed, 705 insertions(+), 43 deletions(-) diff --git a/src/windows/include/display_device/windows/settings_manager.h b/src/windows/include/display_device/windows/settings_manager.h index d9caca6..4d02a89 100644 --- a/src/windows/include/display_device/windows/settings_manager.h +++ b/src/windows/include/display_device/windows/settings_manager.h @@ -128,18 +128,20 @@ namespace display_device { * @param modified_state Modified state data to revert. * @param guard_fn Reference to the guard function which will be set to restore the current state if needed. * @param system_settings_touched Indicates whether a "write" operation could have been performed on the OS. + * @param query_failed [Optional] Flag set to true when querying current HDR states returned an empty map. * @returns Result enum indicating success or failure. */ - [[nodiscard]] RevertResult revertModifiedHdrStates(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched); + [[nodiscard]] RevertResult revertModifiedHdrStates(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched, bool *query_failed = nullptr); /** * @brief Revert display mode changes tracked in the modified settings state. * @param modified_state Modified state data to revert. * @param guard_fn Reference to the guard function which will be set to restore the current state if needed. * @param system_settings_touched Indicates whether a "write" operation could have been performed on the OS. + * @param query_failed [Optional] Flag set to true when querying current display modes returned an empty map. * @returns Result enum indicating success or failure. */ - [[nodiscard]] RevertResult revertModifiedDisplayModes(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched); + [[nodiscard]] RevertResult revertModifiedDisplayModes(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched, bool *query_failed = nullptr); /** * @brief Revert primary device changes tracked in the modified settings state. diff --git a/src/windows/include/display_device/windows/types.h b/src/windows/include/display_device/windows/types.h index 038b0cb..206f2f2 100644 --- a/src/windows/include/display_device/windows/types.h +++ b/src/windows/include/display_device/windows/types.h @@ -147,6 +147,8 @@ namespace display_device { HdrStateMap m_original_hdr_states {}; ///< Original HDR states before modification. std::string m_original_primary_device {}; ///< Original primary device before modification. std::string m_interim_primary_device {}; ///< Primary device to restore while the original one is unavailable. + StringSet m_pending_topology_devices {}; ///< Original devices whose saved Windows database topology still needs to be restored once they return. + StringSet m_activated_devices {}; ///< Stream-only devices excluded when pending topology recovery runs later. /** * @brief Check if the changed topology has any other modifications. diff --git a/src/windows/include/display_device/windows/win_display_device.h b/src/windows/include/display_device/windows/win_display_device.h index 7d37f06..4bdcad6 100644 --- a/src/windows/include/display_device/windows/win_display_device.h +++ b/src/windows/include/display_device/windows/win_display_device.h @@ -29,6 +29,11 @@ namespace display_device { */ [[nodiscard]] bool isApiAccessAvailable() const override; + /** + * @copydoc WinDisplayDeviceInterface::savesToDatabase + */ + [[nodiscard]] bool savesToDatabase() const override; + /** * @copydoc WinDisplayDeviceInterface::enumAvailableDevices */ diff --git a/src/windows/include/display_device/windows/win_display_device_interface.h b/src/windows/include/display_device/windows/win_display_device_interface.h index a567cd7..d509686 100644 --- a/src/windows/include/display_device/windows/win_display_device_interface.h +++ b/src/windows/include/display_device/windows/win_display_device_interface.h @@ -31,6 +31,14 @@ namespace display_device { */ [[nodiscard]] virtual bool isApiAccessAvailable() const = 0; + /** + * @brief Check whether topology and mode changes are saved to Windows' display database. + * @returns True if writes update Windows' display database, false if writes are session-only. + */ + [[nodiscard]] virtual bool savesToDatabase() const { + return false; + } + /** * @brief Enumerate the available (active and inactive) devices. * @returns A list of available devices. diff --git a/src/windows/json_serializer.cpp b/src/windows/json_serializer.cpp index e65a7c8..85e23e0 100644 --- a/src/windows/json_serializer.cpp +++ b/src/windows/json_serializer.cpp @@ -15,7 +15,7 @@ namespace display_device { DD_JSON_DEFINE_SERIALIZE_STRUCT(SingleDisplayConfigState::Initial, topology, primary_devices) /** - * @brief Serialize the modified state, including the interim primary device when there is one. + * @brief Serialize the modified state, including optional recovery metadata when present. * @param nlohmann_json_j JSON output object. * @param nlohmann_json_t Modified state to serialize. */ @@ -27,10 +27,16 @@ namespace display_device { if (!nlohmann_json_t.m_interim_primary_device.empty()) { DD_JSON_TO(interim_primary_device) } + if (!nlohmann_json_t.m_pending_topology_devices.empty()) { + DD_JSON_TO(pending_topology_devices) + } + if (!nlohmann_json_t.m_activated_devices.empty()) { + DD_JSON_TO(activated_devices) + } } /** - * @brief Deserialize the modified state, treating a missing interim primary device as none. + * @brief Deserialize the modified state, treating missing optional recovery fields as empty. * @param nlohmann_json_j JSON input object. * @param nlohmann_json_t Modified state to populate. */ @@ -40,6 +46,8 @@ namespace display_device { DD_JSON_FROM(original_hdr_states) DD_JSON_FROM(original_primary_device) nlohmann_json_t.m_interim_primary_device = nlohmann_json_j.value("interim_primary_device", std::string {}); + nlohmann_json_t.m_pending_topology_devices = nlohmann_json_j.value("pending_topology_devices", StringSet {}); + nlohmann_json_t.m_activated_devices = nlohmann_json_j.value("activated_devices", StringSet {}); } DD_JSON_DEFINE_SERIALIZE_STRUCT(SingleDisplayConfigState, initial, modified) diff --git a/src/windows/settings_manager_apply.cpp b/src/windows/settings_manager_apply.cpp index d68d2b0..49b8e4b 100644 --- a/src/windows/settings_manager_apply.cpp +++ b/src/windows/settings_manager_apply.cpp @@ -221,6 +221,10 @@ namespace display_device { release_context = m_dd_api->isTopologyTheSame(new_state.m_initial.m_topology, new_topology) && audio_is_captured; } + if (cached_state) { + new_state.m_modified.m_pending_topology_devices = cached_state->m_modified.m_pending_topology_devices; + new_state.m_modified.m_activated_devices = cached_state->m_modified.m_activated_devices; + } new_state.m_modified.m_topology = new_topology; return std::make_tuple(new_state, device_to_configure, additional_devices_to_configure); } diff --git a/src/windows/settings_manager_revert.cpp b/src/windows/settings_manager_revert.cpp index e28bf9b..41d0735 100644 --- a/src/windows/settings_manager_revert.cpp +++ b/src/windows/settings_manager_revert.cpp @@ -89,6 +89,115 @@ namespace display_device { } } + /** + * @brief Compare two topologies ignoring group and member order. + * @param lhs First topology to compare. + * @param rhs Second topology to compare. + * @return True when both topologies contain the same clone groups. + */ + bool areTopologiesEquivalent(ActiveTopology lhs, ActiveTopology rhs) { + const auto normalize {[](ActiveTopology &topology) { + for (auto &group : topology) { + std::ranges::sort(group); + } + std::ranges::sort(topology); + }}; + normalize(lhs); + normalize(rhs); + return lhs == rhs; + } + + /** + * @brief Collect all stream-only devices activated by the current or earlier pending session. + * @param state Persisted state to inspect. + * @return Device IDs activated only for streaming and excluded from recovery topologies. + */ + StringSet collectActivatedDevices(const SingleDisplayConfigState &state) { + const auto initial {win_utils::flattenTopology(state.m_initial.m_topology)}; + const auto modified {win_utils::flattenTopology(state.m_modified.m_topology)}; + StringSet activated {state.m_modified.m_activated_devices}; + std::ranges::set_difference(modified, initial, std::inserter(activated, activated.end())); + for (const auto &id : initial) { + activated.erase(id); + } + return activated; + } + + /** + * @brief Check whether every device in a topology is stream-only (absent from the initial topology). + * @param topology Topology to inspect. + * @param initial_ids Device IDs belonging to the initial topology. + * @return True if `topology` is non-empty and none of its devices belong to `initial_ids`. + */ + bool isStreamOnlyTopology(const ActiveTopology &topology, const StringSet &initial_ids) { + const auto ids {win_utils::flattenTopology(topology)}; + return !ids.empty() && std::ranges::none_of(ids, [&initial_ids](const auto &id) { + return initial_ids.contains(id); + }); + } + + /** + * @brief Remove stream-only devices that are no longer active from the modified state. + * + * A stream-only device (absent from the initial topology) can be deactivated externally by + * Windows or HPD before or during revert. Dropping only inactive stream-only devices lets + * revert finish restoring remaining active devices and return to the initial topology instead + * of failing into full-extended mode. + * + * @param modified_state Modified state to prune in place. + * @param initial_ids Device IDs belonging to the initial topology. + * @param active_ids Device IDs currently active in the OS topology. + * @return True if at least one inactive device was removed and none of the inactive devices belonged to `initial_ids`. + */ + bool dropInactiveStreamOnlyDevices(SingleDisplayConfigState::Modified &modified_state, const StringSet &initial_ids, const StringSet &active_ids) { + if (active_ids.empty()) { + return false; + } + + const auto modified_ids {win_utils::flattenTopology(modified_state.m_topology)}; + StringSet inactive_stream_only; + for (const auto &id : modified_ids) { + if (active_ids.contains(id)) { + continue; + } + if (initial_ids.contains(id)) { + return false; + } + inactive_stream_only.insert(id); + } + + if (inactive_stream_only.empty()) { + return false; + } + + ActiveTopology remaining_topology; + for (const auto &group : modified_state.m_topology) { + std::vector remaining_group; + for (const auto &id : group) { + if (!inactive_stream_only.contains(id)) { + remaining_group.push_back(id); + } + } + if (!remaining_group.empty()) { + remaining_topology.push_back(std::move(remaining_group)); + } + } + modified_state.m_topology = std::move(remaining_topology); + std::erase_if(modified_state.m_original_modes, [&inactive_stream_only](const auto &entry) { + return inactive_stream_only.contains(entry.first); + }); + std::erase_if(modified_state.m_original_hdr_states, [&inactive_stream_only](const auto &entry) { + return inactive_stream_only.contains(entry.first); + }); + if (inactive_stream_only.contains(modified_state.m_original_primary_device)) { + modified_state.m_original_primary_device.clear(); + } + if (inactive_stream_only.contains(modified_state.m_interim_primary_device)) { + modified_state.m_interim_primary_device.clear(); + } + return true; + } + /** * @brief Check whether an original device is away, so that its settings have to wait for its return. * @param id Device ID to check. @@ -104,15 +213,19 @@ namespace display_device { * @brief Keep only the pending settings of original devices that are currently unavailable. * * These settings cannot be restored until the devices return, so they must outlive a topology recovery. + * When CCD writes update Windows' display database, original devices that are still unavailable also + * retain a pending topology record so their saved database layout is restored once they return. * The modified topology is reduced to those devices, as they are all that is needed to restore the settings. * The initial topology is extended with the recovered one, so that new settings can still be applied while the devices are away. * @param state State to filter. * @param available Currently enumerated device IDs. * @param recovered_topology Topology that replaced the original one. + * @param keep_pending_topology True when Windows' display database was updated and needs restoration on return. * @return State with only the settings of unavailable original devices, or nothing if there are none. */ - std::optional keepUnavailableSettings(const SingleDisplayConfigState &state, const StringSet &available, const ActiveTopology &recovered_topology) { + std::optional keepUnavailableSettings(const SingleDisplayConfigState &state, const StringSet &available, const ActiveTopology &recovered_topology, const bool keep_pending_topology) { const auto initial {win_utils::flattenTopology(state.m_initial.m_topology)}; + const auto activated {collectActivatedDevices(state)}; SingleDisplayConfigState result {state}; std::erase_if(result.m_modified.m_original_modes, [&initial, &available](const auto &entry) { @@ -125,10 +238,27 @@ namespace display_device { result.m_modified.m_original_primary_device.clear(); } result.m_modified.m_interim_primary_device.clear(); // Already restored by the revert that led here. - if (!result.m_modified.hasModifications()) { + + result.m_modified.m_pending_topology_devices.clear(); + if (keep_pending_topology) { + // Track only the originally missing displays so a fallback panel added during recovery + // does not stay pending if the laptop lid is closed again before redocking. + const auto &tracked_topology_devices { + state.m_modified.m_pending_topology_devices.empty() ? initial : state.m_modified.m_pending_topology_devices + }; + for (const auto &id : tracked_topology_devices) { + if (isPendingDevice(id, initial, available)) { + result.m_modified.m_pending_topology_devices.insert(id); + } + } + } + + if (!result.m_modified.hasModifications() && result.m_modified.m_pending_topology_devices.empty()) { return std::nullopt; } + result.m_modified.m_activated_devices = activated; + // Only the returning devices need to be active to restore their settings. result.m_modified.m_topology.clear(); StringSet included; @@ -266,13 +396,28 @@ namespace display_device { return RevertResult::TopologyIsInvalid; } + const ActiveTopology initial_topology {cached_state->m_initial.m_topology}; bool system_settings_touched {false}; + bool switched_to_modified_topology {false}; boost::scope::scope_exit hdr_blank_always_executed_guard {[this, &system_settings_touched]() { if (system_settings_touched) { win_utils::blankHdrStates(*m_dd_api, m_workarounds.m_hdr_blank_delay); } }}; - boost::scope::scope_exit topology_prep_guard {[this, ¤t_topology, &system_settings_touched]() { + boost::scope::scope_exit topology_prep_guard {[this, ¤t_topology, &initial_topology, &system_settings_touched, &switched_to_modified_topology]() { + if (areTopologiesEquivalent(current_topology, initial_topology)) { + // The desktop already matched the original layout before revert started; avoid force-enabling + // inactive or virtual displays into an extended layout on failure. + if (switched_to_modified_topology) { + system_settings_touched = true; + if (!m_dd_api->setTopology(current_topology)) { + DD_LOG(error) << "failed to revert topology in revertSettings topology guard! Used the following topology:\n" + << toJson(current_topology); + } + } + return; + } + auto topology_to_restore {win_utils::createFullExtendedTopology(*m_dd_api)}; if (!m_dd_api->isTopologyValid(topology_to_restore)) { topology_to_restore = current_topology; @@ -287,7 +432,6 @@ namespace display_device { }}; // We can revert the modified setting independently before playing around with initial topology. - bool switched_to_modified_topology {false}; if (const auto result = revertModifiedSettings(current_topology, system_settings_touched, &switched_to_modified_topology); result != RevertResult::Ok) { // Error already logged return result; @@ -310,8 +454,8 @@ namespace display_device { return RevertResult::SwitchingTopologyFailed; } - // Original devices that are still unplugged keep their settings until they return. - pending_state = keepUnavailableSettings(*cached_state, win_utils::getDeviceIds(m_dd_api->enumAvailableDevices()), m_dd_api->getCurrentTopology()); + // Original devices that are still unplugged keep their settings (and saved database topology, when enabled) until they return. + pending_state = keepUnavailableSettings(*cached_state, win_utils::getDeviceIds(m_dd_api->enumAvailableDevices()), m_dd_api->getCurrentTopology(), m_dd_api->savesToDatabase()); } if (!m_persistence_state->persistState(pending_state)) { @@ -331,7 +475,6 @@ namespace display_device { bool SettingsManager::recoverMissingTopology(const ActiveTopology ¤t_topology) { const auto &state {*m_persistence_state->getState()}; const auto initial {win_utils::flattenTopology(state.m_initial.m_topology)}; - const auto modified {win_utils::flattenTopology(state.m_modified.m_topology)}; const auto devices {m_dd_api->enumAvailableDevices()}; const auto available {win_utils::getDeviceIds(devices)}; if (available.empty() || std::ranges::all_of(initial, [&available](const auto &id) { @@ -341,8 +484,7 @@ namespace display_device { return false; } - StringSet activated; - std::ranges::set_difference(modified, initial, std::inserter(activated, activated.end())); + const auto activated {collectActivatedDevices(state)}; ActiveTopology target; StringSet included; appendRecoveryGroups(state.m_initial.m_topology, available, activated, target, included); @@ -381,7 +523,7 @@ namespace display_device { return true; } - SettingsManager::RevertResult SettingsManager::revertModifiedHdrStates(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched) { + SettingsManager::RevertResult SettingsManager::revertModifiedHdrStates(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched, bool *query_failed) { using enum RevertResult; if (modified_state.m_original_hdr_states.empty()) { @@ -389,6 +531,14 @@ namespace display_device { } const auto current_states {m_dd_api->getCurrentHdrStates(win_utils::flattenTopology(modified_state.m_topology))}; + if (current_states.empty()) { + if (query_failed) { + *query_failed = true; + } + DD_LOG(error) << "Failed to get current HDR states!"; + return RevertingHdrStatesFailed; + } + if (current_states == modified_state.m_original_hdr_states) { return Ok; } @@ -406,7 +556,7 @@ namespace display_device { return Ok; } - SettingsManager::RevertResult SettingsManager::revertModifiedDisplayModes(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched) { + SettingsManager::RevertResult SettingsManager::revertModifiedDisplayModes(const SingleDisplayConfigState::Modified &modified_state, DdGuardFn &guard_fn, bool &system_settings_touched, bool *query_failed) { using enum RevertResult; if (modified_state.m_original_modes.empty()) { @@ -414,6 +564,14 @@ namespace display_device { } const auto current_modes {m_dd_api->getCurrentDisplayModes(win_utils::flattenTopology(modified_state.m_topology))}; + if (current_modes.empty()) { + if (query_failed) { + *query_failed = true; + } + DD_LOG(error) << "Failed to get current display modes!"; + return RevertingDisplayModesFailed; + } + if (current_modes == modified_state.m_original_modes) { return Ok; } @@ -473,10 +631,12 @@ namespace display_device { return RevertResult::TopologyIsInvalid; } + const auto initial_ids {win_utils::flattenTopology(cached_state->m_initial.m_topology)}; auto modified_state {cached_state->m_modified}; bool keep_record {prepareCarriedDevices(*m_dd_api, *cached_state, modified_state)}; bool is_topology_the_same {m_dd_api->isTopologyTheSame(current_topology, modified_state.m_topology)}; system_settings_touched = !is_topology_the_same; + bool skipped_reactivation {false}; if (!is_topology_the_same && !m_dd_api->setTopology(modified_state.m_topology)) { DD_LOG(error) << "Failed to change topology to:\n" << toJson(modified_state.m_topology); @@ -487,49 +647,104 @@ namespace display_device { return !available.contains(id); })}; !devices_missing) { - return RevertResult::SwitchingTopologyFailed; - } - keep_record = true; + if (!isStreamOnlyTopology(modified_state.m_topology, initial_ids)) { + return RevertResult::SwitchingTopologyFailed; + } - // A display from the modified topology has been unplugged. Revert the settings of the remaining - // displays so that the initial topology, or its recovery, can still be applied. - modified_state = keepAvailableDevices(modified_state, available); - DD_LOG(warning) << "Some modified devices are unavailable, reverting settings for the remaining topology:\n" - << toJson(modified_state.m_topology); - if (modified_state.m_topology.empty()) { - return RevertResult::Ok; - } + DD_LOG(warning) << "Stream-only modified topology could not be reactivated; skipping modified settings restoration."; + modified_state.m_topology.clear(); + modified_state.m_original_modes.clear(); + modified_state.m_original_hdr_states.clear(); + modified_state.m_original_primary_device.clear(); + modified_state.m_interim_primary_device.clear(); + skipped_reactivation = true; + } else { + keep_record = true; + + // A display from the modified topology has been unplugged. Revert the settings of the remaining + // displays so that the initial topology, or its recovery, can still be applied. + modified_state = keepAvailableDevices(modified_state, available); + DD_LOG(warning) << "Some modified devices are unavailable, reverting settings for the remaining topology:\n" + << toJson(modified_state.m_topology); + if (modified_state.m_topology.empty()) { + return RevertResult::Ok; + } - is_topology_the_same = m_dd_api->isTopologyTheSame(current_topology, modified_state.m_topology); - if (!is_topology_the_same && !m_dd_api->setTopology(modified_state.m_topology)) { - DD_LOG(error) << "Failed to change topology to:\n" - << toJson(modified_state.m_topology); - return RevertResult::SwitchingTopologyFailed; + is_topology_the_same = m_dd_api->isTopologyTheSame(current_topology, modified_state.m_topology); + if (!is_topology_the_same && !m_dd_api->setTopology(modified_state.m_topology)) { + DD_LOG(error) << "Failed to change topology to:\n" + << toJson(modified_state.m_topology); + return RevertResult::SwitchingTopologyFailed; + } } } if (switched_topology) { - *switched_topology = !is_topology_the_same; + *switched_topology = !is_topology_the_same && !skipped_reactivation; } + const auto try_prune_inactive_stream_only {[this, &modified_state, &initial_ids](const bool allow_pruning) { + if (!allow_pruning) { + return false; + } + + const auto active_ids {win_utils::flattenTopology(m_dd_api->getCurrentTopology())}; + if (!dropInactiveStreamOnlyDevices(modified_state, initial_ids, active_ids)) { + return false; + } + + DD_LOG(warning) << "Some stream-only modified devices are no longer active; skipping remaining settings restoration for them."; + return true; + }}; + DdGuardFn hdr_guard_fn {noopFn}; boost::scope::scope_exit hdr_guard {hdr_guard_fn}; - if (const auto result {revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched)}; result != RevertResult::Ok) { - // Error already logged - return result; + bool hdr_query_failed {false}; + if (auto result {revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched, &hdr_query_failed)}; result != RevertResult::Ok) { + if (!try_prune_inactive_stream_only(hdr_query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { + // Error already logged + return result; + } + if (modified_state.m_topology.empty()) { + hdr_guard.set_active(false); + } else if (result = revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched); result != RevertResult::Ok) { + // Error already logged + return result; + } } DdGuardFn mode_guard_fn {noopFn}; boost::scope::scope_exit mode_guard {mode_guard_fn}; - if (const auto result {revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched)}; result != RevertResult::Ok) { - // Error already logged - return result; + bool mode_query_failed {false}; + if (auto result {revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched, &mode_query_failed)}; result != RevertResult::Ok) { + if (!try_prune_inactive_stream_only(mode_query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { + // Error already logged + return result; + } + if (modified_state.m_topology.empty()) { + // All modified devices were stream-only and are already inactive; avoid invoking hdr_guard on inactive paths. + hdr_guard.set_active(false); + mode_guard.set_active(false); + } else if (result = revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched); result != RevertResult::Ok) { + // Error already logged + return result; + } } DdGuardFn primary_guard_fn {noopFn}; boost::scope::scope_exit primary_guard {primary_guard_fn}; - if (const auto result {revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched)}; result != RevertResult::Ok) { - // Error already logged - return result; + if (auto result {revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched)}; result != RevertResult::Ok) { + if (!try_prune_inactive_stream_only(isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { + // Error already logged + return result; + } + if (modified_state.m_topology.empty()) { + hdr_guard.set_active(false); + mode_guard.set_active(false); + primary_guard.set_active(false); + } else if (result = revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched); result != RevertResult::Ok) { + // Error already logged + return result; + } } if (keep_record) { @@ -542,6 +757,8 @@ namespace display_device { auto cleared_data {*cached_state}; cleared_data.m_modified = {cleared_data.m_modified.m_topology}; + cleared_data.m_modified.m_pending_topology_devices = cached_state->m_modified.m_pending_topology_devices; + cleared_data.m_modified.m_activated_devices = cached_state->m_modified.m_activated_devices; if (!m_persistence_state->persistState(cleared_data)) { DD_LOG(error) << "Failed to save reverted settings! Undoing changes to modified topology..."; return RevertResult::PersistenceSaveFailed; diff --git a/src/windows/win_display_device_general.cpp b/src/windows/win_display_device_general.cpp index afa9984..3cad80c 100644 --- a/src/windows/win_display_device_general.cpp +++ b/src/windows/win_display_device_general.cpp @@ -31,6 +31,10 @@ namespace display_device { return result == ERROR_SUCCESS; } + bool WinDisplayDevice::savesToDatabase() const { + return m_save_to_database; + } + EnumeratedDeviceList WinDisplayDevice::enumAvailableDevices() const { const auto display_data {m_w_api->queryDisplayConfig(QueryType::All)}; if (!display_data) { diff --git a/tests/unit/windows/test_json_converter.cpp b/tests/unit/windows/test_json_converter.cpp index 67812e7..90ba73a 100644 --- a/tests/unit/windows/test_json_converter.cpp +++ b/tests/unit/windows/test_json_converter.cpp @@ -46,6 +46,7 @@ TEST_F_S(SingleDisplayConfigState) { executeTestCase(display_device::SingleDisplayConfigState {}, R"({"initial":{"primary_devices":[],"topology":[]},"modified":{"original_hdr_states":{},"original_modes":{},"original_primary_device":"","topology":[]}})"); executeTestCase(valid_input, R"({"initial":{"primary_devices":["DeviceId1"],"topology":[["DeviceId1"]]},"modified":{"original_hdr_states":{"DeviceId2":"Disabled"},"original_modes":{"DeviceId2":{"refresh_rate":{"denominator":1,"numerator":120},"resolution":{"height":1080,"width":1920}}},"original_primary_device":"DeviceId2","topology":[["DeviceId2"]]}})"); executeTestCase(display_device::SingleDisplayConfigState {.m_modified = {.m_original_primary_device = "DeviceId2", .m_interim_primary_device = "DeviceId3"}}, R"({"initial":{"primary_devices":[],"topology":[]},"modified":{"interim_primary_device":"DeviceId3","original_hdr_states":{},"original_modes":{},"original_primary_device":"DeviceId2","topology":[]}})"); + executeTestCase(display_device::SingleDisplayConfigState {.m_modified = {.m_pending_topology_devices = {"Dock1"}, .m_activated_devices = {"Stream1"}}}, R"({"initial":{"primary_devices":[],"topology":[]},"modified":{"activated_devices":["Stream1"],"original_hdr_states":{},"original_modes":{},"original_primary_device":"","pending_topology_devices":["Dock1"],"topology":[]}})"); executeInvalidJsonTestCase(); executeFromJsonFailureTestCase(R"({})"); executeToJsonFailureTestCase(display_device::SingleDisplayConfigState { diff --git a/tests/unit/windows/test_settings_manager_revert.cpp b/tests/unit/windows/test_settings_manager_revert.cpp index fc30ff7..83d8af3 100644 --- a/tests/unit/windows/test_settings_manager_revert.cpp +++ b/tests/unit/windows/test_settings_manager_revert.cpp @@ -645,3 +645,312 @@ TEST_F_S_MOCKED(CurrentSettingsMatchPersistentOnes) { EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); } + +TEST_F_S_MOCKED(RevertModifiedSettings, EmptyHdrQueryFailsWithoutCallingSetHdrStates) { + auto sdcs_stripped {ut_consts::SDCS_FULL}; + sdcs_stripped->m_modified.m_original_modes.clear(); + sdcs_stripped->m_modified.m_original_primary_device.clear(); + + InSequence sequence; + expectedDefaultCallsUntilModifiedSettings(sequence, sdcs_stripped); + expectedDefaultMofifiedTopologyCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::win_utils::flattenTopology(sdcs_stripped->m_modified.m_topology))) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()) + .Times(1) + .WillOnce(Return(display_device::ActiveTopology {})) + .RetiresOnSaturation(); + expectedDefaultTopologyGuardCall(sequence); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingHdrStatesFailed); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, EmptyModeQueryFailsWithoutCallingSetDisplayModes) { + auto sdcs_stripped {ut_consts::SDCS_FULL}; + sdcs_stripped->m_modified.m_original_hdr_states.clear(); + sdcs_stripped->m_modified.m_original_primary_device.clear(); + + InSequence sequence; + expectedDefaultCallsUntilModifiedSettings(sequence, sdcs_stripped); + expectedDefaultMofifiedTopologyCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentDisplayModes(display_device::win_utils::flattenTopology(sdcs_stripped->m_modified.m_topology))) + .Times(1) + .WillOnce(Return(display_device::DeviceDisplayModeMap {})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()) + .Times(1) + .WillOnce(Return(display_device::ActiveTopology {{"DeviceId3"}})) + .RetiresOnSaturation(); + expectedDefaultTopologyGuardCall(sequence); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingDisplayModesFailed); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforeModeRevertRestoresInitialWithoutHdrGuard) { + const display_device::ActiveTopology physical_topology {{"Physical1"}}; + const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; + const display_device::SingleDisplayConfigState state { + {physical_topology, {"Physical1"}}, + {virtual_topology, + {{"Virtual1", {{1920, 1080}, {60, 1}}}}, + {{"Virtual1", {display_device::HdrState::Disabled}}}, + {}} + }; + auto cleared_state {state}; + cleared_state.m_modified = {virtual_topology}; + + InSequence sequence; + EXPECT_CALL(*m_settings_persistence_api, load()) + .Times(1) + .WillOnce(Return(serializeState(state))) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + // HDR revert succeeds while the virtual display is briefly active. + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"Virtual1"})) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {{"Virtual1", {display_device::HdrState::Enabled}}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) + .Times(1) + .WillOnce(Return(true)) + .RetiresOnSaturation(); + + // Windows drops the virtual display before display modes are queried; hdrStateGuardFn must not fire. + EXPECT_CALL(*m_dd_api, getCurrentDisplayModes(display_device::StringSet {"Virtual1"})) + .Times(1) + .WillOnce(Return(display_device::DeviceDisplayModeMap {})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyTopologyReactivationFailureSkipsModifiedCleanup) { + const display_device::ActiveTopology physical_topology {{"Physical1"}}; + const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; + const display_device::SingleDisplayConfigState state { + {physical_topology, {"Physical1"}}, + {virtual_topology, + {{"Virtual1", {{1920, 1080}, {60, 1}}}}, + {{"Virtual1", {display_device::HdrState::Disabled}}}, + {}} + }; + auto cleared_state {state}; + cleared_state.m_modified = {virtual_topology}; + + InSequence sequence; + EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, enumAvailableDevices()) + .Times(1) + .WillOnce(Return(display_device::EnumeratedDeviceList {{.m_device_id = "Physical1"}, {.m_device_id = "Virtual1"}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, MixedTopologyPrunesInactiveStreamOnlyDeviceAndRevertsInitialDevice) { + auto state {*ut_consts::SDCS_FULL}; + state.m_modified.m_original_hdr_states.clear(); + state.m_modified.m_original_primary_device.clear(); + auto cleared_state {state}; + cleared_state.m_modified = {state.m_modified.m_topology}; + const display_device::DeviceDisplayModeMap active_initial_mode {{"DeviceId1", {{2560, 1440}, {60, 1}}}}; + const display_device::DeviceDisplayModeMap original_initial_mode {{"DeviceId1", {{1920, 1080}, {120, 1}}}}; + + InSequence sequence; + expectedDefaultCallsUntilModifiedSettings(sequence, state); + expectedDefaultMofifiedTopologyCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentDisplayModes(display_device::StringSet {"DeviceId1", "DeviceId3"})) + .Times(1) + .WillOnce(Return(display_device::DeviceDisplayModeMap {})) + .RetiresOnSaturation(); + // Stream-only DeviceId3 dropped out of active paths, while initial DeviceId1 remains active. + EXPECT_CALL(*m_dd_api, getCurrentTopology()) + .Times(1) + .WillOnce(Return(display_device::ActiveTopology {{"DeviceId1"}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentDisplayModes(display_device::StringSet {"DeviceId1"})) + .Times(1) + .WillOnce(Return(active_initial_mode)) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setDisplayModes(original_initial_mode)) + .Times(1) + .WillOnce(Return(true)) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentDisplayModes(display_device::StringSet {"DeviceId1"})) + .Times(1) + .WillOnce(Return(original_initial_mode)) + .RetiresOnSaturation(); + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))) + .Times(1) + .WillOnce(Return(true)) + .RetiresOnSaturation(); + expectedDefaultInitialTopologyCalls(sequence, state); + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); +} + +TEST_F_S_MOCKED(TopologyGuard, PreservesInitialTopologyOnFailureInsteadOfEnablingAllDisplays) { + auto state {*ut_consts::SDCS_FULL}; + state.m_initial.m_topology = CURRENT_TOPOLOGY; + state.m_modified.m_topology = {{"DeviceId4"}, {"DeviceId3"}}; + state.m_modified.m_original_modes.clear(); + state.m_modified.m_original_primary_device.clear(); + state.m_modified.m_original_hdr_states = {{"DeviceId4", {display_device::HdrState::Disabled}}}; + + InSequence sequence; + expectedDefaultCallsUntilModifiedSettings(sequence, state); + EXPECT_CALL(*m_dd_api, isTopologyValid(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(CURRENT_TOPOLOGY, state.m_modified.m_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"DeviceId3", "DeviceId4"})) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {{"DeviceId4", {display_device::HdrState::Enabled}}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) + .Times(1) + .WillOnce(Return(false)) + .RetiresOnSaturation(); + // Since the system was already in initial topology before revert switched away, restore initial instead of enabling all displays. + EXPECT_CALL(*m_dd_api, setTopology(CURRENT_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingHdrStatesFailed); +} + +TEST_F_S_MOCKED(TopologyGuard, PreservesInitialTopologyLogsFailureWhenRestoreFails) { + auto state {*ut_consts::SDCS_FULL}; + state.m_initial.m_topology = CURRENT_TOPOLOGY; + state.m_modified.m_topology = {{"DeviceId4"}, {"DeviceId3"}}; + state.m_modified.m_original_modes.clear(); + state.m_modified.m_original_primary_device.clear(); + state.m_modified.m_original_hdr_states = {{"DeviceId4", {display_device::HdrState::Disabled}}}; + + InSequence sequence; + expectedDefaultCallsUntilModifiedSettings(sequence, state); + EXPECT_CALL(*m_dd_api, isTopologyValid(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(CURRENT_TOPOLOGY, state.m_modified.m_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"DeviceId3", "DeviceId4"})) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {{"DeviceId4", {display_device::HdrState::Enabled}}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) + .Times(1) + .WillOnce(Return(false)) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(CURRENT_TOPOLOGY)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingHdrStatesFailed); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforeHdrRevertSkipsModifiedCleanup) { + const display_device::ActiveTopology physical_topology {{"Physical1"}}; + const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; + const display_device::SingleDisplayConfigState state { + {physical_topology, {"Physical1"}}, + {virtual_topology, + {{"Virtual1", {{1920, 1080}, {60, 1}}}}, + {{"Virtual1", {display_device::HdrState::Disabled}}}, + {}} + }; + auto cleared_state {state}; + cleared_state.m_modified = {virtual_topology}; + + InSequence sequence; + EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"Virtual1"})) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); +} + +TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforePrimaryRevertClearsPrimaryFields) { + const display_device::ActiveTopology physical_topology {{"Physical1"}}; + const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; + display_device::SingleDisplayConfigState state { + {physical_topology, {"Physical1"}}, + {virtual_topology, {}, {}, "Virtual1"} + }; + state.m_modified.m_interim_primary_device = "Virtual1"; + auto cleared_state {state}; + cleared_state.m_modified = {virtual_topology}; + + InSequence sequence; + EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isPrimary("Virtual1")).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setAsPrimary("Virtual1")).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + + EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + + EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); +} diff --git a/tests/unit/windows/test_settings_manager_undock.cpp b/tests/unit/windows/test_settings_manager_undock.cpp index dd71ddc..2afd169 100644 --- a/tests/unit/windows/test_settings_manager_undock.cpp +++ b/tests/unit/windows/test_settings_manager_undock.cpp @@ -11,6 +11,7 @@ #include "utils/mock_win_display_device.h" #include +#include #include namespace { @@ -31,7 +32,9 @@ namespace { bool fail_clear {}; bool lie_about_cleanup {}; bool split_clones {}; + bool saves_to_database {}; int clears {}; + std::vector stored_record; std::shared_ptr> api = std::make_shared>(); std::shared_ptr> persistence = std::make_shared>(); std::shared_ptr> audio = std::make_shared>(); @@ -76,6 +79,9 @@ namespace { /** @brief Connect the stateful display and persistence mocks to the manager. */ void init() { ON_CALL(*api, isApiAccessAvailable()).WillByDefault(Return(true)); + ON_CALL(*api, savesToDatabase()).WillByDefault([this] { + return saves_to_database; + }); ON_CALL(*api, enumAvailableDevices()).WillByDefault([this] { return devices; }); @@ -91,14 +97,32 @@ namespace { ON_CALL(*api, setTopology(_)).WillByDefault([this](const ActiveTopology &target) { return applyTopology(target); }); + ON_CALL(*api, getCurrentDisplayModes(_)).WillByDefault([](const StringSet &ids) { + DeviceDisplayModeMap modes; + for (const auto &id : ids) { + modes[id] = DisplayMode {{1280, 720}, {30, 1}}; + } + return modes; + }); + ON_CALL(*api, getCurrentHdrStates(_)).WillByDefault([](const StringSet &ids) { + HdrStateMap states; + for (const auto &id : ids) { + states[id] = std::nullopt; + } + return states; + }); ON_CALL(*persistence, load()).WillByDefault([this] { - return serializeState(state); + return stored_record.empty() ? serializeState(state) : std::make_optional(stored_record); + }); + ON_CALL(*persistence, store(_)).WillByDefault([this](const std::vector &data) { + stored_record = data; + return true; }); - ON_CALL(*persistence, store(_)).WillByDefault(Return(true)); ON_CALL(*persistence, clear()).WillByDefault([this] { if (fail_clear) { return false; } + stored_record.clear(); ++clears; return true; }); @@ -376,3 +400,74 @@ TEST_F(UndockRecovery, StagingKeepsSurvivingCloneGroup) { ASSERT_GE(writes.size(), 3u); EXPECT_EQ(writes[writes.size() - 2], (ActiveTopology {{"stream"}, {"left", "right"}})); } + +TEST_F(UndockRecovery, DatabaseBackedTopologyStaysPendingUntilClosedLidRedock) { + saves_to_database = true; + openLid(); + init(); + + // Undocked recovery restores the built-in panel, but retains pending topology recovery for the missing dock. + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"panel"}})); + EXPECT_EQ(clears, 0); + EXPECT_FALSE(stored_record.empty()); + + // Close the lid and redock: Windows loads the saved streaming topology from its database until revert runs. + devices = {{.m_device_id = "stream"}, {.m_device_id = "dock"}}; + active = {{"stream"}}; + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"dock"}})); + EXPECT_EQ(clears, 1); + EXPECT_TRUE(stored_record.empty()); +} + +TEST_F(UndockRecovery, DatabaseBackedPendingTopologySurvivesUndockedStreamAndClearsOnOpenLidRedock) { + saves_to_database = true; + openLid(); + init(); + + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"panel"}})); + EXPECT_EQ(clears, 0); + + // Start and stop another stream while still undocked. + devices[1].m_info = EnumeratedDevice::Info {.m_primary = true}; + SingleDisplayConfiguration config; + config.m_device_id = "stream"; + config.m_device_prep = SingleDisplayConfiguration::DevicePreparation::EnsureOnlyDisplay; + EXPECT_EQ(manager->applySettings(config), SettingsManager::ApplyResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"stream"}})); + + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"panel"}})); + EXPECT_EQ(clears, 0); + + // Redocking with the lid open restores the dock alongside the panel and clears the pending record. + devices.push_back({.m_device_id = "dock"}); + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(win_utils::flattenTopology(active), (StringSet {"dock", "panel"})); + EXPECT_EQ(clears, 1); +} + +TEST_F(UndockRecovery, DatabaseBackedPartialRedockKeepsOnlyStillMissingDisplaysPending) { + saves_to_database = true; + state.m_initial = {{{"dock1"}, {"dock2"}}, {"dock1"}}; + openLid(); + init(); + + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(active, (ActiveTopology {{"panel"}})); + EXPECT_EQ(clears, 0); + + // Returning one of two docked monitors recovers it while keeping the second monitor pending. + devices.push_back({.m_device_id = "dock1"}); + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(win_utils::flattenTopology(active), (StringSet {"dock1", "panel"})); + EXPECT_EQ(clears, 0); + + // Returning the second monitor completes recovery and clears persistence. + devices.push_back({.m_device_id = "dock2"}); + EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok); + EXPECT_EQ(win_utils::flattenTopology(active), (StringSet {"dock1", "dock2", "panel"})); + EXPECT_EQ(clears, 1); +} diff --git a/tests/unit/windows/test_win_display_device_general.cpp b/tests/unit/windows/test_win_display_device_general.cpp index 50275a6..f8380e5 100644 --- a/tests/unit/windows/test_win_display_device_general.cpp +++ b/tests/unit/windows/test_win_display_device_general.cpp @@ -126,6 +126,12 @@ TEST_F_S_MOCKED(IsApiAccessAvailable, FailedToSetDisplayConfig) { EXPECT_FALSE(m_win_dd.isApiAccessAvailable()); } +TEST_F_S_MOCKED(SavesToDatabase, ReflectsConstructorFlag) { + EXPECT_TRUE(m_win_dd.savesToDatabase()); + const display_device::WinDisplayDevice temporary_win_dd {m_layer, false}; + EXPECT_FALSE(temporary_win_dd.savesToDatabase()); +} + TEST_F_S(EnumAvailableDevices) { // Note: we can't verify live data precisely, so just basic check // is performed regarding active vs. inactive devices diff --git a/tests/unit/windows/utils/mock_win_display_device.h b/tests/unit/windows/utils/mock_win_display_device.h index 422e203..c470a0f 100644 --- a/tests/unit/windows/utils/mock_win_display_device.h +++ b/tests/unit/windows/utils/mock_win_display_device.h @@ -10,6 +10,7 @@ namespace display_device { class MockWinDisplayDeviceBase: public WinDisplayDeviceInterface { public: MOCK_METHOD(bool, isApiAccessAvailable, (), (const, override)); + MOCK_METHOD(bool, savesToDatabase, (), (const, override)); MOCK_METHOD(EnumeratedDeviceList, enumAvailableDevices, (), (const, override)); MOCK_METHOD(std::string, getDisplayName, (const std::string &), (const, override)); MOCK_METHOD(ActiveTopology, getCurrentTopology, (), (const, override)); From a91dc4dfec46ca8c6081472f2e1c5fed0bceb4e5 Mon Sep 17 00:00:00 2001 From: Preston Peranich Date: Thu, 26 Nov 2026 00:59:43 -0500 Subject: [PATCH 2/3] refactor(windows): simplify revert helpers and deduplicate revert tests Extract topology group filtering, pending-device collection, revert topology guard fallback, modified-topology switch recovery, and unified stream-only pruning/retry helpers in settings_manager_revert.cpp to reduce cognitive complexity and resolve SonarCloud findings, and share mock setup helpers in test_settings_manager_revert.cpp. --- src/windows/settings_manager_revert.cpp | 488 +++++++++++------- .../windows/test_settings_manager_revert.cpp | 236 +++------ 2 files changed, 381 insertions(+), 343 deletions(-) diff --git a/src/windows/settings_manager_revert.cpp b/src/windows/settings_manager_revert.cpp index 41d0735..0bfda23 100644 --- a/src/windows/settings_manager_revert.cpp +++ b/src/windows/settings_manager_revert.cpp @@ -26,18 +26,18 @@ namespace display_device { } /** - * @brief Append available groups without reactivating stream-only outputs or duplicating devices. - * @param topology Groups to consider, in priority order. - * @param available Currently enumerated device IDs. - * @param activated Device IDs activated only for the stream. - * @param target Recovery topology to extend. - * @param included IDs already included in the recovery topology. + * @brief Append non-empty groups from `source` containing only device IDs accepted by `keep_id`. + * @tparam KeepFn Callable taking `const std::string &` and returning `bool`. + * @param source Topology whose groups are filtered. + * @param keep_id Predicate deciding whether a device ID should be included. + * @param target Topology to append filtered groups into. */ - void appendRecoveryGroups(const ActiveTopology &topology, const StringSet &available, const StringSet &activated, ActiveTopology &target, StringSet &included) { - for (const auto &group : topology) { + template + void appendFilteredTopologyGroups(const ActiveTopology &source, const KeepFn &keep_id, ActiveTopology &target) { + for (const auto &group : source) { std::vector remaining; for (const auto &id : group) { - if (available.contains(id) && !activated.contains(id) && included.insert(id).second) { + if (keep_id(id)) { remaining.push_back(id); } } @@ -47,6 +47,24 @@ namespace display_device { } } + /** + * @brief Append available groups without reactivating stream-only outputs or duplicating devices. + * @param topology Groups to consider, in priority order. + * @param available Currently enumerated device IDs. + * @param activated Device IDs activated only for the stream. + * @param target Recovery topology to extend. + * @param included IDs already included in the recovery topology. + */ + void appendRecoveryGroups(const ActiveTopology &topology, const StringSet &available, const StringSet &activated, ActiveTopology &target, StringSet &included) { + appendFilteredTopologyGroups( + topology, + [&available, &activated, &included](const std::string &id) { + return available.contains(id) && !activated.contains(id) && included.insert(id).second; + }, + target + ); + } + /** * @brief Add the groups of a target topology to a staged topology, keeping clone groups intact. * @@ -171,17 +189,13 @@ namespace display_device { } ActiveTopology remaining_topology; - for (const auto &group : modified_state.m_topology) { - std::vector remaining_group; - for (const auto &id : group) { - if (!inactive_stream_only.contains(id)) { - remaining_group.push_back(id); - } - } - if (!remaining_group.empty()) { - remaining_topology.push_back(std::move(remaining_group)); - } - } + appendFilteredTopologyGroups( + modified_state.m_topology, + [&inactive_stream_only](const std::string &id) { + return !inactive_stream_only.contains(id); + }, + remaining_topology + ); modified_state.m_topology = std::move(remaining_topology); std::erase_if(modified_state.m_original_modes, [&inactive_stream_only](const auto &entry) { return inactive_stream_only.contains(entry.first); @@ -209,6 +223,34 @@ namespace display_device { return initial.contains(id) && !available.contains(id); } + /** + * @brief Collect originally missing devices whose saved Windows database topology still needs restoration. + * + * Tracks only the originally missing displays so a fallback panel added during recovery does not + * stay pending if the laptop lid is closed again before redocking. + * @param state Persisted state to inspect. + * @param initial Device IDs in the initial topology. + * @param available Currently enumerated device IDs. + * @param keep_pending_topology True when Windows' display database was updated and needs restoration on return. + * @return Pending topology device IDs that are still unavailable. + */ + StringSet collectPendingTopologyDevices(const SingleDisplayConfigState &state, const StringSet &initial, const StringSet &available, const bool keep_pending_topology) { + if (!keep_pending_topology) { + return {}; + } + + const auto &tracked_topology_devices { + state.m_modified.m_pending_topology_devices.empty() ? initial : state.m_modified.m_pending_topology_devices + }; + StringSet pending; + for (const auto &id : tracked_topology_devices) { + if (isPendingDevice(id, initial, available)) { + pending.insert(id); + } + } + return pending; + } + /** * @brief Keep only the pending settings of original devices that are currently unavailable. * @@ -238,20 +280,7 @@ namespace display_device { result.m_modified.m_original_primary_device.clear(); } result.m_modified.m_interim_primary_device.clear(); // Already restored by the revert that led here. - - result.m_modified.m_pending_topology_devices.clear(); - if (keep_pending_topology) { - // Track only the originally missing displays so a fallback panel added during recovery - // does not stay pending if the laptop lid is closed again before redocking. - const auto &tracked_topology_devices { - state.m_modified.m_pending_topology_devices.empty() ? initial : state.m_modified.m_pending_topology_devices - }; - for (const auto &id : tracked_topology_devices) { - if (isPendingDevice(id, initial, available)) { - result.m_modified.m_pending_topology_devices.insert(id); - } - } - } + result.m_modified.m_pending_topology_devices = collectPendingTopologyDevices(state, initial, available, keep_pending_topology); if (!result.m_modified.hasModifications() && result.m_modified.m_pending_topology_devices.empty()) { return std::nullopt; @@ -262,31 +291,23 @@ namespace display_device { // Only the returning devices need to be active to restore their settings. result.m_modified.m_topology.clear(); StringSet included; - for (const auto &group : state.m_initial.m_topology) { - std::vector pending_group; - for (const auto &id : group) { - if (isPendingDevice(id, initial, available) && included.insert(id).second) { - pending_group.push_back(id); - } - } - if (!pending_group.empty()) { - result.m_modified.m_topology.push_back(std::move(pending_group)); - } - } + appendFilteredTopologyGroups( + state.m_initial.m_topology, + [&initial, &available, &included](const std::string &id) { + return isPendingDevice(id, initial, available) && included.insert(id).second; + }, + result.m_modified.m_topology + ); // The original devices alone would leave nothing to build on until one of them returns. StringSet known {initial}; - for (const auto &group : recovered_topology) { - std::vector recovered_group; - for (const auto &id : group) { - if (known.insert(id).second) { - recovered_group.push_back(id); - } - } - if (!recovered_group.empty()) { - result.m_initial.m_topology.push_back(std::move(recovered_group)); - } - } + appendFilteredTopologyGroups( + recovered_topology, + [&known](const std::string &id) { + return known.insert(id).second; + }, + result.m_initial.m_topology + ); return result; } @@ -374,6 +395,190 @@ namespace display_device { modified_state = keepAvailableDevices(modified_state, available); return some_unavailable; } + + /** + * @brief Restore a safe fallback topology when `revertSettings()` fails midway. + * + * When the desktop already matched the original layout before revert started, restore that layout + * (only if revert switched away) instead of force-enabling all available displays into Extended mode. + * @param dd_api Display device API. + * @param current_topology Active topology observed when `revertSettings()` started. + * @param initial_topology Persisted original topology. + * @param switched_to_modified_topology True if revert switched away from `current_topology`. + * @param system_settings_touched Updated to true when a topology write is attempted. + */ + void restoreTopologyOnRevertFailure( + WinDisplayDeviceInterface &dd_api, + const ActiveTopology ¤t_topology, + const ActiveTopology &initial_topology, + const bool switched_to_modified_topology, + bool &system_settings_touched + ) { + if (areTopologiesEquivalent(current_topology, initial_topology)) { + if (switched_to_modified_topology) { + system_settings_touched = true; + if (!dd_api.setTopology(current_topology)) { + DD_LOG(error) << "failed to revert topology in revertSettings topology guard! Used the following topology:\n" + << toJson(current_topology); + } + } + return; + } + + auto topology_to_restore {win_utils::createFullExtendedTopology(dd_api)}; + if (!dd_api.isTopologyValid(topology_to_restore)) { + topology_to_restore = current_topology; + } + + const bool is_topology_the_same {dd_api.isTopologyTheSame(current_topology, topology_to_restore)}; + system_settings_touched = system_settings_touched || !is_topology_the_same; + if (!is_topology_the_same && !dd_api.setTopology(topology_to_restore)) { + DD_LOG(error) << "failed to revert topology in revertSettings topology guard! Used the following topology:\n" + << toJson(topology_to_restore); + } + } + + /** + * @brief Clear transient modified settings fields while keeping pending recovery metadata intact. + * @param modified_state Modified state whose per-session fields should be cleared. + */ + void clearTransientModifications(SingleDisplayConfigState::Modified &modified_state) { + modified_state.m_topology.clear(); + modified_state.m_original_modes.clear(); + modified_state.m_original_hdr_states.clear(); + modified_state.m_original_primary_device.clear(); + modified_state.m_interim_primary_device.clear(); + } + + /** + * @brief Working state produced while preparing the modified topology for settings revert. + */ + struct ModifiedTopologyState { + SingleDisplayConfigState::Modified m_modified {}; ///< Modified state adjusted for available devices. + bool m_keep_record {false}; ///< True when missing devices require retaining the persisted record. + bool m_switched_topology {false}; ///< True when the OS topology was switched away from `current_topology`. + }; + + /** + * @brief Recover when switching to the modified topology fails during `revertModifiedSettings()`. + * @param dd_api Display device API. + * @param current_topology Current active topology before revert. + * @param initial_ids Device IDs belonging to the initial topology. + * @param state Working modified topology state updated in place. + * @return An early revert result to return immediately, or `std::nullopt` to continue reverting settings. + */ + std::optional recoverModifiedTopologySwitchFailure( + WinDisplayDeviceInterface &dd_api, + const ActiveTopology ¤t_topology, + const StringSet &initial_ids, + ModifiedTopologyState &state + ) { + DD_LOG(error) << "Failed to change topology to:\n" + << toJson(state.m_modified.m_topology); + + const auto available {win_utils::getDeviceIds(dd_api.enumAvailableDevices())}; + const auto modified_ids {win_utils::flattenTopology(state.m_modified.m_topology)}; + const bool devices_missing {!available.empty() && std::ranges::any_of(modified_ids, [&available](const auto &id) { + return !available.contains(id); + })}; + if (!devices_missing) { + if (!isStreamOnlyTopology(state.m_modified.m_topology, initial_ids)) { + return SettingsManager::RevertResult::SwitchingTopologyFailed; + } + + DD_LOG(warning) << "Stream-only modified topology could not be reactivated; skipping modified settings restoration."; + clearTransientModifications(state.m_modified); + state.m_switched_topology = false; + return std::nullopt; + } + + state.m_keep_record = true; + + // A display from the modified topology has been unplugged. Revert the settings of the remaining + // displays so that the initial topology, or its recovery, can still be applied. + state.m_modified = keepAvailableDevices(state.m_modified, available); + DD_LOG(warning) << "Some modified devices are unavailable, reverting settings for the remaining topology:\n" + << toJson(state.m_modified.m_topology); + if (state.m_modified.m_topology.empty()) { + return SettingsManager::RevertResult::Ok; + } + + const bool is_topology_the_same {dd_api.isTopologyTheSame(current_topology, state.m_modified.m_topology)}; + if (!is_topology_the_same && !dd_api.setTopology(state.m_modified.m_topology)) { + DD_LOG(error) << "Failed to change topology to:\n" + << toJson(state.m_modified.m_topology); + return SettingsManager::RevertResult::SwitchingTopologyFailed; + } + + state.m_switched_topology = !is_topology_the_same; + return std::nullopt; + } + + /** + * @brief Prune inactive stream-only devices from `modified_state` when allowed. + * @param dd_api Display device API. + * @param modified_state Modified state to prune in place. + * @param initial_ids Device IDs belonging to the initial topology. + * @param allow_pruning True when pruning inactive stream-only devices is permitted for this failure. + * @return True if one or more inactive stream-only devices were pruned. + */ + bool tryPruneInactiveStreamOnlyDevices( + const WinDisplayDeviceInterface &dd_api, + SingleDisplayConfigState::Modified &modified_state, + const StringSet &initial_ids, + const bool allow_pruning + ) { + if (!allow_pruning) { + return false; + } + + if (const auto active_ids {win_utils::flattenTopology(dd_api.getCurrentTopology())}; !dropInactiveStreamOnlyDevices(modified_state, initial_ids, active_ids)) { + return false; + } + + DD_LOG(warning) << "Some stream-only modified devices are no longer active; skipping remaining settings restoration for them."; + return true; + } + + /** + * @brief Run a modified-settings revert step, pruning inactive stream-only devices and retrying if needed. + * @tparam RevertFn Callable taking `bool *query_failed` and returning `SettingsManager::RevertResult`. + * @tparam DisarmGuardsFn Callable disarming rollback guards when all modified devices were pruned. + * @param dd_api Display device API. + * @param modified_state Modified state being reverted. + * @param initial_ids Device IDs belonging to the initial topology. + * @param revert_fn Step function to execute. + * @param disarm_guards Callback invoked if pruning leaves no modified devices to revert. + * @return Result of the step or retry. + */ + template + SettingsManager::RevertResult revertStepWithPruning( + const WinDisplayDeviceInterface &dd_api, + SingleDisplayConfigState::Modified &modified_state, + const StringSet &initial_ids, + const RevertFn &revert_fn, + const DisarmGuardsFn &disarm_guards + ) { + bool query_failed {false}; + const auto first_result {revert_fn(&query_failed)}; + if (first_result == SettingsManager::RevertResult::Ok) { + return first_result; + } + + const bool allow_pruning {query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids)}; + if (!tryPruneInactiveStreamOnlyDevices(dd_api, modified_state, initial_ids, allow_pruning)) { + // Error already logged + return first_result; + } + + if (modified_state.m_topology.empty()) { + // All modified devices were stream-only and are already inactive; avoid invoking guards on inactive paths. + disarm_guards(); + return SettingsManager::RevertResult::Ok; + } + + return revert_fn(nullptr); + } } // namespace SettingsManager::RevertResult SettingsManager::revertSettings() { @@ -405,30 +610,7 @@ namespace display_device { } }}; boost::scope::scope_exit topology_prep_guard {[this, ¤t_topology, &initial_topology, &system_settings_touched, &switched_to_modified_topology]() { - if (areTopologiesEquivalent(current_topology, initial_topology)) { - // The desktop already matched the original layout before revert started; avoid force-enabling - // inactive or virtual displays into an extended layout on failure. - if (switched_to_modified_topology) { - system_settings_touched = true; - if (!m_dd_api->setTopology(current_topology)) { - DD_LOG(error) << "failed to revert topology in revertSettings topology guard! Used the following topology:\n" - << toJson(current_topology); - } - } - return; - } - - auto topology_to_restore {win_utils::createFullExtendedTopology(*m_dd_api)}; - if (!m_dd_api->isTopologyValid(topology_to_restore)) { - topology_to_restore = current_topology; - } - - const bool is_topology_the_same {m_dd_api->isTopologyTheSame(current_topology, topology_to_restore)}; - system_settings_touched = system_settings_touched || !is_topology_the_same; - if (!is_topology_the_same && !m_dd_api->setTopology(topology_to_restore)) { - DD_LOG(error) << "failed to revert topology in revertSettings topology guard! Used the following topology:\n" - << toJson(topology_to_restore); - } + restoreTopologyOnRevertFailure(*m_dd_api, current_topology, initial_topology, switched_to_modified_topology, system_settings_touched); }}; // We can revert the modified setting independently before playing around with initial topology. @@ -632,126 +814,57 @@ namespace display_device { } const auto initial_ids {win_utils::flattenTopology(cached_state->m_initial.m_topology)}; - auto modified_state {cached_state->m_modified}; - bool keep_record {prepareCarriedDevices(*m_dd_api, *cached_state, modified_state)}; - bool is_topology_the_same {m_dd_api->isTopologyTheSame(current_topology, modified_state.m_topology)}; + ModifiedTopologyState state {cached_state->m_modified}; + state.m_keep_record = prepareCarriedDevices(*m_dd_api, *cached_state, state.m_modified); + const bool is_topology_the_same {m_dd_api->isTopologyTheSame(current_topology, state.m_modified.m_topology)}; system_settings_touched = !is_topology_the_same; - bool skipped_reactivation {false}; - if (!is_topology_the_same && !m_dd_api->setTopology(modified_state.m_topology)) { - DD_LOG(error) << "Failed to change topology to:\n" - << toJson(modified_state.m_topology); - - const auto available {win_utils::getDeviceIds(m_dd_api->enumAvailableDevices())}; - const auto modified_ids {win_utils::flattenTopology(modified_state.m_topology)}; - if (const bool devices_missing {!available.empty() && std::ranges::any_of(modified_ids, [&available](const auto &id) { - return !available.contains(id); - })}; - !devices_missing) { - if (!isStreamOnlyTopology(modified_state.m_topology, initial_ids)) { - return RevertResult::SwitchingTopologyFailed; - } - - DD_LOG(warning) << "Stream-only modified topology could not be reactivated; skipping modified settings restoration."; - modified_state.m_topology.clear(); - modified_state.m_original_modes.clear(); - modified_state.m_original_hdr_states.clear(); - modified_state.m_original_primary_device.clear(); - modified_state.m_interim_primary_device.clear(); - skipped_reactivation = true; - } else { - keep_record = true; - - // A display from the modified topology has been unplugged. Revert the settings of the remaining - // displays so that the initial topology, or its recovery, can still be applied. - modified_state = keepAvailableDevices(modified_state, available); - DD_LOG(warning) << "Some modified devices are unavailable, reverting settings for the remaining topology:\n" - << toJson(modified_state.m_topology); - if (modified_state.m_topology.empty()) { - return RevertResult::Ok; - } - - is_topology_the_same = m_dd_api->isTopologyTheSame(current_topology, modified_state.m_topology); - if (!is_topology_the_same && !m_dd_api->setTopology(modified_state.m_topology)) { - DD_LOG(error) << "Failed to change topology to:\n" - << toJson(modified_state.m_topology); - return RevertResult::SwitchingTopologyFailed; - } + state.m_switched_topology = !is_topology_the_same; + if (!is_topology_the_same && !m_dd_api->setTopology(state.m_modified.m_topology)) { + if (const auto early_result {recoverModifiedTopologySwitchFailure(*m_dd_api, current_topology, initial_ids, state)}; early_result.has_value()) { + return *early_result; } } if (switched_topology) { - *switched_topology = !is_topology_the_same && !skipped_reactivation; + *switched_topology = state.m_switched_topology; } - const auto try_prune_inactive_stream_only {[this, &modified_state, &initial_ids](const bool allow_pruning) { - if (!allow_pruning) { - return false; - } - - const auto active_ids {win_utils::flattenTopology(m_dd_api->getCurrentTopology())}; - if (!dropInactiveStreamOnlyDevices(modified_state, initial_ids, active_ids)) { - return false; - } - - DD_LOG(warning) << "Some stream-only modified devices are no longer active; skipping remaining settings restoration for them."; - return true; - }}; - + auto &modified_state {state.m_modified}; DdGuardFn hdr_guard_fn {noopFn}; boost::scope::scope_exit hdr_guard {hdr_guard_fn}; - bool hdr_query_failed {false}; - if (auto result {revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched, &hdr_query_failed)}; result != RevertResult::Ok) { - if (!try_prune_inactive_stream_only(hdr_query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { - // Error already logged - return result; - } - if (modified_state.m_topology.empty()) { - hdr_guard.set_active(false); - } else if (result = revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched); result != RevertResult::Ok) { - // Error already logged - return result; - } - } - DdGuardFn mode_guard_fn {noopFn}; boost::scope::scope_exit mode_guard {mode_guard_fn}; - bool mode_query_failed {false}; - if (auto result {revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched, &mode_query_failed)}; result != RevertResult::Ok) { - if (!try_prune_inactive_stream_only(mode_query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { - // Error already logged - return result; - } - if (modified_state.m_topology.empty()) { - // All modified devices were stream-only and are already inactive; avoid invoking hdr_guard on inactive paths. - hdr_guard.set_active(false); - mode_guard.set_active(false); - } else if (result = revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched); result != RevertResult::Ok) { - // Error already logged - return result; - } - } - DdGuardFn primary_guard_fn {noopFn}; boost::scope::scope_exit primary_guard {primary_guard_fn}; - if (auto result {revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched)}; result != RevertResult::Ok) { - if (!try_prune_inactive_stream_only(isStreamOnlyTopology(modified_state.m_topology, initial_ids))) { - // Error already logged - return result; - } - if (modified_state.m_topology.empty()) { - hdr_guard.set_active(false); - mode_guard.set_active(false); - primary_guard.set_active(false); - } else if (result = revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched); result != RevertResult::Ok) { - // Error already logged - return result; - } - } - - if (keep_record) { - // Keep the full record so that the unplugged displays can still be reverted if they return. + const auto disarm_all_guards {[&hdr_guard, &mode_guard, &primary_guard]() { hdr_guard.set_active(false); mode_guard.set_active(false); primary_guard.set_active(false); + }}; + + const auto revert_hdr {[this, &modified_state, &hdr_guard_fn, &system_settings_touched](bool *query_failed) { + return revertModifiedHdrStates(modified_state, hdr_guard_fn, system_settings_touched, query_failed); + }}; + if (const auto result {revertStepWithPruning(*m_dd_api, modified_state, initial_ids, revert_hdr, disarm_all_guards)}; result != RevertResult::Ok) { + return result; + } + + const auto revert_modes {[this, &modified_state, &mode_guard_fn, &system_settings_touched](bool *query_failed) { + return revertModifiedDisplayModes(modified_state, mode_guard_fn, system_settings_touched, query_failed); + }}; + if (const auto result {revertStepWithPruning(*m_dd_api, modified_state, initial_ids, revert_modes, disarm_all_guards)}; result != RevertResult::Ok) { + return result; + } + + const auto revert_primary {[this, &modified_state, &primary_guard_fn, &system_settings_touched](bool *) { + return revertModifiedPrimaryDevice(modified_state, primary_guard_fn, system_settings_touched); + }}; + if (const auto result {revertStepWithPruning(*m_dd_api, modified_state, initial_ids, revert_primary, disarm_all_guards)}; result != RevertResult::Ok) { + return result; + } + + if (state.m_keep_record) { + // Keep the full record so that the unplugged displays can still be reverted if they return. + disarm_all_guards(); return RevertResult::Ok; } @@ -764,10 +877,7 @@ namespace display_device { return RevertResult::PersistenceSaveFailed; } - // Disable guards - hdr_guard.set_active(false); - mode_guard.set_active(false); - primary_guard.set_active(false); + disarm_all_guards(); return RevertResult::Ok; } } // namespace display_device diff --git a/tests/unit/windows/test_settings_manager_revert.cpp b/tests/unit/windows/test_settings_manager_revert.cpp index 83d8af3..35b1657 100644 --- a/tests/unit/windows/test_settings_manager_revert.cpp +++ b/tests/unit/windows/test_settings_manager_revert.cpp @@ -18,6 +18,8 @@ namespace { // Additional convenience global const(s) const display_device::ActiveTopology CURRENT_TOPOLOGY {{"DeviceId4"}}; + const display_device::ActiveTopology PHYSICAL_ONLY_TOPOLOGY {{"Physical1"}}; + const display_device::ActiveTopology VIRTUAL_ONLY_TOPOLOGY {{"Virtual1"}}; const display_device::HdrStateMap CURRENT_MODIFIED_HDR_STATES { {"DeviceId1", {display_device::HdrState::Enabled}}, {"DeviceId3", std::nullopt} @@ -199,6 +201,69 @@ namespace { .RetiresOnSaturation(); } + [[nodiscard]] static display_device::SingleDisplayConfigState makeStreamOnlyState(const bool with_modes_and_hdr, const std::string &primary_device = {}) { + display_device::SingleDisplayConfigState state { + {PHYSICAL_ONLY_TOPOLOGY, {"Physical1"}}, + {VIRTUAL_ONLY_TOPOLOGY, {}, {}, primary_device} + }; + if (with_modes_and_hdr) { + state.m_modified.m_original_modes = {{"Virtual1", {{1920, 1080}, {60, 1}}}}; + state.m_modified.m_original_hdr_states = {{"Virtual1", {display_device::HdrState::Disabled}}}; + } + if (!primary_device.empty()) { + state.m_modified.m_interim_primary_device = primary_device; + } + return state; + } + + void expectStreamOnlyRevertStart(InSequence & /* To ensure that sequence is created outside this scope */, const display_device::SingleDisplayConfigState &state, const bool reactivation_succeeds) { + EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(PHYSICAL_ONLY_TOPOLOGY)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(PHYSICAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(VIRTUAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(PHYSICAL_ONLY_TOPOLOGY, VIRTUAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(VIRTUAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(reactivation_succeeds)).RetiresOnSaturation(); + } + + void expectStreamOnlyRevertFinish(InSequence &sequence, const display_device::SingleDisplayConfigState &state, const bool switch_back_to_physical) { + auto cleared_state {state}; + cleared_state.m_modified = {VIRTUAL_ONLY_TOPOLOGY}; + EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyValid(PHYSICAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(PHYSICAL_ONLY_TOPOLOGY, PHYSICAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + if (switch_back_to_physical) { + EXPECT_CALL(*m_dd_api, setTopology(PHYSICAL_ONLY_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + } + expectedDefaultFinalPersistenceCalls(sequence); + expectedDefaultAudioContextCalls(sequence, false); + expectedHdrWorkaroundCalls(sequence); + } + + void expectTopologyGuardPreservesInitial(InSequence &sequence, const bool restore_succeeds) { + auto state {*ut_consts::SDCS_FULL}; + state.m_initial.m_topology = CURRENT_TOPOLOGY; + state.m_modified.m_topology = {{"DeviceId4"}, {"DeviceId3"}}; + state.m_modified.m_original_modes.clear(); + state.m_modified.m_original_primary_device.clear(); + state.m_modified.m_original_hdr_states = {{"DeviceId4", {display_device::HdrState::Disabled}}}; + + expectedDefaultCallsUntilModifiedSettings(sequence, state); + EXPECT_CALL(*m_dd_api, isTopologyValid(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, isTopologyTheSame(CURRENT_TOPOLOGY, state.m_modified.m_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"DeviceId3", "DeviceId4"})) + .Times(1) + .WillOnce(Return(display_device::HdrStateMap {{"DeviceId4", {display_device::HdrState::Enabled}}})) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) + .Times(1) + .WillOnce(Return(false)) + .RetiresOnSaturation(); + EXPECT_CALL(*m_dd_api, setTopology(CURRENT_TOPOLOGY)).Times(1).WillOnce(Return(restore_succeeds)).RetiresOnSaturation(); + expectedHdrWorkaroundCalls(sequence); + } + void expectedDefaultAudioContextCalls(InSequence & /* To ensure that sequence is created outside this scope */, const bool audio_captured) { EXPECT_CALL(*m_audio_context_api, isCaptured()) .Times(1) @@ -691,30 +756,10 @@ TEST_F_S_MOCKED(RevertModifiedSettings, EmptyModeQueryFailsWithoutCallingSetDisp } TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforeModeRevertRestoresInitialWithoutHdrGuard) { - const display_device::ActiveTopology physical_topology {{"Physical1"}}; - const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; - const display_device::SingleDisplayConfigState state { - {physical_topology, {"Physical1"}}, - {virtual_topology, - {{"Virtual1", {{1920, 1080}, {60, 1}}}}, - {{"Virtual1", {display_device::HdrState::Disabled}}}, - {}} - }; - auto cleared_state {state}; - cleared_state.m_modified = {virtual_topology}; + const auto state {makeStreamOnlyState(true)}; InSequence sequence; - EXPECT_CALL(*m_settings_persistence_api, load()) - .Times(1) - .WillOnce(Return(serializeState(state))) - .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectStreamOnlyRevertStart(sequence, state, true); // HDR revert succeeds while the virtual display is briefly active. EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"Virtual1"})) @@ -731,52 +776,22 @@ TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforeModeRevertRes .Times(1) .WillOnce(Return(display_device::DeviceDisplayModeMap {})) .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - expectedDefaultFinalPersistenceCalls(sequence); - expectedDefaultAudioContextCalls(sequence, false); - expectedHdrWorkaroundCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(PHYSICAL_ONLY_TOPOLOGY)).RetiresOnSaturation(); + expectStreamOnlyRevertFinish(sequence, state, true); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); } TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyTopologyReactivationFailureSkipsModifiedCleanup) { - const display_device::ActiveTopology physical_topology {{"Physical1"}}; - const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; - const display_device::SingleDisplayConfigState state { - {physical_topology, {"Physical1"}}, - {virtual_topology, - {{"Virtual1", {{1920, 1080}, {60, 1}}}}, - {{"Virtual1", {display_device::HdrState::Disabled}}}, - {}} - }; - auto cleared_state {state}; - cleared_state.m_modified = {virtual_topology}; + const auto state {makeStreamOnlyState(true)}; InSequence sequence; - EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); + expectStreamOnlyRevertStart(sequence, state, false); EXPECT_CALL(*m_dd_api, enumAvailableDevices()) .Times(1) .WillOnce(Return(display_device::EnumeratedDeviceList {{.m_device_id = "Physical1"}, {.m_device_id = "Virtual1"}})) .RetiresOnSaturation(); - EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - expectedDefaultFinalPersistenceCalls(sequence); - expectedDefaultAudioContextCalls(sequence, false); - expectedHdrWorkaroundCalls(sequence); + expectStreamOnlyRevertFinish(sequence, state, false); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); } @@ -827,130 +842,43 @@ TEST_F_S_MOCKED(RevertModifiedSettings, MixedTopologyPrunesInactiveStreamOnlyDev } TEST_F_S_MOCKED(TopologyGuard, PreservesInitialTopologyOnFailureInsteadOfEnablingAllDisplays) { - auto state {*ut_consts::SDCS_FULL}; - state.m_initial.m_topology = CURRENT_TOPOLOGY; - state.m_modified.m_topology = {{"DeviceId4"}, {"DeviceId3"}}; - state.m_modified.m_original_modes.clear(); - state.m_modified.m_original_primary_device.clear(); - state.m_modified.m_original_hdr_states = {{"DeviceId4", {display_device::HdrState::Disabled}}}; - InSequence sequence; - expectedDefaultCallsUntilModifiedSettings(sequence, state); - EXPECT_CALL(*m_dd_api, isTopologyValid(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(CURRENT_TOPOLOGY, state.m_modified.m_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"DeviceId3", "DeviceId4"})) - .Times(1) - .WillOnce(Return(display_device::HdrStateMap {{"DeviceId4", {display_device::HdrState::Enabled}}})) - .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) - .Times(1) - .WillOnce(Return(false)) - .RetiresOnSaturation(); - // Since the system was already in initial topology before revert switched away, restore initial instead of enabling all displays. - EXPECT_CALL(*m_dd_api, setTopology(CURRENT_TOPOLOGY)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - expectedHdrWorkaroundCalls(sequence); + expectTopologyGuardPreservesInitial(sequence, true); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingHdrStatesFailed); } TEST_F_S_MOCKED(TopologyGuard, PreservesInitialTopologyLogsFailureWhenRestoreFails) { - auto state {*ut_consts::SDCS_FULL}; - state.m_initial.m_topology = CURRENT_TOPOLOGY; - state.m_modified.m_topology = {{"DeviceId4"}, {"DeviceId3"}}; - state.m_modified.m_original_modes.clear(); - state.m_modified.m_original_primary_device.clear(); - state.m_modified.m_original_hdr_states = {{"DeviceId4", {display_device::HdrState::Disabled}}}; - InSequence sequence; - expectedDefaultCallsUntilModifiedSettings(sequence, state); - EXPECT_CALL(*m_dd_api, isTopologyValid(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(CURRENT_TOPOLOGY, state.m_modified.m_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(state.m_modified.m_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"DeviceId3", "DeviceId4"})) - .Times(1) - .WillOnce(Return(display_device::HdrStateMap {{"DeviceId4", {display_device::HdrState::Enabled}}})) - .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setHdrStates(state.m_modified.m_original_hdr_states)) - .Times(1) - .WillOnce(Return(false)) - .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(CURRENT_TOPOLOGY)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - expectedHdrWorkaroundCalls(sequence); + expectTopologyGuardPreservesInitial(sequence, false); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::RevertingHdrStatesFailed); } TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforeHdrRevertSkipsModifiedCleanup) { - const display_device::ActiveTopology physical_topology {{"Physical1"}}; - const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; - const display_device::SingleDisplayConfigState state { - {physical_topology, {"Physical1"}}, - {virtual_topology, - {{"Virtual1", {{1920, 1080}, {60, 1}}}}, - {{"Virtual1", {display_device::HdrState::Disabled}}}, - {}} - }; - auto cleared_state {state}; - cleared_state.m_modified = {virtual_topology}; + const auto state {makeStreamOnlyState(true)}; InSequence sequence; - EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectStreamOnlyRevertStart(sequence, state, true); EXPECT_CALL(*m_dd_api, getCurrentHdrStates(display_device::StringSet {"Virtual1"})) .Times(1) .WillOnce(Return(display_device::HdrStateMap {})) .RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - expectedDefaultFinalPersistenceCalls(sequence); - expectedDefaultAudioContextCalls(sequence, false); - expectedHdrWorkaroundCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(PHYSICAL_ONLY_TOPOLOGY)).RetiresOnSaturation(); + expectStreamOnlyRevertFinish(sequence, state, true); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); } TEST_F_S_MOCKED(RevertModifiedSettings, StreamOnlyDeviceDropsBeforePrimaryRevertClearsPrimaryFields) { - const display_device::ActiveTopology physical_topology {{"Physical1"}}; - const display_device::ActiveTopology virtual_topology {{"Virtual1"}}; - display_device::SingleDisplayConfigState state { - {physical_topology, {"Physical1"}}, - {virtual_topology, {}, {}, "Virtual1"} - }; - state.m_modified.m_interim_primary_device = "Virtual1"; - auto cleared_state {state}; - cleared_state.m_modified = {virtual_topology}; + const auto state {makeStreamOnlyState(false, "Virtual1")}; InSequence sequence; - EXPECT_CALL(*m_settings_persistence_api, load()).Times(1).WillOnce(Return(serializeState(state))).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isApiAccessAvailable()).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, virtual_topology)).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(virtual_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); + expectStreamOnlyRevertStart(sequence, state, true); EXPECT_CALL(*m_dd_api, isPrimary("Virtual1")).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); EXPECT_CALL(*m_dd_api, setAsPrimary("Virtual1")).Times(1).WillOnce(Return(false)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(physical_topology)).RetiresOnSaturation(); - EXPECT_CALL(*m_settings_persistence_api, store(*serializeState(cleared_state))).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - - EXPECT_CALL(*m_dd_api, isTopologyValid(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, isTopologyTheSame(physical_topology, physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - EXPECT_CALL(*m_dd_api, setTopology(physical_topology)).Times(1).WillOnce(Return(true)).RetiresOnSaturation(); - expectedDefaultFinalPersistenceCalls(sequence); - expectedDefaultAudioContextCalls(sequence, false); - expectedHdrWorkaroundCalls(sequence); + EXPECT_CALL(*m_dd_api, getCurrentTopology()).Times(1).WillOnce(Return(PHYSICAL_ONLY_TOPOLOGY)).RetiresOnSaturation(); + expectStreamOnlyRevertFinish(sequence, state, true); EXPECT_EQ(getImpl().revertSettings(), display_device::SettingsManager::RevertResult::Ok); } From 3211d054cfbd06c0aedd5a6a54aaa6f0dcd6bf47 Mon Sep 17 00:00:00 2001 From: Preston Peranich Date: Thu, 26 Nov 2026 09:58:36 -0500 Subject: [PATCH 3/3] refactor(windows): scope revert helper variables to if init-statements --- src/windows/settings_manager_revert.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/windows/settings_manager_revert.cpp b/src/windows/settings_manager_revert.cpp index 0bfda23..7f296c5 100644 --- a/src/windows/settings_manager_revert.cpp +++ b/src/windows/settings_manager_revert.cpp @@ -477,11 +477,9 @@ namespace display_device { << toJson(state.m_modified.m_topology); const auto available {win_utils::getDeviceIds(dd_api.enumAvailableDevices())}; - const auto modified_ids {win_utils::flattenTopology(state.m_modified.m_topology)}; - const bool devices_missing {!available.empty() && std::ranges::any_of(modified_ids, [&available](const auto &id) { - return !available.contains(id); - })}; - if (!devices_missing) { + if (const auto modified_ids {win_utils::flattenTopology(state.m_modified.m_topology)}; available.empty() || std::ranges::all_of(modified_ids, [&available](const auto &id) { + return available.contains(id); + })) { if (!isStreamOnlyTopology(state.m_modified.m_topology, initial_ids)) { return SettingsManager::RevertResult::SwitchingTopologyFailed; } @@ -565,8 +563,7 @@ namespace display_device { return first_result; } - const bool allow_pruning {query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids)}; - if (!tryPruneInactiveStreamOnlyDevices(dd_api, modified_state, initial_ids, allow_pruning)) { + if (const bool allow_pruning {query_failed || isStreamOnlyTopology(modified_state.m_topology, initial_ids)}; !tryPruneInactiveStreamOnlyDevices(dd_api, modified_state, initial_ids, allow_pruning)) { // Error already logged return first_result; }