1 /////////////////////////////////////////////////////////////////////////////
2 // WinMerge: an interactive diff/merge utility
3 // Copyright (C) 1997-2000 Thingamahoochie Software
5 // SPDX-License-Identifier: GPL-2.0-or-later
6 /////////////////////////////////////////////////////////////////////////////
10 * @brief Main implementation file for CDirView
15 #include "Constants.h"
17 #include "ClipBoard.h"
18 #include "DirActions.h"
19 #include "DirViewColItems.h"
20 #include "DirFrame.h" // StatePane
22 #include "IMergeDoc.h"
23 #include "FileLocation.h"
26 #include "FileTransform.h"
27 #include "SelectUnpackerDlg.h"
30 #include "OptionsDef.h"
31 #include "OptionsMgr.h"
33 #include "DirCmpReportDlg.h"
34 #include "DirCmpReport.h"
35 #include "DirCompProgressBar.h"
36 #include "CompareStatisticsDlg.h"
37 #include "LoadSaveCodepageDlg.h"
38 #include "ConfirmFolderCopyDlg.h"
39 #include "DirColsDlg.h"
40 #include "DirSelectFilesDlg.h"
42 #include "ShellContextMenu.h"
44 #include "IListCtrlImpl.h"
45 #include "Merge7zFormatMergePluginImpl.h"
46 #include "FileOrFolderSelect.h"
47 #include "IntToIntMap.h"
48 #include "PatchTool.h"
49 #include "SyntaxColors.h"
59 using namespace std::placeholders;
62 * @brief Location for folder compare specific help to open.
64 static TCHAR DirViewHelpLocation[] = _T("::/htmlhelp/Compare_dirs.html");
67 * @brief Limit (in seconds) to signal compare is ready for user.
68 * If compare takes longer than this value (in seconds) we inform
69 * user about it. Current implementation uses MessageBeep(IDOK).
71 const int TimeToSignalCompare = 3;
73 // The resource ID constants/limits for the Shell context menu
74 const UINT LeftCmdFirst = 0x9000; // this should be greater than any of already defined command IDs
75 const UINT RightCmdLast = 0xffff; // maximum available value
76 const UINT LeftCmdLast = LeftCmdFirst + (RightCmdLast - LeftCmdFirst) / 3; // divide available range equally between two context menus
77 const UINT MiddleCmdFirst = LeftCmdLast + 1;
78 const UINT MiddleCmdLast = MiddleCmdFirst + (RightCmdLast - LeftCmdFirst) / 3;
79 const UINT RightCmdFirst = MiddleCmdLast + 1;
81 /////////////////////////////////////////////////////////////////////////////
86 STATUSBAR_UPDATE = 100
89 IMPLEMENT_DYNCREATE(CDirView, CListView)
94 , m_pCmpProgressBar(nullptr)
97 , m_dirfilter(std::bind(&COptionsMgr::GetBool, GetOptionsMgr(), _1))
98 , m_pShellContextMenuLeft(nullptr)
99 , m_pShellContextMenuMiddle(nullptr)
100 , m_pShellContextMenuRight(nullptr)
101 , m_hCurrentMenu(nullptr)
102 , m_pSavedTreeState(nullptr)
103 , m_pColItems(nullptr)
106 m_dwDefaultStyle &= ~LVS_TYPEMASK;
107 // Show selection all the time, so user can see current item even when
108 // focus is elsewhere (ie, on file edit window)
109 m_dwDefaultStyle |= LVS_REPORT | LVS_SHOWSELALWAYS | LVS_EDITLABELS;
111 m_bTreeMode = GetOptionsMgr()->GetBool(OPT_TREE_MODE);
112 m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
113 m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
114 Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
115 m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
118 CDirView::~CDirView()
122 BEGIN_MESSAGE_MAP(CDirView, CListView)
124 //{{AFX_MSG_MAP(CDirView)
125 ON_WM_LBUTTONDBLCLK()
126 ON_COMMAND_RANGE(ID_L2R, ID_R2L, OnDirCopy)
127 ON_UPDATE_COMMAND_UI_RANGE(ID_L2R, ID_R2L, OnUpdateDirCopy)
128 ON_COMMAND(ID_DIR_COPY_LEFT_TO_RIGHT, (OnCtxtDirCopy<SIDE_LEFT, SIDE_RIGHT>))
129 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_RIGHT, (OnUpdateCtxtDirCopy<SIDE_LEFT, SIDE_RIGHT>))
130 ON_COMMAND(ID_DIR_COPY_LEFT_TO_MIDDLE, (OnCtxtDirCopy<SIDE_LEFT, SIDE_MIDDLE>))
131 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_MIDDLE, (OnUpdateCtxtDirCopy<SIDE_LEFT, SIDE_MIDDLE>))
132 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_LEFT, (OnCtxtDirCopy<SIDE_RIGHT, SIDE_LEFT>))
133 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_LEFT, (OnUpdateCtxtDirCopy<SIDE_RIGHT, SIDE_LEFT>))
134 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_MIDDLE, (OnCtxtDirCopy<SIDE_RIGHT, SIDE_MIDDLE>))
135 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_MIDDLE, (OnUpdateCtxtDirCopy<SIDE_RIGHT, SIDE_MIDDLE>))
136 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_LEFT, (OnCtxtDirCopy<SIDE_MIDDLE, SIDE_LEFT>))
137 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_LEFT, (OnUpdateCtxtDirCopy<SIDE_MIDDLE, SIDE_LEFT>))
138 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_RIGHT, (OnCtxtDirCopy<SIDE_MIDDLE, SIDE_RIGHT>))
139 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_RIGHT, (OnUpdateCtxtDirCopy<SIDE_MIDDLE, SIDE_RIGHT>))
140 ON_COMMAND(ID_DIR_DEL_LEFT, OnCtxtDirDel<SIDE_LEFT>)
141 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_LEFT, OnUpdateCtxtDirDel<SIDE_LEFT>)
142 ON_COMMAND(ID_DIR_DEL_RIGHT, OnCtxtDirDel<SIDE_RIGHT>)
143 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_MIDDLE, OnUpdateCtxtDirDel<SIDE_MIDDLE>)
144 ON_COMMAND(ID_DIR_DEL_MIDDLE, OnCtxtDirDel<SIDE_MIDDLE>)
145 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_RIGHT, OnUpdateCtxtDirDel<SIDE_RIGHT>)
146 ON_COMMAND(ID_DIR_DEL_BOTH, OnCtxtDirDelBoth)
147 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_BOTH, OnUpdateCtxtDirDelBoth)
148 ON_COMMAND(ID_DIR_DEL_ALL, OnCtxtDirDelBoth)
149 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_ALL, OnUpdateCtxtDirDelBoth)
150 ON_COMMAND(ID_DIR_OPEN_LEFT, OnCtxtDirOpen<SIDE_LEFT>)
151 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT, OnUpdateCtxtDirOpen<SIDE_LEFT>)
152 ON_COMMAND(ID_DIR_OPEN_LEFT_WITH, OnCtxtDirOpenWith<SIDE_LEFT>)
153 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_WITH, OnUpdateCtxtDirOpenWith<SIDE_LEFT>)
154 ON_COMMAND(ID_DIR_OPEN_LEFT_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_LEFT>)
155 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_LEFT>)
156 ON_COMMAND(ID_DIR_OPEN_MIDDLE, OnCtxtDirOpen<SIDE_MIDDLE>)
157 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE, OnUpdateCtxtDirOpen<SIDE_MIDDLE>)
158 ON_COMMAND(ID_DIR_OPEN_MIDDLE_WITH, OnCtxtDirOpenWith<SIDE_MIDDLE>)
159 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_WITH, OnUpdateCtxtDirOpenWith<SIDE_MIDDLE>)
160 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_MIDDLE>)
161 ON_COMMAND(ID_DIR_OPEN_MIDDLE_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_MIDDLE>)
162 ON_COMMAND(ID_DIR_OPEN_RIGHT, OnCtxtDirOpen<SIDE_RIGHT>)
163 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT, OnUpdateCtxtDirOpen<SIDE_RIGHT>)
164 ON_COMMAND(ID_DIR_OPEN_RIGHT_WITH, OnCtxtDirOpenWith<SIDE_RIGHT>)
165 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_WITH, OnUpdateCtxtDirOpenWith<SIDE_RIGHT>)
166 ON_COMMAND(ID_DIR_OPEN_RIGHT_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_RIGHT>)
167 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_RIGHT>)
168 ON_COMMAND(ID_POPUP_OPEN_WITH_UNPACKER, OnCtxtOpenWithUnpacker)
169 ON_UPDATE_COMMAND_UI(ID_POPUP_OPEN_WITH_UNPACKER, OnUpdateCtxtOpenWithUnpacker)
170 ON_COMMAND(ID_DIR_OPEN_LEFT_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_LEFT>)
171 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_LEFT>)
172 ON_COMMAND(ID_DIR_OPEN_MIDDLE_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_MIDDLE>)
173 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_MIDDLE>)
174 ON_COMMAND(ID_DIR_OPEN_RIGHT_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_RIGHT>)
175 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_RIGHT>)
176 ON_COMMAND(ID_DIR_COPY_LEFT_TO_BROWSE, OnCtxtDirCopyTo<SIDE_LEFT>)
177 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_BROWSE, OnCtxtDirCopyTo<SIDE_MIDDLE>)
178 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_BROWSE, OnCtxtDirCopyTo<SIDE_RIGHT>)
179 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
180 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
181 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
185 ON_COMMAND(ID_FIRSTDIFF, OnFirstdiff)
186 ON_UPDATE_COMMAND_UI(ID_FIRSTDIFF, OnUpdateFirstdiff)
187 ON_COMMAND(ID_LASTDIFF, OnLastdiff)
188 ON_UPDATE_COMMAND_UI(ID_LASTDIFF, OnUpdateLastdiff)
189 ON_COMMAND(ID_NEXTDIFF, OnNextdiff)
190 ON_UPDATE_COMMAND_UI(ID_NEXTDIFF, OnUpdateNextdiff)
191 ON_COMMAND(ID_PREVDIFF, OnPrevdiff)
192 ON_UPDATE_COMMAND_UI(ID_PREVDIFF, OnUpdatePrevdiff)
193 ON_COMMAND(ID_CURDIFF, OnCurdiff)
194 ON_UPDATE_COMMAND_UI(ID_CURDIFF, OnUpdateCurdiff)
195 ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateSave)
196 ON_MESSAGE(MSG_UI_UPDATE, OnUpdateUIMessage)
197 ON_COMMAND(ID_REFRESH, OnRefresh)
198 ON_UPDATE_COMMAND_UI(ID_REFRESH, OnUpdateRefresh)
200 ON_UPDATE_COMMAND_UI(ID_STATUS_RIGHTDIR_RO, OnUpdateStatusRightRO)
201 ON_UPDATE_COMMAND_UI(ID_STATUS_MIDDLEDIR_RO, OnUpdateStatusMiddleRO)
202 ON_UPDATE_COMMAND_UI(ID_STATUS_LEFTDIR_RO, OnUpdateStatusLeftRO)
203 ON_COMMAND(ID_FILE_LEFT_READONLY, OnReadOnly<SIDE_LEFT>)
204 ON_UPDATE_COMMAND_UI(ID_FILE_LEFT_READONLY, OnUpdateReadOnly<SIDE_LEFT>)
205 ON_COMMAND(ID_FILE_MIDDLE_READONLY, OnReadOnly<SIDE_MIDDLE>)
206 ON_UPDATE_COMMAND_UI(ID_FILE_MIDDLE_READONLY, OnUpdateReadOnly<SIDE_MIDDLE>)
207 ON_COMMAND(ID_FILE_RIGHT_READONLY, OnReadOnly<SIDE_RIGHT>)
208 ON_UPDATE_COMMAND_UI(ID_FILE_RIGHT_READONLY, OnUpdateReadOnly<SIDE_RIGHT>)
209 ON_COMMAND(ID_TOOLS_CUSTOMIZECOLUMNS, OnCustomizeColumns)
210 ON_COMMAND(ID_TOOLS_GENERATEREPORT, OnToolsGenerateReport)
211 ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
212 ON_MESSAGE(MSG_GENERATE_FLIE_COMPARE_REPORT, OnGenerateFileCmpReport)
213 ON_COMMAND(ID_DIR_ZIP_LEFT, OnCtxtDirZip<DirItemEnumerator::Left>)
214 ON_COMMAND(ID_DIR_ZIP_MIDDLE, OnCtxtDirZip<DirItemEnumerator::Middle>)
215 ON_COMMAND(ID_DIR_ZIP_RIGHT, OnCtxtDirZip<DirItemEnumerator::Right>)
216 ON_COMMAND(ID_DIR_ZIP_BOTH, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
217 ON_COMMAND(ID_DIR_ZIP_ALL, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
218 ON_COMMAND(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders | DirItemEnumerator::DiffsOnly>)
219 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_LEFT, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
220 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_MIDDLE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
221 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_RIGHT, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
222 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH, OnUpdateCtxtDirCopyBothTo)
223 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_ALL, OnUpdateCtxtDirCopyBothTo)
224 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnUpdateCtxtDirCopyBothDiffsOnlyTo)
225 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_LEFT, OnCtxtDirShellContextMenu<SIDE_LEFT>)
226 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, OnCtxtDirShellContextMenu<SIDE_MIDDLE>)
227 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_RIGHT, OnCtxtDirShellContextMenu<SIDE_RIGHT>)
228 ON_COMMAND(ID_EDIT_SELECT_ALL, OnSelectAll)
229 ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateSelectAll)
230 ON_COMMAND_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnPluginPredifferMode)
231 ON_UPDATE_COMMAND_UI_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnUpdatePluginPredifferMode)
232 ON_COMMAND(ID_DIR_COPY_PATHNAMES_LEFT, OnCopyPathnames<SIDE_LEFT>)
233 ON_COMMAND(ID_DIR_COPY_PATHNAMES_MIDDLE, OnCopyPathnames<SIDE_MIDDLE>)
234 ON_COMMAND(ID_DIR_COPY_PATHNAMES_RIGHT, OnCopyPathnames<SIDE_RIGHT>)
235 ON_COMMAND(ID_DIR_COPY_PATHNAMES_BOTH, OnCopyBothPathnames)
236 ON_COMMAND(ID_DIR_COPY_PATHNAMES_ALL, OnCopyBothPathnames)
237 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_LEFT, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
238 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_MIDDLE, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
239 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_RIGHT, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
240 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_BOTH, OnUpdateCtxtDirCopyBoth2)
241 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_ALL, OnUpdateCtxtDirCopyBoth2)
242 ON_COMMAND(ID_DIR_COPY_FILENAMES, OnCopyFilenames)
243 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_FILENAMES, OnUpdateCopyFilenames)
244 ON_COMMAND(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_LEFT>)
245 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnCopyToClipboard<SIDE_MIDDLE>)
246 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_RIGHT>)
247 ON_COMMAND(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnCopyBothToClipboard)
248 ON_COMMAND(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnCopyBothToClipboard)
249 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
250 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
251 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
252 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
253 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
254 ON_COMMAND(ID_DIR_ITEM_RENAME, OnItemRename)
255 ON_UPDATE_COMMAND_UI(ID_DIR_ITEM_RENAME, OnUpdateItemRename)
256 ON_COMMAND(ID_DIR_HIDE_FILENAMES, OnHideFilenames)
257 ON_COMMAND(ID_DIR_MOVE_LEFT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_LEFT>)
258 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_LEFT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_LEFT>)
259 ON_COMMAND(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnCtxtDirMoveTo<SIDE_MIDDLE>)
260 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_MIDDLE>)
261 ON_COMMAND(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_RIGHT>)
262 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_RIGHT>)
263 ON_UPDATE_COMMAND_UI(ID_DIR_HIDE_FILENAMES, OnUpdateHideFilenames)
265 ON_COMMAND(ID_MERGE_DELETE, OnDelete)
266 ON_UPDATE_COMMAND_UI(ID_MERGE_DELETE, OnUpdateDelete)
267 ON_COMMAND(ID_RESCAN, OnMarkedRescan)
268 ON_UPDATE_COMMAND_UI(ID_STATUS_DIFFNUM, OnUpdateStatusNum)
269 ON_COMMAND(ID_VIEW_SHOWHIDDENITEMS, OnViewShowHiddenItems)
270 ON_UPDATE_COMMAND_UI(ID_VIEW_SHOWHIDDENITEMS, OnUpdateViewShowHiddenItems)
271 ON_COMMAND(ID_MERGE_COMPARE, OnMergeCompare)
272 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE, OnUpdateMergeCompare)
273 ON_COMMAND(ID_MERGE_COMPARE_LEFT1_LEFT2, OnMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
274 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_LEFT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
275 ON_COMMAND(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
276 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
277 ON_COMMAND(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
278 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
279 ON_COMMAND(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
280 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
281 ON_COMMAND(ID_MERGE_COMPARE_NONHORIZONTALLY, OnMergeCompareNonHorizontally)
282 ON_COMMAND(ID_MERGE_COMPARE_XML, OnMergeCompareXML)
283 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_XML, OnUpdateMergeCompare)
284 ON_COMMAND_RANGE(ID_MERGE_COMPARE_TEXT, ID_MERGE_COMPARE_IMAGE, OnMergeCompareAs)
285 ON_UPDATE_COMMAND_UI_RANGE(ID_MERGE_COMPARE_TEXT, ID_MERGE_COMPARE_IMAGE, OnUpdateMergeCompare)
286 ON_COMMAND(ID_VIEW_TREEMODE, OnViewTreeMode)
287 ON_UPDATE_COMMAND_UI(ID_VIEW_TREEMODE, OnUpdateViewTreeMode)
288 ON_COMMAND(ID_VIEW_EXPAND_ALLSUBDIRS, OnViewExpandAllSubdirs)
289 ON_UPDATE_COMMAND_UI(ID_VIEW_EXPAND_ALLSUBDIRS, OnUpdateViewExpandAllSubdirs)
290 ON_COMMAND(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnViewCollapseAllSubdirs)
291 ON_UPDATE_COMMAND_UI(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnUpdateViewCollapseAllSubdirs)
292 ON_COMMAND(ID_SWAPPANES_SWAP12, (OnViewSwapPanes<0, 1>))
293 ON_COMMAND(ID_SWAPPANES_SWAP23, (OnViewSwapPanes<1, 2>))
294 ON_COMMAND(ID_SWAPPANES_SWAP13, (OnViewSwapPanes<0, 2>))
295 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP12, (OnUpdateViewSwapPanes<0, 1>))
296 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP23, (OnUpdateViewSwapPanes<1, 2>))
297 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP13, (OnUpdateViewSwapPanes<0, 2>))
298 ON_COMMAND(ID_VIEW_DIR_STATISTICS, OnViewCompareStatistics)
299 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENT, OnOptionsShowDifferent)
300 ON_COMMAND(ID_OPTIONS_SHOWIDENTICAL, OnOptionsShowIdentical)
301 ON_COMMAND(ID_OPTIONS_SHOWUNIQUELEFT, OnOptionsShowUniqueLeft)
302 ON_COMMAND(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnOptionsShowUniqueMiddle)
303 ON_COMMAND(ID_OPTIONS_SHOWUNIQUERIGHT, OnOptionsShowUniqueRight)
304 ON_COMMAND(ID_OPTIONS_SHOWBINARIES, OnOptionsShowBinaries)
305 ON_COMMAND(ID_OPTIONS_SHOWSKIPPED, OnOptionsShowSkipped)
306 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnOptionsShowDifferentLeftOnly)
307 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnOptionsShowDifferentMiddleOnly)
308 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnOptionsShowDifferentRightOnly)
309 ON_COMMAND(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnOptionsShowMissingLeftOnly)
310 ON_COMMAND(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnOptionsShowMissingMiddleOnly)
311 ON_COMMAND(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnOptionsShowMissingRightOnly)
312 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENT, OnUpdateOptionsShowdifferent)
313 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWIDENTICAL, OnUpdateOptionsShowidentical)
314 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUELEFT, OnUpdateOptionsShowuniqueleft)
315 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnUpdateOptionsShowuniquemiddle)
316 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUERIGHT, OnUpdateOptionsShowuniqueright)
317 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWBINARIES, OnUpdateOptionsShowBinaries)
318 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWSKIPPED, OnUpdateOptionsShowSkipped)
319 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnUpdateOptionsShowDifferentLeftOnly)
320 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnUpdateOptionsShowDifferentMiddleOnly)
321 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnUpdateOptionsShowDifferentRightOnly)
322 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnUpdateOptionsShowMissingLeftOnly)
323 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnUpdateOptionsShowMissingMiddleOnly)
324 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnUpdateOptionsShowMissingRightOnly)
325 ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
326 ON_COMMAND(ID_HELP, OnHelp)
327 ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
328 ON_COMMAND(ID_EDIT_CUT, OnEditCut)
329 ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
330 ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
331 ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
333 ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
334 ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
335 ON_NOTIFY_REFLECT(LVN_BEGINLABELEDIT, OnBeginLabelEdit)
336 ON_NOTIFY_REFLECT(LVN_ENDLABELEDIT, OnEndLabelEdit)
337 ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
338 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
339 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
340 ON_BN_CLICKED(IDC_COMPARISON_STOP, OnBnClickedComparisonStop)
341 ON_BN_CLICKED(IDC_COMPARISON_PAUSE, OnBnClickedComparisonPause)
342 ON_BN_CLICKED(IDC_COMPARISON_CONTINUE, OnBnClickedComparisonContinue)
345 /////////////////////////////////////////////////////////////////////////////
346 // CDirView diagnostics
350 CDirDoc* CDirView::GetDocument() // non-debug version is inline
352 ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDirDoc)));
353 return (CDirDoc*)m_pDocument;
357 /////////////////////////////////////////////////////////////////////////////
358 // CDirView message handlers
360 void CDirView::OnInitialUpdate()
362 const int iconCX = []() {
363 const int cx = GetSystemMetrics(SM_CXSMICON);
372 const int iconCY = iconCX;
373 CListView::OnInitialUpdate();
374 m_pList = &GetListCtrl();
375 m_pIList.reset(new IListCtrlImpl(m_pList->m_hWnd));
376 GetDocument()->SetDirView(this);
377 m_pColItems.reset(new DirViewColItems(GetDocument()->m_nDirs));
379 m_pList->SendMessage(CCM_SETUNICODEFORMAT, TRUE, 0);
381 // Load user-selected font
382 if (GetOptionsMgr()->GetBool(OPT_FONT_DIRCMP + OPT_FONT_USECUSTOM))
384 m_font.CreateFontIndirect(&GetMainFrame()->m_lfDir);
385 CWnd::SetFont(&m_font, TRUE);
389 m_pList->SetBkColor(m_cachedColors.clrDirMargin);
391 // Replace standard header with sort header
392 HWND hWnd = ListView_GetHeader(m_pList->m_hWnd);
394 m_ctlSortHeader.SubclassWindow(hWnd);
396 // Load the icons used for the list view (to reflect diff status)
397 // NOTE: these must be in the exactly the same order as in the `enum`
398 // definition in the DirActions.h file (ref: DIFFIMG_LUNIQUE)
399 VERIFY(m_imageList.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
401 IDI_LFILE, IDI_MFILE, IDI_RFILE,
402 IDI_MRFILE, IDI_LRFILE, IDI_LMFILE,
403 IDI_NOTEQUALFILE, IDI_EQUALFILE, IDI_FILE,
404 IDI_EQUALBINARY, IDI_BINARYDIFF,
405 IDI_LFOLDER, IDI_MFOLDER, IDI_RFOLDER,
406 IDI_MRFOLDER, IDI_LRFOLDER, IDI_LMFOLDER,
407 IDI_FILESKIP, IDI_FOLDERSKIP,
408 IDI_NOTEQUALFOLDER, IDI_EQUALFOLDER, IDI_FOLDER,
410 IDI_FOLDERUP, IDI_FOLDERUP_DISABLE,
412 IDI_NOTEQUALTEXTFILE, IDI_EQUALTEXTFILE,
413 IDI_NOTEQUALIMAGE, IDI_EQUALIMAGE,
415 for (auto id : icon_ids)
416 VERIFY(-1 != m_imageList.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
417 m_pList->SetImageList(&m_imageList, LVSIL_SMALL);
419 // Load the icons used for the list view (expanded/collapsed state icons)
420 VERIFY(m_imageState.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
421 for (auto id : { IDI_TREE_STATE_COLLAPSED, IDI_TREE_STATE_EXPANDED })
422 VERIFY(-1 != m_imageState.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
424 // Restore column orders as they had them last time they ran
425 m_pColItems->LoadColumnOrders(
426 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS));
428 // Display column headers (in appropriate order)
431 // Show selection across entire row.u
432 // Also allow user to rearrange columns via drag&drop of headers.
433 // Also enable infotips.
434 DWORD exstyle = LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_INFOTIP;
435 m_pList->SetExtendedStyle(exstyle);
438 BOOL CDirView::PreCreateWindow(CREATESTRUCT& cs)
440 CListView::PreCreateWindow(cs);
441 cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
446 * @brief Called before compare is started.
447 * CDirDoc calls this function before new compare is started, so this
448 * is good place to setup GUI for compare.
449 * @param [in] pCompareStats Pointer to class having current compare stats.
451 void CDirView::StartCompare(CompareStats *pCompareStats)
453 if (m_pCmpProgressBar == nullptr)
454 m_pCmpProgressBar.reset(new DirCompProgressBar());
456 if (!::IsWindow(m_pCmpProgressBar->GetSafeHwnd()))
457 m_pCmpProgressBar->Create(GetParentFrame());
459 m_pCmpProgressBar->SetCompareStat(pCompareStats);
460 m_pCmpProgressBar->StartUpdating();
462 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), TRUE, FALSE);
464 m_compareStart = clock();
468 * @brief Called when folder compare row is double-clicked with mouse.
469 * Selected item is opened to folder or file compare.
471 void CDirView::OnLButtonDblClk(UINT nFlags, CPoint point)
475 m_pList->SubItemHitTest(&lvhti);
476 if (lvhti.iItem >= 0)
478 const DIFFITEM& di = GetDiffItem(lvhti.iItem);
479 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
481 if (di.customFlags & ViewCustomFlags::EXPANDED)
482 CollapseSubdir(lvhti.iItem);
484 ExpandSubdir(lvhti.iItem);
488 CWaitCursor waitstatus;
492 CListView::OnLButtonDblClk(nFlags, point);
496 * @brief Load or reload the columns (headers) of the list view
498 void CDirView::ReloadColumns()
500 LoadColumnHeaderItems();
503 m_pColItems->LoadColumnWidths(
504 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
505 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
510 * @brief Redisplay items in subfolder
511 * @param [in] diffpos First item position in subfolder.
512 * @param [in] level Indent level
513 * @param [in,out] index Index of the item to be inserted.
514 * @param [in,out] alldiffs Number of different items
516 void CDirView::RedisplayChildren(DIFFITEM *diffpos, int level, UINT &index, int &alldiffs)
518 const CDiffContext &ctxt = GetDiffContext();
519 while (diffpos != nullptr)
521 DIFFITEM *curdiffpos = diffpos;
522 const DIFFITEM &di = ctxt.GetNextSiblingDiffPosition(diffpos);
524 if (di.diffcode.isResultDiff() || (!di.diffcode.existAll() && !di.diffcode.isResultFiltered()))
527 bool bShowable = IsShowable(ctxt, di, m_dirfilter);
532 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, level);
534 if (di.HasChildren())
536 m_pList->SetItemState(index - 1, INDEXTOSTATEIMAGEMASK((di.customFlags & ViewCustomFlags::EXPANDED) ? 2 : 1), LVIS_STATEIMAGEMASK);
537 if (di.customFlags & ViewCustomFlags::EXPANDED)
538 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
543 if (!ctxt.m_bRecursive || !di.diffcode.isDirectory() || !di.diffcode.existAll())
545 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, 0);
548 if (di.HasChildren())
550 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
555 m_firstDiffItem.reset();
556 m_lastDiffItem.reset();
560 * @brief Redisplay folder compare view.
561 * This function clears folder compare view and then adds
562 * items from current compare to it.
564 void CDirView::Redisplay()
566 const CDirDoc *pDoc = GetDocument();
567 const CDiffContext &ctxt = GetDiffContext();
568 PathContext pathsParent;
569 CImageList emptyImageList;
572 // Disable redrawing while adding new items
575 DeleteAllDisplayItems();
577 m_pList->SetImageList((m_bTreeMode && ctxt.m_bRecursive) ? &m_imageState : &emptyImageList, LVSIL_STATE);
579 // If non-recursive compare, add special item(s)
580 if (!ctxt.m_bRecursive ||
581 CheckAllowUpwardDirectory(ctxt, pDoc->m_pTempPathContext, pathsParent) == AllowUpwardDirectory::ParentIsTempPath)
583 cnt += AddSpecialItems();
587 DIFFITEM *diffpos = ctxt.GetFirstDiffPosition();
588 RedisplayChildren(diffpos, 0, cnt, alldiffs);
589 if (pDoc->m_diffThread.GetThreadState() == CDiffThread::THREAD_COMPLETED)
590 GetParentFrame()->SetLastCompareResult(alldiffs);
591 SortColumnsAppropriately();
596 * @brief User right-clicked somewhere in this view
598 void CDirView::OnContextMenu(CWnd*, CPoint point)
600 if (GetListCtrl().GetItemCount() == 0)
602 // Make sure window is active
603 GetParentFrame()->ActivateFrame();
606 if (point.x == -1 && point.y == -1)
608 //keystroke invocation
611 ClientToScreen(rect);
613 point = rect.TopLeft();
618 // Check if user right-clicked on header
619 // convert screen coordinates to client coordinates of listview
620 CPoint insidePt = point;
621 GetListCtrl().ScreenToClient(&insidePt);
622 // TODO: correct for hscroll ?
623 // Ask header control if click was on one of its header items
624 HDHITTESTINFO hhti = { 0 };
626 int col = static_cast<int>(GetListCtrl().GetHeaderCtrl()->SendMessage(HDM_HITTEST, 0, (LPARAM) & hhti));
629 // Presumably hhti.flags & HHT_ONHEADER is true
630 HeaderContextMenu(point, m_pColItems->ColPhysToLog(col));
633 // bail out if point is not in any row
634 LVHITTESTINFO lhti = { 0 };
636 ScreenToClient(&insidePt);
638 i = GetListCtrl().HitTest(insidePt);
639 TRACE(_T("i=%d\n"), i);
644 ListContextMenu(point, i);
648 * @brief Format context menu string and disable item if it cannot be applied.
650 static void NTAPI FormatContextMenu(BCMenu *pPopup, UINT uIDItem, int n1, int n2 = 0, int n3 = 0)
653 pPopup->GetMenuText(uIDItem, s1, MF_BYCOMMAND);
654 s2.FormatMessage(s1, NumToStr(n1).c_str(), NumToStr(n2).c_str(), NumToStr(n3).c_str());
655 pPopup->SetMenuText(uIDItem, s2, MF_BYCOMMAND);
658 pPopup->EnableMenuItem(uIDItem, MF_GRAYED);
663 * @brief Toggle context menu item
665 static void NTAPI CheckContextMenu(BCMenu *pPopup, UINT uIDItem, BOOL bCheck)
668 pPopup->CheckMenuItem(uIDItem, MF_CHECKED);
670 pPopup->CheckMenuItem(uIDItem, MF_UNCHECKED);
674 * @brief User right-clicked in listview rows
676 void CDirView::ListContextMenu(CPoint point, int /*i*/)
678 CDirDoc* pDoc = GetDocument();
680 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
681 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
682 theApp.TranslateMenu(menu.m_hMenu);
684 // 1st submenu of IDR_POPUP_DIRVIEW is for item popup
685 BCMenu *pPopup = static_cast<BCMenu*>(menu.GetSubMenu(0));
686 ASSERT(pPopup != nullptr);
688 if (pDoc->m_nDirs < 3)
690 pPopup->RemoveMenu(ID_DIR_COPY_LEFT_TO_MIDDLE, MF_BYCOMMAND);
691 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_LEFT, MF_BYCOMMAND);
692 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_RIGHT, MF_BYCOMMAND);
693 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
694 pPopup->RemoveMenu(ID_DIR_COPY_RIGHT_TO_MIDDLE, MF_BYCOMMAND);
695 pPopup->RemoveMenu(ID_DIR_MOVE_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
696 pPopup->RemoveMenu(ID_DIR_DEL_MIDDLE, MF_BYCOMMAND);
697 pPopup->RemoveMenu(ID_DIR_DEL_ALL, MF_BYCOMMAND);
698 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE, MF_BYCOMMAND);
700 for (int i = 0; i < pPopup->GetMenuItemCount(); ++i)
702 if (pPopup->GetMenuItemID(i) == ID_DIR_HIDE_FILENAMES)
703 pPopup->RemoveMenu(i + 3, MF_BYPOSITION);
706 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITHEDITOR, MF_BYCOMMAND);
707 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITH, MF_BYCOMMAND);
708 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_MIDDLE, MF_BYCOMMAND);
709 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_ALL, MF_BYCOMMAND);
710 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, MF_BYCOMMAND);
711 pPopup->RemoveMenu(ID_DIR_COPY_ALL_TO_CLIPBOARD, MF_BYCOMMAND);
712 pPopup->RemoveMenu(ID_DIR_ZIP_MIDDLE, MF_BYCOMMAND);
713 pPopup->RemoveMenu(ID_DIR_ZIP_ALL, MF_BYCOMMAND);
714 pPopup->RemoveMenu(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, MF_BYCOMMAND);
715 pPopup->RemoveMenu(ID_MERGE_COMPARE_NONHORIZONTALLY, MF_BYCOMMAND);
719 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_BOTH, MF_BYCOMMAND);
720 pPopup->RemoveMenu(ID_DIR_COPY_BOTH_TO_CLIPBOARD, MF_BYCOMMAND);
721 pPopup->RemoveMenu(ID_DIR_ZIP_BOTH, MF_BYCOMMAND);
722 pPopup->RemoveMenu(ID_DIR_DEL_BOTH, MF_BYCOMMAND);
723 pPopup->RemoveMenu(2, MF_BYPOSITION); // Compare Non-horizontally
726 CMenu menuPluginsHolder;
727 menuPluginsHolder.LoadMenu(IDR_POPUP_PLUGINS_SETTINGS);
728 theApp.TranslateMenu(menuPluginsHolder.m_hMenu);
729 String s = _("Plugin Settings");
730 pPopup->AppendMenu(MF_SEPARATOR);
731 pPopup->AppendMenu(MF_POPUP, static_cast<int>(reinterpret_cast<uintptr_t>(menuPluginsHolder.m_hMenu)), s.c_str());
733 CFrameWnd *pFrame = GetTopLevelFrame();
734 ASSERT(pFrame != nullptr);
735 pFrame->m_bAutoMenuEnable = FALSE;
736 // invoke context menu
737 // this will invoke all the OnUpdate methods to enable/disable the individual items
738 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
741 pFrame->m_bAutoMenuEnable = TRUE;
745 * @brief User right-clicked on specified logical column
747 void CDirView::HeaderContextMenu(CPoint point, int /*i*/)
750 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
751 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
752 theApp.TranslateMenu(menu.m_hMenu);
753 // 2nd submenu of IDR_POPUP_DIRVIEW is for header popup
754 BCMenu* pPopup = static_cast<BCMenu *>(menu.GetSubMenu(1));
755 ASSERT(pPopup != nullptr);
757 // invoke context menu
758 // this will invoke all the OnUpdate methods to enable/disable the individual items
759 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
764 * @brief Gets Explorer's context menu for a group of selected files.
766 * @param [in] Side whether to get context menu for the files from the left or
768 * @retval true menu successfully retrieved.
769 * @retval falsea an error occurred while retrieving the menu.
771 bool CDirView::ListShellContextMenu(SIDE_TYPE stype)
773 CShellContextMenu* shellContextMenu;
776 shellContextMenu = m_pShellContextMenuMiddle.get(); break;
778 shellContextMenu = m_pShellContextMenuRight.get(); break;
780 shellContextMenu = m_pShellContextMenuLeft.get(); break;
782 shellContextMenu->Initialize();
783 ApplyFolderNameAndFileName(SelBegin(), SelEnd(), stype, GetDiffContext(),
784 [&](const String& path, const String& filename) { shellContextMenu->AddItem(path, filename); });
785 return shellContextMenu->RequeryShellContextMenu();
789 * @brief User chose (main menu) Copy from right to left
791 void CDirView::OnDirCopy(UINT id)
793 bool to_right = (id == ID_L2R) ? true : false;
794 if (GetDocument()->m_nDirs < 3)
797 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_RIGHT>, _("Copying files..."));
799 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_LEFT>, _("Copying files..."));
805 switch (m_nActivePane)
808 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_MIDDLE>, _("Copying files..."));
812 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_RIGHT>, _("Copying files..."));
818 switch (m_nActivePane)
822 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_LEFT>, _("Copying files..."));
825 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_MIDDLE>, _("Copying files..."));
832 /// User chose (context men) Copy from right to left
833 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
834 void CDirView::OnCtxtDirCopy()
836 DoDirAction(&DirActions::Copy<srctype, dsttype>, _("Copying files..."));
839 /// User chose (context menu) Copy left to...
840 template<SIDE_TYPE stype>
841 void CDirView::OnCtxtDirCopyTo()
843 DoDirActionTo(stype, &DirActions::CopyTo<stype>, _("Copying files..."));
846 /// Update context menu Copy Right to Left item
847 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
848 void CDirView::OnUpdateCtxtDirCopy(CCmdUI* pCmdUI)
850 DoUpdateDirCopy<srctype, dsttype>(pCmdUI, eContext);
853 /// Update main menu Copy Right to Left item
854 void CDirView::OnUpdateDirCopy(CCmdUI* pCmdUI)
856 bool to_right = pCmdUI->m_nID == ID_L2R ? true : false;
857 if (GetDocument()->m_nDirs < 3)
860 DoUpdateDirCopy<SIDE_LEFT, SIDE_RIGHT>(pCmdUI, eContext);
862 DoUpdateDirCopy<SIDE_RIGHT, SIDE_LEFT>(pCmdUI, eContext);
868 switch (m_nActivePane)
871 DoUpdateDirCopy<SIDE_LEFT, SIDE_MIDDLE>(pCmdUI, eContext);
875 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_RIGHT>(pCmdUI, eContext);
881 switch (m_nActivePane)
885 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_LEFT>(pCmdUI, eContext);
888 DoUpdateDirCopy<SIDE_RIGHT, SIDE_MIDDLE>(pCmdUI, eContext);
895 void CDirView::DoDirAction(DirActions::method_type func, const String& status_message)
897 CWaitCursor waitstatus;
900 // First we build a list of desired actions
901 FileActionScript actionScript;
902 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
903 DirItemWithIndexIterator end;
904 FileActionScript *rsltScript;
905 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
906 ASSERT(rsltScript == &actionScript);
907 // Now we prompt, and execute actions
908 ConfirmAndPerformActions(actionScript);
909 } catch (ContentsChangedException& e) {
910 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
911 } catch (FileOperationException& e) {
912 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
916 void CDirView::DoDirActionTo(SIDE_TYPE stype, DirActions::method_type func, const String& status_message)
919 String startPath(m_lastCopyFolder);
920 String selectfolder_title;
922 if (stype == SIDE_LEFT)
923 selectfolder_title = _("Left side - select destination folder:");
924 else if (stype == SIDE_MIDDLE)
925 selectfolder_title = _("Middle side - select destination folder:");
926 else if (stype == SIDE_RIGHT)
927 selectfolder_title = _("Right side - select destination folder:");
929 if (!SelectFolder(destPath, startPath.c_str(), selectfolder_title))
932 m_lastCopyFolder = destPath;
933 CWaitCursor waitstatus;
936 // First we build a list of desired actions
937 FileActionScript actionScript;
938 actionScript.m_destBase = destPath;
939 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
940 DirItemWithIndexIterator end;
941 FileActionScript *rsltScript;
942 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
943 ASSERT(rsltScript == &actionScript);
944 // Now we prompt, and execute actions
945 ConfirmAndPerformActions(actionScript);
946 } catch (ContentsChangedException& e) {
947 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
951 // Confirm with user, then perform the action list
952 void CDirView::ConfirmAndPerformActions(FileActionScript & actionList)
954 if (actionList.GetActionItemCount() == 0) // Not sure it is possible to get right-click menu without
955 return; // any selected items, but may as well be safe
957 ASSERT(actionList.GetActionItemCount()>0); // Or else the update handler got it wrong
959 // Set parent window so modality is correct and correct window gets focus
961 actionList.SetParentWindow(this->GetSafeHwnd());
964 ConfirmActionList(GetDiffContext(), actionList);
965 } catch (ConfirmationNeededException& e) {
966 ConfirmFolderCopyDlg dlg;
967 dlg.m_caption = e.m_caption;
968 dlg.m_question = e.m_question;
969 dlg.m_fromText = e.m_fromText;
970 dlg.m_toText = e.m_toText;
971 dlg.m_fromPath = e.m_fromPath;
972 dlg.m_toPath = e.m_toPath;
973 INT_PTR ans = dlg.DoModal();
974 if (ans != IDOK && ans != IDYES)
977 PerformActionList(actionList);
981 * @brief Perform an array of actions
982 * @note There can be only COPY or DELETE actions, not both!
984 void CDirView::PerformActionList(FileActionScript & actionScript)
986 // Check option and enable putting deleted items to Recycle Bin
987 if (GetOptionsMgr()->GetBool(OPT_USE_RECYCLE_BIN))
988 actionScript.UseRecycleBin(true);
990 actionScript.UseRecycleBin(false);
992 actionScript.SetParentWindow(GetMainFrame()->GetSafeHwnd());
994 theApp.AddOperation();
995 bool succeeded = actionScript.Run();
997 UpdateAfterFileScript(actionScript);
998 theApp.RemoveOperation();
999 if (!succeeded && !actionScript.IsCanceled())
1000 throw FileOperationException(_T("File operation failed"));
1004 * @brief Update results after running FileActionScript.
1005 * This functions is called after script is finished to update
1006 * results (including UI).
1007 * @param [in] actionlist Script that was run.
1009 void CDirView::UpdateAfterFileScript(FileActionScript & actionList)
1011 bool bItemsRemoved = false;
1012 int curSel = GetFirstSelectedInd();
1013 CDiffContext& ctxt = GetDiffContext();
1014 while (actionList.GetActionItemCount()>0)
1016 // Start handling from tail of list, so removing items
1017 // doesn't invalidate our item indexes.
1018 FileActionItem act = actionList.RemoveTailActionItem();
1020 // Update doc (difflist)
1021 UPDATEITEM_TYPE updatetype = UpdateDiffAfterOperation(act, ctxt, GetDiffItem(act.context));
1022 if (updatetype == UPDATEITEM_REMOVE)
1024 DeleteItem(act.context, true);
1025 bItemsRemoved = true;
1027 else if (updatetype == UPDATEITEM_UPDATE)
1028 UpdateDiffItemStatus(act.context);
1031 // Make sure selection is at sensible place if all selected items
1035 UINT selected = GetSelectedCount();
1040 MoveFocus(0, curSel - 1, selected);
1045 Counts CDirView::Count(DirActions::method_type2 func) const
1047 return ::Count(SelBegin(), SelEnd(), MakeDirActions(func));
1050 /// Should Copy to Left be enabled or disabled ? (both main menu & context menu use this)
1051 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
1052 void CDirView::DoUpdateDirCopy(CCmdUI* pCmdUI, eMenuType menuType)
1054 Counts counts = Count(&DirActions::IsItemCopyableOnTo<srctype, dsttype>);
1055 pCmdUI->Enable(counts.count > 0);
1056 if (menuType == eContext)
1057 pCmdUI->SetText(FormatMenuItemString(srctype, dsttype, counts.count, counts.total).c_str());
1061 * @brief Update any resources necessary after a GUI language change
1063 void CDirView::UpdateResources()
1065 UpdateColumnNames();
1066 GetParentFrame()->UpdateResources();
1070 * @brief User just clicked a column, so perform sort
1072 void CDirView::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
1074 // set sort parameters and handle ascending/descending
1075 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*) pNMHDR;
1076 int oldSortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1077 int sortcol = m_pColItems->ColPhysToLog(pNMListView->iSubItem);
1078 if (sortcol == oldSortColumn)
1081 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1082 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, !bSortAscending);
1086 GetOptionsMgr()->SaveOption((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3, sortcol);
1087 // most columns start off ascending, but not dates
1088 bool bSortAscending = m_pColItems->IsDefaultSortAscending(sortcol);
1089 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, bSortAscending);
1092 SortColumnsAppropriately();
1096 void CDirView::SortColumnsAppropriately()
1098 int sortCol = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1099 if (sortCol == -1 || sortCol >= m_pColItems->GetColCount())
1102 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1103 m_ctlSortHeader.SetSortImage(m_pColItems->ColLogToPhys(sortCol), bSortAscending);
1104 //sort using static CompareFunc comparison function
1105 CompareState cs(&GetDiffContext(), m_pColItems.get(), sortCol, bSortAscending, m_bTreeMode);
1106 GetListCtrl().SortItems(cs.CompareFunc, reinterpret_cast<DWORD_PTR>(&cs));
1108 m_firstDiffItem.reset();
1109 m_lastDiffItem.reset();
1112 /// Do any last minute work as view closes
1113 void CDirView::OnDestroy()
1115 DeleteAllDisplayItems();
1118 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
1119 GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
1122 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
1123 GetOptionsMgr()->SaveOption(keyname,
1124 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)));
1127 CListView::OnDestroy();
1129 GetMainFrame()->ClearStatusbarItemCount();
1133 * @brief Open selected item when user presses ENTER key.
1135 void CDirView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
1137 if (nChar == VK_RETURN)
1139 int sel = GetFocusedItem();
1142 const DIFFITEM& di = GetDiffItem(sel);
1143 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
1145 if (di.customFlags & ViewCustomFlags::EXPANDED)
1146 CollapseSubdir(sel);
1152 CWaitCursor waitstatus;
1157 CListView::OnChar(nChar, nRepCnt, nFlags);
1161 * @brief Expand/collapse subfolder when "+/-" icon is clicked.
1163 void CDirView::OnClick(NMHDR* pNMHDR, LRESULT* pResult)
1165 LPNMITEMACTIVATE pNM = (LPNMITEMACTIVATE)pNMHDR;
1166 LVHITTESTINFO lvhti;
1167 lvhti.pt = pNM->ptAction;
1168 m_pList->SubItemHitTest(&lvhti);
1169 if (lvhti.flags == LVHT_ONITEMSTATEICON)
1171 const DIFFITEM &di = GetDiffItem(pNM->iItem);
1172 if (di.customFlags & ViewCustomFlags::EXPANDED)
1173 CollapseSubdir(pNM->iItem);
1175 ExpandSubdir(pNM->iItem);
1182 * @brief Collapse subfolder
1183 * @param [in] sel Folder item index in listview.
1185 void CDirView::CollapseSubdir(int sel)
1187 DIFFITEM& dip = this->GetDiffItem(sel);
1188 if (!m_bTreeMode || !(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1191 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1193 dip.customFlags &= ~ViewCustomFlags::EXPANDED;
1194 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(1), LVIS_STATEIMAGEMASK);
1196 int count = m_pList->GetItemCount();
1197 for (int i = sel + 1; i < count; i++)
1199 const DIFFITEM& di = GetDiffItem(i);
1200 if (!di.IsAncestor(&dip))
1202 m_pList->DeleteItem(i--);
1206 m_pList->SetRedraw(TRUE); // Turn updating back on
1210 * @brief Expand subfolder
1211 * @param [in] sel Folder item index in listview.
1213 void CDirView::ExpandSubdir(int sel, bool bRecursive)
1215 DIFFITEM& dip = GetDiffItem(sel);
1216 if (!m_bTreeMode || (dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1219 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1220 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(2), LVIS_STATEIMAGEMASK);
1222 CDiffContext &ctxt = GetDiffContext();
1223 dip.customFlags |= ViewCustomFlags::EXPANDED;
1225 ExpandSubdirs(ctxt, dip);
1227 DIFFITEM *diffpos = ctxt.GetFirstChildDiffPosition(GetItemKey(sel));
1228 UINT indext = sel + 1;
1230 RedisplayChildren(diffpos, dip.GetDepth() + 1, indext, alldiffs);
1232 SortColumnsAppropriately();
1234 m_pList->SetRedraw(TRUE); // Turn updating back on
1238 * @brief Open parent folder if possible.
1240 void CDirView::OpenParentDirectory()
1242 CDirDoc *pDoc = GetDocument();
1243 PathContext pathsParent;
1244 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
1246 case AllowUpwardDirectory::ParentIsTempPath:
1247 pDoc->m_pTempPathContext = pDoc->m_pTempPathContext->DeleteHead();
1249 case AllowUpwardDirectory::ParentIsRegularPath:
1251 for (int nIndex = 0; nIndex < pathsParent.GetSize(); ++nIndex)
1252 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nIndex) ? FFILEOPEN_READONLY : 0);
1253 GetMainFrame()->DoFileOpen(&pathsParent, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1255 case AllowUpwardDirectory::No:
1258 LangMessageBox(IDS_INVALID_DIRECTORY, MB_ICONSTOP);
1264 * @brief Get one or two selected items
1266 * Returns false if 0 or more than 3 items selecte
1268 bool CDirView::GetSelectedItems(int * sel1, int * sel2, int * sel3)
1272 *sel1 = m_pList->GetNextItem(-1, LVNI_SELECTED);
1275 *sel2 = m_pList->GetNextItem(*sel1, LVNI_SELECTED);
1278 *sel3 = m_pList->GetNextItem(*sel2, LVNI_SELECTED);
1281 int extra = m_pList->GetNextItem(*sel3, LVNI_SELECTED);
1282 return (extra == -1);
1286 * @brief Open special items (parent folders etc).
1287 * @param [in] pos1 First item position.
1288 * @param [in] pos2 Second item position.
1290 void CDirView::OpenSpecialItems(DIFFITEM *pos1, DIFFITEM *pos2, DIFFITEM *pos3)
1292 if (pos2==nullptr && pos3==nullptr)
1294 // Browse to parent folder(s) selected
1295 // SPECIAL_ITEM_POS is position for
1296 // special items, but there is currenly
1297 // only one (parent folder)
1298 OpenParentDirectory();
1302 // Parent directory & something else selected
1308 * @brief Creates a pairing folder for unique folder item.
1309 * This function creates a pairing folder for unique folder item in
1310 * folder compare. This way user can browse into unique folder's
1311 * contents and don't necessarily need to copy whole folder structure.
1312 * @return true if user agreed and folder was created.
1314 static bool CreateFoldersPair(const PathContext& paths)
1316 bool created = false;
1317 for (const auto& path : paths)
1319 if (!paths::DoesPathExist(path))
1322 strutils::format_string1(
1323 _("The folder exists only in other side and cannot be opened.\n\nDo you want to create a matching folder:\n%1\nto the other side and open these folders?"),
1325 int res = AfxMessageBox(message.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN);
1327 created = paths::CreateIfNeeded(path);
1333 void CDirView::Open(const PathContext& paths, DWORD dwFlags[3], FileTextEncoding encoding[3], PackingInfo * infoUnpacker)
1336 for (auto path : paths)
1338 if (paths::DoesPathExist(path) == paths::IS_EXISTING_DIR)
1341 CDirDoc * pDoc = GetDocument();
1345 // Don't add folders to MRU
1346 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1348 else if (HasZipSupport() && std::count_if(paths.begin(), paths.end(), ArchiveGuessFormat) == paths.GetSize())
1350 // Open archives, not adding paths to MRU
1351 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, nullptr, _T(""), infoUnpacker);
1355 // Regular file case
1357 // Binary attributes are set after files are unpacked
1358 // so after plugins such as the MS-Office plugins have had a chance to make them textual
1359 // We haven't done unpacking yet in this diff, but if a binary flag is already set,
1360 // then it was set in a previous diff after unpacking, so we trust it
1362 // Open identical and different files
1363 FileLocation fileloc[3];
1365 const String sUntitled[] = { _("Untitled left"), paths.GetSize() < 3 ? _("Untitled right") : _("Untitled middle"), _("Untitled right") };
1366 for (int i = 0; i < paths.GetSize(); ++i)
1368 if (paths::DoesPathExist(paths[i]) == paths::DOES_NOT_EXIST)
1369 strDesc[i] = sUntitled[i];
1372 fileloc[i].setPath(paths[i]);
1373 fileloc[i].encoding = encoding[i];
1377 GetMainFrame()->ShowAutoMergeDoc(pDoc, paths.GetSize(), fileloc,
1378 dwFlags, strDesc, _T(""), infoUnpacker);
1383 * @brief Open selected files or directories.
1385 * Opens selected files to file compare. If comparing
1386 * directories non-recursively, then subfolders and parent
1387 * folder are opened too.
1389 * This handles the case that one item is selected
1390 * and the case that two items are selected (one on each side)
1392 void CDirView::OpenSelection(SELECTIONTYPE selectionType /*= SELECTIONTYPE_NORMAL*/, PackingInfo * infoUnpacker /*= nullptr*/, bool openableForDir /*= true*/)
1394 Merge7zFormatMergePluginScope scope(infoUnpacker);
1395 CDirDoc * pDoc = GetDocument();
1396 const CDiffContext& ctxt = GetDiffContext();
1398 // First, figure out what was selected (store into pos1 & pos2)
1399 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1400 int sel1 = -1, sel2 = -1, sel3 = -1;
1401 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1403 // Must have 1 or 2 or 3 items selected
1408 pos1 = GetItemKey(sel1);
1409 ASSERT(pos1 != nullptr);
1412 pos2 = GetItemKey(sel2);
1413 ASSERT(pos2 != nullptr);
1415 pos3 = GetItemKey(sel3);
1418 // Now handle the various cases of what was selected
1420 if (IsDiffItemSpecial(pos1))
1422 OpenSpecialItems(pos1, pos2, pos3);
1426 // Common variables which both code paths below are responsible for setting
1428 const DIFFITEM *pdi[3] = {0}; // left & right items (di1==di2 if single selection)
1429 bool isdir = false; // set if we're comparing directories
1431 FileTextEncoding encoding[3];
1435 success = GetOpenTwoItems(ctxt, selectionType, pos1, pos2, pdi,
1436 paths, sel1, sel2, isdir, nPane, encoding, errmsg, openableForDir);
1437 else if (pos2 && pos3)
1438 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1439 paths, sel1, sel2, sel3, isdir, nPane, encoding, errmsg, openableForDir);
1442 // Only one item selected, so perform diff on its sides
1443 success = GetOpenOneItem(ctxt, pos1, pdi,
1444 paths, sel1, isdir, nPane, encoding, errmsg, openableForDir);
1446 CreateFoldersPair(paths);
1450 if (!errmsg.empty())
1451 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1455 // Now pathLeft, pathRight, di1, di2, and isdir are all set
1456 // We have two items to compare, no matter whether same or different underlying DirView item
1459 for (int nIndex = 0; nIndex < paths.GetSize(); nIndex++)
1460 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[nIndex]) ? FFILEOPEN_READONLY : 0);
1462 Open(paths, dwFlags, encoding, infoUnpacker);
1465 void CDirView::OpenSelectionAs(UINT id)
1467 CDirDoc * pDoc = GetDocument();
1468 const CDiffContext& ctxt = GetDiffContext();
1470 // First, figure out what was selected (store into pos1 & pos2 & pos3)
1471 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1472 int sel1 = -1, sel2 = -1, sel3 = -1;
1473 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1475 // Must have 1 or 2 or 3 items selected
1480 pos1 = GetItemKey(sel1);
1484 pos2 = GetItemKey(sel2);
1485 ASSERT(pos2 != nullptr);
1487 pos3 = GetItemKey(sel3);
1490 // Now handle the various cases of what was selected
1492 if (IsDiffItemSpecial(pos1))
1498 // Common variables which both code paths below are responsible for setting
1500 const DIFFITEM *pdi[3]; // left & right items (di1==di2 if single selection)
1501 bool isdir = false; // set if we're comparing directories
1503 FileTextEncoding encoding[3];
1507 success = GetOpenTwoItems(ctxt, SELECTIONTYPE_NORMAL, pos1, pos2, pdi,
1508 paths, sel1, sel2, isdir, nPane, encoding, errmsg, false);
1509 else if (pos2 && pos3)
1510 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1511 paths, sel1, sel2, sel3, isdir, nPane, encoding, errmsg, false);
1514 // Only one item selected, so perform diff on its sides
1515 success = GetOpenOneItem(ctxt, pos1, pdi,
1516 paths, sel1, isdir, nPane, encoding, errmsg, false);
1520 if (!errmsg.empty())
1521 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1525 // Open identical and different files
1526 const String sUntitled[] = { _("Untitled left"), paths.GetSize() < 3 ? _("Untitled right") : _("Untitled middle"), _("Untitled right") };
1527 DWORD dwFlags[3] = { 0 };
1529 FileLocation fileloc[3];
1530 for (int pane = 0; pane < paths.GetSize(); pane++)
1532 if (paths::DoesPathExist(paths[pane]) == paths::DOES_NOT_EXIST)
1533 strDesc[pane] = sUntitled[pane];
1536 fileloc[pane].setPath(paths[pane]);
1537 fileloc[pane].encoding = encoding[pane];
1539 dwFlags[pane] |= FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[pane]) ? FFILEOPEN_READONLY : 0);
1541 GetMainFrame()->ShowMergeDoc(id, pDoc, paths.GetSize(), fileloc, dwFlags, strDesc);
1544 /// User chose (context menu) delete left
1545 template<SIDE_TYPE stype>
1546 void CDirView::OnCtxtDirDel()
1548 DoDirAction(&DirActions::DeleteOn<stype>, _("Deleting files..."));
1551 /// User chose (context menu) delete both
1552 void CDirView::OnCtxtDirDelBoth()
1554 DoDirAction(&DirActions::DeleteOnBoth, _("Deleting files..."));
1557 /// Enable/disable Delete Left menu choice on context menu
1558 template<SIDE_TYPE stype>
1559 void CDirView::OnUpdateCtxtDirDel(CCmdUI* pCmdUI)
1561 Counts counts = Count(&DirActions::IsItemDeletableOn<stype>);
1562 pCmdUI->Enable(counts.count > 0);
1563 pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1566 /// Enable/disable Delete Both menu choice on context menu
1567 void CDirView::OnUpdateCtxtDirDelBoth(CCmdUI* pCmdUI)
1569 Counts counts = Count(&DirActions::IsItemDeletableOnBoth);
1570 pCmdUI->Enable(counts.count > 0);
1571 pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1575 * @brief Update "Copy | Right to..." item
1577 template<SIDE_TYPE stype>
1578 void CDirView::OnUpdateCtxtDirCopyTo(CCmdUI* pCmdUI)
1580 Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1581 pCmdUI->Enable(counts.count > 0);
1582 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
1585 void CDirView::OnUpdateCtxtDirCopyBothTo(CCmdUI* pCmdUI)
1587 Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1588 pCmdUI->Enable(counts.count > 0);
1589 pCmdUI->SetText(FormatMenuItemStringAllTo(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1592 void CDirView::OnUpdateCtxtDirCopyBothDiffsOnlyTo(CCmdUI* pCmdUI)
1594 Counts counts = Count(&DirActions::IsItemNavigableDiff);
1595 pCmdUI->Enable(counts.count > 0);
1596 pCmdUI->SetText(FormatMenuItemStringDifferencesTo(counts.count, counts.total).c_str());
1600 * @brief Update "Copy | Left/Right/Both " item
1602 template<SIDE_TYPE stype>
1603 void CDirView::OnUpdateCtxtDirCopy2(CCmdUI* pCmdUI)
1605 Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1606 pCmdUI->Enable(counts.count > 0);
1607 pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1610 void CDirView::OnUpdateCtxtDirCopyBoth2(CCmdUI* pCmdUI)
1612 Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1613 pCmdUI->Enable(counts.count > 0);
1614 pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1618 * @brief Get keydata associated with item in given index.
1619 * @param [in] idx Item's index to list in UI.
1620 * @return Key for item in given index.
1622 DIFFITEM *CDirView::GetItemKey(int idx) const
1624 return (DIFFITEM *) m_pList->GetItemData(idx);
1627 // SetItemKey & GetItemKey encapsulate how the display list items
1628 // are mapped to DiffItems, which in turn are DiffContext keys to the actual DIFFITEM data
1631 * @brief Get DIFFITEM data for item.
1632 * This function returns DIFFITEM data for item in given index in GUI.
1633 * @param [in] sel Item's index in folder compare GUI list.
1634 * @return DIFFITEM for item.
1636 const DIFFITEM &CDirView::GetDiffItem(int sel) const
1638 CDirView * pDirView = const_cast<CDirView *>(this);
1639 return pDirView->GetDiffItem(sel);
1643 * Given index in list control, get modifiable reference to its DIFFITEM data
1645 DIFFITEM &CDirView::GetDiffItem(int sel)
1647 DIFFITEM *diffpos = GetItemKey(sel);
1649 // If it is special item, return empty DIFFITEM
1650 if (IsDiffItemSpecial(diffpos))
1652 return *DIFFITEM::GetEmptyItem();
1654 return GetDiffContext().GetDiffRefAt(diffpos);
1657 void CDirView::DeleteItem(int sel, bool removeDIFFITEM)
1659 DIFFITEM *diffpos = GetItemKey(sel);
1660 if (IsDiffItemSpecial(diffpos))
1664 CollapseSubdir(sel);
1665 m_pList->DeleteItem(sel);
1667 else if (GetDiffContext().m_bRecursive || diffpos->HasChildren())
1670 for (it = RevBegin(); it != RevEnd(); )
1673 int cursel = it.m_sel;
1675 if (di.IsAncestor(diffpos) || diffpos == &di)
1676 m_pList->DeleteItem(cursel);
1681 m_pList->DeleteItem(sel);
1685 if (diffpos->HasChildren())
1686 diffpos->RemoveChildren();
1687 diffpos->DelinkFromSiblings();
1691 m_firstDiffItem.reset();
1692 m_lastDiffItem.reset();
1695 void CDirView::DeleteAllDisplayItems()
1697 // item data are just positions (diffposes)
1698 // that is, they contain no memory needing to be freed
1699 m_pList->DeleteAllItems();
1701 m_firstDiffItem.reset();
1702 m_lastDiffItem.reset();
1706 * @brief Given key, get index of item which has it stored.
1707 * This function searches from list in UI.
1709 int CDirView::GetItemIndex(DIFFITEM *key)
1711 LVFINDINFO findInfo;
1713 findInfo.flags = LVFI_PARAM; // Search for itemdata
1714 findInfo.lParam = (LPARAM)key;
1715 return m_pList->FindItem(&findInfo);
1719 * @brief Get the file names on both sides for specified item.
1720 * @note Return empty strings if item is special item.
1722 void CDirView::GetItemFileNames(int sel, String& strLeft, String& strRight) const
1724 DIFFITEM *diffpos = GetItemKey(sel);
1725 if (IsDiffItemSpecial(diffpos))
1732 const CDiffContext& ctxt = GetDiffContext();
1733 ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos), strLeft, strRight);
1738 * @brief Get the file names on both sides for specified item.
1739 * @note Return empty strings if item is special item.
1741 void CDirView::GetItemFileNames(int sel, PathContext * paths) const
1743 DIFFITEM *diffpos = GetItemKey(sel);
1744 if (IsDiffItemSpecial(diffpos))
1746 for (int nIndex = 0; nIndex < GetDocument()->m_nDirs; nIndex++)
1747 paths->SetPath(nIndex, _T(""));
1751 const CDiffContext& ctxt = GetDiffContext();
1752 *paths = ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos));
1757 * @brief Open selected file with registered application.
1758 * Uses shell file associations to open file with registered
1759 * application. We first try to use "Edit" action which should
1760 * open file to editor, since we are more interested editing
1761 * files than running them (scripts).
1762 * @param [in] stype Side of file to open.
1764 void CDirView::DoOpen(SIDE_TYPE stype)
1766 int sel = GetSingleSelectedItem();
1767 if (sel == -1) return;
1768 DirItemIterator dirBegin = SelBegin();
1769 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1770 if (file.empty()) return;
1771 shell::Edit(file.c_str());
1774 /// Open with dialog for file on selected side
1775 void CDirView::DoOpenWith(SIDE_TYPE stype)
1777 int sel = GetSingleSelectedItem();
1778 if (sel == -1) return;
1779 DirItemIterator dirBegin = SelBegin();
1780 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1781 if (file.empty()) return;
1782 shell::OpenWith(file.c_str());
1785 /// Open selected file on specified side to external editor
1786 void CDirView::DoOpenWithEditor(SIDE_TYPE stype)
1788 int sel = GetSingleSelectedItem();
1789 if (sel == -1) return;
1790 DirItemIterator dirBegin = SelBegin();
1791 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1792 if (file.empty()) return;
1794 CMergeApp::OpenFileToExternalEditor(file);
1797 void CDirView::DoOpenParentFolder(SIDE_TYPE stype)
1799 int sel = GetSingleSelectedItem();
1800 if (sel == -1) return;
1801 DirItemIterator dirBegin = SelBegin();
1802 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1803 if (file.empty()) return;
1804 shell::OpenParentFolder(file.c_str());
1807 /// User chose (context menu) open left
1808 template<SIDE_TYPE stype>
1809 void CDirView::OnCtxtDirOpen()
1814 /// User chose (context menu) open left with
1815 template<SIDE_TYPE stype>
1816 void CDirView::OnCtxtDirOpenWith()
1821 /// User chose (context menu) open left with editor
1822 template<SIDE_TYPE stype>
1823 void CDirView::OnCtxtDirOpenWithEditor()
1825 DoOpenWithEditor(stype);
1828 /// User chose (context menu) open left parent folder
1829 template<SIDE_TYPE stype>
1830 void CDirView::OnCtxtDirOpenParentFolder()
1832 DoOpenParentFolder(stype);
1835 /// Update context menuitem "Open left | with editor"
1836 template<SIDE_TYPE stype>
1837 void CDirView::OnUpdateCtxtDirOpenWithEditor(CCmdUI* pCmdUI)
1839 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1840 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1843 // return selected item index, or -1 if none or multiple
1844 int CDirView::GetSingleSelectedItem() const
1846 int sel = -1, sel2 = -1;
1847 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
1848 if (sel == -1) return -1;
1849 sel2 = m_pList->GetNextItem(sel, LVNI_SELECTED);
1850 if (sel2 != -1) return -1;
1853 // Enable/disable Open Left menu choice on context menu
1854 template<SIDE_TYPE stype>
1855 void CDirView::OnUpdateCtxtDirOpen(CCmdUI* pCmdUI)
1857 Counts counts = Count(&DirActions::IsItemOpenableOn<stype>);
1858 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1861 // Enable/disable Open Left With menu choice on context menu
1862 template<SIDE_TYPE stype>
1863 void CDirView::OnUpdateCtxtDirOpenWith(CCmdUI* pCmdUI)
1865 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1866 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1869 // Enable/disable Open Parent Folder menu choice on context menu
1870 template<SIDE_TYPE stype>
1871 void CDirView::OnUpdateCtxtDirOpenParentFolder(CCmdUI* pCmdUI)
1873 Counts counts = Count(&DirActions::IsParentFolderOpenable<stype>);
1874 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1878 void CDirView::DoUpdateOpen(SELECTIONTYPE selectionType, CCmdUI* pCmdUI, bool openableForDir /*= true*/)
1880 int sel1 = -1, sel2 = -1, sel3 = -1;
1881 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1883 // 0 items or more than 2 items seleted
1884 pCmdUI->Enable(FALSE);
1889 // One item selected
1890 if (selectionType != SELECTIONTYPE_NORMAL)
1892 pCmdUI->Enable(FALSE);
1895 if (!openableForDir)
1897 const DIFFITEM& di1 = GetDiffItem(sel1);
1898 if (di1.diffcode.isDirectory() || IsDiffItemSpecial(GetItemKey(sel1)))
1900 pCmdUI->Enable(FALSE);
1905 else if (sel3 == -1)
1907 // Two items selected
1908 const DIFFITEM& di1 = GetDiffItem(sel1);
1909 const DIFFITEM& di2 = GetDiffItem(sel2);
1910 if (!AreItemsOpenable(GetDiffContext(), selectionType, di1, di2, openableForDir))
1912 pCmdUI->Enable(FALSE);
1918 // Three items selected
1919 const DIFFITEM& di1 = GetDiffItem(sel1);
1920 const DIFFITEM& di2 = GetDiffItem(sel2);
1921 const DIFFITEM& di3 = GetDiffItem(sel3);
1922 if (selectionType != SELECTIONTYPE_NORMAL || !::AreItemsOpenable(GetDiffContext(), di1, di2, di3, openableForDir))
1924 pCmdUI->Enable(FALSE);
1928 pCmdUI->Enable(TRUE);
1932 * @brief Return count of selected items in folder compare.
1934 UINT CDirView::GetSelectedCount() const
1936 return m_pList->GetSelectedCount();
1940 * @brief Return index of first selected item in folder compare.
1942 int CDirView::GetFirstSelectedInd()
1944 return m_pList->GetNextItem(-1, LVNI_SELECTED);
1948 // If none or one item selected select found item
1949 // This is used for scrolling to first diff too
1950 void CDirView::OnFirstdiff()
1952 DirItemIterator it =
1953 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1955 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1958 void CDirView::OnUpdateFirstdiff(CCmdUI* pCmdUI)
1960 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1964 // If none or one item selected select found item
1965 void CDirView::OnLastdiff()
1967 DirItemIterator it =
1968 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1970 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1973 void CDirView::OnUpdateLastdiff(CCmdUI* pCmdUI)
1975 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1978 bool CDirView::HasNextDiff()
1980 int lastDiff = GetLastDifferentItem();
1982 // Check if different files were found and
1983 // there is different item after focused item
1984 return (lastDiff > -1) && (GetFocusedItem() < lastDiff);
1987 bool CDirView::HasPrevDiff()
1989 int firstDiff = GetFirstDifferentItem();
1991 // Check if different files were found and
1992 // there is different item before focused item
1993 return (firstDiff > -1) && (firstDiff < GetFocusedItem());
1996 void CDirView::MoveToNextDiff()
1998 int currentInd = GetFocusedItem();
1999 DirItemIterator begin(m_pIList.get(), currentInd + 1);
2000 DirItemIterator it =
2001 std::find_if(begin, End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2003 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2006 void CDirView::MoveToPrevDiff()
2008 int currentInd = GetFocusedItem();
2009 if (currentInd <= 0)
2011 DirItemIterator begin(m_pIList.get(), currentInd - 1, false, true);
2012 DirItemIterator it =
2013 std::find_if(begin, RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2015 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2018 void CDirView::OpenNextDiff()
2021 int currentInd = GetFocusedItem();
2022 const DIFFITEM& dip = GetDiffItem(currentInd);
2023 if (!dip.diffcode.isDirectory())
2029 GetParentFrame()->ActivateFrame();
2033 void CDirView::OpenPrevDiff()
2036 int currentInd = GetFocusedItem();
2037 const DIFFITEM& dip = GetDiffItem(currentInd);
2038 if (!dip.diffcode.isDirectory())
2044 GetParentFrame()->ActivateFrame();
2048 void CDirView::OpenFirstFile()
2050 int currentInd = GetFocusedItem();
2051 int firstFileInd = 0;
2053 while (firstFileInd <= currentInd)
2055 DIFFITEM& dip = GetDiffItem(firstFileInd);
2056 if (!dip.diffcode.isDirectory())
2058 MoveFocus(currentInd, firstFileInd, 1);
2066 bool CDirView::IsFirstFile()
2068 int currentInd = GetFocusedItem();
2069 int firstFileInd = 0;
2070 while (firstFileInd <= currentInd)
2072 DIFFITEM& dip = GetDiffItem(firstFileInd);
2073 if (!dip.diffcode.isDirectory())
2075 if (currentInd == firstFileInd)
2085 void CDirView::OpenLastFile()
2087 const int count = m_pList->GetItemCount();
2088 int currentInd = GetFocusedItem();
2089 int lastFileInd = count - 1;
2091 while (lastFileInd >= 0)
2093 DIFFITEM& dip = GetDiffItem(lastFileInd);
2094 if (!dip.diffcode.isDirectory())
2096 MoveFocus(currentInd, lastFileInd, 1);
2104 bool CDirView::IsLastFile()
2106 const int count = m_pList->GetItemCount();
2107 int currentInd = GetFocusedItem();
2108 int lastFileInd = count - 1;
2109 while (lastFileInd >= currentInd)
2111 DIFFITEM& dip = GetDiffItem(lastFileInd);
2112 if (!dip.diffcode.isDirectory())
2114 if (currentInd == lastFileInd)
2124 void CDirView::OpenNextFile()
2126 const int count = m_pList->GetItemCount();
2127 int currentInd = GetFocusedItem();
2128 int nextInd = currentInd + 1;
2129 if (currentInd >= 0)
2131 while (nextInd < count)
2133 DIFFITEM& dip = GetDiffItem(nextInd);
2134 MoveFocus(nextInd - 1, nextInd, 1);
2135 if (!dip.diffcode.isDirectory())
2145 void CDirView::OpenPrevFile()
2147 int currentInd = GetFocusedItem();
2148 int prevInd = currentInd - 1;
2149 if (currentInd >= 0)
2151 while (prevInd >= 0)
2153 DIFFITEM& dip = GetDiffItem(prevInd);
2154 MoveFocus(prevInd + 1, prevInd, 1);
2155 if (!dip.diffcode.isDirectory())
2165 void CDirView::SetActivePane(int pane)
2167 if (m_nActivePane >= 0)
2168 GetParentFrame()->GetHeaderInterface()->SetActive(m_nActivePane, false);
2169 GetParentFrame()->GetHeaderInterface()->SetActive(pane, true);
2170 m_nActivePane = pane;
2174 // If none or one item selected select found item
2175 void CDirView::OnNextdiff()
2181 void CDirView::OnUpdateNextdiff(CCmdUI* pCmdUI)
2183 pCmdUI->Enable(HasNextDiff());
2187 // If none or one item selected select found item
2188 void CDirView::OnPrevdiff()
2194 void CDirView::OnUpdatePrevdiff(CCmdUI* pCmdUI)
2196 pCmdUI->Enable(HasPrevDiff());
2199 void CDirView::OnCurdiff()
2201 const int count = m_pList->GetItemCount();
2203 int i = GetFirstSelectedInd();
2205 // No selection - no diff to go
2209 while (i < count && !found)
2211 UINT selected = m_pList->GetItemState(i, LVIS_SELECTED);
2212 UINT focused = m_pList->GetItemState(i, LVIS_FOCUSED);
2214 if (selected == LVIS_SELECTED && focused == LVIS_FOCUSED)
2216 m_pList->EnsureVisible(i, FALSE);
2223 void CDirView::OnUpdateCurdiff(CCmdUI* pCmdUI)
2225 pCmdUI->Enable(GetFirstSelectedInd() > -1);
2228 int CDirView::GetFocusedItem()
2230 return m_pList->GetNextItem(-1, LVNI_FOCUSED);
2233 int CDirView::GetFirstDifferentItem()
2235 if (!m_firstDiffItem.has_value())
2237 DirItemIterator it =
2238 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2239 m_firstDiffItem = it.m_sel;
2241 return m_firstDiffItem.value();
2244 int CDirView::GetLastDifferentItem()
2246 if (!m_lastDiffItem.has_value())
2248 DirItemIterator it =
2249 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2250 m_lastDiffItem = it.m_sel;
2252 return m_lastDiffItem.value();
2256 * @brief Move focus to specified item (and selection if multiple items not selected)
2258 * Moves the focus from item [currentInd] to item [i]
2259 * Additionally, if there are not multiple items selected,
2260 * deselects item [currentInd] and selects item [i]
2262 void CDirView::MoveFocus(int currentInd, int i, int selCount)
2266 // Not multiple items selected, so bring selection with us
2267 m_pList->SetItemState(currentInd, 0, LVIS_SELECTED);
2268 m_pList->SetItemState(currentInd, 0, LVIS_FOCUSED);
2269 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2272 // Move focus to specified item
2273 // (this automatically defocuses old item)
2274 m_pList->SetItemState(i, LVIS_FOCUSED, LVIS_FOCUSED);
2275 m_pList->EnsureVisible(i, FALSE);
2278 void CDirView::OnUpdateSave(CCmdUI* pCmdUI)
2280 pCmdUI->Enable(FALSE);
2283 CDirFrame * CDirView::GetParentFrame()
2285 // can't verify cast without introducing more coupling
2286 // (CDirView doesn't include DirFrame.h)
2287 return static_cast<CDirFrame *>(CListView::GetParentFrame());
2290 void CDirView::OnRefresh()
2292 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
2293 GetDocument()->Rescan();
2296 BOOL CDirView::PreTranslateMessage(MSG* pMsg)
2298 // Handle special shortcuts here
2299 if (pMsg->message == WM_KEYDOWN)
2303 // Check if we got 'ESC pressed' -message
2304 if (pMsg->wParam == VK_ESCAPE)
2306 if (m_pCmpProgressBar != nullptr)
2308 OnBnClickedComparisonStop();
2312 if (m_nEscCloses != 0)
2314 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_CLOSE);
2318 // Check if we got 'DEL pressed' -message
2319 if (pMsg->wParam == VK_DELETE)
2321 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_MERGE_DELETE);
2324 int sel = GetFocusedItem();
2325 // Check if we got 'Backspace pressed' -message
2326 if (pMsg->wParam == VK_BACK)
2328 if (!GetDiffContext().m_bRecursive)
2330 OpenParentDirectory();
2333 else if (m_bTreeMode && sel >= 0)
2335 const DIFFITEM& di = GetDiffItem(sel);
2336 assert(di.HasParent());
2339 int i = GetItemIndex(di.GetParentLink());
2341 MoveFocus(sel, i, GetSelectedCount());
2347 DIFFITEM& dip = this->GetDiffItem(sel);
2348 if (pMsg->wParam == VK_LEFT)
2350 if (m_bTreeMode && GetDiffContext().m_bRecursive && (!(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren()))
2351 PostMessage(WM_KEYDOWN, VK_BACK);
2353 CollapseSubdir(sel);
2356 if (pMsg->wParam == VK_SUBTRACT)
2358 CollapseSubdir(sel);
2361 if (pMsg->wParam == VK_RIGHT)
2363 if (m_bTreeMode && GetDiffContext().m_bRecursive && dip.customFlags & ViewCustomFlags::EXPANDED && dip.HasChildren())
2364 PostMessage(WM_KEYDOWN, VK_DOWN);
2369 if (pMsg->wParam == VK_ADD)
2374 if (pMsg->wParam == VK_MULTIPLY)
2376 ExpandSubdir(sel, true);
2383 // ESC doesn't close window when user is renaming an item.
2384 if (pMsg->wParam == VK_ESCAPE)
2386 m_bUserCancelEdit = true;
2388 // The edit control send LVN_ENDLABELEDIT when it loses focus,
2389 // so we use it to cancel the rename action.
2390 m_pList->SetFocus();
2392 // Stop the ESC before it reach the main frame which might
2393 // cause a program termination.
2398 return CListView::PreTranslateMessage(pMsg);
2401 void CDirView::OnUpdateRefresh(CCmdUI* pCmdUI)
2403 UINT threadState = GetDocument()->m_diffThread.GetThreadState();
2404 pCmdUI->Enable(threadState != CDiffThread::THREAD_COMPARING);
2408 * @brief Called when compare thread asks UI update.
2409 * @note Currently thread asks update after compare is ready
2412 LRESULT CDirView::OnUpdateUIMessage(WPARAM wParam, LPARAM lParam)
2414 UNREFERENCED_PARAMETER(lParam);
2416 CDirDoc * pDoc = GetDocument();
2417 ASSERT(pDoc != nullptr);
2419 if (wParam == CDiffThread::EVENT_COMPARE_COMPLETED)
2421 // Close and destroy the dialog after compare
2422 if (m_pCmpProgressBar != nullptr)
2423 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), FALSE, FALSE);
2424 m_pCmpProgressBar.reset();
2426 pDoc->CompareReady();
2428 if (!pDoc->GetGeneratingReport())
2431 if (!pDoc->GetReportFile().empty())
2433 OnToolsGenerateReport();
2434 pDoc->SetReportFile(_T(""));
2437 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST))
2442 // If compare took more than TimeToSignalCompare seconds, notify user
2443 clock_t elapsed = clock() - m_compareStart;
2444 GetParentFrame()->SetStatus(
2445 strutils::format(_("Elapsed time: %ld ms"), elapsed).c_str()
2447 if (elapsed > TimeToSignalCompare * CLOCKS_PER_SEC)
2449 GetMainFrame()->StartFlashing();
2451 else if (wParam == CDiffThread::EVENT_COMPARE_PROGRESSED)
2453 InvalidateRect(nullptr, FALSE);
2455 else if (wParam == CDiffThread::EVENT_COLLECT_COMPLETED)
2457 if (m_pSavedTreeState != nullptr)
2459 RestoreTreeState(GetDiffContext(), m_pSavedTreeState.get());
2460 m_pSavedTreeState.reset();
2465 if (m_bExpandSubdirs)
2466 OnViewExpandAllSubdirs();
2472 return 0; // return value unused
2476 BOOL CDirView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2478 NMHDR * hdr = reinterpret_cast<NMHDR *>(lParam);
2479 if (hdr->code == HDN_ENDDRAG)
2480 return OnHeaderEndDrag((LPNMHEADER)hdr, pResult);
2481 if (hdr->code == HDN_BEGINDRAG)
2482 return OnHeaderBeginDrag((LPNMHEADER)hdr, pResult);
2484 return CListView::OnNotify(wParam, lParam, pResult);
2487 BOOL CDirView::OnChildNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2489 if (uMsg == WM_NOTIFY)
2491 NMHDR *pNMHDR = (NMHDR *)lParam;
2492 switch (pNMHDR->code)
2494 case LVN_GETDISPINFO:
2495 ReflectGetdispinfo((NMLVDISPINFO *)lParam);
2497 case LVN_GETINFOTIPW:
2498 case LVN_GETINFOTIPA:
2502 return CListView::OnChildNotify(uMsg, wParam, lParam, pResult);
2506 * @brief User is starting to drag a column header
2508 bool CDirView::OnHeaderBeginDrag(LPNMHEADER hdr, LRESULT* pResult)
2510 // save column widths before user reorders them
2511 // so we can reload them on the end drag
2512 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
2513 GetOptionsMgr()->SaveOption(keyname,
2514 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)).c_str());
2519 * @brief User just finished dragging a column header
2521 bool CDirView::OnHeaderEndDrag(LPNMHEADER hdr, LRESULT* pResult)
2523 int src = hdr->iItem;
2524 int dest = hdr->pitem->iOrder;
2525 bool allowDrop = true;
2526 *pResult = allowDrop ? FALSE : TRUE;
2527 if (allowDrop && src != dest && dest != -1)
2529 m_pColItems->MoveColumn(src, dest);
2536 * @brief Remove any windows reordering of columns
2538 void CDirView::FixReordering()
2541 lvcol.mask = LVCF_ORDER;
2544 lvcol.pszText = nullptr;
2546 for (int i = 0; i < m_pColItems->GetColCount(); ++i)
2549 GetListCtrl().SetColumn(i, &lvcol);
2553 /** @brief Add columns to display, loading width & order from registry. */
2554 void CDirView::LoadColumnHeaderItems()
2556 bool dummyflag = false;
2558 CHeaderCtrl * h = m_pList->GetHeaderCtrl();
2559 if (h->GetItemCount())
2562 while (m_pList->GetHeaderCtrl()->GetItemCount() > 1)
2563 m_pList->DeleteColumn(1);
2566 for (int i = 0; i < m_pColItems->GetDispColCount(); ++i)
2569 lvc.mask = LVCF_FMT + LVCF_SUBITEM + LVCF_TEXT;
2570 lvc.fmt = LVCFMT_LEFT;
2572 lvc.pszText = _T("text");
2574 m_pList->InsertColumn(i, &lvc);
2577 m_pList->DeleteColumn(1);
2581 void CDirView::SetFont(const LOGFONT & lf)
2583 m_font.DeleteObject();
2584 m_font.CreateFontIndirect(&lf);
2585 CWnd::SetFont(&m_font);
2588 /** @brief Fire off a resort of the data, to take place when things stabilize. */
2589 void CDirView::InitiateSort()
2591 PostMessage(WM_TIMER, COLUMN_REORDER);
2594 void CDirView::OnTimer(UINT_PTR nIDEvent)
2596 if (nIDEvent == COLUMN_REORDER)
2598 // Remove the windows reordering, as we're doing it ourselves
2600 // Now redraw screen
2601 UpdateColumnNames();
2602 m_pColItems->LoadColumnWidths(
2603 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
2604 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
2607 else if (nIDEvent == STATUSBAR_UPDATE)
2609 KillTimer(STATUSBAR_UPDATE);
2610 int items = GetSelectedCount();
2611 String msg = (items == 1) ? _("1 item selected") : strutils::format_string1(_("%1 items selected"), strutils::to_str(items));
2612 GetParentFrame()->SetStatus(msg.c_str());
2615 CListView::OnTimer(nIDEvent);
2619 * @brief Change left-side readonly-status
2621 template<SIDE_TYPE stype>
2622 void CDirView::OnReadOnly()
2624 const int index = SideToIndex(GetDiffContext(), stype);
2625 bool bReadOnly = GetDocument()->GetReadOnly(index);
2626 GetDocument()->SetReadOnly(index, !bReadOnly);
2630 * @brief Update left-readonly menu item
2632 template<SIDE_TYPE stype>
2633 void CDirView::OnUpdateReadOnly(CCmdUI* pCmdUI)
2635 const int index = SideToIndex(GetDiffContext(), stype);
2636 bool bReadOnly = GetDocument()->GetReadOnly(index);
2637 if (stype != SIDE_MIDDLE)
2639 pCmdUI->Enable(TRUE);
2640 pCmdUI->SetCheck(bReadOnly);
2644 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
2645 pCmdUI->SetCheck(bReadOnly && GetDocument()->m_nDirs > 2);
2650 * @brief Update left-side readonly statusbar item
2652 void CDirView::OnUpdateStatusLeftRO(CCmdUI* pCmdUI)
2654 bool bROLeft = GetDocument()->GetReadOnly(0);
2655 pCmdUI->Enable(bROLeft);
2659 * @brief Update middle readonly statusbar item
2661 void CDirView::OnUpdateStatusMiddleRO(CCmdUI* pCmdUI)
2663 bool bROMiddle = GetDocument()->GetReadOnly(1);
2664 pCmdUI->Enable(bROMiddle && GetDocument()->m_nDirs > 2);
2668 * @brief Update right-side readonly statusbar item
2670 void CDirView::OnUpdateStatusRightRO(CCmdUI* pCmdUI)
2672 bool bRORight = GetDocument()->GetReadOnly(GetDocument()->m_nDirs - 1);
2673 pCmdUI->Enable(bRORight);
2677 * @brief Open dialog to customize dirview columns
2679 void CDirView::OnCustomizeColumns()
2681 // Located in DirViewColHandler.cpp
2683 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
2684 GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
2687 void CDirView::OnCtxtOpenWithUnpacker()
2690 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2693 // let the user choose a handler
2694 CSelectUnpackerDlg dlg(GetDiffItem(sel).diffFileInfo[0].filename, this);
2695 // create now a new infoUnpacker to initialize the manual/automatic flag
2696 PackingInfo infoUnpacker(PLUGIN_MODE::PLUGIN_AUTO);
2697 dlg.SetInitialInfoHandler(&infoUnpacker);
2699 if (dlg.DoModal() == IDOK)
2701 infoUnpacker = dlg.GetInfoHandler();
2702 OpenSelection(SELECTIONTYPE_NORMAL, &infoUnpacker, false);
2708 void CDirView::OnUpdateCtxtOpenWithUnpacker(CCmdUI* pCmdUI)
2710 if (!GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
2712 pCmdUI->Enable(FALSE);
2716 // we need one selected file, existing on both side
2717 if (m_pList->GetSelectedCount() != 1)
2718 pCmdUI->Enable(FALSE);
2722 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2723 const DIFFITEM& di = GetDiffItem(sel);
2724 if (di.diffcode.isDirectory())
2726 pCmdUI->Enable(FALSE);
2729 pCmdUI->Enable(IsItemDeletableOnBoth(GetDiffContext(), di));
2734 * @brief Fill string list with current dirview column registry key names
2736 std::vector<String> CDirView::GetCurrentColRegKeys()
2738 std::vector<String> colKeys;
2739 int nphyscols = GetListCtrl().GetHeaderCtrl()->GetItemCount();
2740 for (int col = 0; col < nphyscols; ++col)
2742 int logcol = m_pColItems->ColPhysToLog(col);
2743 colKeys.push_back(m_pColItems->GetColRegValueNameBase(logcol));
2748 struct FileCmpReport: public IFileCmpReport
2750 explicit FileCmpReport(CDirView *pDirView) : m_pDirView(pDirView) {}
2751 ~FileCmpReport() override {}
2752 bool operator()(REPORT_TYPE nReportType, IListCtrl *pList, int nIndex, const String &sDestDir, String &sLinkPath) override
2754 const CDiffContext& ctxt = m_pDirView->GetDiffContext();
2755 const DIFFITEM &di = m_pDirView->GetDiffItem(nIndex);
2757 String sLinkFullPath = paths::ConcatPath(ctxt.GetLeftPath(), di.diffFileInfo[0].GetFile());
2759 if (di.diffcode.isDirectory() || !IsItemNavigableDiff(ctxt, di) || IsArchiveFile(sLinkFullPath))
2765 sLinkPath = di.diffFileInfo[0].GetFile();
2767 strutils::replace(sLinkPath, _T("\\"), _T("_"));
2768 sLinkPath += _T(".html");
2769 String sReportPath = paths::ConcatPath(sDestDir, sLinkPath);
2770 bool completed = false;
2772 m_pDirView->MoveFocus(m_pDirView->GetFirstSelectedInd(), nIndex, m_pDirView->GetSelectedCount());
2773 m_pDirView->PostMessage(MSG_GENERATE_FLIE_COMPARE_REPORT,
2774 reinterpret_cast<WPARAM>(sReportPath.c_str()),
2775 reinterpret_cast<LPARAM>(&completed));
2780 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2782 if (!AfxGetApp()->PumpMessage())
2792 CDirView *m_pDirView;
2795 LRESULT CDirView::OnGenerateFileCmpReport(WPARAM wParam, LPARAM lParam)
2799 auto *pReportFileName = reinterpret_cast<const TCHAR *>(wParam);
2800 bool *pCompleted = reinterpret_cast<bool *>(lParam);
2801 if (IMergeDoc * pMergeDoc = GetMainFrame()->GetActiveIMergeDoc())
2803 pMergeDoc->GenerateReport(pReportFileName);
2804 pMergeDoc->CloseNow();
2807 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2808 if (!AfxGetApp()->PumpMessage())
2810 GetMainFrame()->OnUpdateFrameTitle(FALSE);
2816 * @brief Generate report from dir compare results.
2818 void CDirView::OnToolsGenerateReport()
2820 CDirDoc *pDoc = GetDocument();
2821 DirCmpReportDlg dlg;
2823 dlg.m_sReportFile = pDoc->GetReportFile();
2824 if (dlg.m_sReportFile.empty() && dlg.DoModal() != IDOK)
2827 pDoc->SetGeneratingReport(true);
2828 const CDiffContext& ctxt = GetDiffContext();
2830 PathContext paths = ctxt.GetNormalizedPaths();
2832 // If inside archive, convert paths
2833 if (pDoc->IsArchiveFolders())
2835 for (int i = 0; i < paths.GetSize(); i++)
2836 pDoc->ApplyDisplayRoot(i, paths[i]);
2839 DirCmpReport *pReport = new DirCmpReport(GetCurrentColRegKeys());
2840 pReport->SetRootPaths(paths);
2841 pReport->SetColumns(m_pColItems->GetDispColCount());
2842 pReport->SetFileCmpReport(new FileCmpReport(this));
2843 pReport->SetList(new IListCtrlImpl(m_pList->m_hWnd));
2844 pReport->SetReportType(dlg.m_nReportType);
2845 pReport->SetReportFile(dlg.m_sReportFile);
2846 pReport->SetCopyToClipboard(dlg.m_bCopyToClipboard);
2847 pReport->SetIncludeFileCmpReport(dlg.m_bIncludeFileCmpReport);
2848 pDoc->SetReport(pReport);
2853 * @brief Generate patch from files selected.
2855 * Creates a patch from selected files in active directory compare, or
2856 * active file compare. Files in file compare must be saved before
2859 void CDirView::OnToolsGeneratePatch()
2862 const CDiffContext& ctxt = GetDiffContext();
2864 // Get selected items from folder compare
2865 bool bValidFiles = true;
2866 for (DirItemIterator it = SelBegin(); bValidFiles && it != SelEnd(); ++it)
2868 const DIFFITEM &item = *it;
2869 if (item.diffcode.isBin())
2871 LangMessageBox(IDS_CANNOT_CREATE_BINARYPATCH, MB_ICONWARNING |
2872 MB_DONT_DISPLAY_AGAIN, IDS_CANNOT_CREATE_BINARYPATCH);
2873 bValidFiles = false;
2878 // Format full paths to files (leftFile/rightFile)
2879 String leftFile = item.getFilepath(0, ctxt.GetNormalizedPath(0));
2880 if (!leftFile.empty())
2881 leftFile = paths::ConcatPath(leftFile, item.diffFileInfo[0].filename);
2882 String rightFile = item.getFilepath(1, ctxt.GetNormalizedPath(1));
2883 if (!rightFile.empty())
2884 rightFile = paths::ConcatPath(rightFile, item.diffFileInfo[1].filename);
2886 // Format relative paths to files in folder compare
2887 String leftpatch = item.diffFileInfo[0].path;
2888 if (!leftpatch.empty())
2889 leftpatch += _T("/");
2890 leftpatch += item.diffFileInfo[0].filename;
2891 String rightpatch = item.diffFileInfo[1].path;
2892 if (!rightpatch.empty())
2893 rightpatch += _T("/");
2894 rightpatch += item.diffFileInfo[1].filename;
2895 patcher.AddFiles(leftFile, leftpatch, rightFile, rightpatch);
2899 patcher.CreatePatch();
2903 * @brief Add special items for non-recursive compare
2904 * to directory view.
2906 * Currently only special item is ".." for browsing to
2908 * @return number of items added to view
2910 int CDirView::AddSpecialItems()
2912 CDirDoc *pDoc = GetDocument();
2914 bool bEnable = true;
2915 PathContext pathsParent;
2916 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
2918 case AllowUpwardDirectory::No:
2922 AddParentFolderItem(bEnable);
2925 case AllowUpwardDirectory::Never:
2932 * @brief Add "Parent folder" ("..") item to directory view
2934 void CDirView::AddParentFolderItem(bool bEnable)
2936 AddNewItem(0, (DIFFITEM *)SPECIAL_ITEM_POS, bEnable ? DIFFIMG_DIRUP : DIFFIMG_DIRUP_DISABLE, 0);
2940 void CDirView::OnCtxtDirZip()
2942 if (!HasZipSupport())
2944 LangMessageBox(IDS_NO_ZIP_SUPPORT, MB_ICONINFORMATION);
2950 this, LVNI_SELECTED | flag
2951 ).CompressArchive();
2954 void CDirView::ShowShellContextMenu(SIDE_TYPE stype)
2956 CShellContextMenu *pContextMenu = nullptr;
2960 if (m_pShellContextMenuLeft == nullptr)
2961 m_pShellContextMenuLeft.reset(new CShellContextMenu(LeftCmdFirst, LeftCmdLast));
2962 pContextMenu = m_pShellContextMenuLeft.get();
2965 if (m_pShellContextMenuMiddle == nullptr)
2966 m_pShellContextMenuMiddle.reset(new CShellContextMenu(MiddleCmdFirst, MiddleCmdLast));
2967 pContextMenu = m_pShellContextMenuMiddle.get();
2970 if (m_pShellContextMenuRight == nullptr)
2971 m_pShellContextMenuRight.reset(new CShellContextMenu(RightCmdFirst, RightCmdLast));
2972 pContextMenu = m_pShellContextMenuRight.get();
2975 if (pContextMenu!=nullptr && ListShellContextMenu(stype))
2978 GetCursorPos(&point);
2979 HWND hWnd = GetSafeHwnd();
2980 CFrameWnd *pFrame = GetTopLevelFrame();
2981 ASSERT(pFrame != nullptr);
2982 BOOL bAutoMenuEnableOld = pFrame->m_bAutoMenuEnable;
2983 pFrame->m_bAutoMenuEnable = FALSE;
2984 BOOL nCmd = TrackPopupMenu(pContextMenu->GetHMENU(), TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hWnd, nullptr);
2986 pContextMenu->InvokeCommand(nCmd, hWnd);
2987 pContextMenu->ReleaseShellContextMenu();
2988 pFrame->m_bAutoMenuEnable = bAutoMenuEnableOld;
2992 template <SIDE_TYPE stype>
2993 void CDirView::OnCtxtDirShellContextMenu()
2995 ShowShellContextMenu(stype);
2999 * @brief Select all visible items in dir compare
3001 void CDirView::OnSelectAll()
3003 // While the user is renaming an item, select all the edited text.
3004 CEdit *pEdit = m_pList->GetEditControl();
3005 if (pEdit != nullptr)
3007 pEdit->SetSel(pEdit->GetWindowTextLength());
3011 int selCount = m_pList->GetItemCount();
3013 for (int i = 0; i < selCount; i++)
3015 // Don't select special items (SPECIAL_ITEM_POS)
3016 DIFFITEM *diffpos = GetItemKey(i);
3017 if (!IsDiffItemSpecial(diffpos))
3018 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3024 * @brief Update "Select All" item
3026 void CDirView::OnUpdateSelectAll(CCmdUI* pCmdUI)
3028 bool bEnable = (!IsLabelEdit()) || (m_pList->GetItemCount() > 0);
3029 pCmdUI->Enable(bEnable);
3033 * @brief Handle clicks in plugin context view in list
3035 void CDirView::OnPluginPredifferMode(UINT nID)
3037 ApplyPluginPrediffSetting(SelBegin(), SelEnd(), GetDiffContext(),
3038 (nID == ID_PREDIFF_AUTO) ? PLUGIN_MODE::PLUGIN_AUTO : PLUGIN_MODE::PLUGIN_MANUAL);
3042 * @brief Updates just before displaying plugin context view in list
3044 void CDirView::OnUpdatePluginPredifferMode(CCmdUI* pCmdUI)
3046 // 2004-04-03, Perry
3047 // CMainFrame::OnUpdatePluginUnpackMode handles this for global unpacking
3048 // and is the template to copy, but here, this is a bit tricky
3049 // as a group of files may be selected
3050 // and they may not all have the same setting
3051 // so I'm not trying this right now
3053 pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
3055 BCMenu *pPopup = static_cast<BCMenu*>(pCmdUI->m_pSubMenu);
3056 if (pPopup == nullptr)
3059 std::pair<int, int> counts = CountPredifferYesNo(SelBegin(), SelEnd(), GetDiffContext());
3061 CheckContextMenu(pPopup, ID_PREDIFF_AUTO, (counts.first > 0));
3062 CheckContextMenu(pPopup, ID_PREDIFF_MANUAL, (counts.second > 0));
3066 * @brief Refresh cached options.
3068 void CDirView::RefreshOptions()
3070 m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
3071 m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
3072 Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
3073 m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
3074 m_pList->SetBkColor(m_bUseColors ? m_cachedColors.clrDirMargin : GetSysColor(COLOR_WINDOW));
3079 * @brief Copy selected item left side paths (containing filenames) to clipboard.
3081 template<SIDE_TYPE stype>
3082 void CDirView::OnCopyPathnames()
3084 std::list<String> list;
3085 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3086 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3089 void CDirView::OnCopyBothPathnames()
3091 std::list<String> list;
3092 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3093 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3097 * @brief Copy selected item filenames to clipboard.
3099 void CDirView::OnCopyFilenames()
3101 std::list<String> list;
3102 CopyFilenames(SelBegin(), SelEnd(), std::back_inserter(list));
3103 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3107 * @brief Enable/Disable dirview Copy Filenames context menu item.
3109 void CDirView::OnUpdateCopyFilenames(CCmdUI* pCmdUI)
3111 pCmdUI->Enable(Count(&DirActions::IsItemFile).count > 0);
3115 * @brief Copy selected item left side to clipboard.
3117 template<SIDE_TYPE stype>
3118 void CDirView::OnCopyToClipboard()
3120 std::list<String> list;
3121 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3122 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3126 * @brief Copy selected item both side to clipboard.
3128 void CDirView::OnCopyBothToClipboard()
3130 std::list<String> list;
3131 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3132 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3136 * @brief Rename a selected item on both sides.
3139 void CDirView::OnItemRename()
3141 ASSERT(1 == m_pList->GetSelectedCount());
3142 int nSelItem = m_pList->GetNextItem(-1, LVNI_SELECTED);
3143 ASSERT(-1 != nSelItem);
3144 m_pList->EditLabel(nSelItem);
3148 * @brief Enable/Disable dirview Rename context menu item.
3151 void CDirView::OnUpdateItemRename(CCmdUI* pCmdUI)
3153 bool bEnabled = (1 == m_pList->GetSelectedCount());
3154 pCmdUI->Enable(bEnabled && SelBegin() != SelEnd());
3158 * @brief hide selected item filenames (removes them from the ListView)
3160 void CDirView::OnHideFilenames()
3162 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
3164 while ((it = SelRevBegin()) != SelRevEnd())
3167 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
3168 DeleteItem(it.m_sel);
3171 m_pList->SetRedraw(TRUE); // Turn updating back on
3175 * @brief update menu item
3177 void CDirView::OnUpdateHideFilenames(CCmdUI* pCmdUI)
3179 pCmdUI->Enable(m_pList->GetSelectedCount() != 0);
3182 /// User chose (context menu) Move left to...
3183 template<SIDE_TYPE stype>
3184 void CDirView::OnCtxtDirMoveTo()
3186 DoDirActionTo(stype, &DirActions::MoveTo<stype>, _("Moving files..."));
3190 * @brief Update "Move | Left to..." item
3192 template<SIDE_TYPE stype>
3193 void CDirView::OnUpdateCtxtDirMoveTo(CCmdUI* pCmdUI)
3195 Counts counts = Count(&DirActions::IsItemMovableToOn<stype>);
3196 pCmdUI->Enable(counts.count > 0);
3197 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
3201 * @brief Update title after window is resized.
3203 void CDirView::OnSize(UINT nType, int cx, int cy)
3205 CListView::OnSize(nType, cx, cy);
3206 GetDocument()->SetTitle(nullptr);
3210 * @brief Called when user selects 'Delete' from 'Merge' menu.
3212 void CDirView::OnDelete()
3214 DoDirAction(&DirActions::DeleteOnEitherOrBoth, _("Deleting files..."));
3218 * @brief Enables/disables 'Delete' item in 'Merge' menu.
3220 void CDirView::OnUpdateDelete(CCmdUI* pCmdUI)
3222 pCmdUI->Enable(Count(&DirActions::IsItemDeletableOnEitherOrBoth).count > 0);
3226 * @brief Called when item state is changed.
3228 * Show count of selected items in statusbar.
3230 void CDirView::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)
3232 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
3234 // If item's selected state changed
3235 if ((pNMListView->uOldState & LVIS_SELECTED) !=
3236 (pNMListView->uNewState & LVIS_SELECTED))
3238 if ((pNMListView->iItem % 5000) > 0)
3239 SetTimer(STATUSBAR_UPDATE, 100, nullptr);
3241 OnTimer(STATUSBAR_UPDATE);
3247 * @brief Called before user start to item label edit.
3249 * Disable label edit if initiated from a user double-click.
3251 afx_msg void CDirView::OnBeginLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3253 *pResult = (SelBegin() == SelEnd());
3255 // If label edit is allowed.
3256 if (*pResult == FALSE)
3258 const NMLVDISPINFO *pdi = (NMLVDISPINFO*)pNMHDR;
3259 ASSERT(pdi != nullptr);
3261 // Locate the edit box on the right column in case the user changed the
3263 const int nColPos = m_pColItems->ColLogToPhys(0);
3265 // Get text from the "File Name" column.
3266 CString sText = m_pList->GetItemText(pdi->item.iItem, nColPos);
3267 ASSERT(!sText.IsEmpty());
3269 // Keep only left file name (separated by '|'). This form occurs
3270 // when two files exists with same name but not in same case.
3271 int nPos = sText.Find('|');
3274 sText = sText.Left(nPos);
3277 // Set the edit control with the updated text.
3278 CEdit *pEdit = m_pList->GetEditControl();
3279 ASSERT(pEdit != nullptr);
3280 pEdit->SetWindowText(sText);
3282 m_bUserCancelEdit = false;
3287 * @brief Called when user done with item label edit.
3290 afx_msg void CDirView::OnEndLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3294 // We can't use the normal condition of pszText==`nullptr` to know if the
3295 // user cancels editing when file names had different case (e.g.
3296 // "file.txt|FILE.txt"). The edit text was changed to "file.txt" and
3297 // if the user accept it as the new file name, pszText is `nullptr`.
3299 if (!m_bUserCancelEdit)
3301 CEdit *pEdit = m_pList->GetEditControl();
3302 ASSERT(pEdit != nullptr);
3305 pEdit->GetWindowText(sText);
3307 if (!sText.IsEmpty())
3310 DirItemIterator it(m_pIList.get(), reinterpret_cast<NMLVDISPINFO *>(pNMHDR)->item.iItem);
3311 *pResult = DoItemRename(it, GetDiffContext(), String(sText));
3312 } catch (ContentsChangedException& e) {
3313 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
3320 * @brief Called when item is marked for rescan.
3321 * This function marks selected items for rescan and rescans them.
3323 void CDirView::OnMarkedRescan()
3325 std::for_each(SelBegin(), SelEnd(), MarkForRescan);
3326 if (std::distance(SelBegin(), SelEnd()) > 0)
3328 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
3329 GetDocument()->SetMarkedRescan();
3330 GetDocument()->Rescan();
3335 * @brief Called to update the item count in the status bar
3337 void CDirView::OnUpdateStatusNum(CCmdUI* pCmdUI)
3339 String s; // text to display
3341 int count = m_pList->GetItemCount();
3342 int focusItem = GetFocusedItem();
3344 if (focusItem == -1)
3346 // No item has focus
3348 s = strutils::format_string1(_("Items: %1"), strutils::to_str(count));
3352 // Don't show number to special items
3353 DIFFITEM *pos = GetItemKey(focusItem);
3354 if (!IsDiffItemSpecial(pos))
3356 // If compare is non-recursive reduce special items count
3357 bool bRecursive = GetDiffContext().m_bRecursive;
3364 s = strutils::format_string2(_("Item %1 of %2"),
3365 strutils::to_str(focusItem + 1), strutils::to_str(count));
3368 pCmdUI->SetText(s.c_str());
3372 * @brief Show all hidden items.
3374 void CDirView::OnViewShowHiddenItems()
3376 SetItemViewFlag(GetDiffContext(), ViewCustomFlags::VISIBLE, ViewCustomFlags::VISIBILITY);
3382 * @brief Enable/Disable 'Show hidden items' menuitem.
3384 void CDirView::OnUpdateViewShowHiddenItems(CCmdUI* pCmdUI)
3386 pCmdUI->Enable(m_nHiddenItems > 0);
3390 * @brief Toggle Tree Mode
3392 void CDirView::OnViewTreeMode()
3394 m_bTreeMode = !m_bTreeMode;
3395 m_dirfilter.tree_mode = m_bTreeMode;
3396 GetOptionsMgr()->SaveOption(OPT_TREE_MODE, m_bTreeMode); // reverse
3401 * @brief Check/Uncheck 'Tree Mode' menuitem.
3403 void CDirView::OnUpdateViewTreeMode(CCmdUI* pCmdUI)
3405 // Don't show Tree Mode as 'checked' if the
3406 // menu item is greyed out (disabled). Its very confusing.
3407 if( GetDocument()->GetDiffContext().m_bRecursive ) {
3408 pCmdUI->SetCheck(m_bTreeMode);
3409 pCmdUI->Enable(TRUE);
3411 pCmdUI->SetCheck(FALSE);
3412 pCmdUI->Enable(FALSE);
3417 * @brief Expand all subfolders
3419 void CDirView::OnViewExpandAllSubdirs()
3421 ExpandAllSubdirs(GetDiffContext());
3426 * @brief Update "Expand All Subfolders" item
3428 void CDirView::OnUpdateViewExpandAllSubdirs(CCmdUI* pCmdUI)
3430 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3434 * @brief Collapse all subfolders
3436 void CDirView::OnViewCollapseAllSubdirs()
3438 CollapseAllSubdirs(GetDiffContext());
3443 * @brief Update "Collapse All Subfolders" item
3445 void CDirView::OnUpdateViewCollapseAllSubdirs(CCmdUI* pCmdUI)
3447 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3450 template <int pane1, int pane2>
3451 void CDirView::OnViewSwapPanes()
3453 GetDocument()->Swap(pane1, pane2);
3457 template <int pane1, int pane2>
3458 void CDirView::OnUpdateViewSwapPanes(CCmdUI* pCmdUI)
3460 pCmdUI->Enable(pane2 < GetDocument()->m_nDirs);
3464 * @brief Show/Hide different files/directories
3466 void CDirView::OnOptionsShowDifferent()
3468 m_dirfilter.show_different = !m_dirfilter.show_different;
3469 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT, m_dirfilter.show_different);
3474 * @brief Show/Hide identical files/directories
3476 void CDirView::OnOptionsShowIdentical()
3478 m_dirfilter.show_identical = !m_dirfilter.show_identical;
3479 GetOptionsMgr()->SaveOption(OPT_SHOW_IDENTICAL, m_dirfilter.show_identical);
3484 * @brief Show/Hide left-only files/directories
3486 void CDirView::OnOptionsShowUniqueLeft()
3488 m_dirfilter.show_unique_left = !m_dirfilter.show_unique_left;
3489 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_LEFT, m_dirfilter.show_unique_left);
3494 * @brief Show/Hide middle-only files/directories
3496 void CDirView::OnOptionsShowUniqueMiddle()
3498 m_dirfilter.show_unique_middle = !m_dirfilter.show_unique_middle;
3499 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_MIDDLE, m_dirfilter.show_unique_middle);
3504 * @brief Show/Hide right-only files/directories
3506 void CDirView::OnOptionsShowUniqueRight()
3508 m_dirfilter.show_unique_right = !m_dirfilter.show_unique_right;
3509 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_RIGHT, m_dirfilter.show_unique_right);
3514 * @brief Show/Hide binary files
3516 void CDirView::OnOptionsShowBinaries()
3518 m_dirfilter.show_binaries = !m_dirfilter.show_binaries;
3519 GetOptionsMgr()->SaveOption(OPT_SHOW_BINARIES, m_dirfilter.show_binaries);
3524 * @brief Show/Hide skipped files/directories
3526 void CDirView::OnOptionsShowSkipped()
3528 m_dirfilter.show_skipped = !m_dirfilter.show_skipped;
3529 GetOptionsMgr()->SaveOption(OPT_SHOW_SKIPPED, m_dirfilter.show_skipped);
3534 * @brief Show/Hide different files/folders (Middle and right are identical)
3536 void CDirView::OnOptionsShowDifferentLeftOnly()
3538 m_dirfilter.show_different_left_only = !m_dirfilter.show_different_left_only;
3539 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_LEFT_ONLY, m_dirfilter.show_different_left_only);
3544 * @brief Show/Hide different files/folders (Left and right are identical)
3546 void CDirView::OnOptionsShowDifferentMiddleOnly()
3548 m_dirfilter.show_different_middle_only = !m_dirfilter.show_different_middle_only;
3549 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_MIDDLE_ONLY, m_dirfilter.show_different_middle_only);
3554 * @brief Show/Hide different files/folders (Left and middle are identical)
3556 void CDirView::OnOptionsShowDifferentRightOnly()
3558 m_dirfilter.show_different_right_only = !m_dirfilter.show_different_right_only;
3559 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_RIGHT_ONLY, m_dirfilter.show_different_right_only);
3564 * @brief Show/Hide missing left only files/folders
3566 void CDirView::OnOptionsShowMissingLeftOnly()
3568 m_dirfilter.show_missing_left_only = !m_dirfilter.show_missing_left_only;
3569 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_LEFT_ONLY, m_dirfilter.show_missing_left_only);
3574 * @brief Show/Hide missing middle only files/folders
3576 void CDirView::OnOptionsShowMissingMiddleOnly()
3578 m_dirfilter.show_missing_middle_only = !m_dirfilter.show_missing_middle_only;
3579 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_MIDDLE_ONLY, m_dirfilter.show_missing_middle_only);
3584 * @brief Show/Hide missing right only files/folders
3586 void CDirView::OnOptionsShowMissingRightOnly()
3588 m_dirfilter.show_missing_right_only = !m_dirfilter.show_missing_right_only;
3589 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_RIGHT_ONLY, m_dirfilter.show_missing_right_only);
3593 void CDirView::OnUpdateOptionsShowdifferent(CCmdUI* pCmdUI)
3595 pCmdUI->SetCheck(m_dirfilter.show_different);
3598 void CDirView::OnUpdateOptionsShowidentical(CCmdUI* pCmdUI)
3600 pCmdUI->SetCheck(m_dirfilter.show_identical);
3603 void CDirView::OnUpdateOptionsShowuniqueleft(CCmdUI* pCmdUI)
3605 pCmdUI->SetCheck(m_dirfilter.show_unique_left);
3608 void CDirView::OnUpdateOptionsShowuniquemiddle(CCmdUI* pCmdUI)
3610 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3611 pCmdUI->SetCheck(m_dirfilter.show_unique_middle);
3614 void CDirView::OnUpdateOptionsShowuniqueright(CCmdUI* pCmdUI)
3616 pCmdUI->SetCheck(m_dirfilter.show_unique_right);
3619 void CDirView::OnUpdateOptionsShowBinaries(CCmdUI* pCmdUI)
3621 pCmdUI->SetCheck(m_dirfilter.show_binaries);
3624 void CDirView::OnUpdateOptionsShowSkipped(CCmdUI* pCmdUI)
3626 pCmdUI->SetCheck(m_dirfilter.show_skipped);
3629 void CDirView::OnUpdateOptionsShowDifferentLeftOnly(CCmdUI* pCmdUI)
3631 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3632 pCmdUI->SetCheck(m_dirfilter.show_different_left_only);
3635 void CDirView::OnUpdateOptionsShowDifferentMiddleOnly(CCmdUI* pCmdUI)
3637 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3638 pCmdUI->SetCheck(m_dirfilter.show_different_middle_only);
3641 void CDirView::OnUpdateOptionsShowDifferentRightOnly(CCmdUI* pCmdUI)
3643 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3644 pCmdUI->SetCheck(m_dirfilter.show_different_right_only);
3647 void CDirView::OnUpdateOptionsShowMissingLeftOnly(CCmdUI* pCmdUI)
3649 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3650 pCmdUI->SetCheck(m_dirfilter.show_missing_left_only);
3653 void CDirView::OnUpdateOptionsShowMissingMiddleOnly(CCmdUI* pCmdUI)
3655 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3656 pCmdUI->SetCheck(m_dirfilter.show_missing_middle_only);
3659 void CDirView::OnUpdateOptionsShowMissingRightOnly(CCmdUI* pCmdUI)
3661 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3662 pCmdUI->SetCheck(m_dirfilter.show_missing_right_only);
3665 void CDirView::OnMergeCompare()
3667 CWaitCursor waitstatus;
3671 template<SELECTIONTYPE seltype>
3672 void CDirView::OnMergeCompare2()
3674 CWaitCursor waitstatus;
3675 OpenSelection(seltype);
3678 void CDirView::OnMergeCompareNonHorizontally()
3680 int sel1, sel2, sel3;
3681 if (!GetSelectedItems(&sel1, &sel2, &sel3))
3683 DirSelectFilesDlg dlg;
3685 dlg.m_pdi[0] = &GetDiffItem(sel1);
3687 dlg.m_pdi[1] = &GetDiffItem(sel2);
3689 dlg.m_pdi[2] = &GetDiffItem(sel3);
3690 if (dlg.DoModal() == IDOK && dlg.m_selectedButtons.size() > 0)
3692 CDirDoc *pDoc = GetDocument();
3693 FileTextEncoding encoding[3];
3694 DWORD dwFlags[3] = {};
3696 for (int nIndex = 0; nIndex < static_cast<int>(dlg.m_selectedButtons.size()); ++nIndex)
3698 int n = dlg.m_selectedButtons[nIndex];
3699 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(n % 3) ? FFILEOPEN_READONLY : 0);
3700 if (dlg.m_pdi[n / 3])
3702 paths.SetPath(nIndex, GetItemFileName(pDoc->GetDiffContext(), *dlg.m_pdi[n / 3], n % 3));
3703 encoding[nIndex] = dlg.m_pdi[n / 3]->diffFileInfo[n % 3].encoding;
3706 if (paths.GetSize() == 1)
3707 paths.SetRight(_T(""));
3708 Open(paths, dwFlags, encoding);
3712 void CDirView::OnMergeCompareXML()
3714 CWaitCursor waitstatus;
3715 PackingInfo packingInfo(PLUGIN_MODE::PLUGIN_BUILTIN_XML);
3716 OpenSelection(SELECTIONTYPE_NORMAL, &packingInfo, false);
3719 void CDirView::OnMergeCompareAs(UINT nID)
3721 CWaitCursor waitstatus;
3722 OpenSelectionAs(nID);
3725 void CDirView::OnUpdateMergeCompare(CCmdUI *pCmdUI)
3727 bool openableForDir = !(pCmdUI->m_nID >= ID_MERGE_COMPARE_TEXT &&
3728 pCmdUI->m_nID <= ID_MERGE_COMPARE_XML);
3730 DoUpdateOpen(SELECTIONTYPE_NORMAL, pCmdUI, openableForDir);
3733 template<SELECTIONTYPE seltype>
3734 void CDirView::OnUpdateMergeCompare2(CCmdUI *pCmdUI)
3736 DoUpdateOpen(seltype, pCmdUI);
3739 void CDirView::OnViewCompareStatistics()
3741 CompareStatisticsDlg dlg(GetDocument()->GetCompareStats());
3746 * @brief Count left & right files, and number with editable text encoding
3747 * @param nLeft [out] #files on left side selected
3748 * @param nLeftAffected [out] #files on left side selected which can have text encoding changed
3749 * @param nRight [out] #files on right side selected
3750 * @param nRightAffected [out] #files on right side selected which can have text encoding changed
3752 * Affected files include all except unicode files
3754 void CDirView::FormatEncodingDialogDisplays(CLoadSaveCodepageDlg * dlg)
3756 IntToIntMap currentCodepages = CountCodepages(SelBegin(), SelEnd(), GetDiffContext());
3758 Counts left, middle, right;
3759 left = Count(&DirActions::IsItemEditableEncoding<SIDE_LEFT>);
3760 if (GetDocument()->m_nDirs > 2)
3761 middle = Count(&DirActions::IsItemEditableEncoding<SIDE_MIDDLE>);
3762 right = Count(&DirActions::IsItemEditableEncoding<SIDE_RIGHT>);
3764 // Format strings such as "25 of 30 Files Affected"
3765 String sLeftAffected = FormatFilesAffectedString(left.count, left.total);
3766 String sMiddleAffected = (GetDocument()->m_nDirs < 3) ? _T("") : FormatFilesAffectedString(middle.count, middle.total);
3767 String sRightAffected = FormatFilesAffectedString(right.count, right.total);
3768 dlg->SetLeftRightAffectStrings(sLeftAffected, sMiddleAffected, sRightAffected);
3769 int codepage = currentCodepages.FindMaxKey();
3770 dlg->SetCodepages(codepage);
3774 * @brief Display file encoding dialog to user & handle user's choices
3776 * This handles DirView invocation, so multiple files may be affected
3778 void CDirView::DoFileEncodingDialog()
3780 CLoadSaveCodepageDlg dlg(GetDocument()->m_nDirs);
3781 // set up labels about what will be affected
3782 FormatEncodingDialogDisplays(&dlg);
3783 dlg.EnableSaveCodepage(false); // disallow setting a separate codepage for saving
3786 if (dlg.DoModal() != IDOK)
3790 affected[0] = dlg.DoesAffectLeft();
3791 affected[1] = dlg.DoesAffectMiddle();
3792 affected[SideToIndex(GetDiffContext(), SIDE_RIGHT)] = dlg.DoesAffectRight();
3794 ApplyCodepage(SelBegin(), SelEnd(), GetDiffContext(), affected, dlg.GetLoadCodepage());
3796 m_pList->InvalidateRect(nullptr);
3797 m_pList->UpdateWindow();
3799 // TODO: We could loop through any active merge windows belonging to us
3800 // and see if any of their files are affected
3801 // but, if they've been edited, we cannot throw away the user's work?
3805 * @brief Display file encoding dialog & handle user's actions
3807 void CDirView::OnFileEncoding()
3809 DoFileEncodingDialog();
3812 /** @brief Open help from mainframe when user presses F1*/
3813 void CDirView::OnHelp()
3815 theApp.ShowHelp(DirViewHelpLocation);
3819 * @brief true while user is editing a file name.
3821 bool CDirView::IsLabelEdit() const
3823 return (m_pList->GetEditControl() != nullptr);
3827 * @brief Allow edit "Paste" when renaming an item.
3829 void CDirView::OnEditCopy()
3831 CEdit *pEdit = m_pList->GetEditControl();
3832 if (pEdit != nullptr)
3839 * @brief Allow edit "Cut" when renaming an item.
3841 void CDirView::OnEditCut()
3843 CEdit *pEdit = m_pList->GetEditControl();
3844 if (pEdit != nullptr)
3851 * @brief Allow edit "Paste" when renaming an item.
3853 void CDirView::OnEditPaste()
3855 CEdit *pEdit = m_pList->GetEditControl();
3856 if (pEdit != nullptr)
3863 * @brief Allow edit "Undo" when renaming an item.
3865 void CDirView::OnEditUndo()
3867 CEdit *pEdit = m_pList->GetEditControl();
3868 if (pEdit != nullptr)
3875 * @brief Update the tool bar's "Undo" icon. It should be enabled when
3876 * renaming an item and undo is possible.
3878 void CDirView::OnUpdateEditUndo(CCmdUI* pCmdUI)
3880 CEdit *pEdit = m_pList->GetEditControl();
3881 pCmdUI->Enable(pEdit && pEdit->CanUndo());
3884 * @brief Returns CShellContextMenu object that owns given HMENU.
3886 * @param [in] hMenu Handle to the menu to check ownership of.
3887 * @return Either m_pShellContextMenuLeft, m_pShellContextMenuRight
3888 * or `nullptr` if hMenu is not owned by these two.
3890 CShellContextMenu* CDirView::GetCorrespondingShellContextMenu(HMENU hMenu) const
3892 CShellContextMenu* pMenu = nullptr;
3893 if (m_pShellContextMenuLeft!=nullptr && hMenu == m_pShellContextMenuLeft->GetHMENU())
3894 pMenu = m_pShellContextMenuLeft.get();
3895 else if (m_pShellContextMenuMiddle!=nullptr && hMenu == m_pShellContextMenuMiddle->GetHMENU())
3896 pMenu = m_pShellContextMenuMiddle.get();
3897 else if (m_pShellContextMenuRight!=nullptr && hMenu == m_pShellContextMenuRight->GetHMENU())
3898 pMenu = m_pShellContextMenuRight.get();
3904 * @brief Handle messages related to correct menu working.
3906 * We need to requery shell context menu each time we switch from context menu
3907 * for one side to context menu for other side. Here we check whether we need to
3908 * requery and call ShellContextMenuHandleMenuMessage.
3910 LRESULT CDirView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
3912 while (message == WM_INITMENUPOPUP)
3914 HMENU hMenu = (HMENU)wParam;
3915 if (CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(hMenu))
3917 if (m_hCurrentMenu != hMenu)
3919 // re-query context menu once more, because if context menu was queried for right
3920 // group of files and we are showing menu for left group (or vice versa) menu will
3921 // be shown incorrectly
3922 // also, if context menu was last queried for right group of files and we are
3923 // invoking command for left command will be executed for right group (the last
3924 // group that menu was requested for)
3925 // may be a "feature" of Shell
3927 pMenu->RequeryShellContextMenu();
3928 m_hCurrentMenu = hMenu;
3934 CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(m_hCurrentMenu);
3936 if (pMenu != nullptr)
3939 pMenu->HandleMenuMessage(message, wParam, lParam, res);
3942 return CListView::WindowProc(message, wParam, lParam);
3946 * @brief Implement background item coloring
3948 void CDirView::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
3950 if (!m_bUseColors) {
3954 LPNMLISTVIEW pNM = (LPNMLISTVIEW)pNMHDR;
3955 *pResult = CDRF_DODEFAULT;
3957 if (pNM->hdr.code == NM_CUSTOMDRAW)
3959 LPNMLVCUSTOMDRAW lpC = (LPNMLVCUSTOMDRAW)pNMHDR;
3961 if (lpC->nmcd.dwDrawStage == CDDS_PREPAINT)
3963 *pResult = CDRF_NOTIFYITEMDRAW;
3967 if (lpC->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
3969 *pResult = CDRF_NOTIFYITEMDRAW;
3973 if (lpC->nmcd.dwDrawStage == (CDDS_ITEMPREPAINT | CDDS_SUBITEM ))
3975 GetColors (static_cast<int>(lpC->nmcd.dwItemSpec), lpC->iSubItem, lpC->clrTextBk, lpC->clrText);
3980 void CDirView::OnBnClickedComparisonStop()
3982 if (m_pCmpProgressBar != nullptr)
3983 m_pCmpProgressBar->EndUpdating();
3984 GetDocument()->AbortCurrentScan();
3987 void CDirView::OnBnClickedComparisonPause()
3989 if (m_pCmpProgressBar != nullptr)
3990 m_pCmpProgressBar->SetPaused(true);
3991 GetDocument()->PauseCurrentScan();
3994 void CDirView::OnBnClickedComparisonContinue()
3996 if (m_pCmpProgressBar != nullptr)
3997 m_pCmpProgressBar->SetPaused(false);
3998 GetDocument()->ContinueCurrentScan();
4002 * @brief Populate colors for items in view, depending on difference status
4004 void CDirView::GetColors (int nRow, int nCol, COLORREF& clrBk, COLORREF& clrText) const
4006 const DIFFITEM& di = GetDiffItem (nRow);
4010 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4011 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4013 else if (di.diffcode.isResultFiltered())
4015 clrText = m_cachedColors.clrDirItemFilteredText;
4016 clrBk = m_cachedColors.clrDirItemFiltered;
4018 else if (!IsItemExistAll(GetDiffContext(), di))
4020 clrText = m_cachedColors.clrDirItemNotExistAllText;
4021 clrBk = m_cachedColors.clrDirItemNotExistAll;
4023 else if (di.diffcode.isResultDiff())
4025 clrText = m_cachedColors.clrDirItemDiffText;
4026 clrBk = m_cachedColors.clrDirItemDiff;
4028 else if (di.diffcode.isResultSame())
4030 clrText = m_cachedColors.clrDirItemEqualText;
4031 clrBk = m_cachedColors.clrDirItemEqual;
4035 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4036 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4040 void CDirView::OnSearch()
4042 CDirDoc *pDoc = GetDocument();
4043 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
4044 int nRows = m_pList->GetItemCount();
4045 for (int currRow = nRows - 1; currRow >= 0; currRow--)
4047 DIFFITEM *pos = GetItemKey(currRow);
4048 if (IsDiffItemSpecial(pos))
4051 bool bFound = false;
4052 DIFFITEM &di = GetDiffItem(currRow);
4054 for (int i = 0; i < pDoc->m_nDirs; i++)
4056 if (di.diffcode.exists(i) && !di.diffcode.isDirectory())
4058 GetItemFileNames(currRow, &paths);
4060 if (!ufile.OpenReadOnly(paths[i]))
4063 ufile.SetUnicoding(di.diffFileInfo[i].encoding.m_unicoding);
4064 ufile.SetBom(di.diffFileInfo[i].encoding.m_bom);
4065 ufile.SetCodepage(di.diffFileInfo[i].encoding.m_codepage);
4073 if (!ufile.ReadString(line, &lossy))
4076 if (_tcsstr(line.c_str(), _T("DirView")))
4090 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
4091 DeleteItem(currRow);
4095 m_pList->SetRedraw(TRUE); // Turn updating back on
4099 * @brief Drag files/directories from folder compare listing view.
4101 void CDirView::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
4103 COleDataSource *DropData = new COleDataSource();
4105 std::list<String> list;
4106 CopyPathnamesForDragAndDrop(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
4107 String filesForDroping = strutils::join(list.begin(), list.end(), _T("\n")) + _T("\n");
4109 CSharedFile file(GMEM_DDESHARE | GMEM_MOVEABLE | GMEM_ZEROINIT);
4110 file.Write(filesForDroping.data(), static_cast<unsigned>((filesForDroping.length() + 1) * sizeof(TCHAR)));
4112 HGLOBAL hMem = GlobalReAlloc(file.Detach(), (filesForDroping.length() + 1) * sizeof(TCHAR), 0);
4113 if (hMem != nullptr)
4115 DropData->CacheGlobalData(CF_UNICODETEXT, hMem);
4116 DROPEFFECT de = DropData->DoDragDrop(DROPEFFECT_COPY | DROPEFFECT_MOVE, nullptr);
4122 /// Assign column name, using string resource & current column ordering
4123 void CDirView::NameColumn(const DirColInfo *col, int subitem)
4125 int phys = m_pColItems->ColLogToPhys(subitem);
4128 String s = tr(col->idNameContext, col->idName);
4130 lvc.mask = LVCF_TEXT;
4131 lvc.pszText = const_cast<LPTSTR>(s.c_str());
4132 m_pList->SetColumn(phys, &lvc);
4136 /// Load column names from string table
4137 void CDirView::UpdateColumnNames()
4139 int ncols = m_pColItems->GetColCount();
4140 for (int i=0; i<ncols; ++i)
4142 const DirColInfo* col = m_pColItems->GetDirColInfo(i);
4148 * @brief Set alignment of columns.
4150 void CDirView::SetColAlignments()
4152 int ncols = m_pColItems->GetColCount();
4153 for (int i=0; i<ncols; ++i)
4155 const DirColInfo * col = m_pColItems->GetDirColInfo(i);
4157 lvc.mask = LVCF_FMT;
4158 lvc.fmt = col->alignment;
4159 m_pList->SetColumn(m_pColItems->ColLogToPhys(i), &lvc);
4163 CDirView::CompareState::CompareState(const CDiffContext *pCtxt, const DirViewColItems *pColItems, int sortCol, bool bSortAscending, bool bTreeMode)
4165 , pColItems(pColItems)
4167 , bSortAscending(bSortAscending)
4168 , bTreeMode(bTreeMode)
4172 /// Compare two specified rows during a sort operation (windows callback)
4173 int CALLBACK CDirView::CompareState::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
4175 CompareState *pThis = reinterpret_cast<CompareState*>(lParamSort);
4176 // Sort special items always first in dir view
4182 DIFFITEM *diffposl = (DIFFITEM *)lParam1;
4183 DIFFITEM *diffposr = (DIFFITEM *)lParam2;
4184 const DIFFITEM &ldi = pThis->pCtxt->GetDiffAt(diffposl);
4185 const DIFFITEM &rdi = pThis->pCtxt->GetDiffAt(diffposr);
4186 // compare 'left' and 'right' parameters as appropriate
4187 int retVal = pThis->pColItems->ColSort(pThis->pCtxt, pThis->sortCol, ldi, rdi, pThis->bTreeMode);
4188 // return compare result, considering sort direction
4189 return pThis->bSortAscending ? retVal : -retVal;
4192 /// Add new item to list view
4193 int CDirView::AddNewItem(int i, DIFFITEM *diffpos, int iImage, int iIndent)
4196 lvItem.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE | LVIF_INDENT;
4198 lvItem.iIndent = iIndent;
4199 lvItem.iSubItem = 0;
4200 lvItem.pszText = LPSTR_TEXTCALLBACK;
4201 lvItem.lParam = (LPARAM)diffpos;
4202 lvItem.iImage = iImage;
4203 return GetListCtrl().InsertItem(&lvItem);
4207 * @brief Update listview display of details for specified row
4208 * @note Customising shownd data should be done here
4210 void CDirView::UpdateDiffItemStatus(UINT nIdx)
4212 GetListCtrl().RedrawItems(nIdx, nIdx);
4213 const DIFFITEM& di = GetDiffItem(nIdx);
4214 if (di.diffcode.isDirectory())
4217 for (it = RevBegin(); it != RevEnd(); )
4219 DIFFITEM& di2 = *it;
4220 int cursel = it.m_sel;
4222 if (di2.IsAncestor(&di))
4224 if ((di2.diffcode.diffcode & DIFFCODE::SIDEFLAGS) == 0)
4225 DeleteItem(cursel, true);
4227 GetListCtrl().RedrawItems(cursel, cursel);
4233 static String rgDispinfoText[2]; // used in function below
4236 * @brief Allocate a text buffer to assign to NMLVDISPINFO::item::pszText
4237 * Quoting from SDK Docs:
4238 * If the LVITEM structure is receiving item text, the pszText and cchTextMax
4239 * members specify the address and size of a buffer. You can either copy text to
4240 * the buffer or assign the address of a string to the pszText member. In the
4241 * latter case, you must not change or delete the string until the corresponding
4242 * item text is deleted or two additional LVN_GETDISPINFO messages have been sent.
4244 static LPTSTR NTAPI AllocDispinfoText(const String &s)
4247 LPCTSTR pszText = (rgDispinfoText[i] = s).c_str();
4249 return (LPTSTR)pszText;
4253 * @brief Respond to LVN_GETDISPINFO message
4255 void CDirView::ReflectGetdispinfo(NMLVDISPINFO *pParam)
4257 int nIdx = pParam->item.iItem;
4258 int i = m_pColItems->ColPhysToLog(pParam->item.iSubItem);
4259 DIFFITEM *key = GetItemKey(nIdx);
4260 if (IsDiffItemSpecial(key))
4262 if (m_pColItems->IsColName(i))
4264 pParam->item.pszText = _T("..");
4268 if (!GetDocument()->HasDiffs())
4270 const CDiffContext &ctxt = GetDiffContext();
4271 const DIFFITEM &di = ctxt.GetDiffAt(key);
4272 if (pParam->item.mask & LVIF_TEXT)
4274 String s = m_pColItems->ColGetTextToDisplay(&ctxt, i, di);
4275 pParam->item.pszText = AllocDispinfoText(s);
4277 if (pParam->item.mask & LVIF_IMAGE)
4279 pParam->item.iImage = GetColImage(di);
4284 * @brief User examines & edits which columns are displayed in dirview, and in which order
4286 void CDirView::OnEditColumns()
4289 // List all the currently displayed columns
4290 for (int col=0; col<GetListCtrl().GetHeaderCtrl()->GetItemCount(); ++col)
4292 int l = m_pColItems->ColPhysToLog(col);
4293 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l, col);
4295 // Now add all the columns not currently displayed
4297 for (l=0; l<m_pColItems->GetColCount(); ++l)
4299 if (m_pColItems->ColLogToPhys(l)==-1)
4301 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l);
4305 // Add default order of columns for resetting to defaults
4306 for (l = 0; l < m_pColItems->GetColCount(); ++l)
4308 int phy = m_pColItems->GetColDefaultOrder(l);
4309 dlg.AddDefColumn(m_pColItems->GetColDisplayName(l), l, phy);
4312 if (dlg.DoModal() != IDOK)
4315 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
4316 GetOptionsMgr()->SaveOption(keyname,
4317 (dlg.m_bReset ? m_pColItems->ResetColumnWidths(GetDefColumnWidth()) :
4318 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1))));
4320 // Reset our data to reflect the new data from the dialog
4321 const CDirColsDlg::ColumnArray & cols = dlg.GetColumns();
4322 m_pColItems->ClearColumnOrders();
4323 const int sortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4324 std::vector<int> colorder(m_pColItems->GetColCount(), -1);
4325 for (CDirColsDlg::ColumnArray::const_iterator iter = cols.begin();
4326 iter != cols.end(); ++iter)
4328 int log = iter->log_col;
4329 int phy = iter->phy_col;
4330 colorder[log] = phy;
4332 // If sorted column was hidden, reset sorting
4333 if (log == sortColumn && phy < 0)
4335 GetOptionsMgr()->Reset((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4336 GetOptionsMgr()->Reset(OPT_DIRVIEW_SORT_ASCENDING);
4340 m_pColItems->SetColumnOrdering(&colorder[0]);
4342 if (m_pColItems->GetDispColCount() < 1)
4344 // Ignore them if they didn't leave a column showing
4345 m_pColItems->ResetColumnOrdering();
4354 DirActions CDirView::MakeDirActions(DirActions::method_type func) const
4356 const CDirDoc *pDoc = GetDocument();
4357 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), func);
4360 DirActions CDirView::MakeDirActions(DirActions::method_type2 func) const
4362 const CDirDoc *pDoc = GetDocument();
4363 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), nullptr, func);
4366 const CDiffContext& CDirView::GetDiffContext() const
4368 return GetDocument()->GetDiffContext();
4371 CDiffContext& CDirView::GetDiffContext()
4373 return GetDocument()->GetDiffContext();