Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 61 additions & 3 deletions src/windows/settings_manager_apply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,60 @@ namespace display_device {
});
return inactive;
}

/**
* @brief Check whether all the devices of a topology are unavailable.
* @param topology Topology to check.
* @param devices Currently enumerated devices.
* @return True if none of the topology's devices are available.
*/
bool isTopologyUnavailable(const ActiveTopology &topology, const EnumeratedDeviceList &devices) {
const auto available {win_utils::getDeviceIds(devices)};
return std::ranges::none_of(win_utils::flattenTopology(topology), [&available](const auto &device_id) {
return available.contains(device_id);
});
}

/**
* @brief Get the initial state to use as a base for the new topology, without the unavailable devices.
*
* The cached initial state cannot be used as a base when all of its devices are gone (e.g. the original displays
* are behind a KVM switch or powered off). It is still kept for the revert once they return, but until then
* the current topology has to be the base, the same as if there was no cached state.
* @param initial_state Initial state that will be persisted.
* @param is_cached Whether the initial state comes from a previous session.
* @param topology_before_changes Currently active topology.
* @param devices Currently enumerated devices.
* @return Stripped initial state to base the new topology on, or empty optional if there is nothing to base it on.
*/
std::optional<SingleDisplayConfigState::Initial> computeBaseInitialState(const SingleDisplayConfigState::Initial &initial_state, const bool is_cached, const ActiveTopology &topology_before_changes, const EnumeratedDeviceList &devices) {
if (!is_cached || !isTopologyUnavailable(initial_state.m_topology, devices)) {
// In case some devices are no longer available in the system, we could try to strip them from the initial state
// and hope that we are still "safe" to make further changes (to be determined by computeNewTopologyAndMetadata call).
return win_utils::stripInitialState(initial_state, devices);
}

DD_LOG(warning) << "None of the devices from the initial topology are available. Will use the current topology as a base until they return:\n"
<< " - initial topology: " << toJson(initial_state.m_topology, JSON_COMPACT) << "\n"
<< " - current topology: " << toJson(topology_before_changes, JSON_COMPACT);
const auto current_state {win_utils::computeInitialState(std::nullopt, topology_before_changes, devices)};
return current_state ? win_utils::stripInitialState(*current_state, devices) : std::nullopt;
}

/**
* @brief Check whether a topology change has to be refused because the original devices are away.
*
* The cached initial state still describes the absent layout, so there would be nothing to restore
* the currently active topology from once it is changed.
* @param change_is_needed Whether the new topology differs from the active one.
* @param is_cached Whether the initial state comes from a previous session.
* @param initial_topology Topology of the initial state that will be persisted.
* @param devices Currently enumerated devices.
* @return True if the topology must not be changed.
*/
bool isTopologyChangeBlocked(const bool change_is_needed, const bool is_cached, const ActiveTopology &initial_topology, const EnumeratedDeviceList &devices) {
return change_is_needed && is_cached && isTopologyUnavailable(initial_topology, devices);
}
} // namespace

SettingsManager::ApplyResult SettingsManager::applySettings(const SingleDisplayConfiguration &config) {
Expand Down Expand Up @@ -167,9 +221,8 @@ namespace display_device {
}
SingleDisplayConfigState new_state {*new_initial_state};

// In case some devices are no longer available in the system, we could try to strip them from the initial state
// and hope that we are still "safe" to make further changes (to be determined by computeNewTopologyAndMetadata call below).
const auto stripped_initial_state {win_utils::stripInitialState(new_state.m_initial, devices)};
// The new topology is based on the initial state, which is the current topology if the cached one is of no use.
const auto stripped_initial_state {computeBaseInitialState(new_state.m_initial, cached_state.has_value(), topology_before_changes, devices)};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Preserve the interim display layout while recovery is pending. With every original device absent and no built-in panel, EnsureOnlyDisplay can now split a temporary clone group. The saved m_initial still describes the absent layout, so the failed revert falls back to extending every enumerated display. I reproduced this with [["stream","clone"]] and one inactive output. Apply succeeded, then disconnect left [["stream"],["clone"],["inactive"]] with the original recovery still pending.

Add this at the start of if (change_is_needed) in prepareTopology(), before reverting previous settings or switching topology.

      if (cached_state && isTopologyUnavailable(new_state.m_initial.m_topology, devices)) {
        DD_LOG(error) << "Cannot switch display topology while all original devices are unavailable!";
        return std::nullopt;
      }

In tests/unit/windows/test_settings_manager_undock.cpp, use the layout above to check that applying EnsureOnlyDisplay to stream leaves the clone group intact and recovery pending. The existing single-display regression verifies that the same request still applies the requested mode when the active topology already matches.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. The interim layout isn't recorded anywhere, so there's nothing to put it back from. Done in 8351756: a topology change is refused while all the original devices are away, and mode/HDR changes within the active topology still go through.

I put the check in a small helper (isTopologyChangeBlocked) and call it just before if (change_is_needed) instead of inside it. Inline, it adds 3 to prepareTopology() (a nested if plus the &&), which takes it from 24 to 27, over Sonar's cognitive complexity limit of 25. As a top-level call it adds 1.

Added UndockRecovery.TopologyIsNotSwitchedWhileRecoveryIsPending with your layout. It fails on the previous commit (apply returns Ok and leaves [["stream"]]) and passes now. 287 mocked and undock tests pass here.

One thing I noticed while testing: with the guard the apply is refused and the clone group survives, but a revertSettings() afterwards still ends at [["stream"],["clone"],["inactive"]]. The topology guard in revertSettings() extends every enumerated display whenever the revert fails, and Sunshine (2026.914 at least) calls revert on disconnect even after a failed apply. This PR doesn't touch that path, so I left it alone, but I can look at it in the follow-up if you want.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Russ. I checked the rebased head (013e7f0): the apply guard and clone-group regression address the apply-side finding, and mode/HDR changes can still proceed when the topology already matches.

Yes, please take the disconnect behavior in a separate follow-up. revertSettings() can still use a fully extended topology when recovery fails, even if apply left the layout alone. A regression test could start with the original monitors absent, an active [["stream", "clone"]] group, and a third inactive output. After a refused apply and a call to revertSettings(), assert that the clone group stays intact, the third output stays inactive, and the saved recovery stays pending. Then reconnect the originals and check that the original layout is restored. Please compare the clone groups explicitly, not just the set of active IDs.

I checked the source, not a live Windows setup. This follow-up doesn’t require changing whether Sunshine saves temporary layouts in #5942.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for checking the rebased head. I'll leave the revertSettings() disconnect behavior out of this PR. It comes from the same cause as #5942, a saved record that disagrees with the displays that are connected, so I'd rather fix it there than patch the revert path on its own. I'll use your scenario as the regression test: the originals absent, an active [["stream", "clone"]] group with a third output inactive, a refused apply, then revertSettings(). It will compare the clone groups explicitly and check that the originals' layout comes back when they return.

if (!stripped_initial_state) {
// Error already logged
return std::nullopt;
Expand All @@ -189,6 +242,11 @@ namespace display_device {
return std::nullopt;
}

if (isTopologyChangeBlocked(change_is_needed, cached_state.has_value(), new_state.m_initial.m_topology, devices)) {
DD_LOG(error) << "Cannot switch display topology while all original devices are unavailable!";
return std::nullopt;
}

if (change_is_needed) {
if (cached_state && !m_dd_api->isTopologyTheSame(cached_state->m_modified.m_topology, new_topology)) {
DD_LOG(warning) << "To apply new display device settings, previous modifications must be undone! Trying to undo them now.";
Expand Down
43 changes: 43 additions & 0 deletions tests/unit/windows/test_settings_manager_apply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,49 @@ TEST_F_S_MOCKED(PrepareTopology, FailedToStripInitialState) {
EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4"}), display_device::SettingsManager::ApplyResult::DevicePrepFailed);
}

TEST_F_S_MOCKED(PrepareTopology, InitialDevicesUnavailable) {
using DevicePrep = display_device::SingleDisplayConfiguration::DevicePreparation;
const display_device::ActiveTopology current_topology {{"DeviceId4"}};
const display_device::EnumeratedDeviceList devices {{.m_device_id = "DeviceId4", .m_info = display_device::EnumeratedDevice::Info {.m_primary = true}}};
const display_device::DeviceDisplayModeMap current_modes {{"DeviceId4", {{2560, 1440}, {60, 1}}}};
const display_device::DeviceDisplayModeMap new_modes {{"DeviceId4", {{1920, 1080}, {60, 1}}}};

// A leftover state from a session that was never reverted, with all the original devices gone since then
auto initial_state {DEFAULT_PERSISTENCE_INPUT_BASE};
initial_state.m_modified = {current_topology};
auto persistence_input {initial_state};
persistence_input.m_modified.m_original_modes = current_modes;

InSequence sequence;
expectedDefaultCallsUntilTopologyPrep(sequence, current_topology, initial_state);
expectedIsCapturedCall(sequence, false);
expectedDeviceEnumCall(sequence, devices);
expectedIsTopologyTheSameCall(sequence, current_topology, current_topology);
expectedGetCurrentDisplayModesCall(sequence, {"DeviceId4"}, current_modes);
expectedSetDisplayModesCall(sequence, new_modes);
expectedGetCurrentDisplayModesCall(sequence, {"DeviceId4"}, new_modes);
expectedPersistenceCall(sequence, persistence_input);
expectedHdrWorkaroundCalls(sequence);

EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4", .m_device_prep = DevicePrep::EnsureOnlyDisplay, .m_resolution = {{1920, 1080}}}), display_device::SettingsManager::ApplyResult::Ok);
}

TEST_F_S_MOCKED(PrepareTopology, InitialDevicesUnavailable, FailedToComputeBaseState) {
const display_device::ActiveTopology current_topology {{"DeviceId4"}};
auto initial_state {DEFAULT_PERSISTENCE_INPUT_BASE};
initial_state.m_modified = {current_topology};

InSequence sequence;
expectedDefaultCallsUntilTopologyPrep(sequence, current_topology, initial_state);
expectedIsCapturedCall(sequence, false);
expectedDeviceEnumCall(sequence, {{.m_device_id = "DeviceId4", .m_info = display_device::EnumeratedDevice::Info {.m_primary = false}}});

expectedTopologyGuardTopologyCall(sequence, current_topology);
expectedTopologyGuardNewlyCapturedContextCall(sequence, false);

EXPECT_EQ(getImpl().applySettings({.m_device_id = "DeviceId4"}), display_device::SettingsManager::ApplyResult::DevicePrepFailed);
}

TEST_F_S_MOCKED(PrepareTopology, DeviceNotFoundInNewTopology) {
InSequence sequence;
expectedDefaultCallsUntilTopologyPrep(sequence);
Expand Down
53 changes: 53 additions & 0 deletions tests/unit/windows/test_settings_manager_undock.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -376,3 +376,56 @@ TEST_F(UndockRecovery, StagingKeepsSurvivingCloneGroup) {
ASSERT_GE(writes.size(), 3u);
EXPECT_EQ(writes[writes.size() - 2], (ActiveTopology {{"stream"}, {"left", "right"}}));
}

TEST_F(UndockRecovery, StreamCanBeConfiguredWhileRecoveryIsPending) {
// Neither the original display nor a panel is available, e.g. a desktop with its monitors behind a KVM switch.
const DeviceDisplayModeMap idle_modes {{"stream", {{2560, 1440}, {60, 1}}}};
const DeviceDisplayModeMap stream_modes {{"stream", {{1920, 1080}, {60, 1}}}};
auto modes {idle_modes};
devices = {{.m_device_id = "stream", .m_info = EnumeratedDevice::Info {.m_primary = true}}};
init();
ON_CALL(*api, getCurrentDisplayModes(_)).WillByDefault([&modes](const auto &) {
return modes;
});
ON_CALL(*api, setDisplayModes(_)).WillByDefault([&modes](const DeviceDisplayModeMap &new_modes) {
modes = new_modes;
return true;
});

SingleDisplayConfiguration config;
config.m_device_id = "stream";
config.m_device_prep = SingleDisplayConfiguration::DevicePreparation::EnsureOnlyDisplay;
config.m_resolution = Resolution {1920, 1080};
EXPECT_EQ(manager->applySettings(config), SettingsManager::ApplyResult::Ok);
EXPECT_EQ(modes, stream_modes);
EXPECT_EQ(active, (ActiveTopology {{"stream"}}));

// The stream ends with the dock still away. Its mode is restored and the recovery stays pending.
EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::SwitchingTopologyFailed);
EXPECT_EQ(modes, idle_modes);
EXPECT_EQ(clears, 0);

// The dock returns and the original layout comes back.
devices.push_back({.m_device_id = "dock"});
EXPECT_EQ(manager->revertSettings(), SettingsManager::RevertResult::Ok);
EXPECT_EQ(active, (ActiveTopology {{"dock"}}));
EXPECT_EQ(clears, 1);
}

TEST_F(UndockRecovery, TopologyIsNotSwitchedWhileRecoveryIsPending) {
// The saved initial state still describes the absent layout, so a split clone group could not be put back together.
active = {{"stream", "clone"}};
devices = {
{.m_device_id = "stream", .m_info = EnumeratedDevice::Info {.m_primary = true}},
{.m_device_id = "clone", .m_info = EnumeratedDevice::Info {.m_primary = true}},
{.m_device_id = "inactive"}
};
init();

SingleDisplayConfiguration config;
config.m_device_id = "stream";
config.m_device_prep = SingleDisplayConfiguration::DevicePreparation::EnsureOnlyDisplay;
EXPECT_EQ(manager->applySettings(config), SettingsManager::ApplyResult::DevicePrepFailed);
EXPECT_EQ(active, (ActiveTopology {{"stream", "clone"}}));
EXPECT_EQ(clears, 0);
}