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, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
237 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_MIDDLE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
238 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_RIGHT, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
239 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_BOTH, OnUpdateCtxtDirCopyBothTo)
240 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_ALL, OnUpdateCtxtDirCopyBothTo)
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, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
249 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
250 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
251 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnUpdateCtxtDirCopyBothTo)
252 ON_UPDATE_COMMAND_UI(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnUpdateCtxtDirCopyBothTo)
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_VIEW_SWAPPANES, OnViewSwapPanes)
292 ON_COMMAND(ID_VIEW_DIR_STATISTICS, OnViewCompareStatistics)
293 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENT, OnOptionsShowDifferent)
294 ON_COMMAND(ID_OPTIONS_SHOWIDENTICAL, OnOptionsShowIdentical)
295 ON_COMMAND(ID_OPTIONS_SHOWUNIQUELEFT, OnOptionsShowUniqueLeft)
296 ON_COMMAND(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnOptionsShowUniqueMiddle)
297 ON_COMMAND(ID_OPTIONS_SHOWUNIQUERIGHT, OnOptionsShowUniqueRight)
298 ON_COMMAND(ID_OPTIONS_SHOWBINARIES, OnOptionsShowBinaries)
299 ON_COMMAND(ID_OPTIONS_SHOWSKIPPED, OnOptionsShowSkipped)
300 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnOptionsShowDifferentLeftOnly)
301 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnOptionsShowDifferentMiddleOnly)
302 ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnOptionsShowDifferentRightOnly)
303 ON_COMMAND(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnOptionsShowMissingLeftOnly)
304 ON_COMMAND(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnOptionsShowMissingMiddleOnly)
305 ON_COMMAND(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnOptionsShowMissingRightOnly)
306 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENT, OnUpdateOptionsShowdifferent)
307 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWIDENTICAL, OnUpdateOptionsShowidentical)
308 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUELEFT, OnUpdateOptionsShowuniqueleft)
309 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnUpdateOptionsShowuniquemiddle)
310 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUERIGHT, OnUpdateOptionsShowuniqueright)
311 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWBINARIES, OnUpdateOptionsShowBinaries)
312 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWSKIPPED, OnUpdateOptionsShowSkipped)
313 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnUpdateOptionsShowDifferentLeftOnly)
314 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnUpdateOptionsShowDifferentMiddleOnly)
315 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnUpdateOptionsShowDifferentRightOnly)
316 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnUpdateOptionsShowMissingLeftOnly)
317 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnUpdateOptionsShowMissingMiddleOnly)
318 ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnUpdateOptionsShowMissingRightOnly)
319 ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
320 ON_COMMAND(ID_HELP, OnHelp)
321 ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
322 ON_COMMAND(ID_EDIT_CUT, OnEditCut)
323 ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
324 ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
325 ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
327 ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
328 ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
329 ON_NOTIFY_REFLECT(LVN_BEGINLABELEDIT, OnBeginLabelEdit)
330 ON_NOTIFY_REFLECT(LVN_ENDLABELEDIT, OnEndLabelEdit)
331 ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
332 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
333 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
334 ON_BN_CLICKED(IDC_COMPARISON_STOP, OnBnClickedComparisonStop)
335 ON_BN_CLICKED(IDC_COMPARISON_PAUSE, OnBnClickedComparisonPause)
336 ON_BN_CLICKED(IDC_COMPARISON_CONTINUE, OnBnClickedComparisonContinue)
339 /////////////////////////////////////////////////////////////////////////////
340 // CDirView diagnostics
344 CDirDoc* CDirView::GetDocument() // non-debug version is inline
346 ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDirDoc)));
347 return (CDirDoc*)m_pDocument;
351 /////////////////////////////////////////////////////////////////////////////
352 // CDirView message handlers
354 void CDirView::OnInitialUpdate()
356 const int iconCX = []() {
357 const int cx = GetSystemMetrics(SM_CXSMICON);
366 const int iconCY = iconCX;
367 CListView::OnInitialUpdate();
368 m_pList = &GetListCtrl();
369 m_pIList.reset(new IListCtrlImpl(m_pList->m_hWnd));
370 GetDocument()->SetDirView(this);
371 m_pColItems.reset(new DirViewColItems(GetDocument()->m_nDirs));
373 m_pList->SendMessage(CCM_SETUNICODEFORMAT, TRUE, 0);
375 // Load user-selected font
376 if (GetOptionsMgr()->GetBool(OPT_FONT_DIRCMP + OPT_FONT_USECUSTOM))
378 m_font.CreateFontIndirect(&GetMainFrame()->m_lfDir);
379 CWnd::SetFont(&m_font, TRUE);
383 m_pList->SetBkColor(m_cachedColors.clrDirMargin);
385 // Replace standard header with sort header
386 HWND hWnd = ListView_GetHeader(m_pList->m_hWnd);
388 m_ctlSortHeader.SubclassWindow(hWnd);
390 // Load the icons used for the list view (to reflect diff status)
391 // NOTE: these must be in the exactly the same order as in the `enum`
392 // definition in the DirActions.h file (ref: DIFFIMG_LUNIQUE)
393 VERIFY(m_imageList.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
395 IDI_LFILE, IDI_MFILE, IDI_RFILE,
396 IDI_MRFILE, IDI_LRFILE, IDI_LMFILE,
397 IDI_NOTEQUALFILE, IDI_EQUALFILE, IDI_FILE,
398 IDI_EQUALBINARY, IDI_BINARYDIFF,
399 IDI_LFOLDER, IDI_MFOLDER, IDI_RFOLDER,
400 IDI_MRFOLDER, IDI_LRFOLDER, IDI_LMFOLDER,
401 IDI_FILESKIP, IDI_FOLDERSKIP,
402 IDI_NOTEQUALFOLDER, IDI_EQUALFOLDER, IDI_FOLDER,
404 IDI_FOLDERUP, IDI_FOLDERUP_DISABLE,
406 IDI_NOTEQUALTEXTFILE, IDI_EQUALTEXTFILE,
407 IDI_NOTEQUALIMAGE, IDI_EQUALIMAGE,
409 for (auto id : icon_ids)
410 VERIFY(-1 != m_imageList.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
411 m_pList->SetImageList(&m_imageList, LVSIL_SMALL);
413 // Load the icons used for the list view (expanded/collapsed state icons)
414 VERIFY(m_imageState.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
415 for (auto id : { IDI_TREE_STATE_COLLAPSED, IDI_TREE_STATE_EXPANDED })
416 VERIFY(-1 != m_imageState.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
418 // Restore column orders as they had them last time they ran
419 m_pColItems->LoadColumnOrders(
420 (const TCHAR *)theApp.GetProfileString(GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3"), _T("ColumnOrders")));
422 // Display column headers (in appropriate order)
425 // Show selection across entire row.u
426 // Also allow user to rearrange columns via drag&drop of headers.
427 // Also enable infotips.
428 DWORD exstyle = LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_INFOTIP;
429 m_pList->SetExtendedStyle(exstyle);
432 BOOL CDirView::PreCreateWindow(CREATESTRUCT& cs)
434 CListView::PreCreateWindow(cs);
435 cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
440 * @brief Called before compare is started.
441 * CDirDoc calls this function before new compare is started, so this
442 * is good place to setup GUI for compare.
443 * @param [in] pCompareStats Pointer to class having current compare stats.
445 void CDirView::StartCompare(CompareStats *pCompareStats)
447 if (m_pCmpProgressBar == nullptr)
448 m_pCmpProgressBar.reset(new DirCompProgressBar());
450 if (!::IsWindow(m_pCmpProgressBar->GetSafeHwnd()))
451 m_pCmpProgressBar->Create(GetParentFrame());
453 m_pCmpProgressBar->SetCompareStat(pCompareStats);
454 m_pCmpProgressBar->StartUpdating();
456 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), TRUE, FALSE);
458 m_compareStart = clock();
462 * @brief Called when folder compare row is double-clicked with mouse.
463 * Selected item is opened to folder or file compare.
465 void CDirView::OnLButtonDblClk(UINT nFlags, CPoint point)
469 m_pList->SubItemHitTest(&lvhti);
470 if (lvhti.iItem >= 0)
472 const DIFFITEM& di = GetDiffItem(lvhti.iItem);
473 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
475 if (di.customFlags & ViewCustomFlags::EXPANDED)
476 CollapseSubdir(lvhti.iItem);
478 ExpandSubdir(lvhti.iItem);
482 CWaitCursor waitstatus;
486 CListView::OnLButtonDblClk(nFlags, point);
490 * @brief Load or reload the columns (headers) of the list view
492 void CDirView::ReloadColumns()
494 LoadColumnHeaderItems();
497 m_pColItems->LoadColumnWidths(
498 (const TCHAR *)theApp.GetProfileString(GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3"), _T("ColumnWidths")),
499 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), DefColumnWidth);
504 * @brief Redisplay items in subfolder
505 * @param [in] diffpos First item position in subfolder.
506 * @param [in] level Indent level
507 * @param [in,out] index Index of the item to be inserted.
508 * @param [in,out] alldiffs Number of different items
510 void CDirView::RedisplayChildren(DIFFITEM *diffpos, int level, UINT &index, int &alldiffs)
512 const CDiffContext &ctxt = GetDiffContext();
513 while (diffpos != nullptr)
515 DIFFITEM *curdiffpos = diffpos;
516 const DIFFITEM &di = ctxt.GetNextSiblingDiffPosition(diffpos);
518 if (di.diffcode.isResultDiff() || (!di.diffcode.existAll() && !di.diffcode.isResultFiltered()))
521 bool bShowable = IsShowable(ctxt, di, m_dirfilter);
526 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, level);
528 if (di.HasChildren())
530 m_pList->SetItemState(index - 1, INDEXTOSTATEIMAGEMASK((di.customFlags & ViewCustomFlags::EXPANDED) ? 2 : 1), LVIS_STATEIMAGEMASK);
531 if (di.customFlags & ViewCustomFlags::EXPANDED)
532 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
537 if (!ctxt.m_bRecursive || !di.diffcode.isDirectory() || !di.diffcode.existAll())
539 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, 0);
542 if (di.HasChildren())
544 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
549 m_firstDiffItem.reset();
550 m_lastDiffItem.reset();
554 * @brief Redisplay folder compare view.
555 * This function clears folder compare view and then adds
556 * items from current compare to it.
558 void CDirView::Redisplay()
560 const CDirDoc *pDoc = GetDocument();
561 const CDiffContext &ctxt = GetDiffContext();
562 PathContext pathsParent;
563 CImageList emptyImageList;
566 // Disable redrawing while adding new items
569 DeleteAllDisplayItems();
571 m_pList->SetImageList((m_bTreeMode && ctxt.m_bRecursive) ? &m_imageState : &emptyImageList, LVSIL_STATE);
573 // If non-recursive compare, add special item(s)
574 if (!ctxt.m_bRecursive ||
575 CheckAllowUpwardDirectory(ctxt, pDoc->m_pTempPathContext, pathsParent) == AllowUpwardDirectory::ParentIsTempPath)
577 cnt += AddSpecialItems();
581 DIFFITEM *diffpos = ctxt.GetFirstDiffPosition();
582 RedisplayChildren(diffpos, 0, cnt, alldiffs);
583 if (pDoc->m_diffThread.GetThreadState() == CDiffThread::THREAD_COMPLETED)
584 GetParentFrame()->SetLastCompareResult(alldiffs);
585 SortColumnsAppropriately();
590 * @brief User right-clicked somewhere in this view
592 void CDirView::OnContextMenu(CWnd*, CPoint point)
594 if (GetListCtrl().GetItemCount() == 0)
596 // Make sure window is active
597 GetParentFrame()->ActivateFrame();
600 if (point.x == -1 && point.y == -1)
602 //keystroke invocation
605 ClientToScreen(rect);
607 point = rect.TopLeft();
612 // Check if user right-clicked on header
613 // convert screen coordinates to client coordinates of listview
614 CPoint insidePt = point;
615 GetListCtrl().ScreenToClient(&insidePt);
616 // TODO: correct for hscroll ?
617 // Ask header control if click was on one of its header items
618 HDHITTESTINFO hhti = { 0 };
620 int col = static_cast<int>(GetListCtrl().GetHeaderCtrl()->SendMessage(HDM_HITTEST, 0, (LPARAM) & hhti));
623 // Presumably hhti.flags & HHT_ONHEADER is true
624 HeaderContextMenu(point, m_pColItems->ColPhysToLog(col));
627 // bail out if point is not in any row
628 LVHITTESTINFO lhti = { 0 };
630 ScreenToClient(&insidePt);
632 i = GetListCtrl().HitTest(insidePt);
633 TRACE(_T("i=%d\n"), i);
638 ListContextMenu(point, i);
642 * @brief Format context menu string and disable item if it cannot be applied.
644 static void NTAPI FormatContextMenu(BCMenu *pPopup, UINT uIDItem, int n1, int n2 = 0, int n3 = 0)
647 pPopup->GetMenuText(uIDItem, s1, MF_BYCOMMAND);
648 s2.FormatMessage(s1, NumToStr(n1).c_str(), NumToStr(n2).c_str(), NumToStr(n3).c_str());
649 pPopup->SetMenuText(uIDItem, s2, MF_BYCOMMAND);
652 pPopup->EnableMenuItem(uIDItem, MF_GRAYED);
657 * @brief Toggle context menu item
659 static void NTAPI CheckContextMenu(BCMenu *pPopup, UINT uIDItem, BOOL bCheck)
662 pPopup->CheckMenuItem(uIDItem, MF_CHECKED);
664 pPopup->CheckMenuItem(uIDItem, MF_UNCHECKED);
668 * @brief User right-clicked in listview rows
670 void CDirView::ListContextMenu(CPoint point, int /*i*/)
672 CDirDoc* pDoc = GetDocument();
674 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
675 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
676 theApp.TranslateMenu(menu.m_hMenu);
678 // 1st submenu of IDR_POPUP_DIRVIEW is for item popup
679 BCMenu *pPopup = static_cast<BCMenu*>(menu.GetSubMenu(0));
680 ASSERT(pPopup != nullptr);
682 if (pDoc->m_nDirs < 3)
684 pPopup->RemoveMenu(ID_DIR_COPY_LEFT_TO_MIDDLE, MF_BYCOMMAND);
685 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_LEFT, MF_BYCOMMAND);
686 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_RIGHT, MF_BYCOMMAND);
687 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
688 pPopup->RemoveMenu(ID_DIR_COPY_RIGHT_TO_MIDDLE, MF_BYCOMMAND);
689 pPopup->RemoveMenu(ID_DIR_MOVE_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
690 pPopup->RemoveMenu(ID_DIR_DEL_MIDDLE, MF_BYCOMMAND);
691 pPopup->RemoveMenu(ID_DIR_DEL_ALL, MF_BYCOMMAND);
692 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE, MF_BYCOMMAND);
694 for (int i = 0; i < pPopup->GetMenuItemCount(); ++i)
696 if (pPopup->GetMenuItemID(i) == ID_DIR_HIDE_FILENAMES)
697 pPopup->RemoveMenu(i + 3, MF_BYPOSITION);
700 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITHEDITOR, MF_BYCOMMAND);
701 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITH, MF_BYCOMMAND);
702 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_MIDDLE, MF_BYCOMMAND);
703 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_ALL, MF_BYCOMMAND);
704 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, MF_BYCOMMAND);
705 pPopup->RemoveMenu(ID_DIR_COPY_ALL_TO_CLIPBOARD, MF_BYCOMMAND);
706 pPopup->RemoveMenu(ID_DIR_ZIP_MIDDLE, MF_BYCOMMAND);
707 pPopup->RemoveMenu(ID_DIR_ZIP_ALL, MF_BYCOMMAND);
708 pPopup->RemoveMenu(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, MF_BYCOMMAND);
709 pPopup->RemoveMenu(ID_MERGE_COMPARE_NONHORIZONTALLY, MF_BYCOMMAND);
713 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_BOTH, MF_BYCOMMAND);
714 pPopup->RemoveMenu(ID_DIR_COPY_BOTH_TO_CLIPBOARD, MF_BYCOMMAND);
715 pPopup->RemoveMenu(ID_DIR_ZIP_BOTH, MF_BYCOMMAND);
716 pPopup->RemoveMenu(ID_DIR_DEL_BOTH, MF_BYCOMMAND);
717 pPopup->RemoveMenu(2, MF_BYPOSITION); // Compare Non-horizontally
720 CMenu menuPluginsHolder;
721 menuPluginsHolder.LoadMenu(IDR_POPUP_PLUGINS_SETTINGS);
722 theApp.TranslateMenu(menuPluginsHolder.m_hMenu);
723 String s = _("Plugin Settings");
724 pPopup->AppendMenu(MF_SEPARATOR);
725 pPopup->AppendMenu(MF_POPUP, static_cast<int>(reinterpret_cast<uintptr_t>(menuPluginsHolder.m_hMenu)), s.c_str());
727 CFrameWnd *pFrame = GetTopLevelFrame();
728 ASSERT(pFrame != nullptr);
729 pFrame->m_bAutoMenuEnable = FALSE;
730 // invoke context menu
731 // this will invoke all the OnUpdate methods to enable/disable the individual items
732 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
735 pFrame->m_bAutoMenuEnable = TRUE;
739 * @brief User right-clicked on specified logical column
741 void CDirView::HeaderContextMenu(CPoint point, int /*i*/)
744 VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
745 VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
746 theApp.TranslateMenu(menu.m_hMenu);
747 // 2nd submenu of IDR_POPUP_DIRVIEW is for header popup
748 BCMenu* pPopup = static_cast<BCMenu *>(menu.GetSubMenu(1));
749 ASSERT(pPopup != nullptr);
751 // invoke context menu
752 // this will invoke all the OnUpdate methods to enable/disable the individual items
753 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
758 * @brief Gets Explorer's context menu for a group of selected files.
760 * @param [in] Side whether to get context menu for the files from the left or
762 * @retval true menu successfully retrieved.
763 * @retval falsea an error occurred while retrieving the menu.
765 bool CDirView::ListShellContextMenu(SIDE_TYPE stype)
767 CShellContextMenu* shellContextMenu;
770 shellContextMenu = m_pShellContextMenuMiddle.get(); break;
772 shellContextMenu = m_pShellContextMenuRight.get(); break;
774 shellContextMenu = m_pShellContextMenuLeft.get(); break;
776 shellContextMenu->Initialize();
777 ApplyFolderNameAndFileName(SelBegin(), SelEnd(), stype, GetDiffContext(),
778 [&](const String& path, const String& filename) { shellContextMenu->AddItem(path, filename); });
779 return shellContextMenu->RequeryShellContextMenu();
783 * @brief User chose (main menu) Copy from right to left
785 void CDirView::OnDirCopy(UINT id)
787 bool to_right = (id == ID_L2R) ? true : false;
788 if (GetDocument()->m_nDirs < 3)
791 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_RIGHT>, _("Copying files..."));
793 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_LEFT>, _("Copying files..."));
799 switch (m_nActivePane)
802 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_MIDDLE>, _("Copying files..."));
806 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_RIGHT>, _("Copying files..."));
812 switch (m_nActivePane)
816 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_LEFT>, _("Copying files..."));
819 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_MIDDLE>, _("Copying files..."));
826 /// User chose (context men) Copy from right to left
827 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
828 void CDirView::OnCtxtDirCopy()
830 DoDirAction(&DirActions::Copy<srctype, dsttype>, _("Copying files..."));
833 /// User chose (context menu) Copy left to...
834 template<SIDE_TYPE stype>
835 void CDirView::OnCtxtDirCopyTo()
837 DoDirActionTo(stype, &DirActions::CopyTo<stype>, _("Copying files..."));
840 /// Update context menu Copy Right to Left item
841 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
842 void CDirView::OnUpdateCtxtDirCopy(CCmdUI* pCmdUI)
844 DoUpdateDirCopy<srctype, dsttype>(pCmdUI, eContext);
847 /// Update main menu Copy Right to Left item
848 void CDirView::OnUpdateDirCopy(CCmdUI* pCmdUI)
850 bool to_right = pCmdUI->m_nID == ID_L2R ? true : false;
851 if (GetDocument()->m_nDirs < 3)
854 DoUpdateDirCopy<SIDE_LEFT, SIDE_RIGHT>(pCmdUI, eContext);
856 DoUpdateDirCopy<SIDE_RIGHT, SIDE_LEFT>(pCmdUI, eContext);
862 switch (m_nActivePane)
865 DoUpdateDirCopy<SIDE_LEFT, SIDE_MIDDLE>(pCmdUI, eContext);
869 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_RIGHT>(pCmdUI, eContext);
875 switch (m_nActivePane)
879 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_LEFT>(pCmdUI, eContext);
882 DoUpdateDirCopy<SIDE_RIGHT, SIDE_MIDDLE>(pCmdUI, eContext);
889 void CDirView::DoDirAction(DirActions::method_type func, const String& status_message)
891 CWaitCursor waitstatus;
894 // First we build a list of desired actions
895 FileActionScript actionScript;
896 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
897 DirItemWithIndexIterator end;
898 FileActionScript *rsltScript;
899 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
900 ASSERT(rsltScript == &actionScript);
901 // Now we prompt, and execute actions
902 ConfirmAndPerformActions(actionScript);
903 } catch (ContentsChangedException& e) {
904 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
905 } catch (FileOperationException& e) {
906 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
910 void CDirView::DoDirActionTo(SIDE_TYPE stype, DirActions::method_type func, const String& status_message)
913 String startPath(m_lastCopyFolder);
914 String selectfolder_title;
916 if (stype == SIDE_LEFT)
917 selectfolder_title = _("Left side - select destination folder:");
918 else if (stype == SIDE_MIDDLE)
919 selectfolder_title = _("Middle side - select destination folder:");
920 else if (stype == SIDE_RIGHT)
921 selectfolder_title = _("Right side - select destination folder:");
923 if (!SelectFolder(destPath, startPath.c_str(), selectfolder_title))
926 m_lastCopyFolder = destPath;
927 CWaitCursor waitstatus;
930 // First we build a list of desired actions
931 FileActionScript actionScript;
932 actionScript.m_destBase = destPath;
933 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
934 DirItemWithIndexIterator end;
935 FileActionScript *rsltScript;
936 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
937 ASSERT(rsltScript == &actionScript);
938 // Now we prompt, and execute actions
939 ConfirmAndPerformActions(actionScript);
940 } catch (ContentsChangedException& e) {
941 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
945 // Confirm with user, then perform the action list
946 void CDirView::ConfirmAndPerformActions(FileActionScript & actionList)
948 if (actionList.GetActionItemCount() == 0) // Not sure it is possible to get right-click menu without
949 return; // any selected items, but may as well be safe
951 ASSERT(actionList.GetActionItemCount()>0); // Or else the update handler got it wrong
953 // Set parent window so modality is correct and correct window gets focus
955 actionList.SetParentWindow(this->GetSafeHwnd());
958 ConfirmActionList(GetDiffContext(), actionList);
959 } catch (ConfirmationNeededException& e) {
960 ConfirmFolderCopyDlg dlg;
961 dlg.m_caption = e.m_caption;
962 dlg.m_question = e.m_question;
963 dlg.m_fromText = e.m_fromText;
964 dlg.m_toText = e.m_toText;
965 dlg.m_fromPath = e.m_fromPath;
966 dlg.m_toPath = e.m_toPath;
967 INT_PTR ans = dlg.DoModal();
968 if (ans != IDOK && ans != IDYES)
971 PerformActionList(actionList);
975 * @brief Perform an array of actions
976 * @note There can be only COPY or DELETE actions, not both!
978 void CDirView::PerformActionList(FileActionScript & actionScript)
980 // Check option and enable putting deleted items to Recycle Bin
981 if (GetOptionsMgr()->GetBool(OPT_USE_RECYCLE_BIN))
982 actionScript.UseRecycleBin(true);
984 actionScript.UseRecycleBin(false);
986 actionScript.SetParentWindow(GetMainFrame()->GetSafeHwnd());
988 theApp.AddOperation();
989 bool succeeded = actionScript.Run();
991 UpdateAfterFileScript(actionScript);
992 theApp.RemoveOperation();
993 if (!succeeded && !actionScript.IsCanceled())
994 throw FileOperationException(_T("File operation failed"));
998 * @brief Update results after running FileActionScript.
999 * This functions is called after script is finished to update
1000 * results (including UI).
1001 * @param [in] actionlist Script that was run.
1003 void CDirView::UpdateAfterFileScript(FileActionScript & actionList)
1005 bool bItemsRemoved = false;
1006 int curSel = GetFirstSelectedInd();
1007 CDiffContext& ctxt = GetDiffContext();
1008 while (actionList.GetActionItemCount()>0)
1010 // Start handling from tail of list, so removing items
1011 // doesn't invalidate our item indexes.
1012 FileActionItem act = actionList.RemoveTailActionItem();
1014 // Update doc (difflist)
1015 UPDATEITEM_TYPE updatetype = UpdateDiffAfterOperation(act, ctxt, GetDiffItem(act.context));
1016 if (updatetype == UPDATEITEM_REMOVE)
1018 DeleteItem(act.context, true);
1019 bItemsRemoved = true;
1021 else if (updatetype == UPDATEITEM_UPDATE)
1022 UpdateDiffItemStatus(act.context);
1025 // Make sure selection is at sensible place if all selected items
1029 UINT selected = GetSelectedCount();
1034 MoveFocus(0, curSel - 1, selected);
1039 Counts CDirView::Count(DirActions::method_type2 func) const
1041 return ::Count(SelBegin(), SelEnd(), MakeDirActions(func));
1044 /// Should Copy to Left be enabled or disabled ? (both main menu & context menu use this)
1045 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
1046 void CDirView::DoUpdateDirCopy(CCmdUI* pCmdUI, eMenuType menuType)
1048 Counts counts = Count(&DirActions::IsItemCopyableOnTo<srctype, dsttype>);
1049 pCmdUI->Enable(counts.count > 0);
1050 if (menuType == eContext)
1051 pCmdUI->SetText(FormatMenuItemString(srctype, dsttype, counts.count, counts.total).c_str());
1055 * @brief Update any resources necessary after a GUI language change
1057 void CDirView::UpdateResources()
1059 UpdateColumnNames();
1060 GetParentFrame()->UpdateResources();
1064 * @brief User just clicked a column, so perform sort
1066 void CDirView::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
1068 // set sort parameters and handle ascending/descending
1069 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*) pNMHDR;
1070 int oldSortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1071 int sortcol = m_pColItems->ColPhysToLog(pNMListView->iSubItem);
1072 if (sortcol == oldSortColumn)
1075 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1076 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, !bSortAscending);
1080 GetOptionsMgr()->SaveOption((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3, sortcol);
1081 // most columns start off ascending, but not dates
1082 bool bSortAscending = m_pColItems->IsDefaultSortAscending(sortcol);
1083 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, bSortAscending);
1086 SortColumnsAppropriately();
1090 void CDirView::SortColumnsAppropriately()
1092 int sortCol = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1093 if (sortCol == -1 || sortCol >= m_pColItems->GetColCount())
1096 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1097 m_ctlSortHeader.SetSortImage(m_pColItems->ColLogToPhys(sortCol), bSortAscending);
1098 //sort using static CompareFunc comparison function
1099 CompareState cs(&GetDiffContext(), m_pColItems.get(), sortCol, bSortAscending, m_bTreeMode);
1100 GetListCtrl().SortItems(cs.CompareFunc, reinterpret_cast<DWORD_PTR>(&cs));
1102 m_firstDiffItem.reset();
1103 m_lastDiffItem.reset();
1106 /// Do any last minute work as view closes
1107 void CDirView::OnDestroy()
1109 DeleteAllDisplayItems();
1111 String secname = GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3");
1112 theApp.WriteProfileString(secname.c_str(), _T("ColumnOrders"), m_pColItems->SaveColumnOrders().c_str());
1113 theApp.WriteProfileString(secname.c_str(), _T("ColumnWidths"),
1114 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)).c_str());
1116 CListView::OnDestroy();
1118 GetMainFrame()->ClearStatusbarItemCount();
1122 * @brief Open selected item when user presses ENTER key.
1124 void CDirView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
1126 if (nChar == VK_RETURN)
1128 int sel = GetFocusedItem();
1131 const DIFFITEM& di = GetDiffItem(sel);
1132 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
1134 if (di.customFlags & ViewCustomFlags::EXPANDED)
1135 CollapseSubdir(sel);
1141 CWaitCursor waitstatus;
1146 CListView::OnChar(nChar, nRepCnt, nFlags);
1150 * @brief Expand/collapse subfolder when "+/-" icon is clicked.
1152 void CDirView::OnClick(NMHDR* pNMHDR, LRESULT* pResult)
1154 LPNMITEMACTIVATE pNM = (LPNMITEMACTIVATE)pNMHDR;
1155 LVHITTESTINFO lvhti;
1156 lvhti.pt = pNM->ptAction;
1157 m_pList->SubItemHitTest(&lvhti);
1158 if (lvhti.flags == LVHT_ONITEMSTATEICON)
1160 const DIFFITEM &di = GetDiffItem(pNM->iItem);
1161 if (di.customFlags & ViewCustomFlags::EXPANDED)
1162 CollapseSubdir(pNM->iItem);
1164 ExpandSubdir(pNM->iItem);
1171 * @brief Collapse subfolder
1172 * @param [in] sel Folder item index in listview.
1174 void CDirView::CollapseSubdir(int sel)
1176 DIFFITEM& dip = this->GetDiffItem(sel);
1177 if (!m_bTreeMode || !(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1180 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1182 dip.customFlags &= ~ViewCustomFlags::EXPANDED;
1183 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(1), LVIS_STATEIMAGEMASK);
1185 int count = m_pList->GetItemCount();
1186 for (int i = sel + 1; i < count; i++)
1188 const DIFFITEM& di = GetDiffItem(i);
1189 if (!di.IsAncestor(&dip))
1191 m_pList->DeleteItem(i--);
1195 m_pList->SetRedraw(TRUE); // Turn updating back on
1199 * @brief Expand subfolder
1200 * @param [in] sel Folder item index in listview.
1202 void CDirView::ExpandSubdir(int sel, bool bRecursive)
1204 DIFFITEM& dip = GetDiffItem(sel);
1205 if (!m_bTreeMode || (dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1208 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
1209 m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(2), LVIS_STATEIMAGEMASK);
1211 CDiffContext &ctxt = GetDiffContext();
1212 dip.customFlags |= ViewCustomFlags::EXPANDED;
1214 ExpandSubdirs(ctxt, dip);
1216 DIFFITEM *diffpos = ctxt.GetFirstChildDiffPosition(GetItemKey(sel));
1217 UINT indext = sel + 1;
1219 RedisplayChildren(diffpos, dip.GetDepth() + 1, indext, alldiffs);
1221 SortColumnsAppropriately();
1223 m_pList->SetRedraw(TRUE); // Turn updating back on
1227 * @brief Open parent folder if possible.
1229 void CDirView::OpenParentDirectory()
1231 CDirDoc *pDoc = GetDocument();
1232 PathContext pathsParent;
1233 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
1235 case AllowUpwardDirectory::ParentIsTempPath:
1236 pDoc->m_pTempPathContext = pDoc->m_pTempPathContext->DeleteHead();
1237 // fall through (no break!)
1238 case AllowUpwardDirectory::ParentIsRegularPath:
1241 for (int nIndex = 0; nIndex < pathsParent.GetSize(); ++nIndex)
1242 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nIndex) ? FFILEOPEN_READONLY : 0);
1243 GetMainFrame()->DoFileOpen(&pathsParent, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1245 // fall through (no break!)
1246 case AllowUpwardDirectory::No:
1249 LangMessageBox(IDS_INVALID_DIRECTORY, MB_ICONSTOP);
1255 * @brief Get one or two selected items
1257 * Returns false if 0 or more than 3 items selecte
1259 bool CDirView::GetSelectedItems(int * sel1, int * sel2, int * sel3)
1263 *sel1 = m_pList->GetNextItem(-1, LVNI_SELECTED);
1266 *sel2 = m_pList->GetNextItem(*sel1, LVNI_SELECTED);
1269 *sel3 = m_pList->GetNextItem(*sel2, LVNI_SELECTED);
1272 int extra = m_pList->GetNextItem(*sel3, LVNI_SELECTED);
1273 return (extra == -1);
1277 * @brief Open special items (parent folders etc).
1278 * @param [in] pos1 First item position.
1279 * @param [in] pos2 Second item position.
1281 void CDirView::OpenSpecialItems(DIFFITEM *pos1, DIFFITEM *pos2, DIFFITEM *pos3)
1283 if (pos2==nullptr && pos3==nullptr)
1285 // Browse to parent folder(s) selected
1286 // SPECIAL_ITEM_POS is position for
1287 // special items, but there is currenly
1288 // only one (parent folder)
1289 OpenParentDirectory();
1293 // Parent directory & something else selected
1299 * @brief Creates a pairing folder for unique folder item.
1300 * This function creates a pairing folder for unique folder item in
1301 * folder compare. This way user can browse into unique folder's
1302 * contents and don't necessarily need to copy whole folder structure.
1303 * @return true if user agreed and folder was created.
1305 static bool CreateFoldersPair(const PathContext& paths)
1307 bool created = false;
1308 for (const auto& path : paths)
1310 if (!paths::DoesPathExist(path))
1313 strutils::format_string1(
1314 _("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?"),
1316 int res = AfxMessageBox(message.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN);
1318 created = paths::CreateIfNeeded(path);
1324 void CDirView::Open(const PathContext& paths, DWORD dwFlags[3], PackingInfo * infoUnpacker)
1327 for (auto path : paths)
1329 if (paths::DoesPathExist(path) == paths::IS_EXISTING_DIR)
1332 CDirDoc * pDoc = GetDocument();
1336 // Don't add folders to MRU
1337 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1339 else if (HasZipSupport() && std::count_if(paths.begin(), paths.end(), ArchiveGuessFormat) == paths.GetSize())
1341 // Open archives, not adding paths to MRU
1342 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, nullptr, _T(""), infoUnpacker);
1346 // Regular file case
1348 // Binary attributes are set after files are unpacked
1349 // so after plugins such as the MS-Office plugins have had a chance to make them textual
1350 // We haven't done unpacking yet in this diff, but if a binary flag is already set,
1351 // then it was set in a previous diff after unpacking, so we trust it
1353 // Open identical and different files
1354 FileLocation fileloc[3];
1356 const String sUntitled[] = { _("Untitled left"), paths.GetSize() < 3 ? _("Untitled right") : _("untitled middle"), _("Untitled right") };
1357 for (int i = 0; i < paths.GetSize(); ++i)
1359 if (paths::DoesPathExist(paths[i]) == paths::DOES_NOT_EXIST)
1360 strDesc[i] = sUntitled[i];
1362 fileloc[i].setPath(paths[i]);
1365 GetMainFrame()->ShowAutoMergeDoc(pDoc, paths.GetSize(), fileloc,
1366 dwFlags, strDesc, _T(""), infoUnpacker);
1371 * @brief Open selected files or directories.
1373 * Opens selected files to file compare. If comparing
1374 * directories non-recursively, then subfolders and parent
1375 * folder are opened too.
1377 * This handles the case that one item is selected
1378 * and the case that two items are selected (one on each side)
1380 void CDirView::OpenSelection(SELECTIONTYPE selectionType /*= SELECTIONTYPE_NORMAL*/, PackingInfo * infoUnpacker /*= nullptr*/, bool openableForDir /*= true*/)
1382 Merge7zFormatMergePluginScope scope(infoUnpacker);
1383 CDirDoc * pDoc = GetDocument();
1384 const CDiffContext& ctxt = GetDiffContext();
1386 // First, figure out what was selected (store into pos1 & pos2)
1387 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1388 int sel1 = -1, sel2 = -1, sel3 = -1;
1389 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1391 // Must have 1 or 2 or 3 items selected
1396 pos1 = GetItemKey(sel1);
1397 ASSERT(pos1 != nullptr);
1400 pos2 = GetItemKey(sel2);
1401 ASSERT(pos2 != nullptr);
1403 pos3 = GetItemKey(sel3);
1406 // Now handle the various cases of what was selected
1408 if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1410 OpenSpecialItems(pos1, pos2, pos3);
1414 // Common variables which both code paths below are responsible for setting
1416 const DIFFITEM *pdi[3] = {0}; // left & right items (di1==di2 if single selection)
1417 bool isdir = false; // set if we're comparing directories
1422 success = GetOpenTwoItems(ctxt, selectionType, pos1, pos2, pdi,
1423 paths, sel1, sel2, isdir, nPane, errmsg, openableForDir);
1424 else if (pos2 && pos3)
1425 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1426 paths, sel1, sel2, sel3, isdir, nPane, errmsg, openableForDir);
1429 // Only one item selected, so perform diff on its sides
1430 success = GetOpenOneItem(ctxt, pos1, pdi,
1431 paths, sel1, isdir, nPane, errmsg, openableForDir);
1433 CreateFoldersPair(paths);
1437 if (!errmsg.empty())
1438 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1442 // Now pathLeft, pathRight, di1, di2, and isdir are all set
1443 // We have two items to compare, no matter whether same or different underlying DirView item
1446 for (int nIndex = 0; nIndex < paths.GetSize(); nIndex++)
1447 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[nIndex]) ? FFILEOPEN_READONLY : 0);
1449 Open(paths, dwFlags, infoUnpacker);
1452 void CDirView::OpenSelectionAs(UINT id)
1454 CDirDoc * pDoc = GetDocument();
1455 const CDiffContext& ctxt = GetDiffContext();
1457 // First, figure out what was selected (store into pos1 & pos2 & pos3)
1458 DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1459 int sel1 = -1, sel2 = -1, sel3 = -1;
1460 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1462 // Must have 1 or 2 or 3 items selected
1467 pos1 = GetItemKey(sel1);
1471 pos2 = GetItemKey(sel2);
1472 ASSERT(pos2 != nullptr);
1474 pos3 = GetItemKey(sel3);
1477 // Now handle the various cases of what was selected
1479 if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1485 // Common variables which both code paths below are responsible for setting
1487 const DIFFITEM *pdi[3]; // left & right items (di1==di2 if single selection)
1488 bool isdir = false; // set if we're comparing directories
1493 success = GetOpenTwoItems(ctxt, SELECTIONTYPE_NORMAL, pos1, pos2, pdi,
1494 paths, sel1, sel2, isdir, nPane, errmsg, false);
1495 else if (pos2 && pos3)
1496 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1497 paths, sel1, sel2, sel3, isdir, nPane, errmsg, false);
1500 // Only one item selected, so perform diff on its sides
1501 success = GetOpenOneItem(ctxt, pos1, pdi,
1502 paths, sel1, isdir, nPane, errmsg, false);
1506 if (!errmsg.empty())
1507 AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1511 // Open identical and different files
1512 DWORD dwFlags[3] = { 0 };
1513 FileLocation fileloc[3];
1514 for (int pane = 0; pane < paths.GetSize(); pane++)
1516 fileloc[pane].setPath(paths[pane]);
1517 dwFlags[pane] |= FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[pane]) ? FFILEOPEN_READONLY : 0);
1519 if (id == ID_MERGE_COMPARE_HEX)
1520 GetMainFrame()->ShowHexMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1522 GetMainFrame()->ShowImgMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1525 /// User chose (context menu) delete left
1526 template<SIDE_TYPE stype>
1527 void CDirView::OnCtxtDirDel()
1529 DoDirAction(&DirActions::DeleteOn<stype>, _("Deleting files..."));
1532 /// User chose (context menu) delete both
1533 void CDirView::OnCtxtDirDelBoth()
1535 DoDirAction(&DirActions::DeleteOnBoth, _("Deleting files..."));
1538 /// Enable/disable Delete Left menu choice on context menu
1539 template<SIDE_TYPE stype>
1540 void CDirView::OnUpdateCtxtDirDel(CCmdUI* pCmdUI)
1542 Counts counts = Count(&DirActions::IsItemDeletableOn<stype>);
1543 pCmdUI->Enable(counts.count > 0);
1544 pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1547 /// Enable/disable Delete Both menu choice on context menu
1548 void CDirView::OnUpdateCtxtDirDelBoth(CCmdUI* pCmdUI)
1550 Counts counts = Count(&DirActions::IsItemDeletableOnBoth);
1551 pCmdUI->Enable(counts.count > 0);
1552 pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1556 * @brief Update "Copy | Right to..." item
1558 template<SIDE_TYPE stype>
1559 void CDirView::OnUpdateCtxtDirCopyTo(CCmdUI* pCmdUI)
1561 Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1562 pCmdUI->Enable(counts.count > 0);
1563 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
1566 void CDirView::OnUpdateCtxtDirCopyBothTo(CCmdUI* pCmdUI)
1568 Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1569 pCmdUI->Enable(counts.count > 0);
1570 pCmdUI->SetText(FormatMenuItemStringAllTo(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1573 void CDirView::OnUpdateCtxtDirCopyBothDiffsOnlyTo(CCmdUI* pCmdUI)
1575 Counts counts = Count(&DirActions::IsItemNavigableDiff);
1576 pCmdUI->Enable(counts.count > 0);
1577 pCmdUI->SetText(FormatMenuItemStringDifferencesTo(counts.count, counts.total).c_str());
1581 * @brief Get keydata associated with item in given index.
1582 * @param [in] idx Item's index to list in UI.
1583 * @return Key for item in given index.
1585 DIFFITEM *CDirView::GetItemKey(int idx) const
1587 return (DIFFITEM *) m_pList->GetItemData(idx);
1590 // SetItemKey & GetItemKey encapsulate how the display list items
1591 // are mapped to DiffItems, which in turn are DiffContext keys to the actual DIFFITEM data
1594 * @brief Get DIFFITEM data for item.
1595 * This function returns DIFFITEM data for item in given index in GUI.
1596 * @param [in] sel Item's index in folder compare GUI list.
1597 * @return DIFFITEM for item.
1599 const DIFFITEM &CDirView::GetDiffItem(int sel) const
1601 CDirView * pDirView = const_cast<CDirView *>(this);
1602 return pDirView->GetDiffItem(sel);
1606 * Given index in list control, get modifiable reference to its DIFFITEM data
1608 DIFFITEM &CDirView::GetDiffItem(int sel)
1610 DIFFITEM *diffpos = GetItemKey(sel);
1612 // If it is special item, return empty DIFFITEM
1613 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1615 return *DIFFITEM::GetEmptyItem();
1617 return GetDiffContext().GetDiffRefAt(diffpos);
1620 void CDirView::DeleteItem(int sel, bool removeDIFFITEM)
1623 CollapseSubdir(sel);
1626 DIFFITEM *diffpos = GetItemKey(sel);
1627 m_pList->DeleteItem(sel);
1628 if (diffpos != (DIFFITEM *)SPECIAL_ITEM_POS)
1630 if (diffpos->HasChildren())
1631 diffpos->RemoveChildren();
1632 diffpos->DelinkFromSiblings();
1638 m_pList->DeleteItem(sel);
1641 m_firstDiffItem.reset();
1642 m_lastDiffItem.reset();
1645 void CDirView::DeleteAllDisplayItems()
1647 // item data are just positions (diffposes)
1648 // that is, they contain no memory needing to be freed
1649 m_pList->DeleteAllItems();
1651 m_firstDiffItem.reset();
1652 m_lastDiffItem.reset();
1656 * @brief Given key, get index of item which has it stored.
1657 * This function searches from list in UI.
1659 int CDirView::GetItemIndex(DIFFITEM *key)
1661 LVFINDINFO findInfo;
1663 findInfo.flags = LVFI_PARAM; // Search for itemdata
1664 findInfo.lParam = (LPARAM)key;
1665 return m_pList->FindItem(&findInfo);
1669 * @brief Get the file names on both sides for specified item.
1670 * @note Return empty strings if item is special item.
1672 void CDirView::GetItemFileNames(int sel, String& strLeft, String& strRight) const
1674 DIFFITEM *diffpos = GetItemKey(sel);
1675 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1682 const CDiffContext& ctxt = GetDiffContext();
1683 ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos), strLeft, strRight);
1688 * @brief Get the file names on both sides for specified item.
1689 * @note Return empty strings if item is special item.
1691 void CDirView::GetItemFileNames(int sel, PathContext * paths) const
1693 DIFFITEM *diffpos = GetItemKey(sel);
1694 if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1696 for (int nIndex = 0; nIndex < GetDocument()->m_nDirs; nIndex++)
1697 paths->SetPath(nIndex, _T(""));
1701 const CDiffContext& ctxt = GetDiffContext();
1702 *paths = ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos));
1707 * @brief Open selected file with registered application.
1708 * Uses shell file associations to open file with registered
1709 * application. We first try to use "Edit" action which should
1710 * open file to editor, since we are more interested editing
1711 * files than running them (scripts).
1712 * @param [in] stype Side of file to open.
1714 void CDirView::DoOpen(SIDE_TYPE stype)
1716 int sel = GetSingleSelectedItem();
1717 if (sel == -1) return;
1718 DirItemIterator dirBegin = SelBegin();
1719 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1720 if (file.empty()) return;
1721 HINSTANCE rtn = ShellExecute(::GetDesktopWindow(), _T("edit"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1722 if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1723 rtn = ShellExecute(::GetDesktopWindow(), _T("open"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1724 if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1728 /// Open with dialog for file on selected side
1729 void CDirView::DoOpenWith(SIDE_TYPE stype)
1731 int sel = GetSingleSelectedItem();
1732 if (sel == -1) return;
1733 DirItemIterator dirBegin = SelBegin();
1734 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1735 if (file.empty()) return;
1737 if (!GetSystemDirectory(sysdir.GetBuffer(MAX_PATH), MAX_PATH)) return;
1738 sysdir.ReleaseBuffer();
1739 CString arg = (CString)_T("shell32.dll,OpenAs_RunDLL ") + file.c_str();
1740 ShellExecute(::GetDesktopWindow(), 0, _T("RUNDLL32.EXE"), arg, sysdir, SW_SHOWNORMAL);
1743 /// Open selected file on specified side to external editor
1744 void CDirView::DoOpenWithEditor(SIDE_TYPE stype)
1746 int sel = GetSingleSelectedItem();
1747 if (sel == -1) return;
1748 DirItemIterator dirBegin = SelBegin();
1749 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1750 if (file.empty()) return;
1752 theApp.OpenFileToExternalEditor(file);
1755 void CDirView::DoOpenParentFolder(SIDE_TYPE stype)
1757 int sel = GetSingleSelectedItem();
1758 if (sel == -1) return;
1759 DirItemIterator dirBegin = SelBegin();
1760 String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1761 if (file.empty()) return;
1762 String parentFolder = paths::GetParentPath(file);
1763 ShellExecute(::GetDesktopWindow(), _T("open"), parentFolder.c_str(), 0, 0, SW_SHOWNORMAL);
1766 /// User chose (context menu) open left
1767 template<SIDE_TYPE stype>
1768 void CDirView::OnCtxtDirOpen()
1773 /// User chose (context menu) open left with
1774 template<SIDE_TYPE stype>
1775 void CDirView::OnCtxtDirOpenWith()
1780 /// User chose (context menu) open left with editor
1781 template<SIDE_TYPE stype>
1782 void CDirView::OnCtxtDirOpenWithEditor()
1784 DoOpenWithEditor(stype);
1787 /// User chose (context menu) open left parent folder
1788 template<SIDE_TYPE stype>
1789 void CDirView::OnCtxtDirOpenParentFolder()
1791 DoOpenParentFolder(stype);
1794 /// Update context menuitem "Open left | with editor"
1795 template<SIDE_TYPE stype>
1796 void CDirView::OnUpdateCtxtDirOpenWithEditor(CCmdUI* pCmdUI)
1798 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1799 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1802 // return selected item index, or -1 if none or multiple
1803 int CDirView::GetSingleSelectedItem() const
1805 int sel = -1, sel2 = -1;
1806 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
1807 if (sel == -1) return -1;
1808 sel2 = m_pList->GetNextItem(sel, LVNI_SELECTED);
1809 if (sel2 != -1) return -1;
1812 // Enable/disable Open Left menu choice on context menu
1813 template<SIDE_TYPE stype>
1814 void CDirView::OnUpdateCtxtDirOpen(CCmdUI* pCmdUI)
1816 Counts counts = Count(&DirActions::IsItemOpenableOn<stype>);
1817 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1820 // Enable/disable Open Left With menu choice on context menu
1821 template<SIDE_TYPE stype>
1822 void CDirView::OnUpdateCtxtDirOpenWith(CCmdUI* pCmdUI)
1824 Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1825 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1828 // Enable/disable Open Parent Folder menu choice on context menu
1829 template<SIDE_TYPE stype>
1830 void CDirView::OnUpdateCtxtDirOpenParentFolder(CCmdUI* pCmdUI)
1832 Counts counts = Count(&DirActions::IsParentFolderOpenable<stype>);
1833 pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1837 void CDirView::DoUpdateOpen(SELECTIONTYPE selectionType, CCmdUI* pCmdUI, bool openableForDir /*= true*/)
1839 int sel1 = -1, sel2 = -1, sel3 = -1;
1840 if (!GetSelectedItems(&sel1, &sel2, &sel3))
1842 // 0 items or more than 2 items seleted
1843 pCmdUI->Enable(FALSE);
1848 // One item selected
1849 if (selectionType != SELECTIONTYPE_NORMAL)
1851 pCmdUI->Enable(FALSE);
1854 if (!openableForDir)
1856 const DIFFITEM& di1 = GetDiffItem(sel1);
1857 if (di1.diffcode.isDirectory())
1859 pCmdUI->Enable(FALSE);
1864 else if (sel3 == -1)
1866 // Two items selected
1867 const DIFFITEM& di1 = GetDiffItem(sel1);
1868 const DIFFITEM& di2 = GetDiffItem(sel2);
1869 if (!AreItemsOpenable(GetDiffContext(), selectionType, di1, di2, openableForDir))
1871 pCmdUI->Enable(FALSE);
1877 // Three items selected
1878 const DIFFITEM& di1 = GetDiffItem(sel1);
1879 const DIFFITEM& di2 = GetDiffItem(sel2);
1880 const DIFFITEM& di3 = GetDiffItem(sel3);
1881 if (selectionType != SELECTIONTYPE_NORMAL || !::AreItemsOpenable(GetDiffContext(), di1, di2, di3, openableForDir))
1883 pCmdUI->Enable(FALSE);
1887 pCmdUI->Enable(TRUE);
1891 * @brief Return count of selected items in folder compare.
1893 UINT CDirView::GetSelectedCount() const
1895 return m_pList->GetSelectedCount();
1899 * @brief Return index of first selected item in folder compare.
1901 int CDirView::GetFirstSelectedInd()
1903 return m_pList->GetNextItem(-1, LVNI_SELECTED);
1907 // If none or one item selected select found item
1908 // This is used for scrolling to first diff too
1909 void CDirView::OnFirstdiff()
1911 DirItemIterator it =
1912 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1914 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1917 void CDirView::OnUpdateFirstdiff(CCmdUI* pCmdUI)
1919 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1923 // If none or one item selected select found item
1924 void CDirView::OnLastdiff()
1926 DirItemIterator it =
1927 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1929 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1932 void CDirView::OnUpdateLastdiff(CCmdUI* pCmdUI)
1934 pCmdUI->Enable(GetFirstDifferentItem() > -1);
1937 bool CDirView::HasNextDiff()
1939 int lastDiff = GetLastDifferentItem();
1941 // Check if different files were found and
1942 // there is different item after focused item
1943 return (lastDiff > -1) && (GetFocusedItem() < lastDiff);
1946 bool CDirView::HasPrevDiff()
1948 int firstDiff = GetFirstDifferentItem();
1950 // Check if different files were found and
1951 // there is different item before focused item
1952 return (firstDiff > -1) && (firstDiff < GetFocusedItem());
1955 void CDirView::MoveToNextDiff()
1957 int currentInd = GetFocusedItem();
1958 DirItemIterator begin(m_pIList.get(), currentInd + 1);
1959 DirItemIterator it =
1960 std::find_if(begin, End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1962 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
1965 void CDirView::MoveToPrevDiff()
1967 int currentInd = GetFocusedItem();
1968 if (currentInd <= 0)
1970 DirItemIterator begin(m_pIList.get(), currentInd - 1, false, true);
1971 DirItemIterator it =
1972 std::find_if(begin, RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1974 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
1977 void CDirView::OpenNextDiff()
1980 int currentInd = GetFocusedItem();
1981 const DIFFITEM& dip = GetDiffItem(currentInd);
1982 if (!dip.diffcode.isDirectory())
1988 GetParentFrame()->ActivateFrame();
1992 void CDirView::OpenPrevDiff()
1995 int currentInd = GetFocusedItem();
1996 const DIFFITEM& dip = GetDiffItem(currentInd);
1997 if (!dip.diffcode.isDirectory())
2003 GetParentFrame()->ActivateFrame();
2007 void CDirView::SetActivePane(int pane)
2009 if (m_nActivePane >= 0)
2010 GetParentFrame()->GetHeaderInterface()->SetActive(m_nActivePane, false);
2011 GetParentFrame()->GetHeaderInterface()->SetActive(pane, true);
2012 m_nActivePane = pane;
2016 // If none or one item selected select found item
2017 void CDirView::OnNextdiff()
2023 void CDirView::OnUpdateNextdiff(CCmdUI* pCmdUI)
2025 pCmdUI->Enable(HasNextDiff());
2029 // If none or one item selected select found item
2030 void CDirView::OnPrevdiff()
2036 void CDirView::OnUpdatePrevdiff(CCmdUI* pCmdUI)
2038 pCmdUI->Enable(HasPrevDiff());
2041 void CDirView::OnCurdiff()
2043 const int count = m_pList->GetItemCount();
2045 int i = GetFirstSelectedInd();
2047 // No selection - no diff to go
2051 while (i < count && !found)
2053 UINT selected = m_pList->GetItemState(i, LVIS_SELECTED);
2054 UINT focused = m_pList->GetItemState(i, LVIS_FOCUSED);
2056 if (selected == LVIS_SELECTED && focused == LVIS_FOCUSED)
2058 m_pList->EnsureVisible(i, FALSE);
2065 void CDirView::OnUpdateCurdiff(CCmdUI* pCmdUI)
2067 pCmdUI->Enable(GetFirstSelectedInd() > -1);
2070 int CDirView::GetFocusedItem()
2072 return m_pList->GetNextItem(-1, LVNI_FOCUSED);
2075 int CDirView::GetFirstDifferentItem()
2077 if (!m_firstDiffItem.has_value())
2079 DirItemIterator it =
2080 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2081 m_firstDiffItem = it.m_sel;
2083 return m_firstDiffItem.value();
2086 int CDirView::GetLastDifferentItem()
2088 if (!m_lastDiffItem.has_value())
2090 DirItemIterator it =
2091 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2092 m_lastDiffItem = it.m_sel;
2094 return m_lastDiffItem.value();
2098 * @brief Move focus to specified item (and selection if multiple items not selected)
2100 * Moves the focus from item [currentInd] to item [i]
2101 * Additionally, if there are not multiple items selected,
2102 * deselects item [currentInd] and selects item [i]
2104 void CDirView::MoveFocus(int currentInd, int i, int selCount)
2108 // Not multiple items selected, so bring selection with us
2109 m_pList->SetItemState(currentInd, 0, LVIS_SELECTED);
2110 m_pList->SetItemState(currentInd, 0, LVIS_FOCUSED);
2111 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2114 // Move focus to specified item
2115 // (this automatically defocuses old item)
2116 m_pList->SetItemState(i, LVIS_FOCUSED, LVIS_FOCUSED);
2117 m_pList->EnsureVisible(i, FALSE);
2120 void CDirView::OnUpdateSave(CCmdUI* pCmdUI)
2122 pCmdUI->Enable(FALSE);
2125 CDirFrame * CDirView::GetParentFrame()
2127 // can't verify cast without introducing more coupling
2128 // (CDirView doesn't include DirFrame.h)
2129 return static_cast<CDirFrame *>(CListView::GetParentFrame());
2132 void CDirView::OnRefresh()
2134 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
2135 GetDocument()->Rescan();
2138 BOOL CDirView::PreTranslateMessage(MSG* pMsg)
2140 // Handle special shortcuts here
2141 if (pMsg->message == WM_KEYDOWN)
2145 // Check if we got 'ESC pressed' -message
2146 if (pMsg->wParam == VK_ESCAPE)
2148 if (m_pCmpProgressBar != nullptr)
2150 OnBnClickedComparisonStop();
2154 if (m_nEscCloses != 0)
2156 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_CLOSE);
2160 // Check if we got 'DEL pressed' -message
2161 if (pMsg->wParam == VK_DELETE)
2163 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_MERGE_DELETE);
2166 int sel = GetFocusedItem();
2167 // Check if we got 'Backspace pressed' -message
2168 if (pMsg->wParam == VK_BACK)
2170 if (!GetDiffContext().m_bRecursive)
2172 OpenParentDirectory();
2175 else if (m_bTreeMode && sel >= 0)
2177 const DIFFITEM& di = GetDiffItem(sel);
2178 assert(di.HasParent());
2181 int i = GetItemIndex(di.GetParentLink());
2183 MoveFocus(sel, i, GetSelectedCount());
2189 DIFFITEM& dip = this->GetDiffItem(sel);
2190 if (pMsg->wParam == VK_LEFT)
2192 if (m_bTreeMode && GetDiffContext().m_bRecursive && (!(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren()))
2193 PostMessage(WM_KEYDOWN, VK_BACK);
2195 CollapseSubdir(sel);
2198 if (pMsg->wParam == VK_SUBTRACT)
2200 CollapseSubdir(sel);
2203 if (pMsg->wParam == VK_RIGHT)
2205 if (m_bTreeMode && GetDiffContext().m_bRecursive && dip.customFlags & ViewCustomFlags::EXPANDED && dip.HasChildren())
2206 PostMessage(WM_KEYDOWN, VK_DOWN);
2211 if (pMsg->wParam == VK_ADD)
2216 if (pMsg->wParam == VK_MULTIPLY)
2218 ExpandSubdir(sel, true);
2225 // ESC doesn't close window when user is renaming an item.
2226 if (pMsg->wParam == VK_ESCAPE)
2228 m_bUserCancelEdit = true;
2230 // The edit control send LVN_ENDLABELEDIT when it loses focus,
2231 // so we use it to cancel the rename action.
2232 m_pList->SetFocus();
2234 // Stop the ESC before it reach the main frame which might
2235 // cause a program termination.
2240 return CListView::PreTranslateMessage(pMsg);
2243 void CDirView::OnUpdateRefresh(CCmdUI* pCmdUI)
2245 UINT threadState = GetDocument()->m_diffThread.GetThreadState();
2246 pCmdUI->Enable(threadState != CDiffThread::THREAD_COMPARING);
2250 * @brief Called when compare thread asks UI update.
2251 * @note Currently thread asks update after compare is ready
2254 LRESULT CDirView::OnUpdateUIMessage(WPARAM wParam, LPARAM lParam)
2256 UNREFERENCED_PARAMETER(lParam);
2258 CDirDoc * pDoc = GetDocument();
2259 ASSERT(pDoc != nullptr);
2261 if (wParam == CDiffThread::EVENT_COMPARE_COMPLETED)
2263 // Close and destroy the dialog after compare
2264 if (m_pCmpProgressBar != nullptr)
2265 GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), FALSE, FALSE);
2266 m_pCmpProgressBar.reset();
2268 pDoc->CompareReady();
2270 if (!pDoc->GetGeneratingReport())
2273 if (!pDoc->GetReportFile().empty())
2275 OnToolsGenerateReport();
2276 pDoc->SetReportFile(_T(""));
2279 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST))
2284 // If compare took more than TimeToSignalCompare seconds, notify user
2285 clock_t elapsed = clock() - m_compareStart;
2286 GetParentFrame()->SetStatus(
2287 strutils::format(_("Elapsed time: %ld ms"), elapsed).c_str()
2289 if (elapsed > TimeToSignalCompare * CLOCKS_PER_SEC)
2291 GetMainFrame()->StartFlashing();
2293 else if (wParam == CDiffThread::EVENT_COMPARE_PROGRESSED)
2295 InvalidateRect(nullptr, FALSE);
2297 else if (wParam == CDiffThread::EVENT_COLLECT_COMPLETED)
2299 if (m_pSavedTreeState != nullptr)
2301 RestoreTreeState(GetDiffContext(), m_pSavedTreeState.get());
2302 m_pSavedTreeState.reset();
2307 if (m_bExpandSubdirs)
2308 OnViewExpandAllSubdirs();
2314 return 0; // return value unused
2318 BOOL CDirView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2320 NMHDR * hdr = reinterpret_cast<NMHDR *>(lParam);
2321 if (hdr->code == HDN_ENDDRAG)
2322 return OnHeaderEndDrag((LPNMHEADER)hdr, pResult);
2323 if (hdr->code == HDN_BEGINDRAG)
2324 return OnHeaderBeginDrag((LPNMHEADER)hdr, pResult);
2326 return CListView::OnNotify(wParam, lParam, pResult);
2329 BOOL CDirView::OnChildNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2331 if (uMsg == WM_NOTIFY)
2333 NMHDR *pNMHDR = (NMHDR *)lParam;
2334 switch (pNMHDR->code)
2336 case LVN_GETDISPINFO:
2337 ReflectGetdispinfo((NMLVDISPINFO *)lParam);
2339 case LVN_GETINFOTIPW:
2340 case LVN_GETINFOTIPA:
2344 return CListView::OnChildNotify(uMsg, wParam, lParam, pResult);
2348 * @brief User is starting to drag a column header
2350 bool CDirView::OnHeaderBeginDrag(LPNMHEADER hdr, LRESULT* pResult)
2352 // save column widths before user reorders them
2353 // so we can reload them on the end drag
2354 String secname = GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3");
2355 theApp.WriteProfileString(secname.c_str(), _T("ColumnWidths"),
2356 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)).c_str());
2361 * @brief User just finished dragging a column header
2363 bool CDirView::OnHeaderEndDrag(LPNMHEADER hdr, LRESULT* pResult)
2365 int src = hdr->iItem;
2366 int dest = hdr->pitem->iOrder;
2367 bool allowDrop = true;
2368 *pResult = allowDrop ? FALSE : TRUE;
2369 if (allowDrop && src != dest && dest != -1)
2371 m_pColItems->MoveColumn(src, dest);
2378 * @brief Remove any windows reordering of columns
2380 void CDirView::FixReordering()
2383 lvcol.mask = LVCF_ORDER;
2386 lvcol.pszText = nullptr;
2388 for (int i = 0; i < m_pColItems->GetColCount(); ++i)
2391 GetListCtrl().SetColumn(i, &lvcol);
2395 /** @brief Add columns to display, loading width & order from registry. */
2396 void CDirView::LoadColumnHeaderItems()
2398 bool dummyflag = false;
2400 CHeaderCtrl * h = m_pList->GetHeaderCtrl();
2401 if (h->GetItemCount())
2404 while (m_pList->GetHeaderCtrl()->GetItemCount() > 1)
2405 m_pList->DeleteColumn(1);
2408 for (int i = 0; i < m_pColItems->GetDispColCount(); ++i)
2411 lvc.mask = LVCF_FMT + LVCF_SUBITEM + LVCF_TEXT;
2412 lvc.fmt = LVCFMT_LEFT;
2414 lvc.pszText = _T("text");
2416 m_pList->InsertColumn(i, &lvc);
2419 m_pList->DeleteColumn(1);
2423 void CDirView::SetFont(const LOGFONT & lf)
2425 m_font.DeleteObject();
2426 m_font.CreateFontIndirect(&lf);
2427 CWnd::SetFont(&m_font);
2430 /** @brief Fire off a resort of the data, to take place when things stabilize. */
2431 void CDirView::InitiateSort()
2433 PostMessage(WM_TIMER, COLUMN_REORDER);
2436 void CDirView::OnTimer(UINT_PTR nIDEvent)
2438 if (nIDEvent == COLUMN_REORDER)
2440 // Remove the windows reordering, as we're doing it ourselves
2442 // Now redraw screen
2443 UpdateColumnNames();
2444 m_pColItems->LoadColumnWidths(
2445 (const TCHAR *)theApp.GetProfileString(GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3"), _T("ColumnWidths")),
2446 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), DefColumnWidth);
2449 else if (nIDEvent == STATUSBAR_UPDATE)
2451 KillTimer(STATUSBAR_UPDATE);
2452 int items = GetSelectedCount();
2453 String msg = (items == 1) ? _("1 item selected") : strutils::format_string1(_("%1 items selected"), strutils::to_str(items));
2454 GetParentFrame()->SetStatus(msg.c_str());
2457 CListView::OnTimer(nIDEvent);
2461 * @brief Change left-side readonly-status
2463 template<SIDE_TYPE stype>
2464 void CDirView::OnReadOnly()
2466 const int index = SideToIndex(GetDiffContext(), stype);
2467 bool bReadOnly = GetDocument()->GetReadOnly(index);
2468 GetDocument()->SetReadOnly(index, !bReadOnly);
2472 * @brief Update left-readonly menu item
2474 template<SIDE_TYPE stype>
2475 void CDirView::OnUpdateReadOnly(CCmdUI* pCmdUI)
2477 const int index = SideToIndex(GetDiffContext(), stype);
2478 bool bReadOnly = GetDocument()->GetReadOnly(index);
2479 if (stype != SIDE_MIDDLE)
2481 pCmdUI->Enable(TRUE);
2482 pCmdUI->SetCheck(bReadOnly);
2486 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
2487 pCmdUI->SetCheck(bReadOnly && GetDocument()->m_nDirs > 2);
2492 * @brief Update left-side readonly statusbar item
2494 void CDirView::OnUpdateStatusLeftRO(CCmdUI* pCmdUI)
2496 bool bROLeft = GetDocument()->GetReadOnly(0);
2497 pCmdUI->Enable(bROLeft);
2501 * @brief Update middle readonly statusbar item
2503 void CDirView::OnUpdateStatusMiddleRO(CCmdUI* pCmdUI)
2505 bool bROMiddle = GetDocument()->GetReadOnly(1);
2506 pCmdUI->Enable(bROMiddle && GetDocument()->m_nDirs > 2);
2510 * @brief Update right-side readonly statusbar item
2512 void CDirView::OnUpdateStatusRightRO(CCmdUI* pCmdUI)
2514 bool bRORight = GetDocument()->GetReadOnly(GetDocument()->m_nDirs - 1);
2515 pCmdUI->Enable(bRORight);
2519 * @brief Open dialog to customize dirview columns
2521 void CDirView::OnCustomizeColumns()
2523 // Located in DirViewColHandler.cpp
2525 String secname = GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3");
2526 theApp.WriteProfileString(secname.c_str(), _T("ColumnOrders"), m_pColItems->SaveColumnOrders().c_str());
2529 void CDirView::OnCtxtOpenWithUnpacker()
2532 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2535 // let the user choose a handler
2536 CSelectUnpackerDlg dlg(GetDiffItem(sel).diffFileInfo[0].filename, this);
2537 // create now a new infoUnpacker to initialize the manual/automatic flag
2538 PackingInfo infoUnpacker(PLUGIN_AUTO);
2539 dlg.SetInitialInfoHandler(&infoUnpacker);
2541 if (dlg.DoModal() == IDOK)
2543 infoUnpacker = dlg.GetInfoHandler();
2544 OpenSelection(SELECTIONTYPE_NORMAL, &infoUnpacker, false);
2550 void CDirView::OnUpdateCtxtOpenWithUnpacker(CCmdUI* pCmdUI)
2552 if (!GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
2554 pCmdUI->Enable(FALSE);
2558 // we need one selected file, existing on both side
2559 if (m_pList->GetSelectedCount() != 1)
2560 pCmdUI->Enable(FALSE);
2564 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2565 const DIFFITEM& di = GetDiffItem(sel);
2566 if (di.diffcode.isDirectory())
2568 pCmdUI->Enable(FALSE);
2571 pCmdUI->Enable(IsItemDeletableOnBoth(GetDiffContext(), di));
2576 * @brief Fill string list with current dirview column registry key names
2578 std::vector<String> CDirView::GetCurrentColRegKeys()
2580 std::vector<String> colKeys;
2581 int nphyscols = GetListCtrl().GetHeaderCtrl()->GetItemCount();
2582 for (int col = 0; col < nphyscols; ++col)
2584 int logcol = m_pColItems->ColPhysToLog(col);
2585 colKeys.push_back(m_pColItems->GetColRegValueNameBase(logcol));
2590 struct FileCmpReport: public IFileCmpReport
2592 explicit FileCmpReport(CDirView *pDirView) : m_pDirView(pDirView) {}
2593 ~FileCmpReport() override {}
2594 bool operator()(REPORT_TYPE nReportType, IListCtrl *pList, int nIndex, const String &sDestDir, String &sLinkPath) override
2596 const CDiffContext& ctxt = m_pDirView->GetDiffContext();
2597 const DIFFITEM &di = m_pDirView->GetDiffItem(nIndex);
2599 String sLinkFullPath = paths::ConcatPath(ctxt.GetLeftPath(), di.diffFileInfo[0].GetFile());
2601 if (di.diffcode.isDirectory() || !IsItemNavigableDiff(ctxt, di) || IsArchiveFile(sLinkFullPath))
2607 sLinkPath = di.diffFileInfo[0].GetFile();
2609 strutils::replace(sLinkPath, _T("\\"), _T("_"));
2610 sLinkPath += _T(".html");
2611 String sReportPath = paths::ConcatPath(sDestDir, sLinkPath);
2612 bool completed = false;
2614 m_pDirView->MoveFocus(m_pDirView->GetFirstSelectedInd(), nIndex, m_pDirView->GetSelectedCount());
2615 m_pDirView->PostMessage(MSG_GENERATE_FLIE_COMPARE_REPORT,
2616 reinterpret_cast<WPARAM>(sReportPath.c_str()),
2617 reinterpret_cast<LPARAM>(&completed));
2622 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2624 if (!AfxGetApp()->PumpMessage())
2634 CDirView *m_pDirView;
2637 LRESULT CDirView::OnGenerateFileCmpReport(WPARAM wParam, LPARAM lParam)
2640 CFrameWnd * pFrame = GetMainFrame()->GetActiveFrame();
2641 IMergeDoc * pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame->GetActiveDocument());
2642 if (pMergeDoc == nullptr)
2643 pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame);
2645 auto *pReportFileName = reinterpret_cast<const TCHAR *>(wParam);
2646 bool *pCompleted = reinterpret_cast<bool *>(lParam);
2647 if (pMergeDoc != nullptr)
2649 pMergeDoc->GenerateReport(pReportFileName);
2650 pMergeDoc->CloseNow();
2653 while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2654 if (!AfxGetApp()->PumpMessage())
2656 GetMainFrame()->OnUpdateFrameTitle(FALSE);
2662 * @brief Generate report from dir compare results.
2664 void CDirView::OnToolsGenerateReport()
2666 CDirDoc *pDoc = GetDocument();
2667 DirCmpReportDlg dlg;
2669 dlg.m_sReportFile = pDoc->GetReportFile();
2670 if (dlg.m_sReportFile.empty() && dlg.DoModal() != IDOK)
2673 pDoc->SetGeneratingReport(true);
2674 const CDiffContext& ctxt = GetDiffContext();
2676 PathContext paths = ctxt.GetNormalizedPaths();
2678 // If inside archive, convert paths
2679 if (pDoc->IsArchiveFolders())
2681 for (int i = 0; i < paths.GetSize(); i++)
2682 pDoc->ApplyDisplayRoot(i, paths[i]);
2685 DirCmpReport *pReport = new DirCmpReport(GetCurrentColRegKeys());
2686 pReport->SetRootPaths(paths);
2687 pReport->SetColumns(m_pColItems->GetDispColCount());
2688 pReport->SetFileCmpReport(new FileCmpReport(this));
2689 pReport->SetList(new IListCtrlImpl(m_pList->m_hWnd));
2690 pReport->SetReportType(dlg.m_nReportType);
2691 pReport->SetReportFile(dlg.m_sReportFile);
2692 pReport->SetCopyToClipboard(dlg.m_bCopyToClipboard);
2693 pReport->SetIncludeFileCmpReport(dlg.m_bIncludeFileCmpReport);
2694 pDoc->SetReport(pReport);
2699 * @brief Generate patch from files selected.
2701 * Creates a patch from selected files in active directory compare, or
2702 * active file compare. Files in file compare must be saved before
2705 void CDirView::OnToolsGeneratePatch()
2708 const CDiffContext& ctxt = GetDiffContext();
2710 // Get selected items from folder compare
2711 bool bValidFiles = true;
2712 for (DirItemIterator it = SelBegin(); bValidFiles && it != SelEnd(); ++it)
2714 const DIFFITEM &item = *it;
2715 if (item.diffcode.isBin())
2717 LangMessageBox(IDS_CANNOT_CREATE_BINARYPATCH, MB_ICONWARNING |
2718 MB_DONT_DISPLAY_AGAIN, IDS_CANNOT_CREATE_BINARYPATCH);
2719 bValidFiles = false;
2724 // Format full paths to files (leftFile/rightFile)
2725 String leftFile = item.getFilepath(0, ctxt.GetNormalizedPath(0));
2726 if (!leftFile.empty())
2727 leftFile = paths::ConcatPath(leftFile, item.diffFileInfo[0].filename);
2728 String rightFile = item.getFilepath(1, ctxt.GetNormalizedPath(1));
2729 if (!rightFile.empty())
2730 rightFile = paths::ConcatPath(rightFile, item.diffFileInfo[1].filename);
2732 // Format relative paths to files in folder compare
2733 String leftpatch = item.diffFileInfo[0].path;
2734 if (!leftpatch.empty())
2735 leftpatch += _T("/");
2736 leftpatch += item.diffFileInfo[0].filename;
2737 String rightpatch = item.diffFileInfo[1].path;
2738 if (!rightpatch.empty())
2739 rightpatch += _T("/");
2740 rightpatch += item.diffFileInfo[1].filename;
2741 patcher.AddFiles(leftFile, leftpatch, rightFile, rightpatch);
2745 patcher.CreatePatch();
2749 * @brief Add special items for non-recursive compare
2750 * to directory view.
2752 * Currently only special item is ".." for browsing to
2754 * @return number of items added to view
2756 int CDirView::AddSpecialItems()
2758 CDirDoc *pDoc = GetDocument();
2760 bool bEnable = true;
2761 PathContext pathsParent;
2762 switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
2764 case AllowUpwardDirectory::No:
2768 AddParentFolderItem(bEnable);
2771 case AllowUpwardDirectory::Never:
2778 * @brief Add "Parent folder" ("..") item to directory view
2780 void CDirView::AddParentFolderItem(bool bEnable)
2782 AddNewItem(0, (DIFFITEM *)SPECIAL_ITEM_POS, bEnable ? DIFFIMG_DIRUP : DIFFIMG_DIRUP_DISABLE, 0);
2786 void CDirView::OnCtxtDirZip()
2788 if (!HasZipSupport())
2790 LangMessageBox(IDS_NO_ZIP_SUPPORT, MB_ICONINFORMATION);
2796 this, LVNI_SELECTED | flag
2797 ).CompressArchive();
2800 void CDirView::ShowShellContextMenu(SIDE_TYPE stype)
2802 CShellContextMenu *pContextMenu = nullptr;
2806 if (m_pShellContextMenuLeft == nullptr)
2807 m_pShellContextMenuLeft.reset(new CShellContextMenu(LeftCmdFirst, LeftCmdLast));
2808 pContextMenu = m_pShellContextMenuLeft.get();
2811 if (m_pShellContextMenuMiddle == nullptr)
2812 m_pShellContextMenuMiddle.reset(new CShellContextMenu(MiddleCmdFirst, MiddleCmdLast));
2813 pContextMenu = m_pShellContextMenuMiddle.get();
2816 if (m_pShellContextMenuRight == nullptr)
2817 m_pShellContextMenuRight.reset(new CShellContextMenu(RightCmdFirst, RightCmdLast));
2818 pContextMenu = m_pShellContextMenuRight.get();
2821 if (pContextMenu!=nullptr && ListShellContextMenu(stype))
2824 GetCursorPos(&point);
2825 HWND hWnd = GetSafeHwnd();
2826 CFrameWnd *pFrame = GetTopLevelFrame();
2827 ASSERT(pFrame != nullptr);
2828 BOOL bAutoMenuEnableOld = pFrame->m_bAutoMenuEnable;
2829 pFrame->m_bAutoMenuEnable = FALSE;
2830 BOOL nCmd = TrackPopupMenu(pContextMenu->GetHMENU(), TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hWnd, nullptr);
2832 pContextMenu->InvokeCommand(nCmd, hWnd);
2833 pContextMenu->ReleaseShellContextMenu();
2834 pFrame->m_bAutoMenuEnable = bAutoMenuEnableOld;
2838 template <SIDE_TYPE stype>
2839 void CDirView::OnCtxtDirShellContextMenu()
2841 ShowShellContextMenu(stype);
2845 * @brief Select all visible items in dir compare
2847 void CDirView::OnSelectAll()
2849 // While the user is renaming an item, select all the edited text.
2850 CEdit *pEdit = m_pList->GetEditControl();
2851 if (pEdit != nullptr)
2853 pEdit->SetSel(pEdit->GetWindowTextLength());
2857 int selCount = m_pList->GetItemCount();
2859 for (int i = 0; i < selCount; i++)
2861 // Don't select special items (SPECIAL_ITEM_POS)
2862 DIFFITEM *diffpos = GetItemKey(i);
2863 if (diffpos != (DIFFITEM *)SPECIAL_ITEM_POS)
2864 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2870 * @brief Update "Select All" item
2872 void CDirView::OnUpdateSelectAll(CCmdUI* pCmdUI)
2874 bool bEnable = (!IsLabelEdit()) || (m_pList->GetItemCount() > 0);
2875 pCmdUI->Enable(bEnable);
2879 * @brief Handle clicks in plugin context view in list
2881 void CDirView::OnPluginPredifferMode(UINT nID)
2883 ApplyPluginPrediffSetting(SelBegin(), SelEnd(), GetDiffContext(),
2884 (nID == ID_PREDIFF_AUTO) ? PLUGIN_AUTO : PLUGIN_MANUAL);
2888 * @brief Updates just before displaying plugin context view in list
2890 void CDirView::OnUpdatePluginPredifferMode(CCmdUI* pCmdUI)
2892 // 2004-04-03, Perry
2893 // CMainFrame::OnUpdatePluginUnpackMode handles this for global unpacking
2894 // and is the template to copy, but here, this is a bit tricky
2895 // as a group of files may be selected
2896 // and they may not all have the same setting
2897 // so I'm not trying this right now
2899 pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
2901 BCMenu *pPopup = static_cast<BCMenu*>(pCmdUI->m_pSubMenu);
2902 if (pPopup == nullptr)
2905 std::pair<int, int> counts = CountPredifferYesNo(SelBegin(), SelEnd(), GetDiffContext());
2907 CheckContextMenu(pPopup, ID_PREDIFF_AUTO, (counts.first > 0));
2908 CheckContextMenu(pPopup, ID_PREDIFF_MANUAL, (counts.second > 0));
2912 * @brief Refresh cached options.
2914 void CDirView::RefreshOptions()
2916 m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
2917 m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
2918 Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
2919 m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
2920 m_pList->SetBkColor(m_bUseColors ? m_cachedColors.clrDirMargin : GetSysColor(COLOR_WINDOW));
2925 * @brief Copy selected item left side paths (containing filenames) to clipboard.
2927 template<SIDE_TYPE stype>
2928 void CDirView::OnCopyPathnames()
2930 std::list<String> list;
2931 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
2932 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
2935 void CDirView::OnCopyBothPathnames()
2937 std::list<String> list;
2938 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
2939 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
2943 * @brief Copy selected item filenames to clipboard.
2945 void CDirView::OnCopyFilenames()
2947 std::list<String> list;
2948 CopyFilenames(SelBegin(), SelEnd(), std::back_inserter(list));
2949 PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
2953 * @brief Enable/Disable dirview Copy Filenames context menu item.
2955 void CDirView::OnUpdateCopyFilenames(CCmdUI* pCmdUI)
2957 pCmdUI->Enable(Count(&DirActions::IsItemFile).count > 0);
2961 * @brief Copy selected item left side to clipboard.
2963 template<SIDE_TYPE stype>
2964 void CDirView::OnCopyToClipboard()
2966 std::list<String> list;
2967 CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
2968 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
2972 * @brief Copy selected item both side to clipboard.
2974 void CDirView::OnCopyBothToClipboard()
2976 std::list<String> list;
2977 CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
2978 PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
2982 * @brief Rename a selected item on both sides.
2985 void CDirView::OnItemRename()
2987 ASSERT(1 == m_pList->GetSelectedCount());
2988 int nSelItem = m_pList->GetNextItem(-1, LVNI_SELECTED);
2989 ASSERT(-1 != nSelItem);
2990 m_pList->EditLabel(nSelItem);
2994 * @brief Enable/Disable dirview Rename context menu item.
2997 void CDirView::OnUpdateItemRename(CCmdUI* pCmdUI)
2999 bool bEnabled = (1 == m_pList->GetSelectedCount());
3000 pCmdUI->Enable(bEnabled && SelBegin() != SelEnd());
3004 * @brief hide selected item filenames (removes them from the ListView)
3006 void CDirView::OnHideFilenames()
3008 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
3010 while ((it = SelRevBegin()) != SelRevEnd())
3013 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
3014 DeleteItem(it.m_sel);
3017 m_pList->SetRedraw(TRUE); // Turn updating back on
3021 * @brief update menu item
3023 void CDirView::OnUpdateHideFilenames(CCmdUI* pCmdUI)
3025 pCmdUI->Enable(m_pList->GetSelectedCount() != 0);
3028 /// User chose (context menu) Move left to...
3029 template<SIDE_TYPE stype>
3030 void CDirView::OnCtxtDirMoveTo()
3032 DoDirActionTo(stype, &DirActions::MoveTo<stype>, _("Moving files..."));
3036 * @brief Update "Move | Left to..." item
3038 template<SIDE_TYPE stype>
3039 void CDirView::OnUpdateCtxtDirMoveTo(CCmdUI* pCmdUI)
3041 Counts counts = Count(&DirActions::IsItemMovableToOn<stype>);
3042 pCmdUI->Enable(counts.count > 0);
3043 pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
3047 * @brief Update title after window is resized.
3049 void CDirView::OnSize(UINT nType, int cx, int cy)
3051 CListView::OnSize(nType, cx, cy);
3052 GetDocument()->SetTitle(nullptr);
3056 * @brief Called when user selects 'Delete' from 'Merge' menu.
3058 void CDirView::OnDelete()
3060 DoDirAction(&DirActions::DeleteOnEitherOrBoth, _("Deleting files..."));
3064 * @brief Enables/disables 'Delete' item in 'Merge' menu.
3066 void CDirView::OnUpdateDelete(CCmdUI* pCmdUI)
3068 pCmdUI->Enable(Count(&DirActions::IsItemDeletableOnEitherOrBoth).count > 0);
3072 * @brief Called when item state is changed.
3074 * Show count of selected items in statusbar.
3076 void CDirView::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)
3078 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
3080 // If item's selected state changed
3081 if ((pNMListView->uOldState & LVIS_SELECTED) !=
3082 (pNMListView->uNewState & LVIS_SELECTED))
3084 if ((pNMListView->iItem % 5000) > 0)
3085 SetTimer(STATUSBAR_UPDATE, 100, nullptr);
3087 OnTimer(STATUSBAR_UPDATE);
3093 * @brief Called before user start to item label edit.
3095 * Disable label edit if initiated from a user double-click.
3097 afx_msg void CDirView::OnBeginLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3099 *pResult = (SelBegin() == SelEnd());
3101 // If label edit is allowed.
3102 if (*pResult == FALSE)
3104 const NMLVDISPINFO *pdi = (NMLVDISPINFO*)pNMHDR;
3105 ASSERT(pdi != nullptr);
3107 // Locate the edit box on the right column in case the user changed the
3109 const int nColPos = m_pColItems->ColLogToPhys(0);
3111 // Get text from the "File Name" column.
3112 CString sText = m_pList->GetItemText(pdi->item.iItem, nColPos);
3113 ASSERT(!sText.IsEmpty());
3115 // Keep only left file name (separated by '|'). This form occurs
3116 // when two files exists with same name but not in same case.
3117 int nPos = sText.Find('|');
3120 sText = sText.Left(nPos);
3123 // Set the edit control with the updated text.
3124 CEdit *pEdit = m_pList->GetEditControl();
3125 ASSERT(pEdit != nullptr);
3126 pEdit->SetWindowText(sText);
3128 m_bUserCancelEdit = false;
3133 * @brief Called when user done with item label edit.
3136 afx_msg void CDirView::OnEndLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3140 // We can't use the normal condition of pszText==`nullptr` to know if the
3141 // user cancels editing when file names had different case (e.g.
3142 // "file.txt|FILE.txt"). The edit text was changed to "file.txt" and
3143 // if the user accept it as the new file name, pszText is `nullptr`.
3145 if (!m_bUserCancelEdit)
3147 CEdit *pEdit = m_pList->GetEditControl();
3148 ASSERT(pEdit != nullptr);
3151 pEdit->GetWindowText(sText);
3153 if (!sText.IsEmpty())
3156 DirItemIterator it(m_pIList.get(), reinterpret_cast<NMLVDISPINFO *>(pNMHDR)->item.iItem);
3157 *pResult = DoItemRename(it, GetDiffContext(), String(sText));
3158 } catch (ContentsChangedException& e) {
3159 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
3166 * @brief Called when item is marked for rescan.
3167 * This function marks selected items for rescan and rescans them.
3169 void CDirView::OnMarkedRescan()
3171 std::for_each(SelBegin(), SelEnd(), MarkForRescan);
3172 if (std::distance(SelBegin(), SelEnd()) > 0)
3174 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
3175 GetDocument()->SetMarkedRescan();
3176 GetDocument()->Rescan();
3181 * @brief Called to update the item count in the status bar
3183 void CDirView::OnUpdateStatusNum(CCmdUI* pCmdUI)
3185 String s; // text to display
3187 int count = m_pList->GetItemCount();
3188 int focusItem = GetFocusedItem();
3190 if (focusItem == -1)
3192 // No item has focus
3194 s = strutils::format_string1(_("Items: %1"), strutils::to_str(count));
3198 // Don't show number to special items
3199 DIFFITEM *pos = GetItemKey(focusItem);
3200 if (pos != (DIFFITEM *)SPECIAL_ITEM_POS)
3202 // If compare is non-recursive reduce special items count
3203 bool bRecursive = GetDiffContext().m_bRecursive;
3210 s = strutils::format_string2(_("Item %1 of %2"),
3211 strutils::to_str(focusItem + 1), strutils::to_str(count));
3214 pCmdUI->SetText(s.c_str());
3218 * @brief Show all hidden items.
3220 void CDirView::OnViewShowHiddenItems()
3222 SetItemViewFlag(GetDiffContext(), ViewCustomFlags::VISIBLE, ViewCustomFlags::VISIBILITY);
3228 * @brief Enable/Disable 'Show hidden items' menuitem.
3230 void CDirView::OnUpdateViewShowHiddenItems(CCmdUI* pCmdUI)
3232 pCmdUI->Enable(m_nHiddenItems > 0);
3236 * @brief Toggle Tree Mode
3238 void CDirView::OnViewTreeMode()
3240 m_bTreeMode = !m_bTreeMode;
3241 m_dirfilter.tree_mode = m_bTreeMode;
3242 GetOptionsMgr()->SaveOption(OPT_TREE_MODE, m_bTreeMode); // reverse
3247 * @brief Check/Uncheck 'Tree Mode' menuitem.
3249 void CDirView::OnUpdateViewTreeMode(CCmdUI* pCmdUI)
3251 // Don't show Tree Mode as 'checked' if the
3252 // menu item is greyed out (disabled). Its very confusing.
3253 if( GetDocument()->GetDiffContext().m_bRecursive ) {
3254 pCmdUI->SetCheck(m_bTreeMode);
3255 pCmdUI->Enable(TRUE);
3257 pCmdUI->SetCheck(FALSE);
3258 pCmdUI->Enable(FALSE);
3263 * @brief Expand all subfolders
3265 void CDirView::OnViewExpandAllSubdirs()
3267 ExpandAllSubdirs(GetDiffContext());
3272 * @brief Update "Expand All Subfolders" item
3274 void CDirView::OnUpdateViewExpandAllSubdirs(CCmdUI* pCmdUI)
3276 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3280 * @brief Collapse all subfolders
3282 void CDirView::OnViewCollapseAllSubdirs()
3284 CollapseAllSubdirs(GetDiffContext());
3289 * @brief Update "Collapse All Subfolders" item
3291 void CDirView::OnUpdateViewCollapseAllSubdirs(CCmdUI* pCmdUI)
3293 pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3296 void CDirView::OnViewSwapPanes()
3298 GetDocument()->Swap(0, GetDocument()->m_nDirs - 1);
3303 * @brief Show/Hide different files/directories
3305 void CDirView::OnOptionsShowDifferent()
3307 m_dirfilter.show_different = !m_dirfilter.show_different;
3308 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT, m_dirfilter.show_different);
3313 * @brief Show/Hide identical files/directories
3315 void CDirView::OnOptionsShowIdentical()
3317 m_dirfilter.show_identical = !m_dirfilter.show_identical;
3318 GetOptionsMgr()->SaveOption(OPT_SHOW_IDENTICAL, m_dirfilter.show_identical);
3323 * @brief Show/Hide left-only files/directories
3325 void CDirView::OnOptionsShowUniqueLeft()
3327 m_dirfilter.show_unique_left = !m_dirfilter.show_unique_left;
3328 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_LEFT, m_dirfilter.show_unique_left);
3333 * @brief Show/Hide middle-only files/directories
3335 void CDirView::OnOptionsShowUniqueMiddle()
3337 m_dirfilter.show_unique_middle = !m_dirfilter.show_unique_middle;
3338 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_MIDDLE, m_dirfilter.show_unique_middle);
3343 * @brief Show/Hide right-only files/directories
3345 void CDirView::OnOptionsShowUniqueRight()
3347 m_dirfilter.show_unique_right = !m_dirfilter.show_unique_right;
3348 GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_RIGHT, m_dirfilter.show_unique_right);
3353 * @brief Show/Hide binary files
3355 void CDirView::OnOptionsShowBinaries()
3357 m_dirfilter.show_binaries = !m_dirfilter.show_binaries;
3358 GetOptionsMgr()->SaveOption(OPT_SHOW_BINARIES, m_dirfilter.show_binaries);
3363 * @brief Show/Hide skipped files/directories
3365 void CDirView::OnOptionsShowSkipped()
3367 m_dirfilter.show_skipped = !m_dirfilter.show_skipped;
3368 GetOptionsMgr()->SaveOption(OPT_SHOW_SKIPPED, m_dirfilter.show_skipped);
3373 * @brief Show/Hide different files/folders (Middle and right are identical)
3375 void CDirView::OnOptionsShowDifferentLeftOnly()
3377 m_dirfilter.show_different_left_only = !m_dirfilter.show_different_left_only;
3378 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_LEFT_ONLY, m_dirfilter.show_different_left_only);
3383 * @brief Show/Hide different files/folders (Left and right are identical)
3385 void CDirView::OnOptionsShowDifferentMiddleOnly()
3387 m_dirfilter.show_different_middle_only = !m_dirfilter.show_different_middle_only;
3388 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_MIDDLE_ONLY, m_dirfilter.show_different_middle_only);
3393 * @brief Show/Hide different files/folders (Left and middle are identical)
3395 void CDirView::OnOptionsShowDifferentRightOnly()
3397 m_dirfilter.show_different_right_only = !m_dirfilter.show_different_right_only;
3398 GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_RIGHT_ONLY, m_dirfilter.show_different_right_only);
3403 * @brief Show/Hide missing left only files/folders
3405 void CDirView::OnOptionsShowMissingLeftOnly()
3407 m_dirfilter.show_missing_left_only = !m_dirfilter.show_missing_left_only;
3408 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_LEFT_ONLY, m_dirfilter.show_missing_left_only);
3413 * @brief Show/Hide missing middle only files/folders
3415 void CDirView::OnOptionsShowMissingMiddleOnly()
3417 m_dirfilter.show_missing_middle_only = !m_dirfilter.show_missing_middle_only;
3418 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_MIDDLE_ONLY, m_dirfilter.show_missing_middle_only);
3423 * @brief Show/Hide missing right only files/folders
3425 void CDirView::OnOptionsShowMissingRightOnly()
3427 m_dirfilter.show_missing_right_only = !m_dirfilter.show_missing_right_only;
3428 GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_RIGHT_ONLY, m_dirfilter.show_missing_right_only);
3432 void CDirView::OnUpdateOptionsShowdifferent(CCmdUI* pCmdUI)
3434 pCmdUI->SetCheck(m_dirfilter.show_different);
3437 void CDirView::OnUpdateOptionsShowidentical(CCmdUI* pCmdUI)
3439 pCmdUI->SetCheck(m_dirfilter.show_identical);
3442 void CDirView::OnUpdateOptionsShowuniqueleft(CCmdUI* pCmdUI)
3444 pCmdUI->SetCheck(m_dirfilter.show_unique_left);
3447 void CDirView::OnUpdateOptionsShowuniquemiddle(CCmdUI* pCmdUI)
3449 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3450 pCmdUI->SetCheck(m_dirfilter.show_unique_middle);
3453 void CDirView::OnUpdateOptionsShowuniqueright(CCmdUI* pCmdUI)
3455 pCmdUI->SetCheck(m_dirfilter.show_unique_right);
3458 void CDirView::OnUpdateOptionsShowBinaries(CCmdUI* pCmdUI)
3460 pCmdUI->SetCheck(m_dirfilter.show_binaries);
3463 void CDirView::OnUpdateOptionsShowSkipped(CCmdUI* pCmdUI)
3465 pCmdUI->SetCheck(m_dirfilter.show_skipped);
3468 void CDirView::OnUpdateOptionsShowDifferentLeftOnly(CCmdUI* pCmdUI)
3470 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3471 pCmdUI->SetCheck(m_dirfilter.show_different_left_only);
3474 void CDirView::OnUpdateOptionsShowDifferentMiddleOnly(CCmdUI* pCmdUI)
3476 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3477 pCmdUI->SetCheck(m_dirfilter.show_different_middle_only);
3480 void CDirView::OnUpdateOptionsShowDifferentRightOnly(CCmdUI* pCmdUI)
3482 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3483 pCmdUI->SetCheck(m_dirfilter.show_different_right_only);
3486 void CDirView::OnUpdateOptionsShowMissingLeftOnly(CCmdUI* pCmdUI)
3488 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3489 pCmdUI->SetCheck(m_dirfilter.show_missing_left_only);
3492 void CDirView::OnUpdateOptionsShowMissingMiddleOnly(CCmdUI* pCmdUI)
3494 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3495 pCmdUI->SetCheck(m_dirfilter.show_missing_middle_only);
3498 void CDirView::OnUpdateOptionsShowMissingRightOnly(CCmdUI* pCmdUI)
3500 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3501 pCmdUI->SetCheck(m_dirfilter.show_missing_right_only);
3504 void CDirView::OnMergeCompare()
3506 CWaitCursor waitstatus;
3510 template<SELECTIONTYPE seltype>
3511 void CDirView::OnMergeCompare2()
3513 CWaitCursor waitstatus;
3514 OpenSelection(seltype);
3517 void CDirView::OnMergeCompareNonHorizontally()
3519 int sel1, sel2, sel3;
3520 if (!GetSelectedItems(&sel1, &sel2, &sel3))
3522 DirSelectFilesDlg dlg;
3524 dlg.m_pdi[0] = &GetDiffItem(sel1);
3526 dlg.m_pdi[1] = &GetDiffItem(sel2);
3528 dlg.m_pdi[2] = &GetDiffItem(sel3);
3529 if (dlg.DoModal() == IDOK && dlg.m_selectedButtons.size() > 0)
3531 CDirDoc *pDoc = GetDocument();
3532 DWORD dwFlags[3] = {};
3534 for (int nIndex = 0; nIndex < static_cast<int>(dlg.m_selectedButtons.size()); ++nIndex)
3536 int n = dlg.m_selectedButtons[nIndex];
3537 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(n % 3) ? FFILEOPEN_READONLY : 0);
3538 if (dlg.m_pdi[n / 3])
3539 paths.SetPath(nIndex, GetItemFileName(pDoc->GetDiffContext(), *dlg.m_pdi[n / 3], n % 3));
3541 if (paths.GetSize() == 1)
3542 paths.SetRight(_T(""));
3543 Open(paths, dwFlags);
3547 void CDirView::OnMergeCompareXML()
3549 CWaitCursor waitstatus;
3550 PackingInfo packingInfo(PLUGIN_BUILTIN_XML);
3551 OpenSelection(SELECTIONTYPE_NORMAL, &packingInfo, false);
3554 void CDirView::OnMergeCompareAs(UINT nID)
3556 CWaitCursor waitstatus;
3557 OpenSelectionAs(nID);
3560 void CDirView::OnUpdateMergeCompare(CCmdUI *pCmdUI)
3562 bool openableForDir = (pCmdUI->m_nID != ID_MERGE_COMPARE_XML &&
3563 pCmdUI->m_nID != ID_MERGE_COMPARE_HEX &&
3564 pCmdUI->m_nID != ID_MERGE_COMPARE_IMAGE);
3566 DoUpdateOpen(SELECTIONTYPE_NORMAL, pCmdUI, openableForDir);
3569 template<SELECTIONTYPE seltype>
3570 void CDirView::OnUpdateMergeCompare2(CCmdUI *pCmdUI)
3572 DoUpdateOpen(seltype, pCmdUI);
3575 void CDirView::OnViewCompareStatistics()
3577 CompareStatisticsDlg dlg(GetDocument()->GetCompareStats());
3582 * @brief Count left & right files, and number with editable text encoding
3583 * @param nLeft [out] #files on left side selected
3584 * @param nLeftAffected [out] #files on left side selected which can have text encoding changed
3585 * @param nRight [out] #files on right side selected
3586 * @param nRightAffected [out] #files on right side selected which can have text encoding changed
3588 * Affected files include all except unicode files
3590 void CDirView::FormatEncodingDialogDisplays(CLoadSaveCodepageDlg * dlg)
3592 IntToIntMap currentCodepages = CountCodepages(SelBegin(), SelEnd(), GetDiffContext());
3594 Counts left, middle, right;
3595 left = Count(&DirActions::IsItemEditableEncoding<SIDE_LEFT>);
3596 if (GetDocument()->m_nDirs > 2)
3597 middle = Count(&DirActions::IsItemEditableEncoding<SIDE_MIDDLE>);
3598 right = Count(&DirActions::IsItemEditableEncoding<SIDE_RIGHT>);
3600 // Format strings such as "25 of 30 Files Affected"
3601 String sLeftAffected = FormatFilesAffectedString(left.count, left.total);
3602 String sMiddleAffected = (GetDocument()->m_nDirs < 3) ? _T("") : FormatFilesAffectedString(middle.count, middle.total);
3603 String sRightAffected = FormatFilesAffectedString(right.count, right.total);
3604 dlg->SetLeftRightAffectStrings(sLeftAffected, sMiddleAffected, sRightAffected);
3605 int codepage = currentCodepages.FindMaxKey();
3606 dlg->SetCodepages(codepage);
3610 * @brief Display file encoding dialog to user & handle user's choices
3612 * This handles DirView invocation, so multiple files may be affected
3614 void CDirView::DoFileEncodingDialog()
3616 CLoadSaveCodepageDlg dlg(GetDocument()->m_nDirs);
3617 // set up labels about what will be affected
3618 FormatEncodingDialogDisplays(&dlg);
3619 dlg.EnableSaveCodepage(false); // disallow setting a separate codepage for saving
3622 if (dlg.DoModal() != IDOK)
3626 affected[0] = dlg.DoesAffectLeft();
3627 affected[1] = dlg.DoesAffectMiddle();
3628 affected[SideToIndex(GetDiffContext(), SIDE_RIGHT)] = dlg.DoesAffectRight();
3630 ApplyCodepage(SelBegin(), SelEnd(), GetDiffContext(), affected, dlg.GetLoadCodepage());
3632 m_pList->InvalidateRect(nullptr);
3633 m_pList->UpdateWindow();
3635 // TODO: We could loop through any active merge windows belonging to us
3636 // and see if any of their files are affected
3637 // but, if they've been edited, we cannot throw away the user's work?
3641 * @brief Display file encoding dialog & handle user's actions
3643 void CDirView::OnFileEncoding()
3645 DoFileEncodingDialog();
3648 /** @brief Open help from mainframe when user presses F1*/
3649 void CDirView::OnHelp()
3651 theApp.ShowHelp(DirViewHelpLocation);
3655 * @brief true while user is editing a file name.
3657 bool CDirView::IsLabelEdit() const
3659 return (m_pList->GetEditControl() != nullptr);
3663 * @brief Allow edit "Paste" when renaming an item.
3665 void CDirView::OnEditCopy()
3667 CEdit *pEdit = m_pList->GetEditControl();
3668 if (pEdit != nullptr)
3675 * @brief Allow edit "Cut" when renaming an item.
3677 void CDirView::OnEditCut()
3679 CEdit *pEdit = m_pList->GetEditControl();
3680 if (pEdit != nullptr)
3687 * @brief Allow edit "Paste" when renaming an item.
3689 void CDirView::OnEditPaste()
3691 CEdit *pEdit = m_pList->GetEditControl();
3692 if (pEdit != nullptr)
3699 * @brief Allow edit "Undo" when renaming an item.
3701 void CDirView::OnEditUndo()
3703 CEdit *pEdit = m_pList->GetEditControl();
3704 if (pEdit != nullptr)
3711 * @brief Update the tool bar's "Undo" icon. It should be enabled when
3712 * renaming an item and undo is possible.
3714 void CDirView::OnUpdateEditUndo(CCmdUI* pCmdUI)
3716 CEdit *pEdit = m_pList->GetEditControl();
3717 pCmdUI->Enable(pEdit && pEdit->CanUndo());
3720 * @brief Returns CShellContextMenu object that owns given HMENU.
3722 * @param [in] hMenu Handle to the menu to check ownership of.
3723 * @return Either m_pShellContextMenuLeft, m_pShellContextMenuRight
3724 * or `nullptr` if hMenu is not owned by these two.
3726 CShellContextMenu* CDirView::GetCorrespondingShellContextMenu(HMENU hMenu) const
3728 CShellContextMenu* pMenu = nullptr;
3729 if (m_pShellContextMenuLeft!=nullptr && hMenu == m_pShellContextMenuLeft->GetHMENU())
3730 pMenu = m_pShellContextMenuLeft.get();
3731 else if (m_pShellContextMenuMiddle!=nullptr && hMenu == m_pShellContextMenuMiddle->GetHMENU())
3732 pMenu = m_pShellContextMenuMiddle.get();
3733 else if (m_pShellContextMenuRight!=nullptr && hMenu == m_pShellContextMenuRight->GetHMENU())
3734 pMenu = m_pShellContextMenuRight.get();
3740 * @brief Handle messages related to correct menu working.
3742 * We need to requery shell context menu each time we switch from context menu
3743 * for one side to context menu for other side. Here we check whether we need to
3744 * requery and call ShellContextMenuHandleMenuMessage.
3746 LRESULT CDirView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
3748 while (message == WM_INITMENUPOPUP)
3750 HMENU hMenu = (HMENU)wParam;
3751 if (CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(hMenu))
3753 if (m_hCurrentMenu != hMenu)
3755 // re-query context menu once more, because if context menu was queried for right
3756 // group of files and we are showing menu for left group (or vice versa) menu will
3757 // be shown incorrectly
3758 // also, if context menu was last queried for right group of files and we are
3759 // invoking command for left command will be executed for right group (the last
3760 // group that menu was requested for)
3761 // may be a "feature" of Shell
3763 pMenu->RequeryShellContextMenu();
3764 m_hCurrentMenu = hMenu;
3770 CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(m_hCurrentMenu);
3772 if (pMenu != nullptr)
3775 pMenu->HandleMenuMessage(message, wParam, lParam, res);
3778 return CListView::WindowProc(message, wParam, lParam);
3782 * @brief Implement background item coloring
3784 void CDirView::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
3786 if (!m_bUseColors) {
3790 LPNMLISTVIEW pNM = (LPNMLISTVIEW)pNMHDR;
3791 *pResult = CDRF_DODEFAULT;
3793 if (pNM->hdr.code == NM_CUSTOMDRAW)
3795 LPNMLVCUSTOMDRAW lpC = (LPNMLVCUSTOMDRAW)pNMHDR;
3797 if (lpC->nmcd.dwDrawStage == CDDS_PREPAINT)
3799 *pResult = CDRF_NOTIFYITEMDRAW;
3803 if (lpC->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
3805 *pResult = CDRF_NOTIFYITEMDRAW;
3809 if (lpC->nmcd.dwDrawStage == (CDDS_ITEMPREPAINT | CDDS_SUBITEM ))
3811 GetColors (static_cast<int>(lpC->nmcd.dwItemSpec), lpC->iSubItem, lpC->clrTextBk, lpC->clrText);
3816 void CDirView::OnBnClickedComparisonStop()
3818 if (m_pCmpProgressBar != nullptr)
3819 m_pCmpProgressBar->EndUpdating();
3820 GetDocument()->AbortCurrentScan();
3823 void CDirView::OnBnClickedComparisonPause()
3825 if (m_pCmpProgressBar != nullptr)
3826 m_pCmpProgressBar->SetPaused(true);
3827 GetDocument()->PauseCurrentScan();
3830 void CDirView::OnBnClickedComparisonContinue()
3832 if (m_pCmpProgressBar != nullptr)
3833 m_pCmpProgressBar->SetPaused(false);
3834 GetDocument()->ContinueCurrentScan();
3838 * @brief Populate colors for items in view, depending on difference status
3840 void CDirView::GetColors (int nRow, int nCol, COLORREF& clrBk, COLORREF& clrText) const
3842 const DIFFITEM& di = GetDiffItem (nRow);
3846 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
3847 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
3849 else if (di.diffcode.isResultFiltered())
3851 clrText = m_cachedColors.clrDirItemFilteredText;
3852 clrBk = m_cachedColors.clrDirItemFiltered;
3854 else if (!IsItemExistAll(GetDiffContext(), di))
3856 clrText = m_cachedColors.clrDirItemNotExistAllText;
3857 clrBk = m_cachedColors.clrDirItemNotExistAll;
3859 else if (di.diffcode.isResultDiff())
3861 clrText = m_cachedColors.clrDirItemDiffText;
3862 clrBk = m_cachedColors.clrDirItemDiff;
3864 else if (di.diffcode.isResultSame())
3866 clrText = m_cachedColors.clrDirItemEqualText;
3867 clrBk = m_cachedColors.clrDirItemEqual;
3871 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
3872 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
3876 void CDirView::OnSearch()
3878 CDirDoc *pDoc = GetDocument();
3879 m_pList->SetRedraw(FALSE); // Turn off updating (better performance)
3880 int nRows = m_pList->GetItemCount();
3881 for (int currRow = nRows - 1; currRow >= 0; currRow--)
3883 DIFFITEM *pos = GetItemKey(currRow);
3884 if (pos == (DIFFITEM *)SPECIAL_ITEM_POS)
3887 bool bFound = false;
3888 DIFFITEM &di = GetDiffItem(currRow);
3890 for (int i = 0; i < pDoc->m_nDirs; i++)
3892 if (di.diffcode.exists(i) && !di.diffcode.isDirectory())
3894 GetItemFileNames(currRow, &paths);
3896 if (!ufile.OpenReadOnly(paths[i]))
3899 ufile.SetUnicoding(di.diffFileInfo[i].encoding.m_unicoding);
3900 ufile.SetBom(di.diffFileInfo[i].encoding.m_bom);
3901 ufile.SetCodepage(di.diffFileInfo[i].encoding.m_codepage);
3909 if (!ufile.ReadString(line, &lossy))
3912 if (_tcsstr(line.c_str(), _T("DirView")))
3926 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
3927 DeleteItem(currRow);
3931 m_pList->SetRedraw(TRUE); // Turn updating back on
3935 * @brief Drag files/directories from folder compare listing view.
3937 void CDirView::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
3939 COleDataSource *DropData = new COleDataSource();
3941 std::list<String> list;
3942 CopyPathnamesForDragAndDrop(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3943 String filesForDroping = strutils::join(list.begin(), list.end(), _T("\n")) + _T("\n");
3945 CSharedFile file(GMEM_DDESHARE | GMEM_MOVEABLE | GMEM_ZEROINIT);
3946 file.Write(filesForDroping.data(), static_cast<unsigned>((filesForDroping.length() + 1) * sizeof(TCHAR)));
3948 HGLOBAL hMem = GlobalReAlloc(file.Detach(), (filesForDroping.length() + 1) * sizeof(TCHAR), 0);
3949 if (hMem != nullptr)
3951 DropData->CacheGlobalData(CF_UNICODETEXT, hMem);
3952 DROPEFFECT de = DropData->DoDragDrop(DROPEFFECT_COPY | DROPEFFECT_MOVE, nullptr);
3958 /// Assign column name, using string resource & current column ordering
3959 void CDirView::NameColumn(const DirColInfo *col, int subitem)
3961 int phys = m_pColItems->ColLogToPhys(subitem);
3964 String s = tr(col->idNameContext, col->idName);
3966 lvc.mask = LVCF_TEXT;
3967 lvc.pszText = const_cast<LPTSTR>(s.c_str());
3968 m_pList->SetColumn(phys, &lvc);
3972 /// Load column names from string table
3973 void CDirView::UpdateColumnNames()
3975 int ncols = m_pColItems->GetColCount();
3976 for (int i=0; i<ncols; ++i)
3978 const DirColInfo* col = m_pColItems->GetDirColInfo(i);
3984 * @brief Set alignment of columns.
3986 void CDirView::SetColAlignments()
3988 int ncols = m_pColItems->GetColCount();
3989 for (int i=0; i<ncols; ++i)
3991 const DirColInfo * col = m_pColItems->GetDirColInfo(i);
3993 lvc.mask = LVCF_FMT;
3994 lvc.fmt = col->alignment;
3995 m_pList->SetColumn(m_pColItems->ColLogToPhys(i), &lvc);
3999 CDirView::CompareState::CompareState(const CDiffContext *pCtxt, const DirViewColItems *pColItems, int sortCol, bool bSortAscending, bool bTreeMode)
4001 , pColItems(pColItems)
4003 , bSortAscending(bSortAscending)
4004 , bTreeMode(bTreeMode)
4008 /// Compare two specified rows during a sort operation (windows callback)
4009 int CALLBACK CDirView::CompareState::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
4011 CompareState *pThis = reinterpret_cast<CompareState*>(lParamSort);
4012 // Sort special items always first in dir view
4018 DIFFITEM *diffposl = (DIFFITEM *)lParam1;
4019 DIFFITEM *diffposr = (DIFFITEM *)lParam2;
4020 const DIFFITEM &ldi = pThis->pCtxt->GetDiffAt(diffposl);
4021 const DIFFITEM &rdi = pThis->pCtxt->GetDiffAt(diffposr);
4022 // compare 'left' and 'right' parameters as appropriate
4023 int retVal = pThis->pColItems->ColSort(pThis->pCtxt, pThis->sortCol, ldi, rdi, pThis->bTreeMode);
4024 // return compare result, considering sort direction
4025 return pThis->bSortAscending ? retVal : -retVal;
4028 /// Add new item to list view
4029 int CDirView::AddNewItem(int i, DIFFITEM *diffpos, int iImage, int iIndent)
4032 lvItem.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE | LVIF_INDENT;
4034 lvItem.iIndent = iIndent;
4035 lvItem.iSubItem = 0;
4036 lvItem.pszText = LPSTR_TEXTCALLBACK;
4037 lvItem.lParam = (LPARAM)diffpos;
4038 lvItem.iImage = iImage;
4039 return GetListCtrl().InsertItem(&lvItem);
4043 * @brief Update listview display of details for specified row
4044 * @note Customising shownd data should be done here
4046 void CDirView::UpdateDiffItemStatus(UINT nIdx)
4048 GetListCtrl().RedrawItems(nIdx, nIdx);
4051 static String rgDispinfoText[2]; // used in function below
4054 * @brief Allocate a text buffer to assign to NMLVDISPINFO::item::pszText
4055 * Quoting from SDK Docs:
4056 * If the LVITEM structure is receiving item text, the pszText and cchTextMax
4057 * members specify the address and size of a buffer. You can either copy text to
4058 * the buffer or assign the address of a string to the pszText member. In the
4059 * latter case, you must not change or delete the string until the corresponding
4060 * item text is deleted or two additional LVN_GETDISPINFO messages have been sent.
4062 static LPTSTR NTAPI AllocDispinfoText(const String &s)
4065 LPCTSTR pszText = (rgDispinfoText[i] = s).c_str();
4067 return (LPTSTR)pszText;
4071 * @brief Respond to LVN_GETDISPINFO message
4073 void CDirView::ReflectGetdispinfo(NMLVDISPINFO *pParam)
4075 int nIdx = pParam->item.iItem;
4076 int i = m_pColItems->ColPhysToLog(pParam->item.iSubItem);
4077 DIFFITEM *key = GetItemKey(nIdx);
4078 if (key == (DIFFITEM *)SPECIAL_ITEM_POS)
4080 if (m_pColItems->IsColName(i))
4082 pParam->item.pszText = _T("..");
4086 if (!GetDocument()->HasDiffs())
4088 const CDiffContext &ctxt = GetDiffContext();
4089 const DIFFITEM &di = ctxt.GetDiffAt(key);
4090 if (pParam->item.mask & LVIF_TEXT)
4092 String s = m_pColItems->ColGetTextToDisplay(&ctxt, i, di);
4093 pParam->item.pszText = AllocDispinfoText(s);
4095 if (pParam->item.mask & LVIF_IMAGE)
4097 pParam->item.iImage = GetColImage(di);
4102 * @brief User examines & edits which columns are displayed in dirview, and in which order
4104 void CDirView::OnEditColumns()
4107 // List all the currently displayed columns
4108 for (int col=0; col<GetListCtrl().GetHeaderCtrl()->GetItemCount(); ++col)
4110 int l = m_pColItems->ColPhysToLog(col);
4111 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l, col);
4113 // Now add all the columns not currently displayed
4115 for (l=0; l<m_pColItems->GetColCount(); ++l)
4117 if (m_pColItems->ColLogToPhys(l)==-1)
4119 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l);
4123 // Add default order of columns for resetting to defaults
4124 for (l = 0; l < m_pColItems->GetColCount(); ++l)
4126 int phy = m_pColItems->GetColDefaultOrder(l);
4127 dlg.AddDefColumn(m_pColItems->GetColDisplayName(l), l, phy);
4130 if (dlg.DoModal() != IDOK)
4133 String secname = GetDocument()->m_nDirs < 3 ? _T("DirView") : _T("DirView3");
4134 theApp.WriteProfileString(secname.c_str(), _T("ColumnWidths"),
4135 (dlg.m_bReset ? m_pColItems->ResetColumnWidths(DefColumnWidth) :
4136 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1))).c_str());
4138 // Reset our data to reflect the new data from the dialog
4139 const CDirColsDlg::ColumnArray & cols = dlg.GetColumns();
4140 m_pColItems->ClearColumnOrders();
4141 const int sortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4142 std::vector<int> colorder(m_pColItems->GetColCount(), -1);
4143 for (CDirColsDlg::ColumnArray::const_iterator iter = cols.begin();
4144 iter != cols.end(); ++iter)
4146 int log = iter->log_col;
4147 int phy = iter->phy_col;
4148 colorder[log] = phy;
4150 // If sorted column was hidden, reset sorting
4151 if (log == sortColumn && phy < 0)
4153 GetOptionsMgr()->Reset((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4154 GetOptionsMgr()->Reset(OPT_DIRVIEW_SORT_ASCENDING);
4158 m_pColItems->SetColumnOrdering(&colorder[0]);
4160 if (m_pColItems->GetDispColCount() < 1)
4162 // Ignore them if they didn't leave a column showing
4163 m_pColItems->ResetColumnOrdering();
4172 DirActions CDirView::MakeDirActions(DirActions::method_type func) const
4174 const CDirDoc *pDoc = GetDocument();
4175 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), func);
4178 DirActions CDirView::MakeDirActions(DirActions::method_type2 func) const
4180 const CDirDoc *pDoc = GetDocument();
4181 return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), nullptr, func);
4184 const CDiffContext& CDirView::GetDiffContext() const
4186 return GetDocument()->GetDiffContext();
4189 CDiffContext& CDirView::GetDiffContext()
4191 return GetDocument()->GetDiffContext();