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"
58 using namespace std::placeholders;
61 * @brief Location for folder compare specific help to open.
63 static TCHAR DirViewHelpLocation[] = _T("::/htmlhelp/Compare_dirs.html");
66 * @brief Limit (in seconds) to signal compare is ready for user.
67 * If compare takes longer than this value (in seconds) we inform
68 * user about it. Current implementation uses MessageBeep(IDOK).
70 const int TimeToSignalCompare = 3;
72 // The resource ID constants/limits for the Shell context menu
73 const UINT LeftCmdFirst = 0x9000; // this should be greater than any of already defined command IDs
74 const UINT RightCmdLast = 0xffff; // maximum available value
75 const UINT LeftCmdLast = LeftCmdFirst + (RightCmdLast - LeftCmdFirst) / 3; // divide available range equally between two context menus
76 const UINT MiddleCmdFirst = LeftCmdLast + 1;
77 const UINT MiddleCmdLast = MiddleCmdFirst + (RightCmdLast - LeftCmdFirst) / 3;
78 const UINT RightCmdFirst = MiddleCmdLast + 1;
80 /////////////////////////////////////////////////////////////////////////////
85 STATUSBAR_UPDATE = 100
88 IMPLEMENT_DYNCREATE(CDirView, CListView)
93 , m_pCmpProgressBar(nullptr)
96 , m_dirfilter(std::bind(&COptionsMgr::GetBool, GetOptionsMgr(), _1))
97 , m_pShellContextMenuLeft(nullptr)
98 , m_pShellContextMenuMiddle(nullptr)
99 , m_pShellContextMenuRight(nullptr)
100 , m_hCurrentMenu(nullptr)
101 , m_pSavedTreeState(nullptr)
102 , m_pColItems(nullptr)
105 m_dwDefaultStyle &= ~LVS_TYPEMASK;
106 // Show selection all the time, so user can see current item even when
107 // focus is elsewhere (ie, on file edit window)
108 m_dwDefaultStyle |= LVS_REPORT | LVS_SHOWSELALWAYS | LVS_EDITLABELS;
110 m_bTreeMode = GetOptionsMgr()->GetBool(OPT_TREE_MODE);
111 m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
112 m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
113 Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
114 m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
117 CDirView::~CDirView()
121 BEGIN_MESSAGE_MAP(CDirView, CListView)
123 //{{AFX_MSG_MAP(CDirView)
124 ON_WM_LBUTTONDBLCLK()
125 ON_COMMAND_RANGE(ID_L2R, ID_R2L, OnDirCopy)
126 ON_UPDATE_COMMAND_UI_RANGE(ID_L2R, ID_R2L, OnUpdateDirCopy)
127 ON_COMMAND(ID_DIR_COPY_LEFT_TO_RIGHT, (OnCtxtDirCopy<SIDE_LEFT, SIDE_RIGHT>))
128 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_RIGHT, (OnUpdateCtxtDirCopy<SIDE_LEFT, SIDE_RIGHT>))
129 ON_COMMAND(ID_DIR_COPY_LEFT_TO_MIDDLE, (OnCtxtDirCopy<SIDE_LEFT, SIDE_MIDDLE>))
130 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_MIDDLE, (OnUpdateCtxtDirCopy<SIDE_LEFT, SIDE_MIDDLE>))
131 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_LEFT, (OnCtxtDirCopy<SIDE_RIGHT, SIDE_LEFT>))
132 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_LEFT, (OnUpdateCtxtDirCopy<SIDE_RIGHT, SIDE_LEFT>))
133 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_MIDDLE, (OnCtxtDirCopy<SIDE_RIGHT, SIDE_MIDDLE>))
134 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_MIDDLE, (OnUpdateCtxtDirCopy<SIDE_RIGHT, SIDE_MIDDLE>))
135 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_LEFT, (OnCtxtDirCopy<SIDE_MIDDLE, SIDE_LEFT>))
136 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_LEFT, (OnUpdateCtxtDirCopy<SIDE_MIDDLE, SIDE_LEFT>))
137 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_RIGHT, (OnCtxtDirCopy<SIDE_MIDDLE, SIDE_RIGHT>))
138 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_RIGHT, (OnUpdateCtxtDirCopy<SIDE_MIDDLE, SIDE_RIGHT>))
139 ON_COMMAND(ID_DIR_DEL_LEFT, OnCtxtDirDel<SIDE_LEFT>)
140 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_LEFT, OnUpdateCtxtDirDel<SIDE_LEFT>)
141 ON_COMMAND(ID_DIR_DEL_RIGHT, OnCtxtDirDel<SIDE_RIGHT>)
142 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_MIDDLE, OnUpdateCtxtDirDel<SIDE_MIDDLE>)
143 ON_COMMAND(ID_DIR_DEL_MIDDLE, OnCtxtDirDel<SIDE_MIDDLE>)
144 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_RIGHT, OnUpdateCtxtDirDel<SIDE_RIGHT>)
145 ON_COMMAND(ID_DIR_DEL_BOTH, OnCtxtDirDelBoth)
146 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_BOTH, OnUpdateCtxtDirDelBoth)
147 ON_COMMAND(ID_DIR_DEL_ALL, OnCtxtDirDelBoth)
148 ON_UPDATE_COMMAND_UI(ID_DIR_DEL_ALL, OnUpdateCtxtDirDelBoth)
149 ON_COMMAND(ID_DIR_OPEN_LEFT, OnCtxtDirOpen<SIDE_LEFT>)
150 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT, OnUpdateCtxtDirOpen<SIDE_LEFT>)
151 ON_COMMAND(ID_DIR_OPEN_LEFT_WITH, OnCtxtDirOpenWith<SIDE_LEFT>)
152 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_WITH, OnUpdateCtxtDirOpenWith<SIDE_LEFT>)
153 ON_COMMAND(ID_DIR_OPEN_LEFT_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_LEFT>)
154 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_LEFT>)
155 ON_COMMAND(ID_DIR_OPEN_MIDDLE, OnCtxtDirOpen<SIDE_MIDDLE>)
156 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE, OnUpdateCtxtDirOpen<SIDE_MIDDLE>)
157 ON_COMMAND(ID_DIR_OPEN_MIDDLE_WITH, OnCtxtDirOpenWith<SIDE_MIDDLE>)
158 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_WITH, OnUpdateCtxtDirOpenWith<SIDE_MIDDLE>)
159 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_MIDDLE>)
160 ON_COMMAND(ID_DIR_OPEN_MIDDLE_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_MIDDLE>)
161 ON_COMMAND(ID_DIR_OPEN_RIGHT, OnCtxtDirOpen<SIDE_RIGHT>)
162 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT, OnUpdateCtxtDirOpen<SIDE_RIGHT>)
163 ON_COMMAND(ID_DIR_OPEN_RIGHT_WITH, OnCtxtDirOpenWith<SIDE_RIGHT>)
164 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_WITH, OnUpdateCtxtDirOpenWith<SIDE_RIGHT>)
165 ON_COMMAND(ID_DIR_OPEN_RIGHT_PARENT_FOLDER, OnCtxtDirOpenParentFolder<SIDE_RIGHT>)
166 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_PARENT_FOLDER, OnUpdateCtxtDirOpenParentFolder<SIDE_RIGHT>)
167 ON_COMMAND(ID_POPUP_OPEN_WITH_UNPACKER, OnCtxtOpenWithUnpacker)
168 ON_UPDATE_COMMAND_UI(ID_POPUP_OPEN_WITH_UNPACKER, OnUpdateCtxtOpenWithUnpacker)
169 ON_COMMAND(ID_DIR_OPEN_LEFT_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_LEFT>)
170 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_LEFT_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_LEFT>)
171 ON_COMMAND(ID_DIR_OPEN_MIDDLE_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_MIDDLE>)
172 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_MIDDLE_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_MIDDLE>)
173 ON_COMMAND(ID_DIR_OPEN_RIGHT_WITHEDITOR, OnCtxtDirOpenWithEditor<SIDE_RIGHT>)
174 ON_UPDATE_COMMAND_UI(ID_DIR_OPEN_RIGHT_WITHEDITOR, OnUpdateCtxtDirOpenWithEditor<SIDE_RIGHT>)
175 ON_COMMAND(ID_DIR_COPY_LEFT_TO_BROWSE, OnCtxtDirCopyTo<SIDE_LEFT>)
176 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_BROWSE, OnCtxtDirCopyTo<SIDE_MIDDLE>)
177 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_BROWSE, OnCtxtDirCopyTo<SIDE_RIGHT>)
178 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
179 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
180 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_BROWSE, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
184 ON_COMMAND(ID_FIRSTDIFF, OnFirstdiff)
185 ON_UPDATE_COMMAND_UI(ID_FIRSTDIFF, OnUpdateFirstdiff)
186 ON_COMMAND(ID_LASTDIFF, OnLastdiff)
187 ON_UPDATE_COMMAND_UI(ID_LASTDIFF, OnUpdateLastdiff)
188 ON_COMMAND(ID_NEXTDIFF, OnNextdiff)
189 ON_UPDATE_COMMAND_UI(ID_NEXTDIFF, OnUpdateNextdiff)
190 ON_COMMAND(ID_PREVDIFF, OnPrevdiff)
191 ON_UPDATE_COMMAND_UI(ID_PREVDIFF, OnUpdatePrevdiff)
192 ON_COMMAND(ID_CURDIFF, OnCurdiff)
193 ON_UPDATE_COMMAND_UI(ID_CURDIFF, OnUpdateCurdiff)
194 ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateSave)
195 ON_MESSAGE(MSG_UI_UPDATE, OnUpdateUIMessage)
196 ON_COMMAND(ID_REFRESH, OnRefresh)
197 ON_UPDATE_COMMAND_UI(ID_REFRESH, OnUpdateRefresh)
199 ON_UPDATE_COMMAND_UI(ID_STATUS_RIGHTDIR_RO, OnUpdateStatusRightRO)
200 ON_UPDATE_COMMAND_UI(ID_STATUS_MIDDLEDIR_RO, OnUpdateStatusMiddleRO)
201 ON_UPDATE_COMMAND_UI(ID_STATUS_LEFTDIR_RO, OnUpdateStatusLeftRO)
202 ON_COMMAND(ID_FILE_LEFT_READONLY, OnReadOnly<SIDE_LEFT>)
203 ON_UPDATE_COMMAND_UI(ID_FILE_LEFT_READONLY, OnUpdateReadOnly<SIDE_LEFT>)
204 ON_COMMAND(ID_FILE_MIDDLE_READONLY, OnReadOnly<SIDE_MIDDLE>)
205 ON_UPDATE_COMMAND_UI(ID_FILE_MIDDLE_READONLY, OnUpdateReadOnly<SIDE_MIDDLE>)
206 ON_COMMAND(ID_FILE_RIGHT_READONLY, OnReadOnly<SIDE_RIGHT>)
207 ON_UPDATE_COMMAND_UI(ID_FILE_RIGHT_READONLY, OnUpdateReadOnly<SIDE_RIGHT>)
208 ON_COMMAND(ID_TOOLS_CUSTOMIZECOLUMNS, OnCustomizeColumns)
209 ON_COMMAND(ID_TOOLS_GENERATEREPORT, OnToolsGenerateReport)
210 ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
211 ON_MESSAGE(MSG_GENERATE_FLIE_COMPARE_REPORT, OnGenerateFileCmpReport)
212 ON_COMMAND(ID_DIR_ZIP_LEFT, OnCtxtDirZip<DirItemEnumerator::Left>)
213 ON_COMMAND(ID_DIR_ZIP_MIDDLE, OnCtxtDirZip<DirItemEnumerator::Middle>)
214 ON_COMMAND(ID_DIR_ZIP_RIGHT, OnCtxtDirZip<DirItemEnumerator::Right>)
215 ON_COMMAND(ID_DIR_ZIP_BOTH, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
216 ON_COMMAND(ID_DIR_ZIP_ALL, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
217 ON_COMMAND(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders | DirItemEnumerator::DiffsOnly>)
218 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_LEFT, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
219 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_MIDDLE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
220 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_RIGHT, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
221 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH, OnUpdateCtxtDirCopyBothTo)
222 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_ALL, OnUpdateCtxtDirCopyBothTo)
223 ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnUpdateCtxtDirCopyBothDiffsOnlyTo)
224 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_LEFT, OnCtxtDirShellContextMenu<SIDE_LEFT>)
225 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, OnCtxtDirShellContextMenu<SIDE_MIDDLE>)
226 ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_RIGHT, OnCtxtDirShellContextMenu<SIDE_RIGHT>)
227 ON_COMMAND(ID_EDIT_SELECT_ALL, OnSelectAll)
228 ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateSelectAll)
229 ON_COMMAND_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnPluginPredifferMode)
230 ON_UPDATE_COMMAND_UI_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnUpdatePluginPredifferMode)
231 ON_COMMAND(ID_DIR_COPY_PATHNAMES_LEFT, OnCopyPathnames<SIDE_LEFT>)
232 ON_COMMAND(ID_DIR_COPY_PATHNAMES_MIDDLE, OnCopyPathnames<SIDE_MIDDLE>)
233 ON_COMMAND(ID_DIR_COPY_PATHNAMES_RIGHT, OnCopyPathnames<SIDE_RIGHT>)
234 ON_COMMAND(ID_DIR_COPY_PATHNAMES_BOTH, OnCopyBothPathnames)
235 ON_COMMAND(ID_DIR_COPY_PATHNAMES_ALL, OnCopyBothPathnames)
236 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_LEFT, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
237 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_MIDDLE, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
238 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_RIGHT, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
239 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_BOTH, OnUpdateCtxtDirCopyBoth2)
240 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_ALL, OnUpdateCtxtDirCopyBoth2)
241 ON_COMMAND(ID_DIR_COPY_FILENAMES, OnCopyFilenames)
242 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_FILENAMES, OnUpdateCopyFilenames)
243 ON_COMMAND(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_LEFT>)
244 ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnCopyToClipboard<SIDE_MIDDLE>)
245 ON_COMMAND(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_RIGHT>)
246 ON_COMMAND(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnCopyBothToClipboard)
247 ON_COMMAND(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnCopyBothToClipboard)
248 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
249 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
250 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
251 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
252 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
253 ON_COMMAND(ID_DIR_ITEM_RENAME, OnItemRename)
254 ON_UPDATE_COMMAND_UI(ID_DIR_ITEM_RENAME, OnUpdateItemRename)
255 ON_COMMAND(ID_DIR_HIDE_FILENAMES, OnHideFilenames)
256 ON_COMMAND(ID_DIR_MOVE_LEFT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_LEFT>)
257 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_LEFT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_LEFT>)
258 ON_COMMAND(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnCtxtDirMoveTo<SIDE_MIDDLE>)
259 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_MIDDLE>)
260 ON_COMMAND(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_RIGHT>)
261 ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_RIGHT>)
262 ON_UPDATE_COMMAND_UI(ID_DIR_HIDE_FILENAMES, OnUpdateHideFilenames)
264 ON_COMMAND(ID_MERGE_DELETE, OnDelete)
265 ON_UPDATE_COMMAND_UI(ID_MERGE_DELETE, OnUpdateDelete)
266 ON_COMMAND(ID_RESCAN, OnMarkedRescan)
267 ON_UPDATE_COMMAND_UI(ID_STATUS_DIFFNUM, OnUpdateStatusNum)
268 ON_COMMAND(ID_VIEW_SHOWHIDDENITEMS, OnViewShowHiddenItems)
269 ON_UPDATE_COMMAND_UI(ID_VIEW_SHOWHIDDENITEMS, OnUpdateViewShowHiddenItems)
270 ON_COMMAND(ID_MERGE_COMPARE, OnMergeCompare)
271 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE, OnUpdateMergeCompare)
272 ON_COMMAND(ID_MERGE_COMPARE_LEFT1_LEFT2, OnMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
273 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_LEFT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
274 ON_COMMAND(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
275 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
276 ON_COMMAND(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
277 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
278 ON_COMMAND(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
279 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
280 ON_COMMAND(ID_MERGE_COMPARE_NONHORIZONTALLY, OnMergeCompareNonHorizontally)
281 ON_COMMAND(ID_MERGE_COMPARE_XML, OnMergeCompareXML)
282 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_XML, OnUpdateMergeCompare)
283 ON_COMMAND_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnMergeCompareAs)
284 ON_UPDATE_COMMAND_UI_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnUpdateMergeCompare)
285 ON_COMMAND(ID_VIEW_TREEMODE, OnViewTreeMode)
286 ON_UPDATE_COMMAND_UI(ID_VIEW_TREEMODE, OnUpdateViewTreeMode)
287 ON_COMMAND(ID_VIEW_EXPAND_ALLSUBDIRS, OnViewExpandAllSubdirs)
288 ON_UPDATE_COMMAND_UI(ID_VIEW_EXPAND_ALLSUBDIRS, OnUpdateViewExpandAllSubdirs)
289 ON_COMMAND(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnViewCollapseAllSubdirs)
290 ON_UPDATE_COMMAND_UI(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnUpdateViewCollapseAllSubdirs)
291 ON_COMMAND(ID_SWAPPANES_SWAP12, (OnViewSwapPanes<0, 1>))
292 ON_COMMAND(ID_SWAPPANES_SWAP23, (OnViewSwapPanes<1, 2>))
293 ON_COMMAND(ID_SWAPPANES_SWAP13, (OnViewSwapPanes<0, 2>))
294 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP12, (OnUpdateViewSwapPanes<0, 1>))
295 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP23, (OnUpdateViewSwapPanes<1, 2>))
296 ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP13, (OnUpdateViewSwapPanes<0, 2>))
297 ON_COMMAND(ID_VIEW_DIR_STATISTICS, OnViewCompareStatistics)
298 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENT, OnOptionsShowDifferent)
299 ON_COMMAND(ID_OPTIONS_SHOWIDENTICAL, OnOptionsShowIdentical)
300 ON_COMMAND(ID_OPTIONS_SHOWUNIQUELEFT, OnOptionsShowUniqueLeft)
301 ON_COMMAND(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnOptionsShowUniqueMiddle)
302 ON_COMMAND(ID_OPTIONS_SHOWUNIQUERIGHT, OnOptionsShowUniqueRight)
303 ON_COMMAND(ID_OPTIONS_SHOWBINARIES, OnOptionsShowBinaries)
304 ON_COMMAND(ID_OPTIONS_SHOWSKIPPED, OnOptionsShowSkipped)
305 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnOptionsShowDifferentLeftOnly)
306 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnOptionsShowDifferentMiddleOnly)
307 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnOptionsShowDifferentRightOnly)
308 ON_COMMAND(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnOptionsShowMissingLeftOnly)
309 ON_COMMAND(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnOptionsShowMissingMiddleOnly)
310 ON_COMMAND(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnOptionsShowMissingRightOnly)
311 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENT, OnUpdateOptionsShowdifferent)
312 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWIDENTICAL, OnUpdateOptionsShowidentical)
313 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUELEFT, OnUpdateOptionsShowuniqueleft)
314 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnUpdateOptionsShowuniquemiddle)
315 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUERIGHT, OnUpdateOptionsShowuniqueright)
316 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWBINARIES, OnUpdateOptionsShowBinaries)
317 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWSKIPPED, OnUpdateOptionsShowSkipped)
318 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnUpdateOptionsShowDifferentLeftOnly)
319 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnUpdateOptionsShowDifferentMiddleOnly)
320 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnUpdateOptionsShowDifferentRightOnly)
321 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnUpdateOptionsShowMissingLeftOnly)
322 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnUpdateOptionsShowMissingMiddleOnly)
323 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnUpdateOptionsShowMissingRightOnly)
324 ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
325 ON_COMMAND(ID_HELP, OnHelp)
326 ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
327 ON_COMMAND(ID_EDIT_CUT, OnEditCut)
328 ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
329 ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
330 ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
332 ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
333 ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
334 ON_NOTIFY_REFLECT(LVN_BEGINLABELEDIT, OnBeginLabelEdit)
335 ON_NOTIFY_REFLECT(LVN_ENDLABELEDIT, OnEndLabelEdit)
336 ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
337 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
338 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
339 ON_BN_CLICKED(IDC_COMPARISON_STOP, OnBnClickedComparisonStop)
340 ON_BN_CLICKED(IDC_COMPARISON_PAUSE, OnBnClickedComparisonPause)
341 ON_BN_CLICKED(IDC_COMPARISON_CONTINUE, OnBnClickedComparisonContinue)
344 /////////////////////////////////////////////////////////////////////////////
345 // CDirView diagnostics
349 CDirDoc* CDirView::GetDocument() // non-debug version is inline
351 ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDirDoc)));
352 return (CDirDoc*)m_pDocument;
356 /////////////////////////////////////////////////////////////////////////////
357 // CDirView message handlers
359 void CDirView::OnInitialUpdate()
361 const int iconCX = []() {
362 const int cx = GetSystemMetrics(SM_CXSMICON);
371 const int iconCY = iconCX;
372 CListView::OnInitialUpdate();
373 m_pList = &GetListCtrl();
374 m_pIList.reset(new IListCtrlImpl(m_pList->m_hWnd));
375 GetDocument()->SetDirView(this);
376 m_pColItems.reset(new DirViewColItems(GetDocument()->m_nDirs));
378 m_pList->SendMessage(CCM_SETUNICODEFORMAT, TRUE, 0);
380 // Load user-selected font
381 if (GetOptionsMgr()->GetBool(OPT_FONT_DIRCMP + OPT_FONT_USECUSTOM))
383 m_font.CreateFontIndirect(&GetMainFrame()->m_lfDir);
384 CWnd::SetFont(&m_font, TRUE);
388 m_pList->SetBkColor(m_cachedColors.clrDirMargin);
390 // Replace standard header with sort header
391 HWND hWnd = ListView_GetHeader(m_pList->m_hWnd);
393 m_ctlSortHeader.SubclassWindow(hWnd);
395 // Load the icons used for the list view (to reflect diff status)
396 // NOTE: these must be in the exactly the same order as in the `enum`
397 // definition in the DirActions.h file (ref: DIFFIMG_LUNIQUE)
398 VERIFY(m_imageList.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
400 IDI_LFILE, IDI_MFILE, IDI_RFILE,
401 IDI_MRFILE, IDI_LRFILE, IDI_LMFILE,
402 IDI_NOTEQUALFILE, IDI_EQUALFILE, IDI_FILE,
403 IDI_EQUALBINARY, IDI_BINARYDIFF,
404 IDI_LFOLDER, IDI_MFOLDER, IDI_RFOLDER,
405 IDI_MRFOLDER, IDI_LRFOLDER, IDI_LMFOLDER,
406 IDI_FILESKIP, IDI_FOLDERSKIP,
407 IDI_NOTEQUALFOLDER, IDI_EQUALFOLDER, IDI_FOLDER,
409 IDI_FOLDERUP, IDI_FOLDERUP_DISABLE,
411 IDI_NOTEQUALTEXTFILE, IDI_EQUALTEXTFILE,
412 IDI_NOTEQUALIMAGE, IDI_EQUALIMAGE,
414 for (auto id : icon_ids)
415 VERIFY(-1 != m_imageList.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
416 m_pList->SetImageList(&m_imageList, LVSIL_SMALL);
418 // Load the icons used for the list view (expanded/collapsed state icons)
419 VERIFY(m_imageState.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
420 for (auto id : { IDI_TREE_STATE_COLLAPSED, IDI_TREE_STATE_EXPANDED })
421 VERIFY(-1 != m_imageState.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
423 // Restore column orders as they had them last time they ran
424 m_pColItems->LoadColumnOrders(
425 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS));
427 // Display column headers (in appropriate order)
430 // Show selection across entire row.u
431 // Also allow user to rearrange columns via drag&drop of headers.
432 // Also enable infotips.
433 DWORD exstyle = LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_INFOTIP;
434 m_pList->SetExtendedStyle(exstyle);
437 BOOL CDirView::PreCreateWindow(CREATESTRUCT& cs)
439 CListView::PreCreateWindow(cs);
440 cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
445 * @brief Called before compare is started.
446 * CDirDoc calls this function before new compare is started, so this
447 * is good place to setup GUI for compare.
448 * @param [in] pCompareStats Pointer to class having current compare stats.
450 void CDirView::StartCompare(CompareStats *pCompareStats)
452 if (m_pCmpProgressBar == nullptr)
453 m_pCmpProgressBar.reset(new DirCompProgressBar());
455 if (!::IsWindow(m_pCmpProgressBar->GetSafeHwnd()))
456 m_pCmpProgressBar->Create(GetParentFrame());
458 m_pCmpProgressBar->SetCompareStat(pCompareStats);
459 m_pCmpProgressBar->StartUpdating();
461 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), TRUE, FALSE);
463 m_compareStart = clock();
467 * @brief Called when folder compare row is double-clicked with mouse.
468 * Selected item is opened to folder or file compare.
470 void CDirView::OnLButtonDblClk(UINT nFlags, CPoint point)
474 m_pList->SubItemHitTest(&lvhti);
475 if (lvhti.iItem >= 0)
477 const DIFFITEM& di = GetDiffItem(lvhti.iItem);
478 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
480 if (di.customFlags & ViewCustomFlags::EXPANDED)
481 CollapseSubdir(lvhti.iItem);
483 ExpandSubdir(lvhti.iItem);
487 CWaitCursor waitstatus;
491 CListView::OnLButtonDblClk(nFlags, point);
495 * @brief Load or reload the columns (headers) of the list view
497 void CDirView::ReloadColumns()
499 LoadColumnHeaderItems();
502 m_pColItems->LoadColumnWidths(
503 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
504 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
509 * @brief Redisplay items in subfolder
510 * @param [in] diffpos First item position in subfolder.
511 * @param [in] level Indent level
512 * @param [in,out] index Index of the item to be inserted.
513 * @param [in,out] alldiffs Number of different items
515 void CDirView::RedisplayChildren(DIFFITEM *diffpos, int level, UINT &index, int &alldiffs)
517 const CDiffContext &ctxt = GetDiffContext();
518 while (diffpos != nullptr)
520 DIFFITEM *curdiffpos = diffpos;
521 const DIFFITEM &di = ctxt.GetNextSiblingDiffPosition(diffpos);
523 if (di.diffcode.isResultDiff() || (!di.diffcode.existAll() && !di.diffcode.isResultFiltered()))
526 bool bShowable = IsShowable(ctxt, di, m_dirfilter);
531 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, level);
533 if (di.HasChildren())
535 m_pList->SetItemState(index - 1, INDEXTOSTATEIMAGEMASK((di.customFlags & ViewCustomFlags::EXPANDED) ? 2 : 1), LVIS_STATEIMAGEMASK);
536 if (di.customFlags & ViewCustomFlags::EXPANDED)
537 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
542 if (!ctxt.m_bRecursive || !di.diffcode.isDirectory() || !di.diffcode.existAll())
544 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, 0);
547 if (di.HasChildren())
549 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
554 m_firstDiffItem.reset();
555 m_lastDiffItem.reset();
559 * @brief Redisplay folder compare view.
560 * This function clears folder compare view and then adds
561 * items from current compare to it.
563 void CDirView::Redisplay()
565 const CDirDoc *pDoc = GetDocument();
566 const CDiffContext &ctxt = GetDiffContext();
567 PathContext pathsParent;
568 CImageList emptyImageList;
571 // Disable redrawing while adding new items
574 DeleteAllDisplayItems();
576 m_pList->SetImageList((m_bTreeMode && ctxt.m_bRecursive) ? &m_imageState : &emptyImageList, LVSIL_STATE);
578 // If non-recursive compare, add special item(s)
579 if (!ctxt.m_bRecursive ||
580 CheckAllowUpwardDirectory(ctxt, pDoc->m_pTempPathContext, pathsParent) == AllowUpwardDirectory::ParentIsTempPath)
582 cnt += AddSpecialItems();
586 DIFFITEM *diffpos = ctxt.GetFirstDiffPosition();
587 RedisplayChildren(diffpos, 0, cnt, alldiffs);
588 if (pDoc->m_diffThread.GetThreadState() == CDiffThread::THREAD_COMPLETED)
589 GetParentFrame()->SetLastCompareResult(alldiffs);
590 SortColumnsAppropriately();
595 * @brief User right-clicked somewhere in this view
597 void CDirView::OnContextMenu(CWnd*, CPoint point)
599 if (GetListCtrl().GetItemCount() == 0)
601 // Make sure window is active
602 GetParentFrame()->ActivateFrame();
605 if (point.x == -1 && point.y == -1)
607 //keystroke invocation
610 ClientToScreen(rect);
612 point = rect.TopLeft();
617 // Check if user right-clicked on header
618 // convert screen coordinates to client coordinates of listview
619 CPoint insidePt = point;
620 GetListCtrl().ScreenToClient(&insidePt);
621 // TODO: correct for hscroll ?
622 // Ask header control if click was on one of its header items
623 HDHITTESTINFO hhti = { 0 };
625 int col = static_cast<int>(GetListCtrl().GetHeaderCtrl()->SendMessage(HDM_HITTEST, 0, (LPARAM) & hhti));
628 // Presumably hhti.flags & HHT_ONHEADER is true
629 HeaderContextMenu(point, m_pColItems->ColPhysToLog(col));
632 // bail out if point is not in any row
633 LVHITTESTINFO lhti = { 0 };
635 ScreenToClient(&insidePt);
637 i = GetListCtrl().HitTest(insidePt);
638 TRACE(_T("i=%d\n"), i);
643 ListContextMenu(point, i);
647 * @brief Format context menu string and disable item if it cannot be applied.
649 static void NTAPI FormatContextMenu(BCMenu *pPopup, UINT uIDItem, int n1, int n2 = 0, int n3 = 0)
652 pPopup->GetMenuText(uIDItem, s1, MF_BYCOMMAND);
653 s2.FormatMessage(s1, NumToStr(n1).c_str(), NumToStr(n2).c_str(), NumToStr(n3).c_str());
654 pPopup->SetMenuText(uIDItem, s2, MF_BYCOMMAND);
657 pPopup->EnableMenuItem(uIDItem, MF_GRAYED);
662 * @brief Toggle context menu item
664 static void NTAPI CheckContextMenu(BCMenu *pPopup, UINT uIDItem, BOOL bCheck)
667 pPopup->CheckMenuItem(uIDItem, MF_CHECKED);
669 pPopup->CheckMenuItem(uIDItem, MF_UNCHECKED);
673 * @brief User right-clicked in listview rows
675 void CDirView::ListContextMenu(CPoint point, int /*i*/)
677 CDirDoc* pDoc = GetDocument();
679 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
680 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
681 theApp.TranslateMenu(menu.m_hMenu);
683 // 1st submenu of IDR_POPUP_DIRVIEW is for item popup
684 BCMenu *pPopup = static_cast<BCMenu*>(menu.GetSubMenu(0));
685 ASSERT(pPopup != nullptr);
687 if (pDoc->m_nDirs < 3)
689 pPopup->RemoveMenu(ID_DIR_COPY_LEFT_TO_MIDDLE, MF_BYCOMMAND);
690 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_LEFT, MF_BYCOMMAND);
691 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_RIGHT, MF_BYCOMMAND);
692 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
693 pPopup->RemoveMenu(ID_DIR_COPY_RIGHT_TO_MIDDLE, MF_BYCOMMAND);
694 pPopup->RemoveMenu(ID_DIR_MOVE_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
695 pPopup->RemoveMenu(ID_DIR_DEL_MIDDLE, MF_BYCOMMAND);
696 pPopup->RemoveMenu(ID_DIR_DEL_ALL, MF_BYCOMMAND);
697 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE, MF_BYCOMMAND);
699 for (int i = 0; i < pPopup->GetMenuItemCount(); ++i)
701 if (pPopup->GetMenuItemID(i) == ID_DIR_HIDE_FILENAMES)
702 pPopup->RemoveMenu(i + 3, MF_BYPOSITION);
705 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITHEDITOR, MF_BYCOMMAND);
706 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITH, MF_BYCOMMAND);
707 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_MIDDLE, MF_BYCOMMAND);
708 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_ALL, MF_BYCOMMAND);
709 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, MF_BYCOMMAND);
710 pPopup->RemoveMenu(ID_DIR_COPY_ALL_TO_CLIPBOARD, MF_BYCOMMAND);
711 pPopup->RemoveMenu(ID_DIR_ZIP_MIDDLE, MF_BYCOMMAND);
712 pPopup->RemoveMenu(ID_DIR_ZIP_ALL, MF_BYCOMMAND);
713 pPopup->RemoveMenu(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, MF_BYCOMMAND);
714 pPopup->RemoveMenu(ID_MERGE_COMPARE_NONHORIZONTALLY, MF_BYCOMMAND);
718 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_BOTH, MF_BYCOMMAND);
719 pPopup->RemoveMenu(ID_DIR_COPY_BOTH_TO_CLIPBOARD, MF_BYCOMMAND);
720 pPopup->RemoveMenu(ID_DIR_ZIP_BOTH, MF_BYCOMMAND);
721 pPopup->RemoveMenu(ID_DIR_DEL_BOTH, MF_BYCOMMAND);
722 pPopup->RemoveMenu(2, MF_BYPOSITION); // Compare Non-horizontally
725 CMenu menuPluginsHolder;
726 menuPluginsHolder.LoadMenu(IDR_POPUP_PLUGINS_SETTINGS);
727 theApp.TranslateMenu(menuPluginsHolder.m_hMenu);
728 String s = _("Plugin Settings");
729 pPopup->AppendMenu(MF_SEPARATOR);
730 pPopup->AppendMenu(MF_POPUP, static_cast<int>(reinterpret_cast<uintptr_t>(menuPluginsHolder.m_hMenu)), s.c_str());
732 CFrameWnd *pFrame = GetTopLevelFrame();
733 ASSERT(pFrame != nullptr);
734 pFrame->m_bAutoMenuEnable = FALSE;
735 // invoke context menu
736 // this will invoke all the OnUpdate methods to enable/disable the individual items
737 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
740 pFrame->m_bAutoMenuEnable = TRUE;
744 * @brief User right-clicked on specified logical column
746 void CDirView::HeaderContextMenu(CPoint point, int /*i*/)
749 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
750 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
751 theApp.TranslateMenu(menu.m_hMenu);
752 // 2nd submenu of IDR_POPUP_DIRVIEW is for header popup
753 BCMenu* pPopup = static_cast<BCMenu *>(menu.GetSubMenu(1));
754 ASSERT(pPopup != nullptr);
756 // invoke context menu
757 // this will invoke all the OnUpdate methods to enable/disable the individual items
758 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
763 * @brief Gets Explorer's context menu for a group of selected files.
765 * @param [in] Side whether to get context menu for the files from the left or
767 * @retval true menu successfully retrieved.
768 * @retval falsea an error occurred while retrieving the menu.
770 bool CDirView::ListShellContextMenu(SIDE_TYPE stype)
772 CShellContextMenu* shellContextMenu;
775 shellContextMenu = m_pShellContextMenuMiddle.get(); break;
777 shellContextMenu = m_pShellContextMenuRight.get(); break;
779 shellContextMenu = m_pShellContextMenuLeft.get(); break;
781 shellContextMenu->Initialize();
782 ApplyFolderNameAndFileName(SelBegin(), SelEnd(), stype, GetDiffContext(),
783 [&](const String& path, const String& filename) { shellContextMenu->AddItem(path, filename); });
784 return shellContextMenu->RequeryShellContextMenu();
788 * @brief User chose (main menu) Copy from right to left
790 void CDirView::OnDirCopy(UINT id)
792 bool to_right = (id == ID_L2R) ? true : false;
793 if (GetDocument()->m_nDirs < 3)
796 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_RIGHT>, _("Copying files..."));
798 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_LEFT>, _("Copying files..."));
804 switch (m_nActivePane)
807 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_MIDDLE>, _("Copying files..."));
811 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_RIGHT>, _("Copying files..."));
817 switch (m_nActivePane)
821 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_LEFT>, _("Copying files..."));
824 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_MIDDLE>, _("Copying files..."));
831 /// User chose (context men) Copy from right to left
832 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
833 void CDirView::OnCtxtDirCopy()
835 DoDirAction(&DirActions::Copy<srctype, dsttype>, _("Copying files..."));
838 /// User chose (context menu) Copy left to...
839 template<SIDE_TYPE stype>
840 void CDirView::OnCtxtDirCopyTo()
842 DoDirActionTo(stype, &DirActions::CopyTo<stype>, _("Copying files..."));
845 /// Update context menu Copy Right to Left item
846 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
847 void CDirView::OnUpdateCtxtDirCopy(CCmdUI* pCmdUI)
849 DoUpdateDirCopy<srctype, dsttype>(pCmdUI, eContext);
852 /// Update main menu Copy Right to Left item
853 void CDirView::OnUpdateDirCopy(CCmdUI* pCmdUI)
855 bool to_right = pCmdUI->m_nID == ID_L2R ? true : false;
856 if (GetDocument()->m_nDirs < 3)
859 DoUpdateDirCopy<SIDE_LEFT, SIDE_RIGHT>(pCmdUI, eContext);
861 DoUpdateDirCopy<SIDE_RIGHT, SIDE_LEFT>(pCmdUI, eContext);
867 switch (m_nActivePane)
870 DoUpdateDirCopy<SIDE_LEFT, SIDE_MIDDLE>(pCmdUI, eContext);
874 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_RIGHT>(pCmdUI, eContext);
880 switch (m_nActivePane)
884 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_LEFT>(pCmdUI, eContext);
887 DoUpdateDirCopy<SIDE_RIGHT, SIDE_MIDDLE>(pCmdUI, eContext);
894 void CDirView::DoDirAction(DirActions::method_type func, const String& status_message)
896 CWaitCursor waitstatus;
899 // First we build a list of desired actions
900 FileActionScript actionScript;
901 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
902 DirItemWithIndexIterator end;
903 FileActionScript *rsltScript;
904 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
905 ASSERT(rsltScript == &actionScript);
906 // Now we prompt, and execute actions
907 ConfirmAndPerformActions(actionScript);
908 } catch (ContentsChangedException& e) {
909 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
910 } catch (FileOperationException& e) {
911 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
915 void CDirView::DoDirActionTo(SIDE_TYPE stype, DirActions::method_type func, const String& status_message)
918 String startPath(m_lastCopyFolder);
919 String selectfolder_title;
921 if (stype == SIDE_LEFT)
922 selectfolder_title = _("Left side - select destination folder:");
923 else if (stype == SIDE_MIDDLE)
924 selectfolder_title = _("Middle side - select destination folder:");
925 else if (stype == SIDE_RIGHT)
926 selectfolder_title = _("Right side - select destination folder:");
928 if (!SelectFolder(destPath, startPath.c_str(), selectfolder_title))
931 m_lastCopyFolder = destPath;
932 CWaitCursor waitstatus;
935 // First we build a list of desired actions
936 FileActionScript actionScript;
937 actionScript.m_destBase = destPath;
938 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
939 DirItemWithIndexIterator end;
940 FileActionScript *rsltScript;
941 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
942 ASSERT(rsltScript == &actionScript);
943 // Now we prompt, and execute actions
944 ConfirmAndPerformActions(actionScript);
945 } catch (ContentsChangedException& e) {
946 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
950 // Confirm with user, then perform the action list
951 void CDirView::ConfirmAndPerformActions(FileActionScript & actionList)
953 if (actionList.GetActionItemCount() == 0) // Not sure it is possible to get right-click menu without
954 return; // any selected items, but may as well be safe
956 ASSERT(actionList.GetActionItemCount()>0); // Or else the update handler got it wrong
958 // Set parent window so modality is correct and correct window gets focus
960 actionList.SetParentWindow(this->GetSafeHwnd());
963 ConfirmActionList(GetDiffContext(), actionList);
964 } catch (ConfirmationNeededException& e) {
965 ConfirmFolderCopyDlg dlg;
966 dlg.m_caption = e.m_caption;
967 dlg.m_question = e.m_question;
968 dlg.m_fromText = e.m_fromText;
969 dlg.m_toText = e.m_toText;
970 dlg.m_fromPath = e.m_fromPath;
971 dlg.m_toPath = e.m_toPath;
972 INT_PTR ans = dlg.DoModal();
973 if (ans != IDOK && ans != IDYES)
976 PerformActionList(actionList);
980 * @brief Perform an array of actions
981 * @note There can be only COPY or DELETE actions, not both!
983 void CDirView::PerformActionList(FileActionScript & actionScript)
985 // Check option and enable putting deleted items to Recycle Bin
986 if (GetOptionsMgr()->GetBool(OPT_USE_RECYCLE_BIN))
987 actionScript.UseRecycleBin(true);
989 actionScript.UseRecycleBin(false);
991 actionScript.SetParentWindow(GetMainFrame()->GetSafeHwnd());
993 theApp.AddOperation();
994 bool succeeded = actionScript.Run();
996 UpdateAfterFileScript(actionScript);
997 theApp.RemoveOperation();
998 if (!succeeded && !actionScript.IsCanceled())
999 throw FileOperationException(_T("File operation failed"));
1003 * @brief Update results after running FileActionScript.
1004 * This functions is called after script is finished to update
1005 * results (including UI).
1006 * @param [in] actionlist Script that was run.
1008 void CDirView::UpdateAfterFileScript(FileActionScript & actionList)
1010 bool bItemsRemoved = false;
1011 int curSel = GetFirstSelectedInd();
1012 CDiffContext& ctxt = GetDiffContext();
1013 while (actionList.GetActionItemCount()>0)
1015 // Start handling from tail of list, so removing items
1016 // doesn't invalidate our item indexes.
1017 FileActionItem act = actionList.RemoveTailActionItem();
1019 // Update doc (difflist)
1020 UPDATEITEM_TYPE updatetype = UpdateDiffAfterOperation(act, ctxt, GetDiffItem(act.context));
1021 if (updatetype == UPDATEITEM_REMOVE)
1023 DeleteItem(act.context, true);
1024 bItemsRemoved = true;
1026 else if (updatetype == UPDATEITEM_UPDATE)
1027 UpdateDiffItemStatus(act.context);
1030 // Make sure selection is at sensible place if all selected items
1034 UINT selected = GetSelectedCount();
1039 MoveFocus(0, curSel - 1, selected);
1044 Counts CDirView::Count(DirActions::method_type2 func) const
1046 return ::Count(SelBegin(), SelEnd(), MakeDirActions(func));
1049 /// Should Copy to Left be enabled or disabled ? (both main menu & context menu use this)
1050 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
1051 void CDirView::DoUpdateDirCopy(CCmdUI* pCmdUI, eMenuType menuType)
1053 Counts counts = Count(&DirActions::IsItemCopyableOnTo<srctype, dsttype>);
1054 pCmdUI->Enable(counts.count > 0);
1055 if (menuType == eContext)
1056 pCmdUI->SetText(FormatMenuItemString(srctype, dsttype, counts.count, counts.total).c_str());
1060 * @brief Update any resources necessary after a GUI language change
1062 void CDirView::UpdateResources()
1064 UpdateColumnNames();
1065 GetParentFrame()->UpdateResources();
1069 * @brief User just clicked a column, so perform sort
1071 void CDirView::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
1073 // set sort parameters and handle ascending/descending
1074 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*) pNMHDR;
1075 int oldSortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1076 int sortcol = m_pColItems->ColPhysToLog(pNMListView->iSubItem);
1077 if (sortcol == oldSortColumn)
1080 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1081 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, !bSortAscending);
1085 GetOptionsMgr()->SaveOption((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3, sortcol);
1086 // most columns start off ascending, but not dates
1087 bool bSortAscending = m_pColItems->IsDefaultSortAscending(sortcol);
1088 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, bSortAscending);
1091 SortColumnsAppropriately();
1095 void CDirView::SortColumnsAppropriately()
1097 int sortCol = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1098 if (sortCol == -1 || sortCol >= m_pColItems->GetColCount())
1101 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1102 m_ctlSortHeader.SetSortImage(m_pColItems->ColLogToPhys(sortCol), bSortAscending);
1103 //sort using static CompareFunc comparison function
1104 CompareState cs(&GetDiffContext(), m_pColItems.get(), sortCol, bSortAscending, m_bTreeMode);
1105 GetListCtrl().SortItems(cs.CompareFunc, reinterpret_cast<DWORD_PTR>(&cs));
1107 m_firstDiffItem.reset();
1108 m_lastDiffItem.reset();
1111 /// Do any last minute work as view closes
1112 void CDirView::OnDestroy()
1114 DeleteAllDisplayItems();
1117 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
1118 GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
1121 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
1122 GetOptionsMgr()->SaveOption(keyname,
1123 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)));
1126 CListView::OnDestroy();
1128 GetMainFrame()->ClearStatusbarItemCount();
1132 * @brief Open selected item when user presses ENTER key.
1134 void CDirView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
1136 if (nChar == VK_RETURN)
1138 int sel = GetFocusedItem();
1141 const DIFFITEM& di = GetDiffItem(sel);
1142 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
1144 if (di.customFlags & ViewCustomFlags::EXPANDED)
1145 CollapseSubdir(sel);
1151 CWaitCursor waitstatus;
1156 CListView::OnChar(nChar, nRepCnt, nFlags);
1160 * @brief Expand/collapse subfolder when "+/-" icon is clicked.
1162 void CDirView::OnClick(NMHDR* pNMHDR, LRESULT* pResult)
1164 LPNMITEMACTIVATE pNM = (LPNMITEMACTIVATE)pNMHDR;
1165 LVHITTESTINFO lvhti;
1166 lvhti.pt = pNM->ptAction;
1167 m_pList->SubItemHitTest(&lvhti);
1168 if (lvhti.flags == LVHT_ONITEMSTATEICON)
1170 const DIFFITEM &di = GetDiffItem(pNM->iItem);
1171 if (di.customFlags & ViewCustomFlags::EXPANDED)
1172 CollapseSubdir(pNM->iItem);
1174 ExpandSubdir(pNM->iItem);
1181 * @brief Collapse subfolder
1182 * @param [in] sel Folder item index in listview.
1184 void CDirView::CollapseSubdir(int sel)
1186 DIFFITEM& dip = this->GetDiffItem(sel);
1187 if (!m_bTreeMode || !(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1190 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1192 dip.customFlags &= ~ViewCustomFlags::EXPANDED;
1193 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(1), LVIS_STATEIMAGEMASK);
1195 int count = m_pList->GetItemCount();
1196 for (int i = sel + 1; i < count; i++)
1198 const DIFFITEM& di = GetDiffItem(i);
1199 if (!di.IsAncestor(&dip))
1201 m_pList->DeleteItem(i--);
1205 m_pList->SetRedraw(TRUE); // Turn updating back on
1209 * @brief Expand subfolder
1210 * @param [in] sel Folder item index in listview.
1212 void CDirView::ExpandSubdir(int sel, bool bRecursive)
1214 DIFFITEM& dip = GetDiffItem(sel);
1215 if (!m_bTreeMode || (dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1218 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1219 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(2), LVIS_STATEIMAGEMASK);
1221 CDiffContext &ctxt = GetDiffContext();
1222 dip.customFlags |= ViewCustomFlags::EXPANDED;
1224 ExpandSubdirs(ctxt, dip);
1226 DIFFITEM *diffpos = ctxt.GetFirstChildDiffPosition(GetItemKey(sel));
1227 UINT indext = sel + 1;
1229 RedisplayChildren(diffpos, dip.GetDepth() + 1, indext, alldiffs);
1231 SortColumnsAppropriately();
1233 m_pList->SetRedraw(TRUE); // Turn updating back on
1237 * @brief Open parent folder if possible.
1239 void CDirView::OpenParentDirectory()
1241 CDirDoc *pDoc = GetDocument();
1242 PathContext pathsParent;
1243 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
1245 case AllowUpwardDirectory::ParentIsTempPath:
1246 pDoc->m_pTempPathContext = pDoc->m_pTempPathContext->DeleteHead();
1248 case AllowUpwardDirectory::ParentIsRegularPath:
1250 for (int nIndex = 0; nIndex < pathsParent.GetSize(); ++nIndex)
1251 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nIndex) ? FFILEOPEN_READONLY : 0);
1252 GetMainFrame()->DoFileOpen(&pathsParent, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1254 case AllowUpwardDirectory::No:
1257 LangMessageBox(IDS_INVALID_DIRECTORY, MB_ICONSTOP);
1263 * @brief Get one or two selected items
1265 * Returns false if 0 or more than 3 items selecte
1267 bool CDirView::GetSelectedItems(int * sel1, int * sel2, int * sel3)
1271 *sel1 = m_pList->GetNextItem(-1, LVNI_SELECTED);
1274 *sel2 = m_pList->GetNextItem(*sel1, LVNI_SELECTED);
1277 *sel3 = m_pList->GetNextItem(*sel2, LVNI_SELECTED);
1280 int extra = m_pList->GetNextItem(*sel3, LVNI_SELECTED);
1281 return (extra == -1);
1285 * @brief Open special items (parent folders etc).
1286 * @param [in] pos1 First item position.
1287 * @param [in] pos2 Second item position.
1289 void CDirView::OpenSpecialItems(DIFFITEM *pos1, DIFFITEM *pos2, DIFFITEM *pos3)
1291 if (pos2==nullptr && pos3==nullptr)
1293 // Browse to parent folder(s) selected
1294 // SPECIAL_ITEM_POS is position for
1295 // special items, but there is currenly
1296 // only one (parent folder)
1297 OpenParentDirectory();
1301 // Parent directory & something else selected
1307 * @brief Creates a pairing folder for unique folder item.
1308 * This function creates a pairing folder for unique folder item in
1309 * folder compare. This way user can browse into unique folder's
1310 * contents and don't necessarily need to copy whole folder structure.
1311 * @return true if user agreed and folder was created.
1313 static bool CreateFoldersPair(const PathContext& paths)
1315 bool created = false;
1316 for (const auto& path : paths)
1318 if (!paths::DoesPathExist(path))
1321 strutils::format_string1(
1322 _("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?"),
1324 int res = AfxMessageBox(message.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN);
1326 created = paths::CreateIfNeeded(path);
1332 void CDirView::Open(const PathContext& paths, DWORD dwFlags[3], PackingInfo * infoUnpacker)
1335 for (auto path : paths)
1337 if (paths::DoesPathExist(path) == paths::IS_EXISTING_DIR)
1340 CDirDoc * pDoc = GetDocument();
1344 // Don't add folders to MRU
1345 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1347 else if (HasZipSupport() && std::count_if(paths.begin(), paths.end(), ArchiveGuessFormat) == paths.GetSize())
1349 // Open archives, not adding paths to MRU
1350 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, nullptr, _T(""), infoUnpacker);
1354 // Regular file case
1356 // Binary attributes are set after files are unpacked
1357 // so after plugins such as the MS-Office plugins have had a chance to make them textual
1358 // We haven't done unpacking yet in this diff, but if a binary flag is already set,
1359 // then it was set in a previous diff after unpacking, so we trust it
1361 // Open identical and different files
1362 FileLocation fileloc[3];
1364 const String sUntitled[] = { _("Untitled left"), paths.GetSize() < 3 ? _("Untitled right") : _("Untitled middle"), _("Untitled right") };
1365 for (int i = 0; i < paths.GetSize(); ++i)
1367 if (paths::DoesPathExist(paths[i]) == paths::DOES_NOT_EXIST)
1368 strDesc[i] = sUntitled[i];
1370 fileloc[i].setPath(paths[i]);
1373 GetMainFrame()->ShowAutoMergeDoc(pDoc, paths.GetSize(), fileloc,
1374 dwFlags, strDesc, _T(""), infoUnpacker);
1379 * @brief Open selected files or directories.
1381 * Opens selected files to file compare. If comparing
1382 * directories non-recursively, then subfolders and parent
1383 * folder are opened too.
1385 * This handles the case that one item is selected
1386 * and the case that two items are selected (one on each side)
1388 void CDirView::OpenSelection(SELECTIONTYPE selectionType /*= SELECTIONTYPE_NORMAL*/, PackingInfo * infoUnpacker /*= nullptr*/, bool openableForDir /*= true*/)
1390 Merge7zFormatMergePluginScope scope(infoUnpacker);
1391 CDirDoc * pDoc = GetDocument();
1392 const CDiffContext& ctxt = GetDiffContext();
1394 // First, figure out what was selected (store into pos1 & pos2)
1395 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1396 int sel1 = -1, sel2 = -1, sel3 = -1;
1397 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1399 // Must have 1 or 2 or 3 items selected
1404 pos1 = GetItemKey(sel1);
1405 ASSERT(pos1 != nullptr);
1408 pos2 = GetItemKey(sel2);
1409 ASSERT(pos2 != nullptr);
1411 pos3 = GetItemKey(sel3);
1414 // Now handle the various cases of what was selected
1416 if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1418 OpenSpecialItems(pos1, pos2, pos3);
1422 // Common variables which both code paths below are responsible for setting
1424 const DIFFITEM *pdi[3] = {0}; // left & right items (di1==di2 if single selection)
1425 bool isdir = false; // set if we're comparing directories
1430 success = GetOpenTwoItems(ctxt, selectionType, pos1, pos2, pdi,
1431 paths, sel1, sel2, isdir, nPane, errmsg, openableForDir);
1432 else if (pos2 && pos3)
1433 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1434 paths, sel1, sel2, sel3, isdir, nPane, errmsg, openableForDir);
1437 // Only one item selected, so perform diff on its sides
1438 success = GetOpenOneItem(ctxt, pos1, pdi,
1439 paths, sel1, isdir, nPane, errmsg, openableForDir);
1441 CreateFoldersPair(paths);
1445 if (!errmsg.empty())
1446 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1450 // Now pathLeft, pathRight, di1, di2, and isdir are all set
1451 // We have two items to compare, no matter whether same or different underlying DirView item
1454 for (int nIndex = 0; nIndex < paths.GetSize(); nIndex++)
1455 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[nIndex]) ? FFILEOPEN_READONLY : 0);
1457 Open(paths, dwFlags, infoUnpacker);
1460 void CDirView::OpenSelectionAs(UINT id)
1462 CDirDoc * pDoc = GetDocument();
1463 const CDiffContext& ctxt = GetDiffContext();
1465 // First, figure out what was selected (store into pos1 & pos2 & pos3)
1466 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1467 int sel1 = -1, sel2 = -1, sel3 = -1;
1468 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1470 // Must have 1 or 2 or 3 items selected
1475 pos1 = GetItemKey(sel1);
1479 pos2 = GetItemKey(sel2);
1480 ASSERT(pos2 != nullptr);
1482 pos3 = GetItemKey(sel3);
1485 // Now handle the various cases of what was selected
1487 if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1493 // Common variables which both code paths below are responsible for setting
1495 const DIFFITEM *pdi[3]; // left & right items (di1==di2 if single selection)
1496 bool isdir = false; // set if we're comparing directories
1501 success = GetOpenTwoItems(ctxt, SELECTIONTYPE_NORMAL, pos1, pos2, pdi,
1502 paths, sel1, sel2, isdir, nPane, errmsg, false);
1503 else if (pos2 && pos3)
1504 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1505 paths, sel1, sel2, sel3, isdir, nPane, errmsg, false);
1508 // Only one item selected, so perform diff on its sides
1509 success = GetOpenOneItem(ctxt, pos1, pdi,
1510 paths, sel1, isdir, nPane, errmsg, false);
1514 if (!errmsg.empty())
1515 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1519 // Open identical and different files
1520 DWORD dwFlags[3] = { 0 };
1521 FileLocation fileloc[3];
1522 for (int pane = 0; pane < paths.GetSize(); pane++)
1524 fileloc[pane].setPath(paths[pane]);
1525 dwFlags[pane] |= FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[pane]) ? FFILEOPEN_READONLY : 0);
1527 if (id == ID_MERGE_COMPARE_HEX)
1528 GetMainFrame()->ShowHexMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1530 GetMainFrame()->ShowImgMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1533 /// User chose (context menu) delete left
1534 template<SIDE_TYPE stype>
1535 void CDirView::OnCtxtDirDel()
1537 DoDirAction(&DirActions::DeleteOn<stype>, _("Deleting files..."));
1540 /// User chose (context menu) delete both
1541 void CDirView::OnCtxtDirDelBoth()
1543 DoDirAction(&DirActions::DeleteOnBoth, _("Deleting files..."));
1546 /// Enable/disable Delete Left menu choice on context menu
1547 template<SIDE_TYPE stype>
1548 void CDirView::OnUpdateCtxtDirDel(CCmdUI* pCmdUI)
1550 Counts counts = Count(&DirActions::IsItemDeletableOn<stype>);
1551 pCmdUI->Enable(counts.count > 0);
1552 pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1555 /// Enable/disable Delete Both menu choice on context menu
1556 void CDirView::OnUpdateCtxtDirDelBoth(CCmdUI* pCmdUI)
1558 Counts counts = Count(&DirActions::IsItemDeletableOnBoth);
1559 pCmdUI->Enable(counts.count > 0);
1560 pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1564 * @brief Update "Copy | Right to..." item
1566 template<SIDE_TYPE stype>
1567 void CDirView::OnUpdateCtxtDirCopyTo(CCmdUI* pCmdUI)
1569 Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1570 pCmdUI->Enable(counts.count > 0);
1571 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
1574 void CDirView::OnUpdateCtxtDirCopyBothTo(CCmdUI* pCmdUI)
1576 Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1577 pCmdUI->Enable(counts.count > 0);
1578 pCmdUI->SetText(FormatMenuItemStringAllTo(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1581 void CDirView::OnUpdateCtxtDirCopyBothDiffsOnlyTo(CCmdUI* pCmdUI)
1583 Counts counts = Count(&DirActions::IsItemNavigableDiff);
1584 pCmdUI->Enable(counts.count > 0);
1585 pCmdUI->SetText(FormatMenuItemStringDifferencesTo(counts.count, counts.total).c_str());
1589 * @brief Update "Copy | Left/Right/Both " item
1591 template<SIDE_TYPE stype>
1592 void CDirView::OnUpdateCtxtDirCopy2(CCmdUI* pCmdUI)
1594 Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1595 pCmdUI->Enable(counts.count > 0);
1596 pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1599 void CDirView::OnUpdateCtxtDirCopyBoth2(CCmdUI* pCmdUI)
1601 Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1602 pCmdUI->Enable(counts.count > 0);
1603 pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1607 * @brief Get keydata associated with item in given index.
1608 * @param [in] idx Item's index to list in UI.
1609 * @return Key for item in given index.
1611 DIFFITEM *CDirView::GetItemKey(int idx) const
1613 return (DIFFITEM *) m_pList->GetItemData(idx);
1616 // SetItemKey & GetItemKey encapsulate how the display list items
1617 // are mapped to DiffItems, which in turn are DiffContext keys to the actual DIFFITEM data
1620 * @brief Get DIFFITEM data for item.
1621 * This function returns DIFFITEM data for item in given index in GUI.
1622 * @param [in] sel Item's index in folder compare GUI list.
1623 * @return DIFFITEM for item.
1625 const DIFFITEM &CDirView::GetDiffItem(int sel) const
1627 CDirView * pDirView = const_cast<CDirView *>(this);
1628 return pDirView->GetDiffItem(sel);
1632 * Given index in list control, get modifiable reference to its DIFFITEM data
1634 DIFFITEM &CDirView::GetDiffItem(int sel)
1636 DIFFITEM *diffpos = GetItemKey(sel);
1638 // If it is special item, return empty DIFFITEM
1639 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1641 return *DIFFITEM::GetEmptyItem();
1643 return GetDiffContext().GetDiffRefAt(diffpos);
1646 void CDirView::DeleteItem(int sel, bool removeDIFFITEM)
1648 DIFFITEM *diffpos = GetItemKey(sel);
1649 if (diffpos == (DIFFITEM*)SPECIAL_ITEM_POS)
1653 CollapseSubdir(sel);
1654 m_pList->DeleteItem(sel);
1656 else if (GetDiffContext().m_bRecursive || diffpos->HasChildren())
1659 for (it = RevBegin(); it != RevEnd(); )
1662 int cursel = it.m_sel;
1664 if (di.IsAncestor(diffpos) || diffpos == &di)
1665 m_pList->DeleteItem(cursel);
1670 m_pList->DeleteItem(sel);
1674 if (diffpos->HasChildren())
1675 diffpos->RemoveChildren();
1676 diffpos->DelinkFromSiblings();
1680 m_firstDiffItem.reset();
1681 m_lastDiffItem.reset();
1684 void CDirView::DeleteAllDisplayItems()
1686 // item data are just positions (diffposes)
1687 // that is, they contain no memory needing to be freed
1688 m_pList->DeleteAllItems();
1690 m_firstDiffItem.reset();
1691 m_lastDiffItem.reset();
1695 * @brief Given key, get index of item which has it stored.
1696 * This function searches from list in UI.
1698 int CDirView::GetItemIndex(DIFFITEM *key)
1700 LVFINDINFO findInfo;
1702 findInfo.flags = LVFI_PARAM; // Search for itemdata
1703 findInfo.lParam = (LPARAM)key;
1704 return m_pList->FindItem(&findInfo);
1708 * @brief Get the file names on both sides for specified item.
1709 * @note Return empty strings if item is special item.
1711 void CDirView::GetItemFileNames(int sel, String& strLeft, String& strRight) const
1713 DIFFITEM *diffpos = GetItemKey(sel);
1714 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1721 const CDiffContext& ctxt = GetDiffContext();
1722 ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos), strLeft, strRight);
1727 * @brief Get the file names on both sides for specified item.
1728 * @note Return empty strings if item is special item.
1730 void CDirView::GetItemFileNames(int sel, PathContext * paths) const
1732 DIFFITEM *diffpos = GetItemKey(sel);
1733 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1735 for (int nIndex = 0; nIndex < GetDocument()->m_nDirs; nIndex++)
1736 paths->SetPath(nIndex, _T(""));
1740 const CDiffContext& ctxt = GetDiffContext();
1741 *paths = ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos));
1746 * @brief Open selected file with registered application.
1747 * Uses shell file associations to open file with registered
1748 * application. We first try to use "Edit" action which should
1749 * open file to editor, since we are more interested editing
1750 * files than running them (scripts).
1751 * @param [in] stype Side of file to open.
1753 void CDirView::DoOpen(SIDE_TYPE stype)
1755 int sel = GetSingleSelectedItem();
1756 if (sel == -1) return;
1757 DirItemIterator dirBegin = SelBegin();
1758 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1759 if (file.empty()) return;
1760 HINSTANCE rtn = ShellExecute(::GetDesktopWindow(), _T("edit"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1761 if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1762 rtn = ShellExecute(::GetDesktopWindow(), _T("open"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1763 if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1767 /// Open with dialog for file on selected side
1768 void CDirView::DoOpenWith(SIDE_TYPE stype)
1770 int sel = GetSingleSelectedItem();
1771 if (sel == -1) return;
1772 DirItemIterator dirBegin = SelBegin();
1773 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1774 if (file.empty()) return;
1776 if (!GetSystemDirectory(sysdir.GetBuffer(MAX_PATH), MAX_PATH)) return;
1777 sysdir.ReleaseBuffer();
1778 CString arg = (CString)_T("shell32.dll,OpenAs_RunDLL ") + file.c_str();
1779 ShellExecute(::GetDesktopWindow(), 0, _T("RUNDLL32.EXE"), arg, sysdir, SW_SHOWNORMAL);
1782 /// Open selected file on specified side to external editor
1783 void CDirView::DoOpenWithEditor(SIDE_TYPE stype)
1785 int sel = GetSingleSelectedItem();
1786 if (sel == -1) return;
1787 DirItemIterator dirBegin = SelBegin();
1788 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1789 if (file.empty()) return;
1791 theApp.OpenFileToExternalEditor(file);
1794 void CDirView::DoOpenParentFolder(SIDE_TYPE stype)
1796 int sel = GetSingleSelectedItem();
1797 if (sel == -1) return;
1798 DirItemIterator dirBegin = SelBegin();
1799 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1800 if (file.empty()) return;
1801 String parentFolder = paths::GetParentPath(file);
1802 ShellExecute(::GetDesktopWindow(), _T("open"), parentFolder.c_str(), 0, 0, SW_SHOWNORMAL);
1805 /// User chose (context menu) open left
1806 template<SIDE_TYPE stype>
1807 void CDirView::OnCtxtDirOpen()
1812 /// User chose (context menu) open left with
1813 template<SIDE_TYPE stype>
1814 void CDirView::OnCtxtDirOpenWith()
1819 /// User chose (context menu) open left with editor
1820 template<SIDE_TYPE stype>
1821 void CDirView::OnCtxtDirOpenWithEditor()
1823 DoOpenWithEditor(stype);
1826 /// User chose (context menu) open left parent folder
1827 template<SIDE_TYPE stype>
1828 void CDirView::OnCtxtDirOpenParentFolder()
1830 DoOpenParentFolder(stype);
1833 /// Update context menuitem "Open left | with editor"
1834 template<SIDE_TYPE stype>
1835 void CDirView::OnUpdateCtxtDirOpenWithEditor(CCmdUI* pCmdUI)
1837 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1838 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1841 // return selected item index, or -1 if none or multiple
1842 int CDirView::GetSingleSelectedItem() const
1844 int sel = -1, sel2 = -1;
1845 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
1846 if (sel == -1) return -1;
1847 sel2 = m_pList->GetNextItem(sel, LVNI_SELECTED);
1848 if (sel2 != -1) return -1;
1851 // Enable/disable Open Left menu choice on context menu
1852 template<SIDE_TYPE stype>
1853 void CDirView::OnUpdateCtxtDirOpen(CCmdUI* pCmdUI)
1855 Counts counts = Count(&DirActions::IsItemOpenableOn<stype>);
1856 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1859 // Enable/disable Open Left With menu choice on context menu
1860 template<SIDE_TYPE stype>
1861 void CDirView::OnUpdateCtxtDirOpenWith(CCmdUI* pCmdUI)
1863 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1864 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1867 // Enable/disable Open Parent Folder menu choice on context menu
1868 template<SIDE_TYPE stype>
1869 void CDirView::OnUpdateCtxtDirOpenParentFolder(CCmdUI* pCmdUI)
1871 Counts counts = Count(&DirActions::IsParentFolderOpenable<stype>);
1872 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1876 void CDirView::DoUpdateOpen(SELECTIONTYPE selectionType, CCmdUI* pCmdUI, bool openableForDir /*= true*/)
1878 int sel1 = -1, sel2 = -1, sel3 = -1;
1879 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1881 // 0 items or more than 2 items seleted
1882 pCmdUI->Enable(FALSE);
1887 // One item selected
1888 if (selectionType != SELECTIONTYPE_NORMAL)
1890 pCmdUI->Enable(FALSE);
1893 if (!openableForDir)
1895 const DIFFITEM& di1 = GetDiffItem(sel1);
1896 if (di1.diffcode.isDirectory())
1898 pCmdUI->Enable(FALSE);
1903 else if (sel3 == -1)
1905 // Two items selected
1906 const DIFFITEM& di1 = GetDiffItem(sel1);
1907 const DIFFITEM& di2 = GetDiffItem(sel2);
1908 if (!AreItemsOpenable(GetDiffContext(), selectionType, di1, di2, openableForDir))
1910 pCmdUI->Enable(FALSE);
1916 // Three items selected
1917 const DIFFITEM& di1 = GetDiffItem(sel1);
1918 const DIFFITEM& di2 = GetDiffItem(sel2);
1919 const DIFFITEM& di3 = GetDiffItem(sel3);
1920 if (selectionType != SELECTIONTYPE_NORMAL || !::AreItemsOpenable(GetDiffContext(), di1, di2, di3, openableForDir))
1922 pCmdUI->Enable(FALSE);
1926 pCmdUI->Enable(TRUE);
1930 * @brief Return count of selected items in folder compare.
1932 UINT CDirView::GetSelectedCount() const
1934 return m_pList->GetSelectedCount();
1938 * @brief Return index of first selected item in folder compare.
1940 int CDirView::GetFirstSelectedInd()
1942 return m_pList->GetNextItem(-1, LVNI_SELECTED);
1946 // If none or one item selected select found item
1947 // This is used for scrolling to first diff too
1948 void CDirView::OnFirstdiff()
1950 DirItemIterator it =
1951 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1953 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1956 void CDirView::OnUpdateFirstdiff(CCmdUI* pCmdUI)
1958 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1962 // If none or one item selected select found item
1963 void CDirView::OnLastdiff()
1965 DirItemIterator it =
1966 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1968 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1971 void CDirView::OnUpdateLastdiff(CCmdUI* pCmdUI)
1973 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1976 bool CDirView::HasNextDiff()
1978 int lastDiff = GetLastDifferentItem();
1980 // Check if different files were found and
1981 // there is different item after focused item
1982 return (lastDiff > -1) && (GetFocusedItem() < lastDiff);
1985 bool CDirView::HasPrevDiff()
1987 int firstDiff = GetFirstDifferentItem();
1989 // Check if different files were found and
1990 // there is different item before focused item
1991 return (firstDiff > -1) && (firstDiff < GetFocusedItem());
1994 void CDirView::MoveToNextDiff()
1996 int currentInd = GetFocusedItem();
1997 DirItemIterator begin(m_pIList.get(), currentInd + 1);
1998 DirItemIterator it =
1999 std::find_if(begin, End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2001 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2004 void CDirView::MoveToPrevDiff()
2006 int currentInd = GetFocusedItem();
2007 if (currentInd <= 0)
2009 DirItemIterator begin(m_pIList.get(), currentInd - 1, false, true);
2010 DirItemIterator it =
2011 std::find_if(begin, RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2013 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2016 void CDirView::OpenNextDiff()
2019 int currentInd = GetFocusedItem();
2020 const DIFFITEM& dip = GetDiffItem(currentInd);
2021 if (!dip.diffcode.isDirectory())
2027 GetParentFrame()->ActivateFrame();
2031 void CDirView::OpenPrevDiff()
2034 int currentInd = GetFocusedItem();
2035 const DIFFITEM& dip = GetDiffItem(currentInd);
2036 if (!dip.diffcode.isDirectory())
2042 GetParentFrame()->ActivateFrame();
2046 void CDirView::OpenFirstFile()
2048 int currentInd = GetFocusedItem();
2049 int firstFileInd = 0;
2051 while (firstFileInd <= currentInd)
2053 DIFFITEM& dip = GetDiffItem(firstFileInd);
2054 if (!dip.diffcode.isDirectory())
2056 MoveFocus(currentInd, firstFileInd, 1);
2064 bool CDirView::IsFirstFile()
2066 int currentInd = GetFocusedItem();
2067 int firstFileInd = 0;
2068 while (firstFileInd <= currentInd)
2070 DIFFITEM& dip = GetDiffItem(firstFileInd);
2071 if (!dip.diffcode.isDirectory())
2073 if (currentInd == firstFileInd)
2083 void CDirView::OpenLastFile()
2085 const int count = m_pList->GetItemCount();
2086 int currentInd = GetFocusedItem();
2087 int lastFileInd = count - 1;
2089 while (lastFileInd >= 0)
2091 DIFFITEM& dip = GetDiffItem(lastFileInd);
2092 if (!dip.diffcode.isDirectory())
2094 MoveFocus(currentInd, lastFileInd, 1);
2102 bool CDirView::IsLastFile()
2104 const int count = m_pList->GetItemCount();
2105 int currentInd = GetFocusedItem();
2106 int lastFileInd = count - 1;
2107 while (lastFileInd >= currentInd)
2109 DIFFITEM& dip = GetDiffItem(lastFileInd);
2110 if (!dip.diffcode.isDirectory())
2112 if (currentInd == lastFileInd)
2122 void CDirView::OpenNextFile()
2124 const int count = m_pList->GetItemCount();
2125 int currentInd = GetFocusedItem();
2126 int nextInd = currentInd + 1;
2127 if (currentInd >= 0)
2129 while (nextInd < count)
2131 DIFFITEM& dip = GetDiffItem(nextInd);
2132 MoveFocus(nextInd - 1, nextInd, 1);
2133 if (!dip.diffcode.isDirectory())
2143 void CDirView::OpenPrevFile()
2145 int currentInd = GetFocusedItem();
2146 int prevInd = currentInd - 1;
2147 if (currentInd >= 0)
2149 while (prevInd >= 0)
2151 DIFFITEM& dip = GetDiffItem(prevInd);
2152 MoveFocus(prevInd + 1, prevInd, 1);
2153 if (!dip.diffcode.isDirectory())
2163 void CDirView::SetActivePane(int pane)
2165 if (m_nActivePane >= 0)
2166 GetParentFrame()->GetHeaderInterface()->SetActive(m_nActivePane, false);
2167 GetParentFrame()->GetHeaderInterface()->SetActive(pane, true);
2168 m_nActivePane = pane;
2172 // If none or one item selected select found item
2173 void CDirView::OnNextdiff()
2179 void CDirView::OnUpdateNextdiff(CCmdUI* pCmdUI)
2181 pCmdUI->Enable(HasNextDiff());
2185 // If none or one item selected select found item
2186 void CDirView::OnPrevdiff()
2192 void CDirView::OnUpdatePrevdiff(CCmdUI* pCmdUI)
2194 pCmdUI->Enable(HasPrevDiff());
2197 void CDirView::OnCurdiff()
2199 const int count = m_pList->GetItemCount();
2201 int i = GetFirstSelectedInd();
2203 // No selection - no diff to go
2207 while (i < count && !found)
2209 UINT selected = m_pList->GetItemState(i, LVIS_SELECTED);
2210 UINT focused = m_pList->GetItemState(i, LVIS_FOCUSED);
2212 if (selected == LVIS_SELECTED && focused == LVIS_FOCUSED)
2214 m_pList->EnsureVisible(i, FALSE);
2221 void CDirView::OnUpdateCurdiff(CCmdUI* pCmdUI)
2223 pCmdUI->Enable(GetFirstSelectedInd() > -1);
2226 int CDirView::GetFocusedItem()
2228 return m_pList->GetNextItem(-1, LVNI_FOCUSED);
2231 int CDirView::GetFirstDifferentItem()
2233 if (!m_firstDiffItem.has_value())
2235 DirItemIterator it =
2236 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2237 m_firstDiffItem = it.m_sel;
2239 return m_firstDiffItem.value();
2242 int CDirView::GetLastDifferentItem()
2244 if (!m_lastDiffItem.has_value())
2246 DirItemIterator it =
2247 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2248 m_lastDiffItem = it.m_sel;
2250 return m_lastDiffItem.value();
2254 * @brief Move focus to specified item (and selection if multiple items not selected)
2256 * Moves the focus from item [currentInd] to item [i]
2257 * Additionally, if there are not multiple items selected,
2258 * deselects item [currentInd] and selects item [i]
2260 void CDirView::MoveFocus(int currentInd, int i, int selCount)
2264 // Not multiple items selected, so bring selection with us
2265 m_pList->SetItemState(currentInd, 0, LVIS_SELECTED);
2266 m_pList->SetItemState(currentInd, 0, LVIS_FOCUSED);
2267 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2270 // Move focus to specified item
2271 // (this automatically defocuses old item)
2272 m_pList->SetItemState(i, LVIS_FOCUSED, LVIS_FOCUSED);
2273 m_pList->EnsureVisible(i, FALSE);
2276 void CDirView::OnUpdateSave(CCmdUI* pCmdUI)
2278 pCmdUI->Enable(FALSE);
2281 CDirFrame * CDirView::GetParentFrame()
2283 // can't verify cast without introducing more coupling
2284 // (CDirView doesn't include DirFrame.h)
2285 return static_cast<CDirFrame *>(CListView::GetParentFrame());
2288 void CDirView::OnRefresh()
2290 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
2291 GetDocument()->Rescan();
2294 BOOL CDirView::PreTranslateMessage(MSG* pMsg)
2296 // Handle special shortcuts here
2297 if (pMsg->message == WM_KEYDOWN)
2301 // Check if we got 'ESC pressed' -message
2302 if (pMsg->wParam == VK_ESCAPE)
2304 if (m_pCmpProgressBar != nullptr)
2306 OnBnClickedComparisonStop();
2310 if (m_nEscCloses != 0)
2312 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_CLOSE);
2316 // Check if we got 'DEL pressed' -message
2317 if (pMsg->wParam == VK_DELETE)
2319 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_MERGE_DELETE);
2322 int sel = GetFocusedItem();
2323 // Check if we got 'Backspace pressed' -message
2324 if (pMsg->wParam == VK_BACK)
2326 if (!GetDiffContext().m_bRecursive)
2328 OpenParentDirectory();
2331 else if (m_bTreeMode && sel >= 0)
2333 const DIFFITEM& di = GetDiffItem(sel);
2334 assert(di.HasParent());
2337 int i = GetItemIndex(di.GetParentLink());
2339 MoveFocus(sel, i, GetSelectedCount());
2345 DIFFITEM& dip = this->GetDiffItem(sel);
2346 if (pMsg->wParam == VK_LEFT)
2348 if (m_bTreeMode && GetDiffContext().m_bRecursive && (!(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren()))
2349 PostMessage(WM_KEYDOWN, VK_BACK);
2351 CollapseSubdir(sel);
2354 if (pMsg->wParam == VK_SUBTRACT)
2356 CollapseSubdir(sel);
2359 if (pMsg->wParam == VK_RIGHT)
2361 if (m_bTreeMode && GetDiffContext().m_bRecursive && dip.customFlags & ViewCustomFlags::EXPANDED && dip.HasChildren())
2362 PostMessage(WM_KEYDOWN, VK_DOWN);
2367 if (pMsg->wParam == VK_ADD)
2372 if (pMsg->wParam == VK_MULTIPLY)
2374 ExpandSubdir(sel, true);
2381 // ESC doesn't close window when user is renaming an item.
2382 if (pMsg->wParam == VK_ESCAPE)
2384 m_bUserCancelEdit = true;
2386 // The edit control send LVN_ENDLABELEDIT when it loses focus,
2387 // so we use it to cancel the rename action.
2388 m_pList->SetFocus();
2390 // Stop the ESC before it reach the main frame which might
2391 // cause a program termination.
2396 return CListView::PreTranslateMessage(pMsg);
2399 void CDirView::OnUpdateRefresh(CCmdUI* pCmdUI)
2401 UINT threadState = GetDocument()->m_diffThread.GetThreadState();
2402 pCmdUI->Enable(threadState != CDiffThread::THREAD_COMPARING);
2406 * @brief Called when compare thread asks UI update.
2407 * @note Currently thread asks update after compare is ready
2410 LRESULT CDirView::OnUpdateUIMessage(WPARAM wParam, LPARAM lParam)
2412 UNREFERENCED_PARAMETER(lParam);
2414 CDirDoc * pDoc = GetDocument();
2415 ASSERT(pDoc != nullptr);
2417 if (wParam == CDiffThread::EVENT_COMPARE_COMPLETED)
2419 // Close and destroy the dialog after compare
2420 if (m_pCmpProgressBar != nullptr)
2421 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), FALSE, FALSE);
2422 m_pCmpProgressBar.reset();
2424 pDoc->CompareReady();
2426 if (!pDoc->GetGeneratingReport())
2429 if (!pDoc->GetReportFile().empty())
2431 OnToolsGenerateReport();
2432 pDoc->SetReportFile(_T(""));
2435 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST))
2440 // If compare took more than TimeToSignalCompare seconds, notify user
2441 clock_t elapsed = clock() - m_compareStart;
2442 GetParentFrame()->SetStatus(
2443 strutils::format(_("Elapsed time: %ld ms"), elapsed).c_str()
2445 if (elapsed > TimeToSignalCompare * CLOCKS_PER_SEC)
2447 GetMainFrame()->StartFlashing();
2449 else if (wParam == CDiffThread::EVENT_COMPARE_PROGRESSED)
2451 InvalidateRect(nullptr, FALSE);
2453 else if (wParam == CDiffThread::EVENT_COLLECT_COMPLETED)
2455 if (m_pSavedTreeState != nullptr)
2457 RestoreTreeState(GetDiffContext(), m_pSavedTreeState.get());
2458 m_pSavedTreeState.reset();
2463 if (m_bExpandSubdirs)
2464 OnViewExpandAllSubdirs();
2470 return 0; // return value unused
2474 BOOL CDirView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2476 NMHDR * hdr = reinterpret_cast<NMHDR *>(lParam);
2477 if (hdr->code == HDN_ENDDRAG)
2478 return OnHeaderEndDrag((LPNMHEADER)hdr, pResult);
2479 if (hdr->code == HDN_BEGINDRAG)
2480 return OnHeaderBeginDrag((LPNMHEADER)hdr, pResult);
2482 return CListView::OnNotify(wParam, lParam, pResult);
2485 BOOL CDirView::OnChildNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2487 if (uMsg == WM_NOTIFY)
2489 NMHDR *pNMHDR = (NMHDR *)lParam;
2490 switch (pNMHDR->code)
2492 case LVN_GETDISPINFO:
2493 ReflectGetdispinfo((NMLVDISPINFO *)lParam);
2495 case LVN_GETINFOTIPW:
2496 case LVN_GETINFOTIPA:
2500 return CListView::OnChildNotify(uMsg, wParam, lParam, pResult);
2504 * @brief User is starting to drag a column header
2506 bool CDirView::OnHeaderBeginDrag(LPNMHEADER hdr, LRESULT* pResult)
2508 // save column widths before user reorders them
2509 // so we can reload them on the end drag
2510 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
2511 GetOptionsMgr()->SaveOption(keyname,
2512 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)).c_str());
2517 * @brief User just finished dragging a column header
2519 bool CDirView::OnHeaderEndDrag(LPNMHEADER hdr, LRESULT* pResult)
2521 int src = hdr->iItem;
2522 int dest = hdr->pitem->iOrder;
2523 bool allowDrop = true;
2524 *pResult = allowDrop ? FALSE : TRUE;
2525 if (allowDrop && src != dest && dest != -1)
2527 m_pColItems->MoveColumn(src, dest);
2534 * @brief Remove any windows reordering of columns
2536 void CDirView::FixReordering()
2539 lvcol.mask = LVCF_ORDER;
2542 lvcol.pszText = nullptr;
2544 for (int i = 0; i < m_pColItems->GetColCount(); ++i)
2547 GetListCtrl().SetColumn(i, &lvcol);
2551 /** @brief Add columns to display, loading width & order from registry. */
2552 void CDirView::LoadColumnHeaderItems()
2554 bool dummyflag = false;
2556 CHeaderCtrl * h = m_pList->GetHeaderCtrl();
2557 if (h->GetItemCount())
2560 while (m_pList->GetHeaderCtrl()->GetItemCount() > 1)
2561 m_pList->DeleteColumn(1);
2564 for (int i = 0; i < m_pColItems->GetDispColCount(); ++i)
2567 lvc.mask = LVCF_FMT + LVCF_SUBITEM + LVCF_TEXT;
2568 lvc.fmt = LVCFMT_LEFT;
2570 lvc.pszText = _T("text");
2572 m_pList->InsertColumn(i, &lvc);
2575 m_pList->DeleteColumn(1);
2579 void CDirView::SetFont(const LOGFONT & lf)
2581 m_font.DeleteObject();
2582 m_font.CreateFontIndirect(&lf);
2583 CWnd::SetFont(&m_font);
2586 /** @brief Fire off a resort of the data, to take place when things stabilize. */
2587 void CDirView::InitiateSort()
2589 PostMessage(WM_TIMER, COLUMN_REORDER);
2592 void CDirView::OnTimer(UINT_PTR nIDEvent)
2594 if (nIDEvent == COLUMN_REORDER)
2596 // Remove the windows reordering, as we're doing it ourselves
2598 // Now redraw screen
2599 UpdateColumnNames();
2600 m_pColItems->LoadColumnWidths(
2601 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
2602 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
2605 else if (nIDEvent == STATUSBAR_UPDATE)
2607 KillTimer(STATUSBAR_UPDATE);
2608 int items = GetSelectedCount();
2609 String msg = (items == 1) ? _("1 item selected") : strutils::format_string1(_("%1 items selected"), strutils::to_str(items));
2610 GetParentFrame()->SetStatus(msg.c_str());
2613 CListView::OnTimer(nIDEvent);
2617 * @brief Change left-side readonly-status
2619 template<SIDE_TYPE stype>
2620 void CDirView::OnReadOnly()
2622 const int index = SideToIndex(GetDiffContext(), stype);
2623 bool bReadOnly = GetDocument()->GetReadOnly(index);
2624 GetDocument()->SetReadOnly(index, !bReadOnly);
2628 * @brief Update left-readonly menu item
2630 template<SIDE_TYPE stype>
2631 void CDirView::OnUpdateReadOnly(CCmdUI* pCmdUI)
2633 const int index = SideToIndex(GetDiffContext(), stype);
2634 bool bReadOnly = GetDocument()->GetReadOnly(index);
2635 if (stype != SIDE_MIDDLE)
2637 pCmdUI->Enable(TRUE);
2638 pCmdUI->SetCheck(bReadOnly);
2642 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
2643 pCmdUI->SetCheck(bReadOnly && GetDocument()->m_nDirs > 2);
2648 * @brief Update left-side readonly statusbar item
2650 void CDirView::OnUpdateStatusLeftRO(CCmdUI* pCmdUI)
2652 bool bROLeft = GetDocument()->GetReadOnly(0);
2653 pCmdUI->Enable(bROLeft);
2657 * @brief Update middle readonly statusbar item
2659 void CDirView::OnUpdateStatusMiddleRO(CCmdUI* pCmdUI)
2661 bool bROMiddle = GetDocument()->GetReadOnly(1);
2662 pCmdUI->Enable(bROMiddle && GetDocument()->m_nDirs > 2);
2666 * @brief Update right-side readonly statusbar item
2668 void CDirView::OnUpdateStatusRightRO(CCmdUI* pCmdUI)
2670 bool bRORight = GetDocument()->GetReadOnly(GetDocument()->m_nDirs - 1);
2671 pCmdUI->Enable(bRORight);
2675 * @brief Open dialog to customize dirview columns
2677 void CDirView::OnCustomizeColumns()
2679 // Located in DirViewColHandler.cpp
2681 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
2682 GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
2685 void CDirView::OnCtxtOpenWithUnpacker()
2688 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2691 // let the user choose a handler
2692 CSelectUnpackerDlg dlg(GetDiffItem(sel).diffFileInfo[0].filename, this);
2693 // create now a new infoUnpacker to initialize the manual/automatic flag
2694 PackingInfo infoUnpacker(PLUGIN_MODE::PLUGIN_AUTO);
2695 dlg.SetInitialInfoHandler(&infoUnpacker);
2697 if (dlg.DoModal() == IDOK)
2699 infoUnpacker = dlg.GetInfoHandler();
2700 OpenSelection(SELECTIONTYPE_NORMAL, &infoUnpacker, false);
2706 void CDirView::OnUpdateCtxtOpenWithUnpacker(CCmdUI* pCmdUI)
2708 if (!GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
2710 pCmdUI->Enable(FALSE);
2714 // we need one selected file, existing on both side
2715 if (m_pList->GetSelectedCount() != 1)
2716 pCmdUI->Enable(FALSE);
2720 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2721 const DIFFITEM& di = GetDiffItem(sel);
2722 if (di.diffcode.isDirectory())
2724 pCmdUI->Enable(FALSE);
2727 pCmdUI->Enable(IsItemDeletableOnBoth(GetDiffContext(), di));
2732 * @brief Fill string list with current dirview column registry key names
2734 std::vector<String> CDirView::GetCurrentColRegKeys()
2736 std::vector<String> colKeys;
2737 int nphyscols = GetListCtrl().GetHeaderCtrl()->GetItemCount();
2738 for (int col = 0; col < nphyscols; ++col)
2740 int logcol = m_pColItems->ColPhysToLog(col);
2741 colKeys.push_back(m_pColItems->GetColRegValueNameBase(logcol));
2746 struct FileCmpReport: public IFileCmpReport
2748 explicit FileCmpReport(CDirView *pDirView) : m_pDirView(pDirView) {}
2749 ~FileCmpReport() override {}
2750 bool operator()(REPORT_TYPE nReportType, IListCtrl *pList, int nIndex, const String &sDestDir, String &sLinkPath) override
2752 const CDiffContext& ctxt = m_pDirView->GetDiffContext();
2753 const DIFFITEM &di = m_pDirView->GetDiffItem(nIndex);
2755 String sLinkFullPath = paths::ConcatPath(ctxt.GetLeftPath(), di.diffFileInfo[0].GetFile());
2757 if (di.diffcode.isDirectory() || !IsItemNavigableDiff(ctxt, di) || IsArchiveFile(sLinkFullPath))
2763 sLinkPath = di.diffFileInfo[0].GetFile();
2765 strutils::replace(sLinkPath, _T("\\"), _T("_"));
2766 sLinkPath += _T(".html");
2767 String sReportPath = paths::ConcatPath(sDestDir, sLinkPath);
2768 bool completed = false;
2770 m_pDirView->MoveFocus(m_pDirView->GetFirstSelectedInd(), nIndex, m_pDirView->GetSelectedCount());
2771 m_pDirView->PostMessage(MSG_GENERATE_FLIE_COMPARE_REPORT,
2772 reinterpret_cast<WPARAM>(sReportPath.c_str()),
2773 reinterpret_cast<LPARAM>(&completed));
2778 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2780 if (!AfxGetApp()->PumpMessage())
2790 CDirView *m_pDirView;
2793 LRESULT CDirView::OnGenerateFileCmpReport(WPARAM wParam, LPARAM lParam)
2796 CFrameWnd * pFrame = GetMainFrame()->GetActiveFrame();
2797 IMergeDoc * pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame->GetActiveDocument());
2798 if (pMergeDoc == nullptr)
2799 pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame);
2801 auto *pReportFileName = reinterpret_cast<const TCHAR *>(wParam);
2802 bool *pCompleted = reinterpret_cast<bool *>(lParam);
2803 if (pMergeDoc != nullptr)
2805 pMergeDoc->GenerateReport(pReportFileName);
2806 pMergeDoc->CloseNow();
2809 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2810 if (!AfxGetApp()->PumpMessage())
2812 GetMainFrame()->OnUpdateFrameTitle(FALSE);
2818 * @brief Generate report from dir compare results.
2820 void CDirView::OnToolsGenerateReport()
2822 CDirDoc *pDoc = GetDocument();
2823 DirCmpReportDlg dlg;
2825 dlg.m_sReportFile = pDoc->GetReportFile();
2826 if (dlg.m_sReportFile.empty() && dlg.DoModal() != IDOK)
2829 pDoc->SetGeneratingReport(true);
2830 const CDiffContext& ctxt = GetDiffContext();
2832 PathContext paths = ctxt.GetNormalizedPaths();
2834 // If inside archive, convert paths
2835 if (pDoc->IsArchiveFolders())
2837 for (int i = 0; i < paths.GetSize(); i++)
2838 pDoc->ApplyDisplayRoot(i, paths[i]);
2841 DirCmpReport *pReport = new DirCmpReport(GetCurrentColRegKeys());
2842 pReport->SetRootPaths(paths);
2843 pReport->SetColumns(m_pColItems->GetDispColCount());
2844 pReport->SetFileCmpReport(new FileCmpReport(this));
2845 pReport->SetList(new IListCtrlImpl(m_pList->m_hWnd));
2846 pReport->SetReportType(dlg.m_nReportType);
2847 pReport->SetReportFile(dlg.m_sReportFile);
2848 pReport->SetCopyToClipboard(dlg.m_bCopyToClipboard);
2849 pReport->SetIncludeFileCmpReport(dlg.m_bIncludeFileCmpReport);
2850 pDoc->SetReport(pReport);
2855 * @brief Generate patch from files selected.
2857 * Creates a patch from selected files in active directory compare, or
2858 * active file compare. Files in file compare must be saved before
2861 void CDirView::OnToolsGeneratePatch()
2864 const CDiffContext& ctxt = GetDiffContext();
2866 // Get selected items from folder compare
2867 bool bValidFiles = true;
2868 for (DirItemIterator it = SelBegin(); bValidFiles && it != SelEnd(); ++it)
2870 const DIFFITEM &item = *it;
2871 if (item.diffcode.isBin())
2873 LangMessageBox(IDS_CANNOT_CREATE_BINARYPATCH, MB_ICONWARNING |
2874 MB_DONT_DISPLAY_AGAIN, IDS_CANNOT_CREATE_BINARYPATCH);
2875 bValidFiles = false;
2880 // Format full paths to files (leftFile/rightFile)
2881 String leftFile = item.getFilepath(0, ctxt.GetNormalizedPath(0));
2882 if (!leftFile.empty())
2883 leftFile = paths::ConcatPath(leftFile, item.diffFileInfo[0].filename);
2884 String rightFile = item.getFilepath(1, ctxt.GetNormalizedPath(1));
2885 if (!rightFile.empty())
2886 rightFile = paths::ConcatPath(rightFile, item.diffFileInfo[1].filename);
2888 // Format relative paths to files in folder compare
2889 String leftpatch = item.diffFileInfo[0].path;
2890 if (!leftpatch.empty())
2891 leftpatch += _T("/");
2892 leftpatch += item.diffFileInfo[0].filename;
2893 String rightpatch = item.diffFileInfo[1].path;
2894 if (!rightpatch.empty())
2895 rightpatch += _T("/");
2896 rightpatch += item.diffFileInfo[1].filename;
2897 patcher.AddFiles(leftFile, leftpatch, rightFile, rightpatch);
2901 patcher.CreatePatch();
2905 * @brief Add special items for non-recursive compare
2906 * to directory view.
2908 * Currently only special item is ".." for browsing to
2910 * @return number of items added to view
2912 int CDirView::AddSpecialItems()
2914 CDirDoc *pDoc = GetDocument();
2916 bool bEnable = true;
2917 PathContext pathsParent;
2918 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
2920 case AllowUpwardDirectory::No:
2924 AddParentFolderItem(bEnable);
2927 case AllowUpwardDirectory::Never:
2934 * @brief Add "Parent folder" ("..") item to directory view
2936 void CDirView::AddParentFolderItem(bool bEnable)
2938 AddNewItem(0, (DIFFITEM *)SPECIAL_ITEM_POS, bEnable ? DIFFIMG_DIRUP : DIFFIMG_DIRUP_DISABLE, 0);
2942 void CDirView::OnCtxtDirZip()
2944 if (!HasZipSupport())
2946 LangMessageBox(IDS_NO_ZIP_SUPPORT, MB_ICONINFORMATION);
2952 this, LVNI_SELECTED | flag
2953 ).CompressArchive();
2956 void CDirView::ShowShellContextMenu(SIDE_TYPE stype)
2958 CShellContextMenu *pContextMenu = nullptr;
2962 if (m_pShellContextMenuLeft == nullptr)
2963 m_pShellContextMenuLeft.reset(new CShellContextMenu(LeftCmdFirst, LeftCmdLast));
2964 pContextMenu = m_pShellContextMenuLeft.get();
2967 if (m_pShellContextMenuMiddle == nullptr)
2968 m_pShellContextMenuMiddle.reset(new CShellContextMenu(MiddleCmdFirst, MiddleCmdLast));
2969 pContextMenu = m_pShellContextMenuMiddle.get();
2972 if (m_pShellContextMenuRight == nullptr)
2973 m_pShellContextMenuRight.reset(new CShellContextMenu(RightCmdFirst, RightCmdLast));
2974 pContextMenu = m_pShellContextMenuRight.get();
2977 if (pContextMenu!=nullptr && ListShellContextMenu(stype))
2980 GetCursorPos(&point);
2981 HWND hWnd = GetSafeHwnd();
2982 CFrameWnd *pFrame = GetTopLevelFrame();
2983 ASSERT(pFrame != nullptr);
2984 BOOL bAutoMenuEnableOld = pFrame->m_bAutoMenuEnable;
2985 pFrame->m_bAutoMenuEnable = FALSE;
2986 BOOL nCmd = TrackPopupMenu(pContextMenu->GetHMENU(), TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hWnd, nullptr);
2988 pContextMenu->InvokeCommand(nCmd, hWnd);
2989 pContextMenu->ReleaseShellContextMenu();
2990 pFrame->m_bAutoMenuEnable = bAutoMenuEnableOld;
2994 template <SIDE_TYPE stype>
2995 void CDirView::OnCtxtDirShellContextMenu()
2997 ShowShellContextMenu(stype);
3001 * @brief Select all visible items in dir compare
3003 void CDirView::OnSelectAll()
3005 // While the user is renaming an item, select all the edited text.
3006 CEdit *pEdit = m_pList->GetEditControl();
3007 if (pEdit != nullptr)
3009 pEdit->SetSel(pEdit->GetWindowTextLength());
3013 int selCount = m_pList->GetItemCount();
3015 for (int i = 0; i < selCount; i++)
3017 // Don't select special items (SPECIAL_ITEM_POS)
3018 DIFFITEM *diffpos = GetItemKey(i);
3019 if (diffpos != (DIFFITEM *)SPECIAL_ITEM_POS)
3020 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3026 * @brief Update "Select All" item
3028 void CDirView::OnUpdateSelectAll(CCmdUI* pCmdUI)
3030 bool bEnable = (!IsLabelEdit()) || (m_pList->GetItemCount() > 0);
3031 pCmdUI->Enable(bEnable);
3035 * @brief Handle clicks in plugin context view in list
3037 void CDirView::OnPluginPredifferMode(UINT nID)
3039 ApplyPluginPrediffSetting(SelBegin(), SelEnd(), GetDiffContext(),
3040 (nID == ID_PREDIFF_AUTO) ? PLUGIN_MODE::PLUGIN_AUTO : PLUGIN_MODE::PLUGIN_MANUAL);
3044 * @brief Updates just before displaying plugin context view in list
3046 void CDirView::OnUpdatePluginPredifferMode(CCmdUI* pCmdUI)
3048 // 2004-04-03, Perry
3049 // CMainFrame::OnUpdatePluginUnpackMode handles this for global unpacking
3050 // and is the template to copy, but here, this is a bit tricky
3051 // as a group of files may be selected
3052 // and they may not all have the same setting
3053 // so I'm not trying this right now
3055 pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
3057 BCMenu *pPopup = static_cast<BCMenu*>(pCmdUI->m_pSubMenu);
3058 if (pPopup == nullptr)
3061 std::pair<int, int> counts = CountPredifferYesNo(SelBegin(), SelEnd(), GetDiffContext());
3063 CheckContextMenu(pPopup, ID_PREDIFF_AUTO, (counts.first > 0));
3064 CheckContextMenu(pPopup, ID_PREDIFF_MANUAL, (counts.second > 0));
3068 * @brief Refresh cached options.
3070 void CDirView::RefreshOptions()
3072 m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
3073 m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
3074 Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
3075 m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
3076 m_pList->SetBkColor(m_bUseColors ? m_cachedColors.clrDirMargin : GetSysColor(COLOR_WINDOW));
3081 * @brief Copy selected item left side paths (containing filenames) to clipboard.
3083 template<SIDE_TYPE stype>
3084 void CDirView::OnCopyPathnames()
3086 std::list<String> list;
3087 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3088 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3091 void CDirView::OnCopyBothPathnames()
3093 std::list<String> list;
3094 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3095 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3099 * @brief Copy selected item filenames to clipboard.
3101 void CDirView::OnCopyFilenames()
3103 std::list<String> list;
3104 CopyFilenames(SelBegin(), SelEnd(), std::back_inserter(list));
3105 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3109 * @brief Enable/Disable dirview Copy Filenames context menu item.
3111 void CDirView::OnUpdateCopyFilenames(CCmdUI* pCmdUI)
3113 pCmdUI->Enable(Count(&DirActions::IsItemFile).count > 0);
3117 * @brief Copy selected item left side to clipboard.
3119 template<SIDE_TYPE stype>
3120 void CDirView::OnCopyToClipboard()
3122 std::list<String> list;
3123 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3124 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3128 * @brief Copy selected item both side to clipboard.
3130 void CDirView::OnCopyBothToClipboard()
3132 std::list<String> list;
3133 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3134 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3138 * @brief Rename a selected item on both sides.
3141 void CDirView::OnItemRename()
3143 ASSERT(1 == m_pList->GetSelectedCount());
3144 int nSelItem = m_pList->GetNextItem(-1, LVNI_SELECTED);
3145 ASSERT(-1 != nSelItem);
3146 m_pList->EditLabel(nSelItem);
3150 * @brief Enable/Disable dirview Rename context menu item.
3153 void CDirView::OnUpdateItemRename(CCmdUI* pCmdUI)
3155 bool bEnabled = (1 == m_pList->GetSelectedCount());
3156 pCmdUI->Enable(bEnabled && SelBegin() != SelEnd());
3160 * @brief hide selected item filenames (removes them from the ListView)
3162 void CDirView::OnHideFilenames()
3164 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
3166 while ((it = SelRevBegin()) != SelRevEnd())
3169 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
3170 DeleteItem(it.m_sel);
3173 m_pList->SetRedraw(TRUE); // Turn updating back on
3177 * @brief update menu item
3179 void CDirView::OnUpdateHideFilenames(CCmdUI* pCmdUI)
3181 pCmdUI->Enable(m_pList->GetSelectedCount() != 0);
3184 /// User chose (context menu) Move left to...
3185 template<SIDE_TYPE stype>
3186 void CDirView::OnCtxtDirMoveTo()
3188 DoDirActionTo(stype, &DirActions::MoveTo<stype>, _("Moving files..."));
3192 * @brief Update "Move | Left to..." item
3194 template<SIDE_TYPE stype>
3195 void CDirView::OnUpdateCtxtDirMoveTo(CCmdUI* pCmdUI)
3197 Counts counts = Count(&DirActions::IsItemMovableToOn<stype>);
3198 pCmdUI->Enable(counts.count > 0);
3199 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
3203 * @brief Update title after window is resized.
3205 void CDirView::OnSize(UINT nType, int cx, int cy)
3207 CListView::OnSize(nType, cx, cy);
3208 GetDocument()->SetTitle(nullptr);
3212 * @brief Called when user selects 'Delete' from 'Merge' menu.
3214 void CDirView::OnDelete()
3216 DoDirAction(&DirActions::DeleteOnEitherOrBoth, _("Deleting files..."));
3220 * @brief Enables/disables 'Delete' item in 'Merge' menu.
3222 void CDirView::OnUpdateDelete(CCmdUI* pCmdUI)
3224 pCmdUI->Enable(Count(&DirActions::IsItemDeletableOnEitherOrBoth).count > 0);
3228 * @brief Called when item state is changed.
3230 * Show count of selected items in statusbar.
3232 void CDirView::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)
3234 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
3236 // If item's selected state changed
3237 if ((pNMListView->uOldState & LVIS_SELECTED) !=
3238 (pNMListView->uNewState & LVIS_SELECTED))
3240 if ((pNMListView->iItem % 5000) > 0)
3241 SetTimer(STATUSBAR_UPDATE, 100, nullptr);
3243 OnTimer(STATUSBAR_UPDATE);
3249 * @brief Called before user start to item label edit.
3251 * Disable label edit if initiated from a user double-click.
3253 afx_msg void CDirView::OnBeginLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3255 *pResult = (SelBegin() == SelEnd());
3257 // If label edit is allowed.
3258 if (*pResult == FALSE)
3260 const NMLVDISPINFO *pdi = (NMLVDISPINFO*)pNMHDR;
3261 ASSERT(pdi != nullptr);
3263 // Locate the edit box on the right column in case the user changed the
3265 const int nColPos = m_pColItems->ColLogToPhys(0);
3267 // Get text from the "File Name" column.
3268 CString sText = m_pList->GetItemText(pdi->item.iItem, nColPos);
3269 ASSERT(!sText.IsEmpty());
3271 // Keep only left file name (separated by '|'). This form occurs
3272 // when two files exists with same name but not in same case.
3273 int nPos = sText.Find('|');
3276 sText = sText.Left(nPos);
3279 // Set the edit control with the updated text.
3280 CEdit *pEdit = m_pList->GetEditControl();
3281 ASSERT(pEdit != nullptr);
3282 pEdit->SetWindowText(sText);
3284 m_bUserCancelEdit = false;
3289 * @brief Called when user done with item label edit.
3292 afx_msg void CDirView::OnEndLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3296 // We can't use the normal condition of pszText==`nullptr` to know if the
3297 // user cancels editing when file names had different case (e.g.
3298 // "file.txt|FILE.txt"). The edit text was changed to "file.txt" and
3299 // if the user accept it as the new file name, pszText is `nullptr`.
3301 if (!m_bUserCancelEdit)
3303 CEdit *pEdit = m_pList->GetEditControl();
3304 ASSERT(pEdit != nullptr);
3307 pEdit->GetWindowText(sText);
3309 if (!sText.IsEmpty())
3312 DirItemIterator it(m_pIList.get(), reinterpret_cast<NMLVDISPINFO *>(pNMHDR)->item.iItem);
3313 *pResult = DoItemRename(it, GetDiffContext(), String(sText));
3314 } catch (ContentsChangedException& e) {
3315 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
3322 * @brief Called when item is marked for rescan.
3323 * This function marks selected items for rescan and rescans them.
3325 void CDirView::OnMarkedRescan()
3327 std::for_each(SelBegin(), SelEnd(), MarkForRescan);
3328 if (std::distance(SelBegin(), SelEnd()) > 0)
3330 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
3331 GetDocument()->SetMarkedRescan();
3332 GetDocument()->Rescan();
3337 * @brief Called to update the item count in the status bar
3339 void CDirView::OnUpdateStatusNum(CCmdUI* pCmdUI)
3341 String s; // text to display
3343 int count = m_pList->GetItemCount();
3344 int focusItem = GetFocusedItem();
3346 if (focusItem == -1)
3348 // No item has focus
3350 s = strutils::format_string1(_("Items: %1"), strutils::to_str(count));
3354 // Don't show number to special items
3355 DIFFITEM *pos = GetItemKey(focusItem);
3356 if (pos != (DIFFITEM *)SPECIAL_ITEM_POS)
3358 // If compare is non-recursive reduce special items count
3359 bool bRecursive = GetDiffContext().m_bRecursive;
3366 s = strutils::format_string2(_("Item %1 of %2"),
3367 strutils::to_str(focusItem + 1), strutils::to_str(count));
3370 pCmdUI->SetText(s.c_str());
3374 * @brief Show all hidden items.
3376 void CDirView::OnViewShowHiddenItems()
3378 SetItemViewFlag(GetDiffContext(), ViewCustomFlags::VISIBLE, ViewCustomFlags::VISIBILITY);
3384 * @brief Enable/Disable 'Show hidden items' menuitem.
3386 void CDirView::OnUpdateViewShowHiddenItems(CCmdUI* pCmdUI)
3388 pCmdUI->Enable(m_nHiddenItems > 0);
3392 * @brief Toggle Tree Mode
3394 void CDirView::OnViewTreeMode()
3396 m_bTreeMode = !m_bTreeMode;
3397 m_dirfilter.tree_mode = m_bTreeMode;
3398 GetOptionsMgr()->SaveOption(OPT_TREE_MODE, m_bTreeMode); // reverse
3403 * @brief Check/Uncheck 'Tree Mode' menuitem.
3405 void CDirView::OnUpdateViewTreeMode(CCmdUI* pCmdUI)
3407 // Don't show Tree Mode as 'checked' if the
3408 // menu item is greyed out (disabled). Its very confusing.
3409 if( GetDocument()->GetDiffContext().m_bRecursive ) {
3410 pCmdUI->SetCheck(m_bTreeMode);
3411 pCmdUI->Enable(TRUE);
3413 pCmdUI->SetCheck(FALSE);
3414 pCmdUI->Enable(FALSE);
3419 * @brief Expand all subfolders
3421 void CDirView::OnViewExpandAllSubdirs()
3423 ExpandAllSubdirs(GetDiffContext());
3428 * @brief Update "Expand All Subfolders" item
3430 void CDirView::OnUpdateViewExpandAllSubdirs(CCmdUI* pCmdUI)
3432 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3436 * @brief Collapse all subfolders
3438 void CDirView::OnViewCollapseAllSubdirs()
3440 CollapseAllSubdirs(GetDiffContext());
3445 * @brief Update "Collapse All Subfolders" item
3447 void CDirView::OnUpdateViewCollapseAllSubdirs(CCmdUI* pCmdUI)
3449 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3452 template <int pane1, int pane2>
3453 void CDirView::OnViewSwapPanes()
3455 GetDocument()->Swap(pane1, pane2);
3459 template <int pane1, int pane2>
3460 void CDirView::OnUpdateViewSwapPanes(CCmdUI* pCmdUI)
3462 pCmdUI->Enable(pane2 < GetDocument()->m_nDirs);
3466 * @brief Show/Hide different files/directories
3468 void CDirView::OnOptionsShowDifferent()
3470 m_dirfilter.show_different = !m_dirfilter.show_different;
3471 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT, m_dirfilter.show_different);
3476 * @brief Show/Hide identical files/directories
3478 void CDirView::OnOptionsShowIdentical()
3480 m_dirfilter.show_identical = !m_dirfilter.show_identical;
3481 GetOptionsMgr()->SaveOption(OPT_SHOW_IDENTICAL, m_dirfilter.show_identical);
3486 * @brief Show/Hide left-only files/directories
3488 void CDirView::OnOptionsShowUniqueLeft()
3490 m_dirfilter.show_unique_left = !m_dirfilter.show_unique_left;
3491 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_LEFT, m_dirfilter.show_unique_left);
3496 * @brief Show/Hide middle-only files/directories
3498 void CDirView::OnOptionsShowUniqueMiddle()
3500 m_dirfilter.show_unique_middle = !m_dirfilter.show_unique_middle;
3501 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_MIDDLE, m_dirfilter.show_unique_middle);
3506 * @brief Show/Hide right-only files/directories
3508 void CDirView::OnOptionsShowUniqueRight()
3510 m_dirfilter.show_unique_right = !m_dirfilter.show_unique_right;
3511 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_RIGHT, m_dirfilter.show_unique_right);
3516 * @brief Show/Hide binary files
3518 void CDirView::OnOptionsShowBinaries()
3520 m_dirfilter.show_binaries = !m_dirfilter.show_binaries;
3521 GetOptionsMgr()->SaveOption(OPT_SHOW_BINARIES, m_dirfilter.show_binaries);
3526 * @brief Show/Hide skipped files/directories
3528 void CDirView::OnOptionsShowSkipped()
3530 m_dirfilter.show_skipped = !m_dirfilter.show_skipped;
3531 GetOptionsMgr()->SaveOption(OPT_SHOW_SKIPPED, m_dirfilter.show_skipped);
3536 * @brief Show/Hide different files/folders (Middle and right are identical)
3538 void CDirView::OnOptionsShowDifferentLeftOnly()
3540 m_dirfilter.show_different_left_only = !m_dirfilter.show_different_left_only;
3541 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_LEFT_ONLY, m_dirfilter.show_different_left_only);
3546 * @brief Show/Hide different files/folders (Left and right are identical)
3548 void CDirView::OnOptionsShowDifferentMiddleOnly()
3550 m_dirfilter.show_different_middle_only = !m_dirfilter.show_different_middle_only;
3551 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_MIDDLE_ONLY, m_dirfilter.show_different_middle_only);
3556 * @brief Show/Hide different files/folders (Left and middle are identical)
3558 void CDirView::OnOptionsShowDifferentRightOnly()
3560 m_dirfilter.show_different_right_only = !m_dirfilter.show_different_right_only;
3561 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_RIGHT_ONLY, m_dirfilter.show_different_right_only);
3566 * @brief Show/Hide missing left only files/folders
3568 void CDirView::OnOptionsShowMissingLeftOnly()
3570 m_dirfilter.show_missing_left_only = !m_dirfilter.show_missing_left_only;
3571 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_LEFT_ONLY, m_dirfilter.show_missing_left_only);
3576 * @brief Show/Hide missing middle only files/folders
3578 void CDirView::OnOptionsShowMissingMiddleOnly()
3580 m_dirfilter.show_missing_middle_only = !m_dirfilter.show_missing_middle_only;
3581 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_MIDDLE_ONLY, m_dirfilter.show_missing_middle_only);
3586 * @brief Show/Hide missing right only files/folders
3588 void CDirView::OnOptionsShowMissingRightOnly()
3590 m_dirfilter.show_missing_right_only = !m_dirfilter.show_missing_right_only;
3591 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_RIGHT_ONLY, m_dirfilter.show_missing_right_only);
3595 void CDirView::OnUpdateOptionsShowdifferent(CCmdUI* pCmdUI)
3597 pCmdUI->SetCheck(m_dirfilter.show_different);
3600 void CDirView::OnUpdateOptionsShowidentical(CCmdUI* pCmdUI)
3602 pCmdUI->SetCheck(m_dirfilter.show_identical);
3605 void CDirView::OnUpdateOptionsShowuniqueleft(CCmdUI* pCmdUI)
3607 pCmdUI->SetCheck(m_dirfilter.show_unique_left);
3610 void CDirView::OnUpdateOptionsShowuniquemiddle(CCmdUI* pCmdUI)
3612 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3613 pCmdUI->SetCheck(m_dirfilter.show_unique_middle);
3616 void CDirView::OnUpdateOptionsShowuniqueright(CCmdUI* pCmdUI)
3618 pCmdUI->SetCheck(m_dirfilter.show_unique_right);
3621 void CDirView::OnUpdateOptionsShowBinaries(CCmdUI* pCmdUI)
3623 pCmdUI->SetCheck(m_dirfilter.show_binaries);
3626 void CDirView::OnUpdateOptionsShowSkipped(CCmdUI* pCmdUI)
3628 pCmdUI->SetCheck(m_dirfilter.show_skipped);
3631 void CDirView::OnUpdateOptionsShowDifferentLeftOnly(CCmdUI* pCmdUI)
3633 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3634 pCmdUI->SetCheck(m_dirfilter.show_different_left_only);
3637 void CDirView::OnUpdateOptionsShowDifferentMiddleOnly(CCmdUI* pCmdUI)
3639 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3640 pCmdUI->SetCheck(m_dirfilter.show_different_middle_only);
3643 void CDirView::OnUpdateOptionsShowDifferentRightOnly(CCmdUI* pCmdUI)
3645 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3646 pCmdUI->SetCheck(m_dirfilter.show_different_right_only);
3649 void CDirView::OnUpdateOptionsShowMissingLeftOnly(CCmdUI* pCmdUI)
3651 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3652 pCmdUI->SetCheck(m_dirfilter.show_missing_left_only);
3655 void CDirView::OnUpdateOptionsShowMissingMiddleOnly(CCmdUI* pCmdUI)
3657 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3658 pCmdUI->SetCheck(m_dirfilter.show_missing_middle_only);
3661 void CDirView::OnUpdateOptionsShowMissingRightOnly(CCmdUI* pCmdUI)
3663 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3664 pCmdUI->SetCheck(m_dirfilter.show_missing_right_only);
3667 void CDirView::OnMergeCompare()
3669 CWaitCursor waitstatus;
3673 template<SELECTIONTYPE seltype>
3674 void CDirView::OnMergeCompare2()
3676 CWaitCursor waitstatus;
3677 OpenSelection(seltype);
3680 void CDirView::OnMergeCompareNonHorizontally()
3682 int sel1, sel2, sel3;
3683 if (!GetSelectedItems(&sel1, &sel2, &sel3))
3685 DirSelectFilesDlg dlg;
3687 dlg.m_pdi[0] = &GetDiffItem(sel1);
3689 dlg.m_pdi[1] = &GetDiffItem(sel2);
3691 dlg.m_pdi[2] = &GetDiffItem(sel3);
3692 if (dlg.DoModal() == IDOK && dlg.m_selectedButtons.size() > 0)
3694 CDirDoc *pDoc = GetDocument();
3695 DWORD dwFlags[3] = {};
3697 for (int nIndex = 0; nIndex < static_cast<int>(dlg.m_selectedButtons.size()); ++nIndex)
3699 int n = dlg.m_selectedButtons[nIndex];
3700 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(n % 3) ? FFILEOPEN_READONLY : 0);
3701 if (dlg.m_pdi[n / 3])
3702 paths.SetPath(nIndex, GetItemFileName(pDoc->GetDiffContext(), *dlg.m_pdi[n / 3], n % 3));
3704 if (paths.GetSize() == 1)
3705 paths.SetRight(_T(""));
3706 Open(paths, dwFlags);
3710 void CDirView::OnMergeCompareXML()
3712 CWaitCursor waitstatus;
3713 PackingInfo packingInfo(PLUGIN_MODE::PLUGIN_BUILTIN_XML);
3714 OpenSelection(SELECTIONTYPE_NORMAL, &packingInfo, false);
3717 void CDirView::OnMergeCompareAs(UINT nID)
3719 CWaitCursor waitstatus;
3720 OpenSelectionAs(nID);
3723 void CDirView::OnUpdateMergeCompare(CCmdUI *pCmdUI)
3725 bool openableForDir = (pCmdUI->m_nID != ID_MERGE_COMPARE_XML &&
3726 pCmdUI->m_nID != ID_MERGE_COMPARE_HEX &&
3727 pCmdUI->m_nID != ID_MERGE_COMPARE_IMAGE);
3729 DoUpdateOpen(SELECTIONTYPE_NORMAL, pCmdUI, openableForDir);
3732 template<SELECTIONTYPE seltype>
3733 void CDirView::OnUpdateMergeCompare2(CCmdUI *pCmdUI)
3735 DoUpdateOpen(seltype, pCmdUI);
3738 void CDirView::OnViewCompareStatistics()
3740 CompareStatisticsDlg dlg(GetDocument()->GetCompareStats());
3745 * @brief Count left & right files, and number with editable text encoding
3746 * @param nLeft [out] #files on left side selected
3747 * @param nLeftAffected [out] #files on left side selected which can have text encoding changed
3748 * @param nRight [out] #files on right side selected
3749 * @param nRightAffected [out] #files on right side selected which can have text encoding changed
3751 * Affected files include all except unicode files
3753 void CDirView::FormatEncodingDialogDisplays(CLoadSaveCodepageDlg * dlg)
3755 IntToIntMap currentCodepages = CountCodepages(SelBegin(), SelEnd(), GetDiffContext());
3757 Counts left, middle, right;
3758 left = Count(&DirActions::IsItemEditableEncoding<SIDE_LEFT>);
3759 if (GetDocument()->m_nDirs > 2)
3760 middle = Count(&DirActions::IsItemEditableEncoding<SIDE_MIDDLE>);
3761 right = Count(&DirActions::IsItemEditableEncoding<SIDE_RIGHT>);
3763 // Format strings such as "25 of 30 Files Affected"
3764 String sLeftAffected = FormatFilesAffectedString(left.count, left.total);
3765 String sMiddleAffected = (GetDocument()->m_nDirs < 3) ? _T("") : FormatFilesAffectedString(middle.count, middle.total);
3766 String sRightAffected = FormatFilesAffectedString(right.count, right.total);
3767 dlg->SetLeftRightAffectStrings(sLeftAffected, sMiddleAffected, sRightAffected);
3768 int codepage = currentCodepages.FindMaxKey();
3769 dlg->SetCodepages(codepage);
3773 * @brief Display file encoding dialog to user & handle user's choices
3775 * This handles DirView invocation, so multiple files may be affected
3777 void CDirView::DoFileEncodingDialog()
3779 CLoadSaveCodepageDlg dlg(GetDocument()->m_nDirs);
3780 // set up labels about what will be affected
3781 FormatEncodingDialogDisplays(&dlg);
3782 dlg.EnableSaveCodepage(false); // disallow setting a separate codepage for saving
3785 if (dlg.DoModal() != IDOK)
3789 affected[0] = dlg.DoesAffectLeft();
3790 affected[1] = dlg.DoesAffectMiddle();
3791 affected[SideToIndex(GetDiffContext(), SIDE_RIGHT)] = dlg.DoesAffectRight();
3793 ApplyCodepage(SelBegin(), SelEnd(), GetDiffContext(), affected, dlg.GetLoadCodepage());
3795 m_pList->InvalidateRect(nullptr);
3796 m_pList->UpdateWindow();
3798 // TODO: We could loop through any active merge windows belonging to us
3799 // and see if any of their files are affected
3800 // but, if they've been edited, we cannot throw away the user's work?
3804 * @brief Display file encoding dialog & handle user's actions
3806 void CDirView::OnFileEncoding()
3808 DoFileEncodingDialog();
3811 /** @brief Open help from mainframe when user presses F1*/
3812 void CDirView::OnHelp()
3814 theApp.ShowHelp(DirViewHelpLocation);
3818 * @brief true while user is editing a file name.
3820 bool CDirView::IsLabelEdit() const
3822 return (m_pList->GetEditControl() != nullptr);
3826 * @brief Allow edit "Paste" when renaming an item.
3828 void CDirView::OnEditCopy()
3830 CEdit *pEdit = m_pList->GetEditControl();
3831 if (pEdit != nullptr)
3838 * @brief Allow edit "Cut" when renaming an item.
3840 void CDirView::OnEditCut()
3842 CEdit *pEdit = m_pList->GetEditControl();
3843 if (pEdit != nullptr)
3850 * @brief Allow edit "Paste" when renaming an item.
3852 void CDirView::OnEditPaste()
3854 CEdit *pEdit = m_pList->GetEditControl();
3855 if (pEdit != nullptr)
3862 * @brief Allow edit "Undo" when renaming an item.
3864 void CDirView::OnEditUndo()
3866 CEdit *pEdit = m_pList->GetEditControl();
3867 if (pEdit != nullptr)
3874 * @brief Update the tool bar's "Undo" icon. It should be enabled when
3875 * renaming an item and undo is possible.
3877 void CDirView::OnUpdateEditUndo(CCmdUI* pCmdUI)
3879 CEdit *pEdit = m_pList->GetEditControl();
3880 pCmdUI->Enable(pEdit && pEdit->CanUndo());
3883 * @brief Returns CShellContextMenu object that owns given HMENU.
3885 * @param [in] hMenu Handle to the menu to check ownership of.
3886 * @return Either m_pShellContextMenuLeft, m_pShellContextMenuRight
3887 * or `nullptr` if hMenu is not owned by these two.
3889 CShellContextMenu* CDirView::GetCorrespondingShellContextMenu(HMENU hMenu) const
3891 CShellContextMenu* pMenu = nullptr;
3892 if (m_pShellContextMenuLeft!=nullptr && hMenu == m_pShellContextMenuLeft->GetHMENU())
3893 pMenu = m_pShellContextMenuLeft.get();
3894 else if (m_pShellContextMenuMiddle!=nullptr && hMenu == m_pShellContextMenuMiddle->GetHMENU())
3895 pMenu = m_pShellContextMenuMiddle.get();
3896 else if (m_pShellContextMenuRight!=nullptr && hMenu == m_pShellContextMenuRight->GetHMENU())
3897 pMenu = m_pShellContextMenuRight.get();
3903 * @brief Handle messages related to correct menu working.
3905 * We need to requery shell context menu each time we switch from context menu
3906 * for one side to context menu for other side. Here we check whether we need to
3907 * requery and call ShellContextMenuHandleMenuMessage.
3909 LRESULT CDirView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
3911 while (message == WM_INITMENUPOPUP)
3913 HMENU hMenu = (HMENU)wParam;
3914 if (CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(hMenu))
3916 if (m_hCurrentMenu != hMenu)
3918 // re-query context menu once more, because if context menu was queried for right
3919 // group of files and we are showing menu for left group (or vice versa) menu will
3920 // be shown incorrectly
3921 // also, if context menu was last queried for right group of files and we are
3922 // invoking command for left command will be executed for right group (the last
3923 // group that menu was requested for)
3924 // may be a "feature" of Shell
3926 pMenu->RequeryShellContextMenu();
3927 m_hCurrentMenu = hMenu;
3933 CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(m_hCurrentMenu);
3935 if (pMenu != nullptr)
3938 pMenu->HandleMenuMessage(message, wParam, lParam, res);
3941 return CListView::WindowProc(message, wParam, lParam);
3945 * @brief Implement background item coloring
3947 void CDirView::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
3949 if (!m_bUseColors) {
3953 LPNMLISTVIEW pNM = (LPNMLISTVIEW)pNMHDR;
3954 *pResult = CDRF_DODEFAULT;
3956 if (pNM->hdr.code == NM_CUSTOMDRAW)
3958 LPNMLVCUSTOMDRAW lpC = (LPNMLVCUSTOMDRAW)pNMHDR;
3960 if (lpC->nmcd.dwDrawStage == CDDS_PREPAINT)
3962 *pResult = CDRF_NOTIFYITEMDRAW;
3966 if (lpC->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
3968 *pResult = CDRF_NOTIFYITEMDRAW;
3972 if (lpC->nmcd.dwDrawStage == (CDDS_ITEMPREPAINT | CDDS_SUBITEM ))
3974 GetColors (static_cast<int>(lpC->nmcd.dwItemSpec), lpC->iSubItem, lpC->clrTextBk, lpC->clrText);
3979 void CDirView::OnBnClickedComparisonStop()
3981 if (m_pCmpProgressBar != nullptr)
3982 m_pCmpProgressBar->EndUpdating();
3983 GetDocument()->AbortCurrentScan();
3986 void CDirView::OnBnClickedComparisonPause()
3988 if (m_pCmpProgressBar != nullptr)
3989 m_pCmpProgressBar->SetPaused(true);
3990 GetDocument()->PauseCurrentScan();
3993 void CDirView::OnBnClickedComparisonContinue()
3995 if (m_pCmpProgressBar != nullptr)
3996 m_pCmpProgressBar->SetPaused(false);
3997 GetDocument()->ContinueCurrentScan();
4001 * @brief Populate colors for items in view, depending on difference status
4003 void CDirView::GetColors (int nRow, int nCol, COLORREF& clrBk, COLORREF& clrText) const
4005 const DIFFITEM& di = GetDiffItem (nRow);
4009 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4010 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4012 else if (di.diffcode.isResultFiltered())
4014 clrText = m_cachedColors.clrDirItemFilteredText;
4015 clrBk = m_cachedColors.clrDirItemFiltered;
4017 else if (!IsItemExistAll(GetDiffContext(), di))
4019 clrText = m_cachedColors.clrDirItemNotExistAllText;
4020 clrBk = m_cachedColors.clrDirItemNotExistAll;
4022 else if (di.diffcode.isResultDiff())
4024 clrText = m_cachedColors.clrDirItemDiffText;
4025 clrBk = m_cachedColors.clrDirItemDiff;
4027 else if (di.diffcode.isResultSame())
4029 clrText = m_cachedColors.clrDirItemEqualText;
4030 clrBk = m_cachedColors.clrDirItemEqual;
4034 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4035 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4039 void CDirView::OnSearch()
4041 CDirDoc *pDoc = GetDocument();
4042 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
4043 int nRows = m_pList->GetItemCount();
4044 for (int currRow = nRows - 1; currRow >= 0; currRow--)
4046 DIFFITEM *pos = GetItemKey(currRow);
4047 if (pos == (DIFFITEM *)SPECIAL_ITEM_POS)
4050 bool bFound = false;
4051 DIFFITEM &di = GetDiffItem(currRow);
4053 for (int i = 0; i < pDoc->m_nDirs; i++)
4055 if (di.diffcode.exists(i) && !di.diffcode.isDirectory())
4057 GetItemFileNames(currRow, &paths);
4059 if (!ufile.OpenReadOnly(paths[i]))
4062 ufile.SetUnicoding(di.diffFileInfo[i].encoding.m_unicoding);
4063 ufile.SetBom(di.diffFileInfo[i].encoding.m_bom);
4064 ufile.SetCodepage(di.diffFileInfo[i].encoding.m_codepage);
4072 if (!ufile.ReadString(line, &lossy))
4075 if (_tcsstr(line.c_str(), _T("DirView")))
4089 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
4090 DeleteItem(currRow);
4094 m_pList->SetRedraw(TRUE); // Turn updating back on
4098 * @brief Drag files/directories from folder compare listing view.
4100 void CDirView::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
4102 COleDataSource *DropData = new COleDataSource();
4104 std::list<String> list;
4105 CopyPathnamesForDragAndDrop(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
4106 String filesForDroping = strutils::join(list.begin(), list.end(), _T("\n")) + _T("\n");
4108 CSharedFile file(GMEM_DDESHARE | GMEM_MOVEABLE | GMEM_ZEROINIT);
4109 file.Write(filesForDroping.data(), static_cast<unsigned>((filesForDroping.length() + 1) * sizeof(TCHAR)));
4111 HGLOBAL hMem = GlobalReAlloc(file.Detach(), (filesForDroping.length() + 1) * sizeof(TCHAR), 0);
4112 if (hMem != nullptr)
4114 DropData->CacheGlobalData(CF_UNICODETEXT, hMem);
4115 DROPEFFECT de = DropData->DoDragDrop(DROPEFFECT_COPY | DROPEFFECT_MOVE, nullptr);
4121 /// Assign column name, using string resource & current column ordering
4122 void CDirView::NameColumn(const DirColInfo *col, int subitem)
4124 int phys = m_pColItems->ColLogToPhys(subitem);
4127 String s = tr(col->idNameContext, col->idName);
4129 lvc.mask = LVCF_TEXT;
4130 lvc.pszText = const_cast<LPTSTR>(s.c_str());
4131 m_pList->SetColumn(phys, &lvc);
4135 /// Load column names from string table
4136 void CDirView::UpdateColumnNames()
4138 int ncols = m_pColItems->GetColCount();
4139 for (int i=0; i<ncols; ++i)
4141 const DirColInfo* col = m_pColItems->GetDirColInfo(i);
4147 * @brief Set alignment of columns.
4149 void CDirView::SetColAlignments()
4151 int ncols = m_pColItems->GetColCount();
4152 for (int i=0; i<ncols; ++i)
4154 const DirColInfo * col = m_pColItems->GetDirColInfo(i);
4156 lvc.mask = LVCF_FMT;
4157 lvc.fmt = col->alignment;
4158 m_pList->SetColumn(m_pColItems->ColLogToPhys(i), &lvc);
4162 CDirView::CompareState::CompareState(const CDiffContext *pCtxt, const DirViewColItems *pColItems, int sortCol, bool bSortAscending, bool bTreeMode)
4164 , pColItems(pColItems)
4166 , bSortAscending(bSortAscending)
4167 , bTreeMode(bTreeMode)
4171 /// Compare two specified rows during a sort operation (windows callback)
4172 int CALLBACK CDirView::CompareState::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
4174 CompareState *pThis = reinterpret_cast<CompareState*>(lParamSort);
4175 // Sort special items always first in dir view
4181 DIFFITEM *diffposl = (DIFFITEM *)lParam1;
4182 DIFFITEM *diffposr = (DIFFITEM *)lParam2;
4183 const DIFFITEM &ldi = pThis->pCtxt->GetDiffAt(diffposl);
4184 const DIFFITEM &rdi = pThis->pCtxt->GetDiffAt(diffposr);
4185 // compare 'left' and 'right' parameters as appropriate
4186 int retVal = pThis->pColItems->ColSort(pThis->pCtxt, pThis->sortCol, ldi, rdi, pThis->bTreeMode);
4187 // return compare result, considering sort direction
4188 return pThis->bSortAscending ? retVal : -retVal;
4191 /// Add new item to list view
4192 int CDirView::AddNewItem(int i, DIFFITEM *diffpos, int iImage, int iIndent)
4195 lvItem.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE | LVIF_INDENT;
4197 lvItem.iIndent = iIndent;
4198 lvItem.iSubItem = 0;
4199 lvItem.pszText = LPSTR_TEXTCALLBACK;
4200 lvItem.lParam = (LPARAM)diffpos;
4201 lvItem.iImage = iImage;
4202 return GetListCtrl().InsertItem(&lvItem);
4206 * @brief Update listview display of details for specified row
4207 * @note Customising shownd data should be done here
4209 void CDirView::UpdateDiffItemStatus(UINT nIdx)
4211 GetListCtrl().RedrawItems(nIdx, nIdx);
4212 const DIFFITEM& di = GetDiffItem(nIdx);
4213 if (di.diffcode.isDirectory())
4216 for (it = RevBegin(); it != RevEnd(); )
4218 DIFFITEM& di2 = *it;
4219 int cursel = it.m_sel;
4221 if (di2.IsAncestor(&di))
4223 if ((di2.diffcode.diffcode & DIFFCODE::SIDEFLAGS) == 0)
4224 DeleteItem(cursel, true);
4226 GetListCtrl().RedrawItems(cursel, cursel);
4232 static String rgDispinfoText[2]; // used in function below
4235 * @brief Allocate a text buffer to assign to NMLVDISPINFO::item::pszText
4236 * Quoting from SDK Docs:
4237 * If the LVITEM structure is receiving item text, the pszText and cchTextMax
4238 * members specify the address and size of a buffer. You can either copy text to
4239 * the buffer or assign the address of a string to the pszText member. In the
4240 * latter case, you must not change or delete the string until the corresponding
4241 * item text is deleted or two additional LVN_GETDISPINFO messages have been sent.
4243 static LPTSTR NTAPI AllocDispinfoText(const String &s)
4246 LPCTSTR pszText = (rgDispinfoText[i] = s).c_str();
4248 return (LPTSTR)pszText;
4252 * @brief Respond to LVN_GETDISPINFO message
4254 void CDirView::ReflectGetdispinfo(NMLVDISPINFO *pParam)
4256 int nIdx = pParam->item.iItem;
4257 int i = m_pColItems->ColPhysToLog(pParam->item.iSubItem);
4258 DIFFITEM *key = GetItemKey(nIdx);
4259 if (key == (DIFFITEM *)SPECIAL_ITEM_POS)
4261 if (m_pColItems->IsColName(i))
4263 pParam->item.pszText = _T("..");
4267 if (!GetDocument()->HasDiffs())
4269 const CDiffContext &ctxt = GetDiffContext();
4270 const DIFFITEM &di = ctxt.GetDiffAt(key);
4271 if (pParam->item.mask & LVIF_TEXT)
4273 String s = m_pColItems->ColGetTextToDisplay(&ctxt, i, di);
4274 pParam->item.pszText = AllocDispinfoText(s);
4276 if (pParam->item.mask & LVIF_IMAGE)
4278 pParam->item.iImage = GetColImage(di);
4283 * @brief User examines & edits which columns are displayed in dirview, and in which order
4285 void CDirView::OnEditColumns()
4288 // List all the currently displayed columns
4289 for (int col=0; col<GetListCtrl().GetHeaderCtrl()->GetItemCount(); ++col)
4291 int l = m_pColItems->ColPhysToLog(col);
4292 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l, col);
4294 // Now add all the columns not currently displayed
4296 for (l=0; l<m_pColItems->GetColCount(); ++l)
4298 if (m_pColItems->ColLogToPhys(l)==-1)
4300 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l);
4304 // Add default order of columns for resetting to defaults
4305 for (l = 0; l < m_pColItems->GetColCount(); ++l)
4307 int phy = m_pColItems->GetColDefaultOrder(l);
4308 dlg.AddDefColumn(m_pColItems->GetColDisplayName(l), l, phy);
4311 if (dlg.DoModal() != IDOK)
4314 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
4315 GetOptionsMgr()->SaveOption(keyname,
4316 (dlg.m_bReset ? m_pColItems->ResetColumnWidths(GetDefColumnWidth()) :
4317 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1))));
4319 // Reset our data to reflect the new data from the dialog
4320 const CDirColsDlg::ColumnArray & cols = dlg.GetColumns();
4321 m_pColItems->ClearColumnOrders();
4322 const int sortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4323 std::vector<int> colorder(m_pColItems->GetColCount(), -1);
4324 for (CDirColsDlg::ColumnArray::const_iterator iter = cols.begin();
4325 iter != cols.end(); ++iter)
4327 int log = iter->log_col;
4328 int phy = iter->phy_col;
4329 colorder[log] = phy;
4331 // If sorted column was hidden, reset sorting
4332 if (log == sortColumn && phy < 0)
4334 GetOptionsMgr()->Reset((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4335 GetOptionsMgr()->Reset(OPT_DIRVIEW_SORT_ASCENDING);
4339 m_pColItems->SetColumnOrdering(&colorder[0]);
4341 if (m_pColItems->GetDispColCount() < 1)
4343 // Ignore them if they didn't leave a column showing
4344 m_pColItems->ResetColumnOrdering();
4353 DirActions CDirView::MakeDirActions(DirActions::method_type func) const
4355 const CDirDoc *pDoc = GetDocument();
4356 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), func);
4359 DirActions CDirView::MakeDirActions(DirActions::method_type2 func) const
4361 const CDirDoc *pDoc = GetDocument();
4362 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), nullptr, func);
4365 const CDiffContext& CDirView::GetDiffContext() const
4367 return GetDocument()->GetDiffContext();
4370 CDiffContext& CDirView::GetDiffContext()
4372 return GetDocument()->GetDiffContext();