From 2ff55d47e27e9d52a8d5c0bf7ee554af211e690d Mon Sep 17 00:00:00 2001 From: akarineren Date: Thu, 3 Dec 2026 22:34:41 +0900 Subject: [PATCH] Fix selection not following items when changing sort order in folder compare The folder compare list is an owner-data list view, so the control tracks the selection, the focused row and the selection mark by row index. Sorting only reorders m_listViewItems, which left a different set of items selected after clicking a column header. Remember the selected, focused and mark items in OnColumnClick before sorting and put the state back on their new rows afterwards. Fixes #2625 --- Src/DirView.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Src/DirView.cpp b/Src/DirView.cpp index 38a52e3c351..06175eaa2d7 100644 --- a/Src/DirView.cpp +++ b/Src/DirView.cpp @@ -1318,7 +1318,32 @@ void CDirView::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult) GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, bSortAscending); } + // The list view is owner-data, so it tracks the selection, the focus and + // the selection mark by index. Move them along with their items. + const int count = static_cast(m_listViewItems.size()); + const auto keyAt = [&](int i) { return (i >= 0 && i < count) ? m_listViewItems[i].lParam : 0; }; + const LPARAM focusedKey = keyAt(GetFocusedItem()); + const LPARAM markKey = keyAt(m_pList->GetSelectionMark()); + std::unordered_set selectedKeys; + for (int i = -1; (i = m_pList->GetNextItem(i, LVNI_SELECTED)) != -1;) + selectedKeys.insert(keyAt(i)); + SortColumnsAppropriately(); + + // Start from the state most items have and flip the others, so that + // sorting with nearly nothing or nearly everything selected stays cheap. + const bool most = selectedKeys.size() > m_listViewItems.size() / 2; + m_pList->SetItemState(-1, most ? LVIS_SELECTED : 0, LVIS_SELECTED); + for (int i = 0; i < count; i++) + { + const LPARAM key = keyAt(i); + if ((selectedKeys.count(key) != 0) != most) + m_pList->SetItemState(i, most ? 0 : LVIS_SELECTED, LVIS_SELECTED); + if (key == focusedKey) + m_pList->SetItemState(i, LVIS_FOCUSED, LVIS_FOCUSED); + if (key == markKey) + m_pList->SetSelectionMark(i); + } *pResult = 0; }