OSDN Git Service

419f06931017bc454e1a8073e29624540d584baa
[winmerge-jp/winmerge-jp.git] / Src / DirView.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 //    WinMerge:  an interactive diff/merge utility
3 //    Copyright (C) 1997-2000  Thingamahoochie Software
4 //    Author: Dean Grimm
5 //    SPDX-License-Identifier: GPL-2.0-or-later
6 /////////////////////////////////////////////////////////////////////////////
7 /**
8  * @file  DirView.cpp
9  *
10  * @brief Main implementation file for CDirView
11  */
12
13 #include "StdAfx.h"
14 #include "DirView.h"
15 #include "Constants.h"
16 #include "Merge.h"
17 #include "ClipBoard.h"
18 #include "DirActions.h"
19 #include "DirViewColItems.h"
20 #include "DirFrame.h"  // StatePane
21 #include "DirDoc.h"
22 #include "IMergeDoc.h"
23 #include "FileLocation.h"
24 #include "MainFrm.h"
25 #include "resource.h"
26 #include "FileTransform.h"
27 #include "SelectUnpackerDlg.h"
28 #include "paths.h"
29 #include "7zCommon.h"
30 #include "OptionsDef.h"
31 #include "OptionsMgr.h"
32 #include "BCMenu.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"
41 #include "UniFile.h"
42 #include "ShellContextMenu.h"
43 #include "DiffItem.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"
50 #include <numeric>
51 #include <functional>
52
53 #ifdef _DEBUG
54 #define new DEBUG_NEW
55 #endif
56
57 using std::swap;
58 using namespace std::placeholders;
59
60 /**
61  * @brief Location for folder compare specific help to open.
62  */
63 static TCHAR DirViewHelpLocation[] = _T("::/htmlhelp/Compare_dirs.html");
64
65 /**
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).
69  */
70 const int TimeToSignalCompare = 3;
71
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;
79
80 /////////////////////////////////////////////////////////////////////////////
81 // CDirView
82
83 enum { 
84         COLUMN_REORDER = 99,
85         STATUSBAR_UPDATE = 100
86 };
87
88 IMPLEMENT_DYNCREATE(CDirView, CListView)
89
90 CDirView::CDirView()
91                 : m_pList(nullptr)
92                 , m_nHiddenItems(0)
93                 , m_pCmpProgressBar(nullptr)
94                 , m_compareStart(0)
95                 , m_bTreeMode(false)
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)
103                 , m_nActivePane(-1)
104 {
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;
109
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);
115 }
116
117 CDirView::~CDirView()
118 {
119 }
120
121 BEGIN_MESSAGE_MAP(CDirView, CListView)
122         ON_WM_CONTEXTMENU()
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>)
181         ON_WM_DESTROY()
182         ON_WM_CHAR()
183         ON_WM_KEYDOWN()
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)
198         ON_WM_TIMER()
199         ON_UPDATE_COMMAND_UI(ID_STATUS_RIGHTDIR_RO, OnUpdateStatusRightRO)
200         ON_UPDATE_COMMAND_UI(ID_STATUS_MIDDLEDIR_RO, OnUpdateStatusMiddleRO)
201         ON_UPDATE_COMMAND_UI(ID_STATUS_LEFTDIR_RO, OnUpdateStatusLeftRO)
202         ON_COMMAND(ID_FILE_LEFT_READONLY, OnReadOnly<SIDE_LEFT>)
203         ON_UPDATE_COMMAND_UI(ID_FILE_LEFT_READONLY, OnUpdateReadOnly<SIDE_LEFT>)
204         ON_COMMAND(ID_FILE_MIDDLE_READONLY, OnReadOnly<SIDE_MIDDLE>)
205         ON_UPDATE_COMMAND_UI(ID_FILE_MIDDLE_READONLY, OnUpdateReadOnly<SIDE_MIDDLE>)
206         ON_COMMAND(ID_FILE_RIGHT_READONLY, OnReadOnly<SIDE_RIGHT>)
207         ON_UPDATE_COMMAND_UI(ID_FILE_RIGHT_READONLY, OnUpdateReadOnly<SIDE_RIGHT>)
208         ON_COMMAND(ID_TOOLS_CUSTOMIZECOLUMNS, OnCustomizeColumns)
209         ON_COMMAND(ID_TOOLS_GENERATEREPORT, OnToolsGenerateReport)
210         ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
211         ON_MESSAGE(MSG_GENERATE_FLIE_COMPARE_REPORT, OnGenerateFileCmpReport)
212         ON_COMMAND(ID_DIR_ZIP_LEFT, OnCtxtDirZip<DirItemEnumerator::Left>)
213         ON_COMMAND(ID_DIR_ZIP_MIDDLE, OnCtxtDirZip<DirItemEnumerator::Middle>)
214         ON_COMMAND(ID_DIR_ZIP_RIGHT, OnCtxtDirZip<DirItemEnumerator::Right>)
215         ON_COMMAND(ID_DIR_ZIP_BOTH, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
216         ON_COMMAND(ID_DIR_ZIP_ALL, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders>)
217         ON_COMMAND(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnCtxtDirZip<DirItemEnumerator::Original | DirItemEnumerator::Altered | DirItemEnumerator::BalanceFolders | DirItemEnumerator::DiffsOnly>)
218         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_LEFT, OnUpdateCtxtDirCopyTo<SIDE_LEFT>)
219         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_MIDDLE, OnUpdateCtxtDirCopyTo<SIDE_MIDDLE>)
220         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_RIGHT, OnUpdateCtxtDirCopyTo<SIDE_RIGHT>)
221         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH, OnUpdateCtxtDirCopyBothTo)
222         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_ALL, OnUpdateCtxtDirCopyBothTo)
223         ON_UPDATE_COMMAND_UI(ID_DIR_ZIP_BOTH_DIFFS_ONLY, OnUpdateCtxtDirCopyBothDiffsOnlyTo)
224         ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_LEFT, OnCtxtDirShellContextMenu<SIDE_LEFT>)
225         ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, OnCtxtDirShellContextMenu<SIDE_MIDDLE>)
226         ON_COMMAND(ID_DIR_SHELL_CONTEXT_MENU_RIGHT, OnCtxtDirShellContextMenu<SIDE_RIGHT>)
227         ON_COMMAND(ID_EDIT_SELECT_ALL, OnSelectAll)
228         ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateSelectAll)
229         ON_COMMAND_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnPluginPredifferMode)
230         ON_UPDATE_COMMAND_UI_RANGE(ID_PREDIFF_MANUAL, ID_PREDIFF_AUTO, OnUpdatePluginPredifferMode)
231         ON_COMMAND(ID_DIR_COPY_PATHNAMES_LEFT, OnCopyPathnames<SIDE_LEFT>)
232         ON_COMMAND(ID_DIR_COPY_PATHNAMES_MIDDLE, OnCopyPathnames<SIDE_MIDDLE>)
233         ON_COMMAND(ID_DIR_COPY_PATHNAMES_RIGHT, OnCopyPathnames<SIDE_RIGHT>)
234         ON_COMMAND(ID_DIR_COPY_PATHNAMES_BOTH, OnCopyBothPathnames)
235         ON_COMMAND(ID_DIR_COPY_PATHNAMES_ALL, OnCopyBothPathnames)
236         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_LEFT, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
237         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_MIDDLE, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
238         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_RIGHT, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
239         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_BOTH, OnUpdateCtxtDirCopyBoth2)
240         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_PATHNAMES_ALL, OnUpdateCtxtDirCopyBoth2)
241         ON_COMMAND(ID_DIR_COPY_FILENAMES, OnCopyFilenames)
242         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_FILENAMES, OnUpdateCopyFilenames)
243         ON_COMMAND(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_LEFT>)
244         ON_COMMAND(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnCopyToClipboard<SIDE_MIDDLE>)
245         ON_COMMAND(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnCopyToClipboard<SIDE_RIGHT>)
246         ON_COMMAND(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnCopyBothToClipboard)
247         ON_COMMAND(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnCopyBothToClipboard)
248         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_LEFT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_LEFT>)
249         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_MIDDLE>)
250         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_RIGHT_TO_CLIPBOARD, OnUpdateCtxtDirCopy2<SIDE_RIGHT>)
251         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_BOTH_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
252         ON_UPDATE_COMMAND_UI(ID_DIR_COPY_ALL_TO_CLIPBOARD, OnUpdateCtxtDirCopyBoth2)
253         ON_COMMAND(ID_DIR_ITEM_RENAME, OnItemRename)
254         ON_UPDATE_COMMAND_UI(ID_DIR_ITEM_RENAME, OnUpdateItemRename)
255         ON_COMMAND(ID_DIR_HIDE_FILENAMES, OnHideFilenames)
256         ON_COMMAND(ID_DIR_MOVE_LEFT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_LEFT>)
257         ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_LEFT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_LEFT>)
258         ON_COMMAND(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnCtxtDirMoveTo<SIDE_MIDDLE>)
259         ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_MIDDLE_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_MIDDLE>)
260         ON_COMMAND(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnCtxtDirMoveTo<SIDE_RIGHT>)
261         ON_UPDATE_COMMAND_UI(ID_DIR_MOVE_RIGHT_TO_BROWSE, OnUpdateCtxtDirMoveTo<SIDE_RIGHT>)
262         ON_UPDATE_COMMAND_UI(ID_DIR_HIDE_FILENAMES, OnUpdateHideFilenames)
263         ON_WM_SIZE()
264         ON_COMMAND(ID_MERGE_DELETE, OnDelete)
265         ON_UPDATE_COMMAND_UI(ID_MERGE_DELETE, OnUpdateDelete)
266         ON_COMMAND(ID_RESCAN, OnMarkedRescan)
267         ON_UPDATE_COMMAND_UI(ID_STATUS_DIFFNUM, OnUpdateStatusNum)
268         ON_COMMAND(ID_VIEW_SHOWHIDDENITEMS, OnViewShowHiddenItems)
269         ON_UPDATE_COMMAND_UI(ID_VIEW_SHOWHIDDENITEMS, OnUpdateViewShowHiddenItems)
270         ON_COMMAND(ID_MERGE_COMPARE, OnMergeCompare)
271         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE, OnUpdateMergeCompare)
272         ON_COMMAND(ID_MERGE_COMPARE_LEFT1_LEFT2, OnMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
273         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_LEFT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1LEFT2>)
274         ON_COMMAND(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
275         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_RIGHT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_RIGHT1RIGHT2>)
276         ON_COMMAND(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
277         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT1_RIGHT2, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT1RIGHT2>)
278         ON_COMMAND(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
279         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_LEFT2_RIGHT1, OnUpdateMergeCompare2<SELECTIONTYPE_LEFT2RIGHT1>)
280         ON_COMMAND(ID_MERGE_COMPARE_NONHORIZONTALLY, OnMergeCompareNonHorizontally)
281         ON_COMMAND(ID_MERGE_COMPARE_XML, OnMergeCompareXML)
282         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_XML, OnUpdateMergeCompare)
283         ON_COMMAND_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnMergeCompareAs)
284         ON_UPDATE_COMMAND_UI_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnUpdateMergeCompare)
285         ON_COMMAND(ID_VIEW_TREEMODE, OnViewTreeMode)
286         ON_UPDATE_COMMAND_UI(ID_VIEW_TREEMODE, OnUpdateViewTreeMode)
287         ON_COMMAND(ID_VIEW_EXPAND_ALLSUBDIRS, OnViewExpandAllSubdirs)
288         ON_UPDATE_COMMAND_UI(ID_VIEW_EXPAND_ALLSUBDIRS, OnUpdateViewExpandAllSubdirs)
289         ON_COMMAND(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnViewCollapseAllSubdirs)
290         ON_UPDATE_COMMAND_UI(ID_VIEW_COLLAPSE_ALLSUBDIRS, OnUpdateViewCollapseAllSubdirs)
291         ON_COMMAND(ID_SWAPPANES_SWAP12, (OnViewSwapPanes<0, 1>))
292         ON_COMMAND(ID_SWAPPANES_SWAP23, (OnViewSwapPanes<1, 2>))
293         ON_COMMAND(ID_SWAPPANES_SWAP13, (OnViewSwapPanes<0, 2>))
294         ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP12, (OnUpdateViewSwapPanes<0, 1>))
295         ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP23, (OnUpdateViewSwapPanes<1, 2>))
296         ON_UPDATE_COMMAND_UI(ID_SWAPPANES_SWAP13, (OnUpdateViewSwapPanes<0, 2>))
297         ON_COMMAND(ID_VIEW_DIR_STATISTICS, OnViewCompareStatistics)
298         ON_COMMAND(ID_OPTIONS_SHOWDIFFERENT, OnOptionsShowDifferent)
299         ON_COMMAND(ID_OPTIONS_SHOWIDENTICAL, OnOptionsShowIdentical)
300         ON_COMMAND(ID_OPTIONS_SHOWUNIQUELEFT, OnOptionsShowUniqueLeft)
301         ON_COMMAND(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnOptionsShowUniqueMiddle)
302         ON_COMMAND(ID_OPTIONS_SHOWUNIQUERIGHT, OnOptionsShowUniqueRight)
303         ON_COMMAND(ID_OPTIONS_SHOWBINARIES, OnOptionsShowBinaries)
304         ON_COMMAND(ID_OPTIONS_SHOWSKIPPED, OnOptionsShowSkipped)
305         ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnOptionsShowDifferentLeftOnly)
306         ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnOptionsShowDifferentMiddleOnly)
307         ON_COMMAND(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnOptionsShowDifferentRightOnly)
308         ON_COMMAND(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnOptionsShowMissingLeftOnly)
309         ON_COMMAND(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnOptionsShowMissingMiddleOnly)
310         ON_COMMAND(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnOptionsShowMissingRightOnly)
311         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENT, OnUpdateOptionsShowdifferent)
312         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWIDENTICAL, OnUpdateOptionsShowidentical)
313         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUELEFT, OnUpdateOptionsShowuniqueleft)
314         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUEMIDDLE, OnUpdateOptionsShowuniquemiddle)
315         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWUNIQUERIGHT, OnUpdateOptionsShowuniqueright)
316         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWBINARIES, OnUpdateOptionsShowBinaries)
317         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWSKIPPED, OnUpdateOptionsShowSkipped)
318         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTLEFTONLY, OnUpdateOptionsShowDifferentLeftOnly)
319         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTMIDDLEONLY, OnUpdateOptionsShowDifferentMiddleOnly)
320         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWDIFFERENTRIGHTONLY, OnUpdateOptionsShowDifferentRightOnly)
321         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGLEFTONLY, OnUpdateOptionsShowMissingLeftOnly)
322         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGMIDDLEONLY, OnUpdateOptionsShowMissingMiddleOnly)
323         ON_UPDATE_COMMAND_UI(ID_OPTIONS_SHOWMISSINGRIGHTONLY, OnUpdateOptionsShowMissingRightOnly)
324         ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
325         ON_COMMAND(ID_HELP, OnHelp)
326         ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
327         ON_COMMAND(ID_EDIT_CUT, OnEditCut)
328         ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
329         ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
330         ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
331         //}}AFX_MSG_MAP
332         ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
333         ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
334         ON_NOTIFY_REFLECT(LVN_BEGINLABELEDIT, OnBeginLabelEdit)
335         ON_NOTIFY_REFLECT(LVN_ENDLABELEDIT, OnEndLabelEdit)
336         ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
337         ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
338         ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
339         ON_BN_CLICKED(IDC_COMPARISON_STOP, OnBnClickedComparisonStop)
340         ON_BN_CLICKED(IDC_COMPARISON_PAUSE, OnBnClickedComparisonPause)
341         ON_BN_CLICKED(IDC_COMPARISON_CONTINUE, OnBnClickedComparisonContinue)
342 END_MESSAGE_MAP()
343
344 /////////////////////////////////////////////////////////////////////////////
345 // CDirView diagnostics
346
347 #ifdef _DEBUG
348
349 CDirDoc* CDirView::GetDocument() // non-debug version is inline
350 {
351         ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDirDoc)));
352         return (CDirDoc*)m_pDocument;
353 }
354 #endif //_DEBUG
355
356 /////////////////////////////////////////////////////////////////////////////
357 // CDirView message handlers
358
359 void CDirView::OnInitialUpdate()
360 {
361         const int iconCX = []() {
362                 const int cx = GetSystemMetrics(SM_CXSMICON);
363                 if (cx < 24)
364                         return 16;
365                 if (cx < 32)
366                         return 24;
367                 if (cx < 48)
368                         return 32;
369                 return 48;
370         }();
371         const int iconCY = iconCX;
372         CListView::OnInitialUpdate();
373         m_pList = &GetListCtrl();
374         m_pIList.reset(new IListCtrlImpl(m_pList->m_hWnd));
375         GetDocument()->SetDirView(this);
376         m_pColItems.reset(new DirViewColItems(GetDocument()->m_nDirs));
377
378         m_pList->SendMessage(CCM_SETUNICODEFORMAT, TRUE, 0);
379
380         // Load user-selected font
381         if (GetOptionsMgr()->GetBool(OPT_FONT_DIRCMP + OPT_FONT_USECUSTOM))
382         {
383                 m_font.CreateFontIndirect(&GetMainFrame()->m_lfDir);
384                 CWnd::SetFont(&m_font, TRUE);
385         }
386
387         if (m_bUseColors)
388                 m_pList->SetBkColor(m_cachedColors.clrDirMargin);
389
390         // Replace standard header with sort header
391         HWND hWnd = ListView_GetHeader(m_pList->m_hWnd);
392         if (hWnd != nullptr)
393                 m_ctlSortHeader.SubclassWindow(hWnd);
394
395         // Load the icons used for the list view (to reflect diff status)
396         // NOTE: these must be in the exactly the same order as in the `enum`
397         // definition in the DirActions.h file (ref: DIFFIMG_LUNIQUE)
398         VERIFY(m_imageList.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
399         int icon_ids[] = {
400                 IDI_LFILE, IDI_MFILE, IDI_RFILE,
401                 IDI_MRFILE, IDI_LRFILE, IDI_LMFILE,
402                 IDI_NOTEQUALFILE, IDI_EQUALFILE, IDI_FILE, 
403                 IDI_EQUALBINARY, IDI_BINARYDIFF,
404                 IDI_LFOLDER, IDI_MFOLDER, IDI_RFOLDER,
405                 IDI_MRFOLDER, IDI_LRFOLDER, IDI_LMFOLDER,
406                 IDI_FILESKIP, IDI_FOLDERSKIP,
407                 IDI_NOTEQUALFOLDER, IDI_EQUALFOLDER, IDI_FOLDER,
408                 IDI_COMPARE_ERROR,
409                 IDI_FOLDERUP, IDI_FOLDERUP_DISABLE,
410                 IDI_COMPARE_ABORTED,
411                 IDI_NOTEQUALTEXTFILE, IDI_EQUALTEXTFILE,
412                 IDI_NOTEQUALIMAGE, IDI_EQUALIMAGE, 
413         };
414         for (auto id : icon_ids)
415                 VERIFY(-1 != m_imageList.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
416         m_pList->SetImageList(&m_imageList, LVSIL_SMALL);
417
418         // Load the icons used for the list view (expanded/collapsed state icons)
419         VERIFY(m_imageState.Create(iconCX, iconCY, ILC_COLOR32 | ILC_MASK, 15, 1));
420         for (auto id : { IDI_TREE_STATE_COLLAPSED, IDI_TREE_STATE_EXPANDED })
421                 VERIFY(-1 != m_imageState.Add((HICON)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(id), IMAGE_ICON, iconCX, iconCY, 0)));
422
423         // Restore column orders as they had them last time they ran
424         m_pColItems->LoadColumnOrders(
425                 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS));
426
427         // Display column headers (in appropriate order)
428         ReloadColumns();
429
430         // Show selection across entire row.u
431         // Also allow user to rearrange columns via drag&drop of headers.
432         // Also enable infotips.
433         DWORD exstyle = LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_INFOTIP;
434         m_pList->SetExtendedStyle(exstyle);
435 }
436
437 BOOL CDirView::PreCreateWindow(CREATESTRUCT& cs)
438 {
439         CListView::PreCreateWindow(cs);
440         cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
441         return TRUE;
442 }
443
444 /**
445  * @brief Called before compare is started.
446  * CDirDoc calls this function before new compare is started, so this
447  * is good place to setup GUI for compare.
448  * @param [in] pCompareStats Pointer to class having current compare stats.
449  */
450 void CDirView::StartCompare(CompareStats *pCompareStats)
451 {
452         if (m_pCmpProgressBar == nullptr)
453                 m_pCmpProgressBar.reset(new DirCompProgressBar());
454
455         if (!::IsWindow(m_pCmpProgressBar->GetSafeHwnd()))
456                 m_pCmpProgressBar->Create(GetParentFrame());
457
458         m_pCmpProgressBar->SetCompareStat(pCompareStats);
459         m_pCmpProgressBar->StartUpdating();
460
461         GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), TRUE, FALSE);
462
463         m_compareStart = clock();
464 }
465
466 /**
467  * @brief Called when folder compare row is double-clicked with mouse.
468  * Selected item is opened to folder or file compare.
469  */
470 void CDirView::OnLButtonDblClk(UINT nFlags, CPoint point)
471 {
472         LVHITTESTINFO lvhti;
473         lvhti.pt = point;
474         m_pList->SubItemHitTest(&lvhti);
475         if (lvhti.iItem >= 0)
476         {
477                 const DIFFITEM& di = GetDiffItem(lvhti.iItem);
478                 if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
479                 {
480                         if (di.customFlags & ViewCustomFlags::EXPANDED)
481                                 CollapseSubdir(lvhti.iItem);
482                         else
483                                 ExpandSubdir(lvhti.iItem);
484                 }
485                 else
486                 {
487                         CWaitCursor waitstatus;
488                         OpenSelection();
489                 }
490         }
491         CListView::OnLButtonDblClk(nFlags, point);
492 }
493
494 /**
495  * @brief Load or reload the columns (headers) of the list view
496  */
497 void CDirView::ReloadColumns()
498 {
499         LoadColumnHeaderItems();
500
501         UpdateColumnNames();
502         m_pColItems->LoadColumnWidths(
503                 GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
504                 std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
505         SetColAlignments();
506 }
507
508 /**
509  * @brief Redisplay items in subfolder
510  * @param [in] diffpos First item position in subfolder.
511  * @param [in] level Indent level
512  * @param [in,out] index Index of the item to be inserted.
513  * @param [in,out] alldiffs Number of different items
514  */
515 void CDirView::RedisplayChildren(DIFFITEM *diffpos, int level, UINT &index, int &alldiffs)
516 {
517         const CDiffContext &ctxt = GetDiffContext();
518         while (diffpos != nullptr)
519         {
520                 DIFFITEM *curdiffpos = diffpos;
521                 const DIFFITEM &di = ctxt.GetNextSiblingDiffPosition(diffpos);
522
523                 if (di.diffcode.isResultDiff() || (!di.diffcode.existAll() && !di.diffcode.isResultFiltered()))
524                         ++alldiffs;
525
526                 bool bShowable = IsShowable(ctxt, di, m_dirfilter);
527                 if (bShowable)
528                 {
529                         if (m_bTreeMode)
530                         {
531                                 AddNewItem(index, curdiffpos, I_IMAGECALLBACK, level);
532                                 index++;
533                                 if (di.HasChildren())
534                                 {
535                                         m_pList->SetItemState(index - 1, INDEXTOSTATEIMAGEMASK((di.customFlags & ViewCustomFlags::EXPANDED) ? 2 : 1), LVIS_STATEIMAGEMASK);
536                                         if (di.customFlags & ViewCustomFlags::EXPANDED)
537                                                 RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
538                                 }
539                         }
540                         else
541                         {
542                                 if (!ctxt.m_bRecursive || !di.diffcode.isDirectory() || !di.diffcode.existAll())
543                                 {
544                                         AddNewItem(index, curdiffpos, I_IMAGECALLBACK, 0);
545                                         index++;
546                                 }
547                                 if (di.HasChildren())
548                                 {
549                                         RedisplayChildren(ctxt.GetFirstChildDiffPosition(curdiffpos), level + 1, index, alldiffs);
550                                 }
551                         }
552                 }
553         }
554         m_firstDiffItem.reset();
555         m_lastDiffItem.reset();
556 }
557
558 /**
559  * @brief Redisplay folder compare view.
560  * This function clears folder compare view and then adds
561  * items from current compare to it.
562  */
563 void CDirView::Redisplay()
564 {
565         const CDirDoc *pDoc = GetDocument();
566         const CDiffContext &ctxt = GetDiffContext();
567         PathContext pathsParent;
568         CImageList emptyImageList;
569
570         UINT cnt = 0;
571         // Disable redrawing while adding new items
572         SetRedraw(FALSE);
573
574         DeleteAllDisplayItems();
575
576         m_pList->SetImageList((m_bTreeMode && ctxt.m_bRecursive) ? &m_imageState : &emptyImageList, LVSIL_STATE);
577
578         // If non-recursive compare, add special item(s)
579         if (!ctxt.m_bRecursive ||
580                 CheckAllowUpwardDirectory(ctxt, pDoc->m_pTempPathContext, pathsParent) == AllowUpwardDirectory::ParentIsTempPath)
581         {
582                 cnt += AddSpecialItems();
583         }
584
585         int alldiffs = 0;
586         DIFFITEM *diffpos = ctxt.GetFirstDiffPosition();
587         RedisplayChildren(diffpos, 0, cnt, alldiffs);
588         if (pDoc->m_diffThread.GetThreadState() == CDiffThread::THREAD_COMPLETED)
589                 GetParentFrame()->SetLastCompareResult(alldiffs);
590         SortColumnsAppropriately();
591         SetRedraw(TRUE);
592 }
593
594 /**
595  * @brief User right-clicked somewhere in this view
596  */
597 void CDirView::OnContextMenu(CWnd*, CPoint point)
598 {
599         if (GetListCtrl().GetItemCount() == 0)
600                 return;
601         // Make sure window is active
602         GetParentFrame()->ActivateFrame();
603
604         int i = 0;
605         if (point.x == -1 && point.y == -1)
606         {
607                 //keystroke invocation
608                 CRect rect;
609                 GetClientRect(rect);
610                 ClientToScreen(rect);
611
612                 point = rect.TopLeft();
613                 point.Offset(5, 5);
614         }
615         else
616         {
617                 // Check if user right-clicked on header
618                 // convert screen coordinates to client coordinates of listview
619                 CPoint insidePt = point;
620                 GetListCtrl().ScreenToClient(&insidePt);
621                 // TODO: correct for hscroll ?
622                 // Ask header control if click was on one of its header items
623                 HDHITTESTINFO hhti = { 0 };
624                 hhti.pt = insidePt;
625                 int col = static_cast<int>(GetListCtrl().GetHeaderCtrl()->SendMessage(HDM_HITTEST, 0, (LPARAM) & hhti));
626                 if (col >= 0)
627                 {
628                         // Presumably hhti.flags & HHT_ONHEADER is true
629                         HeaderContextMenu(point, m_pColItems->ColPhysToLog(col));
630                         return;
631                 }
632                 // bail out if point is not in any row
633                 LVHITTESTINFO lhti = { 0 };
634                 insidePt = point;
635                 ScreenToClient(&insidePt);
636                 lhti.pt = insidePt;
637                 i = GetListCtrl().HitTest(insidePt);
638                 TRACE(_T("i=%d\n"), i);
639                 if (i < 0)
640                         return;
641         }
642
643         ListContextMenu(point, i);
644 }
645
646 /**
647  * @brief Format context menu string and disable item if it cannot be applied.
648  */
649 static void NTAPI FormatContextMenu(BCMenu *pPopup, UINT uIDItem, int n1, int n2 = 0, int n3 = 0)
650 {
651         CString s1, s2;
652         pPopup->GetMenuText(uIDItem, s1, MF_BYCOMMAND);
653         s2.FormatMessage(s1, NumToStr(n1).c_str(), NumToStr(n2).c_str(), NumToStr(n3).c_str());
654         pPopup->SetMenuText(uIDItem, s2, MF_BYCOMMAND);
655         if (n1 == 0)
656         {
657                 pPopup->EnableMenuItem(uIDItem, MF_GRAYED);
658         }
659 }
660
661 /**
662  * @brief Toggle context menu item
663  */
664 static void NTAPI CheckContextMenu(BCMenu *pPopup, UINT uIDItem, BOOL bCheck)
665 {
666         if (bCheck)
667                 pPopup->CheckMenuItem(uIDItem, MF_CHECKED);
668         else
669                 pPopup->CheckMenuItem(uIDItem, MF_UNCHECKED);
670 }
671
672 /**
673  * @brief User right-clicked in listview rows
674  */
675 void CDirView::ListContextMenu(CPoint point, int /*i*/)
676 {
677         CDirDoc* pDoc = GetDocument();
678         BCMenu menu;
679         VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
680         VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
681         theApp.TranslateMenu(menu.m_hMenu);
682
683         // 1st submenu of IDR_POPUP_DIRVIEW is for item popup
684         BCMenu *pPopup = static_cast<BCMenu*>(menu.GetSubMenu(0));
685         ASSERT(pPopup != nullptr);
686
687         if (pDoc->m_nDirs < 3)
688         {
689                 pPopup->RemoveMenu(ID_DIR_COPY_LEFT_TO_MIDDLE, MF_BYCOMMAND);
690                 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_LEFT, MF_BYCOMMAND);
691                 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_RIGHT, MF_BYCOMMAND);
692                 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
693                 pPopup->RemoveMenu(ID_DIR_COPY_RIGHT_TO_MIDDLE, MF_BYCOMMAND);
694                 pPopup->RemoveMenu(ID_DIR_MOVE_MIDDLE_TO_BROWSE, MF_BYCOMMAND);
695                 pPopup->RemoveMenu(ID_DIR_DEL_MIDDLE, MF_BYCOMMAND);
696                 pPopup->RemoveMenu(ID_DIR_DEL_ALL, MF_BYCOMMAND);
697                 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE, MF_BYCOMMAND);
698
699                 for (int i = 0; i < pPopup->GetMenuItemCount(); ++i)
700                 {
701                         if (pPopup->GetMenuItemID(i) == ID_DIR_HIDE_FILENAMES)
702                                 pPopup->RemoveMenu(i + 3, MF_BYPOSITION);
703                 }
704
705                 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITHEDITOR, MF_BYCOMMAND);
706                 pPopup->RemoveMenu(ID_DIR_OPEN_MIDDLE_WITH, MF_BYCOMMAND);
707                 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_MIDDLE, MF_BYCOMMAND);
708                 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_ALL, MF_BYCOMMAND);
709                 pPopup->RemoveMenu(ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, MF_BYCOMMAND);
710                 pPopup->RemoveMenu(ID_DIR_COPY_ALL_TO_CLIPBOARD, MF_BYCOMMAND);
711                 pPopup->RemoveMenu(ID_DIR_ZIP_MIDDLE, MF_BYCOMMAND);
712                 pPopup->RemoveMenu(ID_DIR_ZIP_ALL, MF_BYCOMMAND);
713                 pPopup->RemoveMenu(ID_DIR_SHELL_CONTEXT_MENU_MIDDLE, MF_BYCOMMAND);
714                 pPopup->RemoveMenu(ID_MERGE_COMPARE_NONHORIZONTALLY, MF_BYCOMMAND);
715         }
716         else
717         {
718                 pPopup->RemoveMenu(ID_DIR_COPY_PATHNAMES_BOTH, MF_BYCOMMAND);
719                 pPopup->RemoveMenu(ID_DIR_COPY_BOTH_TO_CLIPBOARD, MF_BYCOMMAND);
720                 pPopup->RemoveMenu(ID_DIR_ZIP_BOTH, MF_BYCOMMAND);
721                 pPopup->RemoveMenu(ID_DIR_DEL_BOTH, MF_BYCOMMAND);
722                 pPopup->RemoveMenu(2, MF_BYPOSITION); // Compare Non-horizontally
723         }
724
725         CMenu menuPluginsHolder;
726         menuPluginsHolder.LoadMenu(IDR_POPUP_PLUGINS_SETTINGS);
727         theApp.TranslateMenu(menuPluginsHolder.m_hMenu);
728         String s = _("Plugin Settings");
729         pPopup->AppendMenu(MF_SEPARATOR);
730         pPopup->AppendMenu(MF_POPUP, static_cast<int>(reinterpret_cast<uintptr_t>(menuPluginsHolder.m_hMenu)), s.c_str());
731
732         CFrameWnd *pFrame = GetTopLevelFrame();
733         ASSERT(pFrame != nullptr);
734         pFrame->m_bAutoMenuEnable = FALSE;
735         // invoke context menu
736         // this will invoke all the OnUpdate methods to enable/disable the individual items
737         pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
738                         AfxGetMainWnd());
739
740         pFrame->m_bAutoMenuEnable = TRUE;
741 }
742
743 /**
744  * @brief User right-clicked on specified logical column
745  */
746 void CDirView::HeaderContextMenu(CPoint point, int /*i*/)
747 {
748         BCMenu menu;
749         VERIFY(menu.LoadMenu(IDR_POPUP_DIRVIEW));
750         VERIFY(menu.LoadToolbar(IDR_MAINFRAME));
751         theApp.TranslateMenu(menu.m_hMenu);
752         // 2nd submenu of IDR_POPUP_DIRVIEW is for header popup
753         BCMenu* pPopup = static_cast<BCMenu *>(menu.GetSubMenu(1));
754         ASSERT(pPopup != nullptr);
755
756         // invoke context menu
757         // this will invoke all the OnUpdate methods to enable/disable the individual items
758         pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
759                         AfxGetMainWnd());
760 }
761
762 /**
763  * @brief Gets Explorer's context menu for a group of selected files.
764  *
765  * @param [in] Side whether to get context menu for the files from the left or
766  *   right side.
767  * @retval true menu successfully retrieved.
768  * @retval falsea an error occurred while retrieving the menu.
769  */
770 bool CDirView::ListShellContextMenu(SIDE_TYPE stype)
771 {
772         CShellContextMenu* shellContextMenu;
773         switch (stype) {
774         case SIDE_MIDDLE:
775                 shellContextMenu = m_pShellContextMenuMiddle.get(); break;
776         case SIDE_RIGHT:
777                 shellContextMenu = m_pShellContextMenuRight.get(); break;
778         default:
779                 shellContextMenu = m_pShellContextMenuLeft.get(); break;
780         }
781         shellContextMenu->Initialize();
782         ApplyFolderNameAndFileName(SelBegin(), SelEnd(), stype, GetDiffContext(),
783                 [&](const String& path, const String& filename) { shellContextMenu->AddItem(path, filename); });
784         return shellContextMenu->RequeryShellContextMenu();
785 }
786
787 /**
788  * @brief User chose (main menu) Copy from right to left
789  */
790 void CDirView::OnDirCopy(UINT id)
791 {
792         bool to_right = (id == ID_L2R) ? true : false;
793         if (GetDocument()->m_nDirs < 3)
794         {
795                 if (to_right)
796                         DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_RIGHT>, _("Copying files..."));
797                 else
798                         DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_LEFT>, _("Copying files..."));
799         }
800         else
801         {
802                 if (to_right)
803                 {
804                         switch (m_nActivePane)
805                         {
806                         case 0:
807                                 DoDirAction(&DirActions::Copy<SIDE_LEFT, SIDE_MIDDLE>, _("Copying files..."));
808                                 break;
809                         case 1:
810                         case 2:
811                                 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_RIGHT>, _("Copying files..."));
812                                 break;
813                         }
814                 }
815                 else
816                 {
817                         switch (m_nActivePane)
818                         {
819                         case 0:
820                         case 1:
821                                 DoDirAction(&DirActions::Copy<SIDE_MIDDLE, SIDE_LEFT>, _("Copying files..."));
822                                 break;
823                         case 2:
824                                 DoDirAction(&DirActions::Copy<SIDE_RIGHT, SIDE_MIDDLE>, _("Copying files..."));
825                                 break;
826                         }
827                 }
828         }
829 }
830
831 /// User chose (context men) Copy from right to left
832 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
833 void CDirView::OnCtxtDirCopy()
834 {
835         DoDirAction(&DirActions::Copy<srctype, dsttype>, _("Copying files..."));
836 }
837
838 /// User chose (context menu) Copy left to...
839 template<SIDE_TYPE stype>
840 void CDirView::OnCtxtDirCopyTo()
841 {
842         DoDirActionTo(stype, &DirActions::CopyTo<stype>, _("Copying files..."));
843 }
844
845 /// Update context menu Copy Right to Left item
846 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
847 void CDirView::OnUpdateCtxtDirCopy(CCmdUI* pCmdUI)
848 {
849         DoUpdateDirCopy<srctype, dsttype>(pCmdUI, eContext);
850 }
851
852 /// Update main menu Copy Right to Left item
853 void CDirView::OnUpdateDirCopy(CCmdUI* pCmdUI)
854 {
855         bool to_right = pCmdUI->m_nID == ID_L2R ? true : false;
856         if (GetDocument()->m_nDirs < 3)
857         {
858                 if (to_right)
859                         DoUpdateDirCopy<SIDE_LEFT, SIDE_RIGHT>(pCmdUI, eContext);
860                 else
861                         DoUpdateDirCopy<SIDE_RIGHT, SIDE_LEFT>(pCmdUI, eContext);
862         }
863         else
864         {
865                 if (to_right)
866                 {
867                         switch (m_nActivePane)
868                         {
869                         case 0:
870                                 DoUpdateDirCopy<SIDE_LEFT, SIDE_MIDDLE>(pCmdUI, eContext);
871                                 break;
872                         case 1:
873                         case 2:
874                                 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_RIGHT>(pCmdUI, eContext);
875                                 break;
876                         }
877                 }
878                 else
879                 {
880                         switch (m_nActivePane)
881                         {
882                         case 0:
883                         case 1:
884                                 DoUpdateDirCopy<SIDE_MIDDLE, SIDE_LEFT>(pCmdUI, eContext);
885                                 break;
886                         case 2:
887                                 DoUpdateDirCopy<SIDE_RIGHT, SIDE_MIDDLE>(pCmdUI, eContext);
888                                 break;
889                         }
890                 }
891         }
892 }
893
894 void CDirView::DoDirAction(DirActions::method_type func, const String& status_message)
895 {
896         CWaitCursor waitstatus;
897
898         try {
899                 // First we build a list of desired actions
900                 FileActionScript actionScript;
901                 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
902                 DirItemWithIndexIterator end;
903                 FileActionScript *rsltScript;
904                 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
905                 ASSERT(rsltScript == &actionScript);
906                 // Now we prompt, and execute actions
907                 ConfirmAndPerformActions(actionScript);
908         } catch (ContentsChangedException& e) {
909                 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
910         } catch (FileOperationException& e) {
911                 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
912         }
913 }
914
915 void CDirView::DoDirActionTo(SIDE_TYPE stype, DirActions::method_type func, const String& status_message)
916 {
917         String destPath;
918         String startPath(m_lastCopyFolder);
919         String selectfolder_title;
920
921         if (stype == SIDE_LEFT)
922                 selectfolder_title = _("Left side - select destination folder:");
923         else if (stype == SIDE_MIDDLE)
924                 selectfolder_title = _("Middle side - select destination folder:");
925         else if (stype == SIDE_RIGHT)
926                 selectfolder_title = _("Right side - select destination folder:");
927
928         if (!SelectFolder(destPath, startPath.c_str(), selectfolder_title))
929                 return;
930
931         m_lastCopyFolder = destPath;
932         CWaitCursor waitstatus;
933
934         try {
935                 // First we build a list of desired actions
936                 FileActionScript actionScript;
937                 actionScript.m_destBase = destPath;
938                 DirItemWithIndexIterator begin(m_pIList.get(), -1, true);
939                 DirItemWithIndexIterator end;
940                 FileActionScript *rsltScript;
941                 rsltScript = std::accumulate(begin, end, &actionScript, MakeDirActions(func));
942                 ASSERT(rsltScript == &actionScript);
943                 // Now we prompt, and execute actions
944                 ConfirmAndPerformActions(actionScript);
945         } catch (ContentsChangedException& e) {
946                 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
947         }
948 }
949
950 // Confirm with user, then perform the action list
951 void CDirView::ConfirmAndPerformActions(FileActionScript & actionList)
952 {
953         if (actionList.GetActionItemCount() == 0) // Not sure it is possible to get right-click menu without
954                 return;    // any selected items, but may as well be safe
955
956         ASSERT(actionList.GetActionItemCount()>0); // Or else the update handler got it wrong
957
958         // Set parent window so modality is correct and correct window gets focus
959         // after dialogs.
960         actionList.SetParentWindow(this->GetSafeHwnd());
961         
962         try {
963                 ConfirmActionList(GetDiffContext(), actionList);
964         } catch (ConfirmationNeededException& e) {
965                 ConfirmFolderCopyDlg dlg;
966                 dlg.m_caption = e.m_caption;
967                 dlg.m_question = e.m_question;
968                 dlg.m_fromText = e.m_fromText;
969                 dlg.m_toText = e.m_toText;
970                 dlg.m_fromPath = e.m_fromPath;
971                 dlg.m_toPath = e.m_toPath;
972                 INT_PTR ans = dlg.DoModal();
973                 if (ans != IDOK && ans != IDYES)
974                         return;
975         }
976         PerformActionList(actionList);
977 }
978
979 /**
980  * @brief Perform an array of actions
981  * @note There can be only COPY or DELETE actions, not both!
982  */
983 void CDirView::PerformActionList(FileActionScript & actionScript)
984 {
985         // Check option and enable putting deleted items to Recycle Bin
986         if (GetOptionsMgr()->GetBool(OPT_USE_RECYCLE_BIN))
987                 actionScript.UseRecycleBin(true);
988         else
989                 actionScript.UseRecycleBin(false);
990
991         actionScript.SetParentWindow(GetMainFrame()->GetSafeHwnd());
992
993         theApp.AddOperation();
994         bool succeeded = actionScript.Run();
995         if (succeeded)
996                 UpdateAfterFileScript(actionScript);
997         theApp.RemoveOperation();
998         if (!succeeded && !actionScript.IsCanceled())
999                 throw FileOperationException(_T("File operation failed"));
1000 }
1001
1002 /**
1003  * @brief Update results after running FileActionScript.
1004  * This functions is called after script is finished to update
1005  * results (including UI).
1006  * @param [in] actionlist Script that was run.
1007  */
1008 void CDirView::UpdateAfterFileScript(FileActionScript & actionList)
1009 {
1010         bool bItemsRemoved = false;
1011         int curSel = GetFirstSelectedInd();
1012         CDiffContext& ctxt = GetDiffContext();
1013         while (actionList.GetActionItemCount()>0)
1014         {
1015                 // Start handling from tail of list, so removing items
1016                 // doesn't invalidate our item indexes.
1017                 FileActionItem act = actionList.RemoveTailActionItem();
1018
1019                 // Update doc (difflist)
1020                 UPDATEITEM_TYPE updatetype = UpdateDiffAfterOperation(act, ctxt, GetDiffItem(act.context));
1021                 if (updatetype == UPDATEITEM_REMOVE)
1022                 {
1023                         DeleteItem(act.context, true);
1024                         bItemsRemoved = true;
1025                 }
1026                 else if (updatetype == UPDATEITEM_UPDATE)
1027                         UpdateDiffItemStatus(act.context);
1028         }
1029         
1030         // Make sure selection is at sensible place if all selected items
1031         // were removed.
1032         if (bItemsRemoved)
1033         {
1034                 UINT selected = GetSelectedCount();
1035                 if (selected == 0)
1036                 {
1037                         if (curSel < 1)
1038                                 ++curSel;
1039                         MoveFocus(0, curSel - 1, selected);
1040                 }
1041         }
1042 }
1043
1044 Counts CDirView::Count(DirActions::method_type2 func) const
1045 {
1046         return ::Count(SelBegin(), SelEnd(), MakeDirActions(func));
1047 }
1048
1049 /// Should Copy to Left be enabled or disabled ? (both main menu & context menu use this)
1050 template<SIDE_TYPE srctype, SIDE_TYPE dsttype>
1051 void CDirView::DoUpdateDirCopy(CCmdUI* pCmdUI, eMenuType menuType)
1052 {
1053         Counts counts = Count(&DirActions::IsItemCopyableOnTo<srctype, dsttype>);
1054         pCmdUI->Enable(counts.count > 0);
1055         if (menuType == eContext)
1056                 pCmdUI->SetText(FormatMenuItemString(srctype, dsttype, counts.count, counts.total).c_str());
1057 }
1058
1059 /**
1060  * @brief Update any resources necessary after a GUI language change
1061  */
1062 void CDirView::UpdateResources()
1063 {
1064         UpdateColumnNames();
1065         GetParentFrame()->UpdateResources();
1066 }
1067
1068 /**
1069  * @brief User just clicked a column, so perform sort
1070  */
1071 void CDirView::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
1072 {
1073         // set sort parameters and handle ascending/descending
1074         NM_LISTVIEW* pNMListView = (NM_LISTVIEW*) pNMHDR;
1075         int oldSortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1076         int sortcol = m_pColItems->ColPhysToLog(pNMListView->iSubItem);
1077         if (sortcol == oldSortColumn)
1078         {
1079                 // Swap direction
1080                 bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1081                 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, !bSortAscending);
1082         }
1083         else
1084         {
1085                 GetOptionsMgr()->SaveOption((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3, sortcol);
1086                 // most columns start off ascending, but not dates
1087                 bool bSortAscending = m_pColItems->IsDefaultSortAscending(sortcol);
1088                 GetOptionsMgr()->SaveOption(OPT_DIRVIEW_SORT_ASCENDING, bSortAscending);
1089         }
1090
1091         SortColumnsAppropriately();
1092         *pResult = 0;
1093 }
1094
1095 void CDirView::SortColumnsAppropriately()
1096 {
1097         int sortCol = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
1098         if (sortCol == -1 || sortCol >= m_pColItems->GetColCount())
1099                 return;
1100
1101         bool bSortAscending = GetOptionsMgr()->GetBool(OPT_DIRVIEW_SORT_ASCENDING);
1102         m_ctlSortHeader.SetSortImage(m_pColItems->ColLogToPhys(sortCol), bSortAscending);
1103         //sort using static CompareFunc comparison function
1104         CompareState cs(&GetDiffContext(), m_pColItems.get(), sortCol, bSortAscending, m_bTreeMode);
1105         GetListCtrl().SortItems(cs.CompareFunc, reinterpret_cast<DWORD_PTR>(&cs));
1106
1107         m_firstDiffItem.reset();
1108         m_lastDiffItem.reset();
1109 }
1110
1111 /// Do any last minute work as view closes
1112 void CDirView::OnDestroy()
1113 {
1114         DeleteAllDisplayItems();
1115
1116         {
1117                 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
1118                 GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
1119         }
1120         {
1121                 const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
1122                 GetOptionsMgr()->SaveOption(keyname,
1123                         m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)));
1124         }
1125
1126         CListView::OnDestroy();
1127
1128         GetMainFrame()->ClearStatusbarItemCount();
1129 }
1130
1131 /**
1132  * @brief Open selected item when user presses ENTER key.
1133  */
1134 void CDirView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
1135 {
1136         if (nChar == VK_RETURN)
1137         {
1138                 int sel = GetFocusedItem();
1139                 if (sel >= 0)
1140                 {
1141                         const DIFFITEM& di = GetDiffItem(sel);
1142                         if (m_bTreeMode && GetDiffContext().m_bRecursive && di.diffcode.isDirectory())
1143                         {
1144                                 if (di.customFlags & ViewCustomFlags::EXPANDED)
1145                                         CollapseSubdir(sel);
1146                                 else
1147                                         ExpandSubdir(sel);
1148                         }
1149                         else
1150                         {
1151                                 CWaitCursor waitstatus;
1152                                 OpenSelection();
1153                         }
1154                 }
1155         }
1156         CListView::OnChar(nChar, nRepCnt, nFlags);
1157 }
1158
1159 /**
1160  * @brief Expand/collapse subfolder when "+/-" icon is clicked.
1161  */
1162 void CDirView::OnClick(NMHDR* pNMHDR, LRESULT* pResult)
1163 {
1164         LPNMITEMACTIVATE pNM = (LPNMITEMACTIVATE)pNMHDR;
1165         LVHITTESTINFO lvhti;
1166         lvhti.pt = pNM->ptAction;
1167         m_pList->SubItemHitTest(&lvhti);
1168         if (lvhti.flags == LVHT_ONITEMSTATEICON)
1169         {
1170                 const DIFFITEM &di = GetDiffItem(pNM->iItem);
1171                 if (di.customFlags & ViewCustomFlags::EXPANDED)
1172                         CollapseSubdir(pNM->iItem);
1173                 else
1174                         ExpandSubdir(pNM->iItem);
1175         }
1176
1177         *pResult = 0;
1178 }
1179
1180 /**
1181  * @brief Collapse subfolder
1182  * @param [in] sel Folder item index in listview.
1183  */
1184 void CDirView::CollapseSubdir(int sel)
1185 {
1186         DIFFITEM& dip = this->GetDiffItem(sel);
1187         if (!m_bTreeMode || !(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1188                 return;
1189
1190         m_pList->SetRedraw(FALSE);      // Turn off updating (better performance)
1191
1192         dip.customFlags &= ~ViewCustomFlags::EXPANDED;
1193         m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(1), LVIS_STATEIMAGEMASK);
1194
1195         int count = m_pList->GetItemCount();
1196         for (int i = sel + 1; i < count; i++)
1197         {
1198                 const DIFFITEM& di = GetDiffItem(i);
1199                 if (!di.IsAncestor(&dip))
1200                         break;
1201                 m_pList->DeleteItem(i--);
1202                 count--;
1203         }
1204
1205         m_pList->SetRedraw(TRUE);       // Turn updating back on
1206 }
1207
1208 /**
1209  * @brief Expand subfolder
1210  * @param [in] sel Folder item index in listview.
1211  */
1212 void CDirView::ExpandSubdir(int sel, bool bRecursive)
1213 {
1214         DIFFITEM& dip = GetDiffItem(sel);
1215         if (!m_bTreeMode || (dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren())
1216                 return;
1217
1218         m_pList->SetRedraw(FALSE);      // Turn off updating (better performance)
1219         m_pList->SetItemState(sel, INDEXTOSTATEIMAGEMASK(2), LVIS_STATEIMAGEMASK);
1220
1221         CDiffContext &ctxt = GetDiffContext();
1222         dip.customFlags |= ViewCustomFlags::EXPANDED;
1223         if (bRecursive)
1224                 ExpandSubdirs(ctxt, dip);
1225
1226         DIFFITEM *diffpos = ctxt.GetFirstChildDiffPosition(GetItemKey(sel));
1227         UINT indext = sel + 1;
1228         int alldiffs;
1229         RedisplayChildren(diffpos, dip.GetDepth() + 1, indext, alldiffs);
1230
1231         SortColumnsAppropriately();
1232
1233         m_pList->SetRedraw(TRUE);       // Turn updating back on
1234 }
1235
1236 /**
1237  * @brief Open parent folder if possible.
1238  */
1239 void CDirView::OpenParentDirectory()
1240 {
1241         CDirDoc *pDoc = GetDocument();
1242         PathContext pathsParent;
1243         switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
1244         {
1245         case AllowUpwardDirectory::ParentIsTempPath:
1246                 pDoc->m_pTempPathContext = pDoc->m_pTempPathContext->DeleteHead();
1247                 [[fallthrough]];
1248         case AllowUpwardDirectory::ParentIsRegularPath: 
1249                 DWORD dwFlags[3];
1250                 for (int nIndex = 0; nIndex < pathsParent.GetSize(); ++nIndex)
1251                         dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nIndex) ? FFILEOPEN_READONLY : 0);
1252                 GetMainFrame()->DoFileOpen(&pathsParent, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1253                 [[fallthrough]];
1254         case AllowUpwardDirectory::No:
1255                 break;
1256         default:
1257                 LangMessageBox(IDS_INVALID_DIRECTORY, MB_ICONSTOP);
1258                 break;
1259         }
1260 }
1261
1262 /**
1263  * @brief Get one or two selected items
1264  *
1265  * Returns false if 0 or more than 3 items selecte
1266  */
1267 bool CDirView::GetSelectedItems(int * sel1, int * sel2, int * sel3)
1268 {
1269         *sel2 = -1;
1270         *sel3 = -1;
1271         *sel1 = m_pList->GetNextItem(-1, LVNI_SELECTED);
1272         if (*sel1 == -1)
1273                 return false;
1274         *sel2 = m_pList->GetNextItem(*sel1, LVNI_SELECTED);
1275         if (*sel2 == -1)
1276                 return true;
1277         *sel3 = m_pList->GetNextItem(*sel2, LVNI_SELECTED);
1278         if (*sel3 == -1)
1279                 return true;
1280         int extra = m_pList->GetNextItem(*sel3, LVNI_SELECTED);
1281         return (extra == -1);
1282 }
1283
1284 /**
1285  * @brief Open special items (parent folders etc).
1286  * @param [in] pos1 First item position.
1287  * @param [in] pos2 Second item position.
1288  */
1289 void CDirView::OpenSpecialItems(DIFFITEM *pos1, DIFFITEM *pos2, DIFFITEM *pos3)
1290 {
1291         if (pos2==nullptr && pos3==nullptr)
1292         {
1293                 // Browse to parent folder(s) selected
1294                 // SPECIAL_ITEM_POS is position for
1295                 // special items, but there is currenly
1296                 // only one (parent folder)
1297                 OpenParentDirectory();
1298         }
1299         else
1300         {
1301                 // Parent directory & something else selected
1302                 // Not valid action
1303         }
1304 }
1305
1306 /**
1307  * @brief Creates a pairing folder for unique folder item.
1308  * This function creates a pairing folder for unique folder item in
1309  * folder compare. This way user can browse into unique folder's
1310  * contents and don't necessarily need to copy whole folder structure.
1311  * @return true if user agreed and folder was created.
1312  */
1313 static bool CreateFoldersPair(const PathContext& paths)
1314 {
1315         bool created = false;
1316         for (const auto& path : paths)
1317         {
1318                 if (!paths::DoesPathExist(path))
1319                 {
1320                         String message =
1321                                 strutils::format_string1( 
1322                                         _("The folder exists only in other side and cannot be opened.\n\nDo you want to create a matching folder:\n%1\nto the other side and open these folders?"),
1323                                         path);
1324                         int res = AfxMessageBox(message.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN);
1325                         if (res == IDYES)
1326                                 created = paths::CreateIfNeeded(path);
1327                 }
1328         }
1329         return created;
1330 }
1331
1332 void CDirView::Open(const PathContext& paths, DWORD dwFlags[3], PackingInfo * infoUnpacker)
1333 {
1334         bool isdir = false;
1335         for (auto path : paths)
1336         {
1337                 if (paths::DoesPathExist(path) == paths::IS_EXISTING_DIR)
1338                         isdir = true;
1339         }
1340         CDirDoc * pDoc = GetDocument();
1341         if (isdir)
1342         {
1343                 // Open subfolders
1344                 // Don't add folders to MRU
1345                 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, (GetAsyncKeyState(VK_CONTROL) & 0x8000) ? nullptr : pDoc);
1346         }
1347         else if (HasZipSupport() && std::count_if(paths.begin(), paths.end(), ArchiveGuessFormat) == paths.GetSize())
1348         {
1349                 // Open archives, not adding paths to MRU
1350                 GetMainFrame()->DoFileOpen(&paths, dwFlags, nullptr, _T(""), GetDiffContext().m_bRecursive, nullptr, _T(""), infoUnpacker);
1351         }
1352         else
1353         {
1354                 // Regular file case
1355
1356                 // Binary attributes are set after files are unpacked
1357                 // so after plugins such as the MS-Office plugins have had a chance to make them textual
1358                 // We haven't done unpacking yet in this diff, but if a binary flag is already set,
1359                 // then it was set in a previous diff after unpacking, so we trust it
1360
1361                 // Open identical and different files
1362                 FileLocation fileloc[3];
1363                 String strDesc[3];
1364                 const String sUntitled[] = { _("Untitled left"), paths.GetSize() < 3 ? _("Untitled right") : _("Untitled middle"), _("Untitled right") };
1365                 for (int i = 0; i < paths.GetSize(); ++i)
1366                 {
1367                         if (paths::DoesPathExist(paths[i]) == paths::DOES_NOT_EXIST)
1368                                 strDesc[i] = sUntitled[i];
1369                         else
1370                                 fileloc[i].setPath(paths[i]);
1371                 }
1372
1373                 GetMainFrame()->ShowAutoMergeDoc(pDoc, paths.GetSize(), fileloc,
1374                         dwFlags, strDesc, _T(""), infoUnpacker);
1375         }
1376 }
1377
1378 /**
1379  * @brief Open selected files or directories.
1380  *
1381  * Opens selected files to file compare. If comparing
1382  * directories non-recursively, then subfolders and parent
1383  * folder are opened too.
1384  *
1385  * This handles the case that one item is selected
1386  * and the case that two items are selected (one on each side)
1387  */
1388 void CDirView::OpenSelection(SELECTIONTYPE selectionType /*= SELECTIONTYPE_NORMAL*/, PackingInfo * infoUnpacker /*= nullptr*/, bool openableForDir /*= true*/)
1389 {
1390         Merge7zFormatMergePluginScope scope(infoUnpacker);
1391         CDirDoc * pDoc = GetDocument();
1392         const CDiffContext& ctxt = GetDiffContext();
1393
1394         // First, figure out what was selected (store into pos1 & pos2)
1395         DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1396         int sel1 = -1, sel2 = -1, sel3 = -1;
1397         if (!GetSelectedItems(&sel1, &sel2, &sel3))
1398         {
1399                 // Must have 1 or 2 or 3 items selected
1400                 // Not valid action
1401                 return;
1402         }
1403
1404         pos1 = GetItemKey(sel1);
1405         ASSERT(pos1 != nullptr);
1406         if (sel2 != -1)
1407         {
1408                 pos2 = GetItemKey(sel2);
1409                 ASSERT(pos2 != nullptr);
1410                 if (sel3 != -1)
1411                         pos3 = GetItemKey(sel3);
1412         }
1413
1414         // Now handle the various cases of what was selected
1415
1416         if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1417         {
1418                 OpenSpecialItems(pos1, pos2, pos3);
1419                 return;
1420         }
1421
1422         // Common variables which both code paths below are responsible for setting
1423         PathContext paths;
1424         const DIFFITEM *pdi[3] = {0}; // left & right items (di1==di2 if single selection)
1425         bool isdir = false; // set if we're comparing directories
1426         int nPane[3];
1427         String errmsg;
1428         bool success;
1429         if (pos2 && !pos3)
1430                 success = GetOpenTwoItems(ctxt, selectionType, pos1, pos2, pdi,
1431                                 paths, sel1, sel2, isdir, nPane, errmsg, openableForDir);
1432         else if (pos2 && pos3)
1433                 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1434                                 paths, sel1, sel2, sel3, isdir, nPane, errmsg, openableForDir);
1435         else
1436         {
1437                 // Only one item selected, so perform diff on its sides
1438                 success = GetOpenOneItem(ctxt, pos1, pdi, 
1439                                 paths, sel1, isdir, nPane, errmsg, openableForDir);
1440                 if (isdir)
1441                         CreateFoldersPair(paths);
1442         }
1443         if (!success)
1444         {
1445                 if (!errmsg.empty())
1446                         AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1447                 return;
1448         }
1449
1450         // Now pathLeft, pathRight, di1, di2, and isdir are all set
1451         // We have two items to compare, no matter whether same or different underlying DirView item
1452
1453         DWORD dwFlags[3];
1454         for (int nIndex = 0; nIndex < paths.GetSize(); nIndex++)
1455                 dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[nIndex]) ? FFILEOPEN_READONLY : 0);
1456
1457         Open(paths, dwFlags, infoUnpacker);
1458 }
1459
1460 void CDirView::OpenSelectionAs(UINT id)
1461 {
1462         CDirDoc * pDoc = GetDocument();
1463         const CDiffContext& ctxt = GetDiffContext();
1464
1465         // First, figure out what was selected (store into pos1 & pos2 & pos3)
1466         DIFFITEM *pos1 = nullptr, *pos2 = nullptr, *pos3 = nullptr;
1467         int sel1 = -1, sel2 = -1, sel3 = -1;
1468         if (!GetSelectedItems(&sel1, &sel2, &sel3))
1469         {
1470                 // Must have 1 or 2 or 3 items selected
1471                 // Not valid action
1472                 return;
1473         }
1474
1475         pos1 = GetItemKey(sel1);
1476         ASSERT(pos1);
1477         if (sel2 != -1)
1478         {
1479                 pos2 = GetItemKey(sel2);
1480                 ASSERT(pos2 != nullptr);
1481                 if (sel3 != -1)
1482                         pos3 = GetItemKey(sel3);
1483         }
1484
1485         // Now handle the various cases of what was selected
1486
1487         if (pos1 == (DIFFITEM *)SPECIAL_ITEM_POS)
1488         {
1489                 ASSERT(false);
1490                 return;
1491         }
1492
1493         // Common variables which both code paths below are responsible for setting
1494         PathContext paths;
1495         const DIFFITEM *pdi[3]; // left & right items (di1==di2 if single selection)
1496         bool isdir = false; // set if we're comparing directories
1497         int nPane[3];
1498         String errmsg;
1499         bool success;
1500         if (pos2 && !pos3)
1501                 success = GetOpenTwoItems(ctxt, SELECTIONTYPE_NORMAL, pos1, pos2, pdi,
1502                                 paths, sel1, sel2, isdir, nPane, errmsg, false);
1503         else if (pos2 && pos3)
1504                 success = GetOpenThreeItems(ctxt, pos1, pos2, pos3, pdi,
1505                                 paths, sel1, sel2, sel3, isdir, nPane, errmsg, false);
1506         else
1507         {
1508                 // Only one item selected, so perform diff on its sides
1509                 success = GetOpenOneItem(ctxt, pos1, pdi,
1510                                 paths, sel1, isdir, nPane, errmsg, false);
1511         }
1512         if (!success)
1513         {
1514                 if (!errmsg.empty())
1515                         AfxMessageBox(errmsg.c_str(), MB_ICONSTOP);
1516                 return;
1517         }
1518
1519         // Open identical and different files
1520         DWORD dwFlags[3] = { 0 };
1521         FileLocation fileloc[3];
1522         for (int pane = 0; pane < paths.GetSize(); pane++)
1523         {
1524                 fileloc[pane].setPath(paths[pane]);
1525                 dwFlags[pane] |= FFILEOPEN_NOMRU | (pDoc->GetReadOnly(nPane[pane]) ? FFILEOPEN_READONLY : 0);
1526         }
1527         if (id == ID_MERGE_COMPARE_HEX)
1528                 GetMainFrame()->ShowHexMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1529         else
1530                 GetMainFrame()->ShowImgMergeDoc(pDoc, paths.GetSize(), fileloc, dwFlags, nullptr);
1531 }
1532
1533 /// User chose (context menu) delete left
1534 template<SIDE_TYPE stype>
1535 void CDirView::OnCtxtDirDel()
1536 {
1537         DoDirAction(&DirActions::DeleteOn<stype>, _("Deleting files..."));
1538 }
1539
1540 /// User chose (context menu) delete both
1541 void CDirView::OnCtxtDirDelBoth()
1542 {
1543         DoDirAction(&DirActions::DeleteOnBoth, _("Deleting files..."));
1544 }
1545
1546 /// Enable/disable Delete Left menu choice on context menu
1547 template<SIDE_TYPE stype>
1548 void CDirView::OnUpdateCtxtDirDel(CCmdUI* pCmdUI)
1549 {
1550         Counts counts = Count(&DirActions::IsItemDeletableOn<stype>);
1551         pCmdUI->Enable(counts.count > 0);
1552         pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1553 }
1554
1555 /// Enable/disable Delete Both menu choice on context menu
1556 void CDirView::OnUpdateCtxtDirDelBoth(CCmdUI* pCmdUI)
1557 {
1558         Counts counts = Count(&DirActions::IsItemDeletableOnBoth);
1559         pCmdUI->Enable(counts.count > 0);
1560         pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1561 }
1562
1563 /**
1564  * @brief Update "Copy | Right to..." item
1565  */
1566 template<SIDE_TYPE stype>
1567 void CDirView::OnUpdateCtxtDirCopyTo(CCmdUI* pCmdUI)
1568 {
1569         Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1570         pCmdUI->Enable(counts.count > 0);
1571         pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
1572 }
1573
1574 void CDirView::OnUpdateCtxtDirCopyBothTo(CCmdUI* pCmdUI)
1575 {
1576         Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1577         pCmdUI->Enable(counts.count > 0);
1578         pCmdUI->SetText(FormatMenuItemStringAllTo(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1579 }
1580
1581 void CDirView::OnUpdateCtxtDirCopyBothDiffsOnlyTo(CCmdUI* pCmdUI)
1582 {
1583         Counts counts = Count(&DirActions::IsItemNavigableDiff);
1584         pCmdUI->Enable(counts.count > 0);
1585         pCmdUI->SetText(FormatMenuItemStringDifferencesTo(counts.count, counts.total).c_str());
1586 }
1587         
1588 /**
1589  * @brief Update "Copy | Left/Right/Both " item
1590  */
1591 template<SIDE_TYPE stype>
1592 void CDirView::OnUpdateCtxtDirCopy2(CCmdUI* pCmdUI)
1593 {
1594         Counts counts = Count(&DirActions::IsItemCopyableToOn<stype>);
1595         pCmdUI->Enable(counts.count > 0);
1596         pCmdUI->SetText(FormatMenuItemString(stype, counts.count, counts.total).c_str());
1597 }
1598
1599 void CDirView::OnUpdateCtxtDirCopyBoth2(CCmdUI* pCmdUI)
1600 {
1601         Counts counts = Count(&DirActions::IsItemCopyableBothToOn);
1602         pCmdUI->Enable(counts.count > 0);
1603         pCmdUI->SetText(FormatMenuItemStringAll(GetDocument()->m_nDirs, counts.count, counts.total).c_str());
1604 }
1605
1606 /**
1607  * @brief Get keydata associated with item in given index.
1608  * @param [in] idx Item's index to list in UI.
1609  * @return Key for item in given index.
1610  */
1611 DIFFITEM *CDirView::GetItemKey(int idx) const
1612 {
1613         return (DIFFITEM *) m_pList->GetItemData(idx);
1614 }
1615
1616 // SetItemKey & GetItemKey encapsulate how the display list items
1617 // are mapped to DiffItems, which in turn are DiffContext keys to the actual DIFFITEM data
1618
1619 /**
1620  * @brief Get DIFFITEM data for item.
1621  * This function returns DIFFITEM data for item in given index in GUI.
1622  * @param [in] sel Item's index in folder compare GUI list.
1623  * @return DIFFITEM for item.
1624  */
1625 const DIFFITEM &CDirView::GetDiffItem(int sel) const
1626 {
1627         CDirView * pDirView = const_cast<CDirView *>(this);
1628         return pDirView->GetDiffItem(sel);
1629 }
1630
1631 /**
1632  * Given index in list control, get modifiable reference to its DIFFITEM data
1633  */
1634 DIFFITEM &CDirView::GetDiffItem(int sel)
1635 {
1636         DIFFITEM *diffpos = GetItemKey(sel);
1637
1638         // If it is special item, return empty DIFFITEM
1639         if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1640         {
1641                 return *DIFFITEM::GetEmptyItem();
1642         }
1643         return GetDiffContext().GetDiffRefAt(diffpos);
1644 }
1645
1646 void CDirView::DeleteItem(int sel, bool removeDIFFITEM)
1647 {
1648         DIFFITEM *diffpos = GetItemKey(sel);
1649         if (diffpos == (DIFFITEM*)SPECIAL_ITEM_POS)
1650                 return;
1651         if (m_bTreeMode)
1652         {
1653                 CollapseSubdir(sel);
1654                 m_pList->DeleteItem(sel);
1655         }
1656         else if (GetDiffContext().m_bRecursive || diffpos->HasChildren())
1657         {
1658                 DirItemIterator it;
1659                 for (it = RevBegin(); it != RevEnd(); )
1660                 {
1661                         DIFFITEM& di = *it;
1662                         int cursel = it.m_sel;
1663                         ++it;
1664                         if (di.IsAncestor(diffpos) || diffpos == &di)
1665                                 m_pList->DeleteItem(cursel);
1666                 }
1667         }
1668         else
1669         {
1670                 m_pList->DeleteItem(sel);
1671         }
1672         if (removeDIFFITEM)
1673         {
1674                 if (diffpos->HasChildren())
1675                         diffpos->RemoveChildren();
1676                 diffpos->DelinkFromSiblings();
1677                 delete diffpos;
1678         }
1679
1680         m_firstDiffItem.reset();
1681         m_lastDiffItem.reset();
1682 }
1683
1684 void CDirView::DeleteAllDisplayItems()
1685 {
1686         // item data are just positions (diffposes)
1687         // that is, they contain no memory needing to be freed
1688         m_pList->DeleteAllItems();
1689
1690         m_firstDiffItem.reset();
1691         m_lastDiffItem.reset();
1692 }
1693
1694 /**
1695  * @brief Given key, get index of item which has it stored.
1696  * This function searches from list in UI.
1697  */
1698 int CDirView::GetItemIndex(DIFFITEM *key)
1699 {
1700         LVFINDINFO findInfo;
1701
1702         findInfo.flags = LVFI_PARAM;  // Search for itemdata
1703         findInfo.lParam = (LPARAM)key;
1704         return m_pList->FindItem(&findInfo);
1705 }
1706
1707 /**
1708  * @brief Get the file names on both sides for specified item.
1709  * @note Return empty strings if item is special item.
1710  */
1711 void CDirView::GetItemFileNames(int sel, String& strLeft, String& strRight) const
1712 {
1713         DIFFITEM *diffpos = GetItemKey(sel);
1714         if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1715         {
1716                 strLeft.erase();
1717                 strRight.erase();
1718         }
1719         else
1720         {
1721                 const CDiffContext& ctxt = GetDiffContext();
1722                 ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos), strLeft, strRight);
1723         }
1724 }
1725
1726 /**
1727  * @brief Get the file names on both sides for specified item.
1728  * @note Return empty strings if item is special item.
1729  */
1730 void CDirView::GetItemFileNames(int sel, PathContext * paths) const
1731 {
1732         DIFFITEM *diffpos = GetItemKey(sel);
1733         if (diffpos == (DIFFITEM *)SPECIAL_ITEM_POS)
1734         {
1735                 for (int nIndex = 0; nIndex < GetDocument()->m_nDirs; nIndex++)
1736                         paths->SetPath(nIndex, _T(""));
1737         }
1738         else
1739         {
1740                 const CDiffContext& ctxt = GetDiffContext();
1741                 *paths = ::GetItemFileNames(ctxt, ctxt.GetDiffAt(diffpos));
1742         }
1743 }
1744
1745 /**
1746  * @brief Open selected file with registered application.
1747  * Uses shell file associations to open file with registered
1748  * application. We first try to use "Edit" action which should
1749  * open file to editor, since we are more interested editing
1750  * files than running them (scripts).
1751  * @param [in] stype Side of file to open.
1752  */
1753 void CDirView::DoOpen(SIDE_TYPE stype)
1754 {
1755         int sel = GetSingleSelectedItem();
1756         if (sel == -1) return;
1757         DirItemIterator dirBegin = SelBegin();
1758         String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1759         if (file.empty()) return;
1760         HINSTANCE rtn = ShellExecute(::GetDesktopWindow(), _T("edit"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1761         if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1762                 rtn = ShellExecute(::GetDesktopWindow(), _T("open"), file.c_str(), 0, 0, SW_SHOWNORMAL);
1763         if (reinterpret_cast<uintptr_t>(rtn) == SE_ERR_NOASSOC)
1764                 DoOpenWith(stype);
1765 }
1766
1767 /// Open with dialog for file on selected side
1768 void CDirView::DoOpenWith(SIDE_TYPE stype)
1769 {
1770         int sel = GetSingleSelectedItem();
1771         if (sel == -1) return;
1772         DirItemIterator dirBegin = SelBegin();
1773         String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1774         if (file.empty()) return;
1775         CString sysdir;
1776         if (!GetSystemDirectory(sysdir.GetBuffer(MAX_PATH), MAX_PATH)) return;
1777         sysdir.ReleaseBuffer();
1778         CString arg = (CString)_T("shell32.dll,OpenAs_RunDLL ") + file.c_str();
1779         ShellExecute(::GetDesktopWindow(), 0, _T("RUNDLL32.EXE"), arg, sysdir, SW_SHOWNORMAL);
1780 }
1781
1782 /// Open selected file  on specified side to external editor
1783 void CDirView::DoOpenWithEditor(SIDE_TYPE stype)
1784 {
1785         int sel = GetSingleSelectedItem();
1786         if (sel == -1) return;
1787         DirItemIterator dirBegin = SelBegin();
1788         String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1789         if (file.empty()) return;
1790
1791         theApp.OpenFileToExternalEditor(file);
1792 }
1793
1794 void CDirView::DoOpenParentFolder(SIDE_TYPE stype)
1795 {
1796         int sel = GetSingleSelectedItem();
1797         if (sel == -1) return;
1798         DirItemIterator dirBegin = SelBegin();
1799         String file = GetSelectedFileName(dirBegin, stype, GetDiffContext());
1800         if (file.empty()) return;
1801         String parentFolder = paths::GetParentPath(file);
1802         ShellExecute(::GetDesktopWindow(), _T("open"), parentFolder.c_str(), 0, 0, SW_SHOWNORMAL);
1803 }
1804
1805 /// User chose (context menu) open left
1806 template<SIDE_TYPE stype>
1807 void CDirView::OnCtxtDirOpen()
1808 {
1809         DoOpen(stype);
1810 }
1811
1812 /// User chose (context menu) open left with
1813 template<SIDE_TYPE stype>
1814 void CDirView::OnCtxtDirOpenWith()
1815 {
1816         DoOpenWith(stype);
1817 }
1818
1819 /// User chose (context menu) open left with editor
1820 template<SIDE_TYPE stype>
1821 void CDirView::OnCtxtDirOpenWithEditor()
1822 {
1823         DoOpenWithEditor(stype);
1824 }
1825
1826 /// User chose (context menu) open left parent folder
1827 template<SIDE_TYPE stype>
1828 void CDirView::OnCtxtDirOpenParentFolder()
1829 {
1830         DoOpenParentFolder(stype);
1831 }
1832
1833 /// Update context menuitem "Open left | with editor"
1834 template<SIDE_TYPE stype>
1835 void CDirView::OnUpdateCtxtDirOpenWithEditor(CCmdUI* pCmdUI)
1836 {
1837         Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1838         pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1839 }
1840
1841 // return selected item index, or -1 if none or multiple
1842 int CDirView::GetSingleSelectedItem() const
1843 {
1844         int sel = -1, sel2 = -1;
1845         sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
1846         if (sel == -1) return -1;
1847         sel2 = m_pList->GetNextItem(sel, LVNI_SELECTED);
1848         if (sel2 != -1) return -1;
1849         return sel;
1850 }
1851 // Enable/disable Open Left menu choice on context menu
1852 template<SIDE_TYPE stype>
1853 void CDirView::OnUpdateCtxtDirOpen(CCmdUI* pCmdUI)
1854 {
1855         Counts counts = Count(&DirActions::IsItemOpenableOn<stype>);
1856         pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1857 }
1858
1859 // Enable/disable Open Left With menu choice on context menu
1860 template<SIDE_TYPE stype>
1861 void CDirView::OnUpdateCtxtDirOpenWith(CCmdUI* pCmdUI)
1862 {
1863         Counts counts = Count(&DirActions::IsItemOpenableOnWith<stype>);
1864         pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1865 }
1866
1867 // Enable/disable Open Parent Folder menu choice on context menu
1868 template<SIDE_TYPE stype>
1869 void CDirView::OnUpdateCtxtDirOpenParentFolder(CCmdUI* pCmdUI)
1870 {
1871         Counts counts = Count(&DirActions::IsParentFolderOpenable<stype>);
1872         pCmdUI->Enable(counts.count > 0 && counts.total == 1);
1873 }
1874
1875 // Used for Open
1876 void CDirView::DoUpdateOpen(SELECTIONTYPE selectionType, CCmdUI* pCmdUI, bool openableForDir /*= true*/)
1877 {
1878         int sel1 = -1, sel2 = -1, sel3 = -1;
1879         if (!GetSelectedItems(&sel1, &sel2, &sel3))
1880         {
1881                 // 0 items or more than 2 items seleted
1882                 pCmdUI->Enable(FALSE);
1883                 return;
1884         }
1885         if (sel2 == -1)
1886         {
1887                 // One item selected
1888                 if (selectionType != SELECTIONTYPE_NORMAL)
1889                 {
1890                         pCmdUI->Enable(FALSE);
1891                         return;
1892                 }
1893                 if (!openableForDir)
1894                 {
1895                         const DIFFITEM& di1 = GetDiffItem(sel1);
1896                         if (di1.diffcode.isDirectory())
1897                         {
1898                                 pCmdUI->Enable(FALSE);
1899                                 return;
1900                         }
1901                 }
1902         }
1903         else if (sel3 == -1)
1904         {
1905                 // Two items selected
1906                 const DIFFITEM& di1 = GetDiffItem(sel1);
1907                 const DIFFITEM& di2 = GetDiffItem(sel2);
1908                 if (!AreItemsOpenable(GetDiffContext(), selectionType, di1, di2, openableForDir))
1909                 {
1910                         pCmdUI->Enable(FALSE);
1911                         return;
1912                 }
1913         }
1914         else
1915         {
1916                 // Three items selected
1917                 const DIFFITEM& di1 = GetDiffItem(sel1);
1918                 const DIFFITEM& di2 = GetDiffItem(sel2);
1919                 const DIFFITEM& di3 = GetDiffItem(sel3);
1920                 if (selectionType != SELECTIONTYPE_NORMAL || !::AreItemsOpenable(GetDiffContext(), di1, di2, di3, openableForDir))
1921                 {
1922                         pCmdUI->Enable(FALSE);
1923                         return;
1924                 }
1925         }
1926         pCmdUI->Enable(TRUE);
1927 }
1928
1929 /**
1930  * @brief Return count of selected items in folder compare.
1931  */
1932 UINT CDirView::GetSelectedCount() const
1933 {
1934         return m_pList->GetSelectedCount();
1935 }
1936
1937 /**
1938  * @brief Return index of first selected item in folder compare.
1939  */
1940 int CDirView::GetFirstSelectedInd()
1941 {
1942         return m_pList->GetNextItem(-1, LVNI_SELECTED);
1943 }
1944
1945 // Go to first diff
1946 // If none or one item selected select found item
1947 // This is used for scrolling to first diff too
1948 void CDirView::OnFirstdiff()
1949 {
1950         DirItemIterator it =
1951                 std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1952         if (it != End())
1953                 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1954 }
1955
1956 void CDirView::OnUpdateFirstdiff(CCmdUI* pCmdUI)
1957 {
1958         pCmdUI->Enable(GetFirstDifferentItem() > -1);
1959 }
1960
1961 // Go to last diff
1962 // If none or one item selected select found item
1963 void CDirView::OnLastdiff()
1964 {
1965         DirItemIterator it =
1966                 std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
1967         if (it != RevEnd())
1968                 MoveFocus(GetFirstSelectedInd(), it.m_sel, GetSelectedCount());
1969 }
1970
1971 void CDirView::OnUpdateLastdiff(CCmdUI* pCmdUI)
1972 {
1973         pCmdUI->Enable(GetFirstDifferentItem() > -1);
1974 }
1975
1976 bool CDirView::HasNextDiff()
1977 {
1978         int lastDiff = GetLastDifferentItem();
1979
1980         // Check if different files were found and
1981         // there is different item after focused item
1982         return (lastDiff > -1) && (GetFocusedItem() < lastDiff);
1983 }
1984
1985 bool CDirView::HasPrevDiff()
1986 {
1987         int firstDiff = GetFirstDifferentItem();
1988
1989         // Check if different files were found and
1990         // there is different item before focused item
1991         return (firstDiff > -1) && (firstDiff < GetFocusedItem());
1992 }
1993
1994 void CDirView::MoveToNextDiff()
1995 {
1996         int currentInd = GetFocusedItem();
1997         DirItemIterator begin(m_pIList.get(), currentInd + 1);
1998         DirItemIterator it =
1999                 std::find_if(begin, End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2000         if (it != End())
2001                 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2002 }
2003
2004 void CDirView::MoveToPrevDiff()
2005 {
2006         int currentInd = GetFocusedItem();
2007         if (currentInd <= 0)
2008                 return;
2009         DirItemIterator begin(m_pIList.get(), currentInd - 1, false, true);
2010         DirItemIterator it =
2011                 std::find_if(begin, RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2012         if (it != RevEnd())
2013                 MoveFocus(currentInd, it.m_sel, GetSelectedCount());
2014 }
2015
2016 void CDirView::OpenNextDiff()
2017 {
2018         MoveToNextDiff();
2019         int currentInd = GetFocusedItem();
2020         const DIFFITEM& dip = GetDiffItem(currentInd);
2021         if (!dip.diffcode.isDirectory())
2022         {
2023                 OpenSelection();
2024         }
2025         else
2026         {
2027                 GetParentFrame()->ActivateFrame();
2028         }
2029 }
2030
2031 void CDirView::OpenPrevDiff()
2032 {
2033         MoveToPrevDiff();
2034         int currentInd = GetFocusedItem();
2035         const DIFFITEM& dip = GetDiffItem(currentInd);
2036         if (!dip.diffcode.isDirectory())
2037         {
2038                 OpenSelection();
2039         }
2040         else
2041         {
2042                 GetParentFrame()->ActivateFrame();
2043         }
2044 }
2045
2046 void CDirView::OpenFirstFile()
2047 {
2048         int currentInd = GetFocusedItem();
2049         int firstFileInd = 0;
2050         // Skip directories
2051         while (firstFileInd <= currentInd)
2052         {
2053                 DIFFITEM& dip = GetDiffItem(firstFileInd);
2054                 if (!dip.diffcode.isDirectory())
2055                 {
2056                         MoveFocus(currentInd, firstFileInd, 1);
2057                         OpenSelection();
2058                         break;
2059                 }               
2060                 firstFileInd++;
2061         }
2062 }
2063
2064 bool CDirView::IsFirstFile()
2065 {
2066         int currentInd = GetFocusedItem();
2067         int firstFileInd = 0;
2068         while (firstFileInd <= currentInd)
2069         {
2070                 DIFFITEM& dip = GetDiffItem(firstFileInd);
2071                 if (!dip.diffcode.isDirectory())
2072                 {
2073                         if (currentInd == firstFileInd)
2074                                 return true;
2075                         else
2076                                 return false;
2077                 }
2078                 firstFileInd++;
2079         }
2080         return false;
2081 }
2082
2083 void CDirView::OpenLastFile()
2084 {
2085         const int count = m_pList->GetItemCount();
2086         int currentInd = GetFocusedItem();
2087         int lastFileInd = count - 1;
2088         // Skip directories
2089         while (lastFileInd >= 0)
2090         {
2091                 DIFFITEM& dip = GetDiffItem(lastFileInd);
2092                 if (!dip.diffcode.isDirectory())
2093                 {
2094                         MoveFocus(currentInd, lastFileInd, 1);
2095                         OpenSelection();
2096                         break;
2097                 }
2098                 lastFileInd--;
2099         }
2100 }
2101
2102 bool CDirView::IsLastFile()
2103 {
2104         const int count = m_pList->GetItemCount();
2105         int currentInd = GetFocusedItem();
2106         int lastFileInd = count - 1;
2107         while (lastFileInd >= currentInd)
2108         {
2109                 DIFFITEM& dip = GetDiffItem(lastFileInd);
2110                 if (!dip.diffcode.isDirectory())
2111                 {
2112                         if (currentInd == lastFileInd)
2113                                 return true;
2114                         else
2115                                 return false;
2116                 }
2117                 lastFileInd--;
2118         }
2119         return false;
2120 }
2121
2122 void CDirView::OpenNextFile()
2123 {
2124         const int count = m_pList->GetItemCount();
2125         int currentInd = GetFocusedItem();
2126         int nextInd = currentInd + 1;
2127         if (currentInd >= 0)
2128         {
2129                 while (nextInd < count)
2130                 {
2131                         DIFFITEM& dip = GetDiffItem(nextInd);
2132                         MoveFocus(nextInd - 1, nextInd, 1);
2133                         if (!dip.diffcode.isDirectory())
2134                         {                               
2135                                 OpenSelection();
2136                                 break;
2137                         }
2138                         nextInd++;
2139                 }
2140         }
2141 }
2142
2143 void CDirView::OpenPrevFile()
2144 {
2145         int currentInd = GetFocusedItem();
2146         int prevInd = currentInd - 1;
2147         if (currentInd >= 0)
2148         {
2149                 while (prevInd >= 0)
2150                 {
2151                         DIFFITEM& dip = GetDiffItem(prevInd);
2152                         MoveFocus(prevInd + 1, prevInd, 1);
2153                         if (!dip.diffcode.isDirectory())
2154                         {
2155                                 OpenSelection();
2156                                 break;
2157                         }
2158                         prevInd--;
2159                 }
2160         }
2161 }
2162
2163 void CDirView::SetActivePane(int pane)
2164 {
2165         if (m_nActivePane >= 0)
2166                 GetParentFrame()->GetHeaderInterface()->SetActive(m_nActivePane, false);
2167         GetParentFrame()->GetHeaderInterface()->SetActive(pane, true);
2168         m_nActivePane = pane;
2169 }
2170
2171 // Go to next diff
2172 // If none or one item selected select found item
2173 void CDirView::OnNextdiff()
2174 {
2175         MoveToNextDiff();
2176 }
2177
2178
2179 void CDirView::OnUpdateNextdiff(CCmdUI* pCmdUI)
2180 {
2181         pCmdUI->Enable(HasNextDiff());
2182 }
2183
2184 // Go to prev diff
2185 // If none or one item selected select found item
2186 void CDirView::OnPrevdiff()
2187 {
2188         MoveToPrevDiff();
2189 }
2190
2191
2192 void CDirView::OnUpdatePrevdiff(CCmdUI* pCmdUI)
2193 {
2194         pCmdUI->Enable(HasPrevDiff());
2195 }
2196
2197 void CDirView::OnCurdiff()
2198 {
2199         const int count = m_pList->GetItemCount();
2200         bool found = false;
2201         int i = GetFirstSelectedInd();
2202
2203         // No selection - no diff to go
2204         if (i == -1)
2205                 i = count;
2206
2207         while (i < count && !found)
2208         {
2209                 UINT selected = m_pList->GetItemState(i, LVIS_SELECTED);
2210                 UINT focused = m_pList->GetItemState(i, LVIS_FOCUSED);
2211
2212                 if (selected == LVIS_SELECTED && focused == LVIS_FOCUSED)
2213                 {
2214                         m_pList->EnsureVisible(i, FALSE);
2215                         found = true;
2216                 }
2217                 i++;
2218         }
2219 }
2220
2221 void CDirView::OnUpdateCurdiff(CCmdUI* pCmdUI)
2222 {
2223         pCmdUI->Enable(GetFirstSelectedInd() > -1);
2224 }
2225
2226 int CDirView::GetFocusedItem()
2227 {
2228         return m_pList->GetNextItem(-1, LVNI_FOCUSED);
2229 }
2230
2231 int CDirView::GetFirstDifferentItem()
2232 {
2233         if (!m_firstDiffItem.has_value())
2234         {
2235                 DirItemIterator it =
2236                         std::find_if(Begin(), End(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2237                 m_firstDiffItem = it.m_sel;
2238         }
2239         return m_firstDiffItem.value();
2240 }
2241
2242 int CDirView::GetLastDifferentItem()
2243 {
2244         if (!m_lastDiffItem.has_value())
2245         {
2246                 DirItemIterator it =
2247                         std::find_if(RevBegin(), RevEnd(), MakeDirActions(&DirActions::IsItemNavigableDiff));
2248                 m_lastDiffItem = it.m_sel;
2249         }
2250         return m_lastDiffItem.value();
2251 }
2252
2253 /**
2254  * @brief Move focus to specified item (and selection if multiple items not selected)
2255  *
2256  * Moves the focus from item [currentInd] to item [i]
2257  * Additionally, if there are not multiple items selected,
2258  *  deselects item [currentInd] and selects item [i]
2259  */
2260 void CDirView::MoveFocus(int currentInd, int i, int selCount)
2261 {
2262         if (selCount <= 1)
2263         {
2264                 // Not multiple items selected, so bring selection with us
2265                 m_pList->SetItemState(currentInd, 0, LVIS_SELECTED);
2266                 m_pList->SetItemState(currentInd, 0, LVIS_FOCUSED);
2267                 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2268         }
2269
2270         // Move focus to specified item
2271         // (this automatically defocuses old item)
2272         m_pList->SetItemState(i, LVIS_FOCUSED, LVIS_FOCUSED);
2273         m_pList->EnsureVisible(i, FALSE);
2274 }
2275
2276 void CDirView::OnUpdateSave(CCmdUI* pCmdUI)
2277 {
2278         pCmdUI->Enable(FALSE);
2279 }
2280
2281 CDirFrame * CDirView::GetParentFrame()
2282 {
2283         // can't verify cast without introducing more coupling
2284         // (CDirView doesn't include DirFrame.h)
2285         return static_cast<CDirFrame *>(CListView::GetParentFrame());
2286 }
2287
2288 void CDirView::OnRefresh()
2289 {
2290         m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
2291         GetDocument()->Rescan();
2292 }
2293
2294 BOOL CDirView::PreTranslateMessage(MSG* pMsg)
2295 {
2296         // Handle special shortcuts here
2297         if (pMsg->message == WM_KEYDOWN)
2298         {
2299                 if (!IsLabelEdit())
2300                 {
2301                         // Check if we got 'ESC pressed' -message
2302                         if (pMsg->wParam == VK_ESCAPE)
2303                         {
2304                                 if (m_pCmpProgressBar != nullptr)
2305                                 {
2306                                         OnBnClickedComparisonStop();
2307                                         return TRUE;
2308                                 }
2309
2310                                 if (m_nEscCloses != 0)
2311                                 {
2312                                         AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_CLOSE);
2313                                         return FALSE;
2314                                 }
2315                         }
2316                         // Check if we got 'DEL pressed' -message
2317                         if (pMsg->wParam == VK_DELETE)
2318                         {
2319                                 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_MERGE_DELETE);
2320                                 return FALSE;
2321                         }
2322                         int sel = GetFocusedItem();
2323                         // Check if we got 'Backspace pressed' -message
2324                         if (pMsg->wParam == VK_BACK)
2325                         {
2326                                 if (!GetDiffContext().m_bRecursive)
2327                                 {
2328                                         OpenParentDirectory();
2329                                         return FALSE;
2330                                 }
2331                                 else if (m_bTreeMode && sel >= 0)
2332                                 {
2333                                         const DIFFITEM& di = GetDiffItem(sel);
2334                                         assert(di.HasParent());
2335                                         if (di.HasParent())
2336                                         {
2337                                                 int i = GetItemIndex(di.GetParentLink());
2338                                                 if (i >= 0)
2339                                                         MoveFocus(sel, i, GetSelectedCount());
2340                                         }
2341                                 }
2342                         }
2343                         if (sel >= 0)
2344                         {
2345                                 DIFFITEM& dip = this->GetDiffItem(sel);
2346                                 if (pMsg->wParam == VK_LEFT)
2347                                 {
2348                                         if (m_bTreeMode && GetDiffContext().m_bRecursive && (!(dip.customFlags & ViewCustomFlags::EXPANDED) || !dip.HasChildren()))
2349                                                 PostMessage(WM_KEYDOWN, VK_BACK);
2350                                         else
2351                                                 CollapseSubdir(sel);
2352                                         return TRUE;
2353                                 }
2354                                 if (pMsg->wParam == VK_SUBTRACT)
2355                                 {
2356                                         CollapseSubdir(sel);
2357                                         return TRUE;
2358                                 }
2359                                 if (pMsg->wParam == VK_RIGHT)
2360                                 {
2361                                         if (m_bTreeMode && GetDiffContext().m_bRecursive && dip.customFlags & ViewCustomFlags::EXPANDED && dip.HasChildren())
2362                                                 PostMessage(WM_KEYDOWN, VK_DOWN);
2363                                         else
2364                                                 ExpandSubdir(sel);
2365                                         return TRUE;
2366                                 }
2367                                 if (pMsg->wParam == VK_ADD)
2368                                 {
2369                                         ExpandSubdir(sel);
2370                                         return TRUE;
2371                                 }
2372                                 if (pMsg->wParam == VK_MULTIPLY)
2373                                 {
2374                                         ExpandSubdir(sel, true);
2375                                         return TRUE;
2376                                 }
2377                         }
2378                 }
2379                 else
2380                 {
2381                         // ESC doesn't close window when user is renaming an item.
2382                         if (pMsg->wParam == VK_ESCAPE)
2383                         {
2384                                 m_bUserCancelEdit = true;
2385
2386                                 // The edit control send LVN_ENDLABELEDIT when it loses focus,
2387                                 // so we use it to cancel the rename action.
2388                                 m_pList->SetFocus();
2389
2390                                 // Stop the ESC before it reach the main frame which might
2391                                 // cause a program termination.
2392                                 return TRUE;
2393                         }
2394                 }
2395         }
2396         return CListView::PreTranslateMessage(pMsg);
2397 }
2398
2399 void CDirView::OnUpdateRefresh(CCmdUI* pCmdUI)
2400 {
2401         UINT threadState = GetDocument()->m_diffThread.GetThreadState();
2402         pCmdUI->Enable(threadState != CDiffThread::THREAD_COMPARING);
2403 }
2404
2405 /**
2406  * @brief Called when compare thread asks UI update.
2407  * @note Currently thread asks update after compare is ready
2408  * or aborted.
2409  */
2410 LRESULT CDirView::OnUpdateUIMessage(WPARAM wParam, LPARAM lParam)
2411 {
2412         UNREFERENCED_PARAMETER(lParam);
2413
2414         CDirDoc * pDoc = GetDocument();
2415         ASSERT(pDoc != nullptr);
2416
2417         if (wParam == CDiffThread::EVENT_COMPARE_COMPLETED)
2418         {
2419                 // Close and destroy the dialog after compare
2420                 if (m_pCmpProgressBar != nullptr)
2421                         GetParentFrame()->ShowControlBar(m_pCmpProgressBar.get(), FALSE, FALSE);
2422                 m_pCmpProgressBar.reset();
2423
2424                 pDoc->CompareReady();
2425
2426                 if (!pDoc->GetGeneratingReport())
2427                         Redisplay();
2428
2429                 if (!pDoc->GetReportFile().empty())
2430                 {
2431                         OnToolsGenerateReport();
2432                         pDoc->SetReportFile(_T(""));
2433                 }
2434
2435                 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST))
2436                         OnFirstdiff();
2437                 else
2438                         MoveFocus(0, 0, 0);
2439
2440                 // If compare took more than TimeToSignalCompare seconds, notify user
2441                 clock_t elapsed = clock() - m_compareStart;
2442                 GetParentFrame()->SetStatus(
2443                         strutils::format(_("Elapsed time: %ld ms"), elapsed).c_str()
2444                 );
2445                 if (elapsed > TimeToSignalCompare * CLOCKS_PER_SEC)
2446                         MessageBeep(IDOK);
2447                 GetMainFrame()->StartFlashing();
2448         }
2449         else if (wParam == CDiffThread::EVENT_COMPARE_PROGRESSED)
2450         {
2451                 InvalidateRect(nullptr, FALSE);
2452         }
2453         else if (wParam == CDiffThread::EVENT_COLLECT_COMPLETED)
2454         {
2455                 if (m_pSavedTreeState != nullptr)
2456                 {
2457                         RestoreTreeState(GetDiffContext(), m_pSavedTreeState.get());
2458                         m_pSavedTreeState.reset();
2459                         Redisplay();
2460                 }
2461                 else
2462                 {
2463                         if (m_bExpandSubdirs)
2464                                 OnViewExpandAllSubdirs();
2465                         else
2466                                 Redisplay();
2467                 }
2468         }
2469
2470         return 0; // return value unused
2471 }
2472
2473
2474 BOOL CDirView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2475 {
2476         NMHDR * hdr = reinterpret_cast<NMHDR *>(lParam);
2477         if (hdr->code == HDN_ENDDRAG)
2478                 return OnHeaderEndDrag((LPNMHEADER)hdr, pResult);
2479         if (hdr->code == HDN_BEGINDRAG)
2480                 return OnHeaderBeginDrag((LPNMHEADER)hdr, pResult);
2481
2482         return CListView::OnNotify(wParam, lParam, pResult);
2483 }
2484
2485 BOOL CDirView::OnChildNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
2486 {
2487         if (uMsg == WM_NOTIFY)
2488         {
2489                 NMHDR *pNMHDR = (NMHDR *)lParam;
2490                 switch (pNMHDR->code)
2491                 {
2492                 case LVN_GETDISPINFO:
2493                         ReflectGetdispinfo((NMLVDISPINFO *)lParam);
2494                         return TRUE;
2495                 case LVN_GETINFOTIPW:
2496                 case LVN_GETINFOTIPA:
2497                         return TRUE;
2498                 }
2499         }
2500         return CListView::OnChildNotify(uMsg, wParam, lParam, pResult);
2501 }
2502
2503 /**
2504  * @brief User is starting to drag a column header
2505  */
2506 bool CDirView::OnHeaderBeginDrag(LPNMHEADER hdr, LRESULT* pResult)
2507 {
2508         // save column widths before user reorders them
2509         // so we can reload them on the end drag
2510         const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
2511         GetOptionsMgr()->SaveOption(keyname,
2512                 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1)).c_str());
2513         return true;
2514 }
2515
2516 /**
2517  * @brief User just finished dragging a column header
2518  */
2519 bool CDirView::OnHeaderEndDrag(LPNMHEADER hdr, LRESULT* pResult)
2520 {
2521         int src = hdr->iItem;
2522         int dest = hdr->pitem->iOrder;
2523         bool allowDrop = true;
2524         *pResult = allowDrop ? FALSE : TRUE;
2525         if (allowDrop && src != dest && dest != -1)
2526         {
2527                 m_pColItems->MoveColumn(src, dest);
2528                 InitiateSort();
2529         }
2530         return true;
2531 }
2532
2533 /**
2534  * @brief Remove any windows reordering of columns
2535  */
2536 void CDirView::FixReordering()
2537 {
2538         LVCOLUMN lvcol;
2539         lvcol.mask = LVCF_ORDER;
2540         lvcol.fmt = 0;
2541         lvcol.cx = 0;
2542         lvcol.pszText = nullptr;
2543         lvcol.iSubItem = 0;
2544         for (int i = 0; i < m_pColItems->GetColCount(); ++i)
2545         {
2546                 lvcol.iOrder = i;
2547                 GetListCtrl().SetColumn(i, &lvcol);
2548         }
2549 }
2550
2551 /** @brief Add columns to display, loading width & order from registry. */
2552 void CDirView::LoadColumnHeaderItems()
2553 {
2554         bool dummyflag = false;
2555
2556         CHeaderCtrl * h = m_pList->GetHeaderCtrl();
2557         if (h->GetItemCount())
2558         {
2559                 dummyflag = true;
2560                 while (m_pList->GetHeaderCtrl()->GetItemCount() > 1)
2561                         m_pList->DeleteColumn(1);
2562         }
2563
2564         for (int i = 0; i < m_pColItems->GetDispColCount(); ++i)
2565         {
2566                 LVCOLUMN lvc;
2567                 lvc.mask = LVCF_FMT + LVCF_SUBITEM + LVCF_TEXT;
2568                 lvc.fmt = LVCFMT_LEFT;
2569                 lvc.cx = 0;
2570                 lvc.pszText = _T("text");
2571                 lvc.iSubItem = i;
2572                 m_pList->InsertColumn(i, &lvc);
2573         }
2574         if (dummyflag)
2575                 m_pList->DeleteColumn(1);
2576
2577 }
2578
2579 void CDirView::SetFont(const LOGFONT & lf)
2580 {
2581         m_font.DeleteObject();
2582         m_font.CreateFontIndirect(&lf);
2583         CWnd::SetFont(&m_font);
2584 }
2585
2586 /** @brief Fire off a resort of the data, to take place when things stabilize. */
2587 void CDirView::InitiateSort()
2588 {
2589         PostMessage(WM_TIMER, COLUMN_REORDER);
2590 }
2591
2592 void CDirView::OnTimer(UINT_PTR nIDEvent)
2593 {
2594         if (nIDEvent == COLUMN_REORDER)
2595         {
2596                 // Remove the windows reordering, as we're doing it ourselves
2597                 FixReordering();
2598                 // Now redraw screen
2599                 UpdateColumnNames();
2600                 m_pColItems->LoadColumnWidths(
2601                         GetOptionsMgr()->GetString(GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS),
2602                         std::bind(&CListCtrl::SetColumnWidth, m_pList, _1, _2), GetDefColumnWidth());
2603                 Redisplay();
2604         }
2605         else if (nIDEvent == STATUSBAR_UPDATE)
2606         {
2607                 KillTimer(STATUSBAR_UPDATE);
2608                 int items = GetSelectedCount();
2609                 String msg = (items == 1) ? _("1 item selected") : strutils::format_string1(_("%1 items selected"), strutils::to_str(items));
2610                 GetParentFrame()->SetStatus(msg.c_str());
2611         }
2612         
2613         CListView::OnTimer(nIDEvent);
2614 }
2615
2616 /**
2617  * @brief Change left-side readonly-status
2618  */
2619 template<SIDE_TYPE stype>
2620 void CDirView::OnReadOnly()
2621 {
2622         const int index = SideToIndex(GetDiffContext(), stype);
2623         bool bReadOnly = GetDocument()->GetReadOnly(index);
2624         GetDocument()->SetReadOnly(index, !bReadOnly);
2625 }
2626
2627 /**
2628  * @brief Update left-readonly menu item
2629  */
2630 template<SIDE_TYPE stype>
2631 void CDirView::OnUpdateReadOnly(CCmdUI* pCmdUI)
2632 {
2633         const int index = SideToIndex(GetDiffContext(), stype);
2634         bool bReadOnly = GetDocument()->GetReadOnly(index);
2635         if (stype != SIDE_MIDDLE)
2636         {
2637                 pCmdUI->Enable(TRUE);
2638                 pCmdUI->SetCheck(bReadOnly);
2639         }
2640         else
2641         {
2642                 pCmdUI->Enable(GetDocument()->m_nDirs > 2);
2643                 pCmdUI->SetCheck(bReadOnly && GetDocument()->m_nDirs > 2);
2644         }
2645 }
2646
2647 /**
2648  * @brief Update left-side readonly statusbar item
2649  */
2650 void CDirView::OnUpdateStatusLeftRO(CCmdUI* pCmdUI)
2651 {
2652         bool bROLeft = GetDocument()->GetReadOnly(0);
2653         pCmdUI->Enable(bROLeft);
2654 }
2655
2656 /**
2657  * @brief Update middle readonly statusbar item
2658  */
2659 void CDirView::OnUpdateStatusMiddleRO(CCmdUI* pCmdUI)
2660 {
2661         bool bROMiddle = GetDocument()->GetReadOnly(1);
2662         pCmdUI->Enable(bROMiddle && GetDocument()->m_nDirs > 2);
2663 }
2664
2665 /**
2666  * @brief Update right-side readonly statusbar item
2667  */
2668 void CDirView::OnUpdateStatusRightRO(CCmdUI* pCmdUI)
2669 {
2670         bool bRORight = GetDocument()->GetReadOnly(GetDocument()->m_nDirs - 1);
2671         pCmdUI->Enable(bRORight);
2672 }
2673
2674 /**
2675  * @brief Open dialog to customize dirview columns
2676  */
2677 void CDirView::OnCustomizeColumns()
2678 {
2679         // Located in DirViewColHandler.cpp
2680         OnEditColumns();
2681         const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_ORDERS : OPT_DIRVIEW3_COLUMN_ORDERS;
2682         GetOptionsMgr()->SaveOption(keyname, m_pColItems->SaveColumnOrders());
2683 }
2684
2685 void CDirView::OnCtxtOpenWithUnpacker()
2686 {
2687         int sel = -1;
2688         sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2689         if (sel != -1)
2690         {
2691                 // let the user choose a handler
2692                 CSelectUnpackerDlg dlg(GetDiffItem(sel).diffFileInfo[0].filename, this);
2693                 // create now a new infoUnpacker to initialize the manual/automatic flag
2694                 PackingInfo infoUnpacker(PLUGIN_MODE::PLUGIN_AUTO);
2695                 dlg.SetInitialInfoHandler(&infoUnpacker);
2696
2697                 if (dlg.DoModal() == IDOK)
2698                 {
2699                         infoUnpacker = dlg.GetInfoHandler();
2700                         OpenSelection(SELECTIONTYPE_NORMAL, &infoUnpacker, false);
2701                 }
2702         }
2703
2704 }
2705
2706 void CDirView::OnUpdateCtxtOpenWithUnpacker(CCmdUI* pCmdUI)
2707 {
2708         if (!GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
2709         {
2710                 pCmdUI->Enable(FALSE);
2711                 return;
2712         }
2713
2714         // we need one selected file, existing on both side
2715         if (m_pList->GetSelectedCount() != 1)
2716                 pCmdUI->Enable(FALSE);
2717         else
2718         {
2719                 int sel = -1;
2720                 sel = m_pList->GetNextItem(sel, LVNI_SELECTED);
2721                 const DIFFITEM& di = GetDiffItem(sel);
2722                 if (di.diffcode.isDirectory())
2723                 {
2724                         pCmdUI->Enable(FALSE);
2725                         return;
2726                 }
2727                 pCmdUI->Enable(IsItemDeletableOnBoth(GetDiffContext(), di));
2728         }
2729 }
2730
2731 /**
2732  * @brief Fill string list with current dirview column registry key names
2733  */
2734 std::vector<String> CDirView::GetCurrentColRegKeys()
2735 {
2736         std::vector<String> colKeys;
2737         int nphyscols = GetListCtrl().GetHeaderCtrl()->GetItemCount();
2738         for (int col = 0; col < nphyscols; ++col)
2739         {
2740                 int logcol = m_pColItems->ColPhysToLog(col);
2741                 colKeys.push_back(m_pColItems->GetColRegValueNameBase(logcol));
2742         }
2743         return colKeys;
2744 }
2745
2746 struct FileCmpReport: public IFileCmpReport
2747 {
2748         explicit FileCmpReport(CDirView *pDirView) : m_pDirView(pDirView) {}
2749         ~FileCmpReport() override {}
2750         bool operator()(REPORT_TYPE nReportType, IListCtrl *pList, int nIndex, const String &sDestDir, String &sLinkPath) override
2751         {
2752                 const CDiffContext& ctxt = m_pDirView->GetDiffContext();
2753                 const DIFFITEM &di = m_pDirView->GetDiffItem(nIndex);
2754                 
2755                 String sLinkFullPath = paths::ConcatPath(ctxt.GetLeftPath(), di.diffFileInfo[0].GetFile());
2756
2757                 if (di.diffcode.isDirectory() || !IsItemNavigableDiff(ctxt, di) || IsArchiveFile(sLinkFullPath))
2758                 {
2759                         sLinkPath.clear();
2760                         return false;
2761                 }
2762
2763                 sLinkPath = di.diffFileInfo[0].GetFile();
2764
2765                 strutils::replace(sLinkPath, _T("\\"), _T("_"));
2766                 sLinkPath += _T(".html");
2767                 String sReportPath = paths::ConcatPath(sDestDir, sLinkPath);
2768                 bool completed = false;
2769
2770                 m_pDirView->MoveFocus(m_pDirView->GetFirstSelectedInd(), nIndex, m_pDirView->GetSelectedCount());
2771                 m_pDirView->PostMessage(MSG_GENERATE_FLIE_COMPARE_REPORT,
2772                         reinterpret_cast<WPARAM>(sReportPath.c_str()), 
2773                         reinterpret_cast<LPARAM>(&completed));
2774
2775                 while (!completed)
2776                 {
2777                         MSG msg;
2778                         while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2779                         {
2780                                 if (!AfxGetApp()->PumpMessage())
2781                                         break;
2782                         }
2783                         Sleep(5);
2784                 }
2785
2786                 return true;
2787         }
2788 private:
2789         FileCmpReport();
2790         CDirView *m_pDirView;
2791 };
2792
2793 LRESULT CDirView::OnGenerateFileCmpReport(WPARAM wParam, LPARAM lParam)
2794 {
2795         OpenSelection();
2796         CFrameWnd * pFrame = GetMainFrame()->GetActiveFrame();
2797         IMergeDoc * pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame->GetActiveDocument());
2798         if (pMergeDoc == nullptr)
2799                 pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame);
2800
2801         auto *pReportFileName = reinterpret_cast<const TCHAR *>(wParam);
2802         bool *pCompleted = reinterpret_cast<bool *>(lParam);
2803         if (pMergeDoc != nullptr)
2804         {
2805                 pMergeDoc->GenerateReport(pReportFileName);
2806                 pMergeDoc->CloseNow();
2807         }
2808         MSG msg;
2809         while (::PeekMessage(&msg, nullptr, NULL, NULL, PM_NOREMOVE))
2810                 if (!AfxGetApp()->PumpMessage())
2811                         break;
2812         GetMainFrame()->OnUpdateFrameTitle(FALSE);
2813         *pCompleted = true;
2814         return 0;
2815 }
2816
2817 /**
2818  * @brief Generate report from dir compare results.
2819  */
2820 void CDirView::OnToolsGenerateReport()
2821 {
2822         CDirDoc *pDoc = GetDocument();
2823         DirCmpReportDlg dlg;
2824         dlg.LoadSettings();
2825         dlg.m_sReportFile = pDoc->GetReportFile();
2826         if (dlg.m_sReportFile.empty() && dlg.DoModal() != IDOK)
2827                 return;
2828
2829         pDoc->SetGeneratingReport(true);
2830         const CDiffContext& ctxt = GetDiffContext();
2831
2832         PathContext paths = ctxt.GetNormalizedPaths();
2833
2834         // If inside archive, convert paths
2835         if (pDoc->IsArchiveFolders())
2836         {
2837                 for (int i = 0; i < paths.GetSize(); i++)
2838                         pDoc->ApplyDisplayRoot(i, paths[i]);
2839         }
2840
2841         DirCmpReport *pReport = new DirCmpReport(GetCurrentColRegKeys());
2842         pReport->SetRootPaths(paths);
2843         pReport->SetColumns(m_pColItems->GetDispColCount());
2844         pReport->SetFileCmpReport(new FileCmpReport(this));
2845         pReport->SetList(new IListCtrlImpl(m_pList->m_hWnd));
2846         pReport->SetReportType(dlg.m_nReportType);
2847         pReport->SetReportFile(dlg.m_sReportFile);
2848         pReport->SetCopyToClipboard(dlg.m_bCopyToClipboard);
2849         pReport->SetIncludeFileCmpReport(dlg.m_bIncludeFileCmpReport);
2850         pDoc->SetReport(pReport);
2851         pDoc->Rescan();
2852 }
2853
2854 /**
2855  * @brief Generate patch from files selected.
2856  *
2857  * Creates a patch from selected files in active directory compare, or
2858  * active file compare. Files in file compare must be saved before
2859  * creating a patch.
2860  */
2861 void CDirView::OnToolsGeneratePatch()
2862 {
2863         CPatchTool patcher;
2864         const CDiffContext& ctxt = GetDiffContext();
2865
2866         // Get selected items from folder compare
2867         bool bValidFiles = true;
2868         for (DirItemIterator it = SelBegin(); bValidFiles && it != SelEnd(); ++it)
2869         {
2870                 const DIFFITEM &item = *it;
2871                 if (item.diffcode.isBin())
2872                 {
2873                         LangMessageBox(IDS_CANNOT_CREATE_BINARYPATCH, MB_ICONWARNING |
2874                                 MB_DONT_DISPLAY_AGAIN, IDS_CANNOT_CREATE_BINARYPATCH);
2875                         bValidFiles = false;
2876                 }
2877
2878                 if (bValidFiles)
2879                 {
2880                         // Format full paths to files (leftFile/rightFile)
2881                         String leftFile = item.getFilepath(0, ctxt.GetNormalizedPath(0));
2882                         if (!leftFile.empty())
2883                                 leftFile = paths::ConcatPath(leftFile, item.diffFileInfo[0].filename);
2884                         String rightFile = item.getFilepath(1, ctxt.GetNormalizedPath(1));
2885                         if (!rightFile.empty())
2886                                 rightFile = paths::ConcatPath(rightFile, item.diffFileInfo[1].filename);
2887
2888                         // Format relative paths to files in folder compare
2889                         String leftpatch = item.diffFileInfo[0].path;
2890                         if (!leftpatch.empty())
2891                                 leftpatch += _T("/");
2892                         leftpatch += item.diffFileInfo[0].filename;
2893                         String rightpatch = item.diffFileInfo[1].path;
2894                         if (!rightpatch.empty())
2895                                 rightpatch += _T("/");
2896                         rightpatch += item.diffFileInfo[1].filename;
2897                         patcher.AddFiles(leftFile, leftpatch, rightFile, rightpatch);
2898                 }
2899         }
2900
2901         patcher.CreatePatch();
2902 }
2903
2904 /**
2905  * @brief Add special items for non-recursive compare
2906  * to directory view.
2907  *
2908  * Currently only special item is ".." for browsing to
2909  * parent folders.
2910  * @return number of items added to view
2911  */
2912 int CDirView::AddSpecialItems()
2913 {
2914         CDirDoc *pDoc = GetDocument();
2915         int retVal = 0;
2916         bool bEnable = true;
2917         PathContext pathsParent;
2918         switch (CheckAllowUpwardDirectory(GetDiffContext(), pDoc->m_pTempPathContext, pathsParent))
2919         {
2920         case AllowUpwardDirectory::No:
2921                 bEnable = false;
2922                 [[fallthrough]];
2923         default:
2924                 AddParentFolderItem(bEnable);
2925                 retVal = 1;
2926                 [[fallthrough]];
2927         case AllowUpwardDirectory::Never:
2928                 break;
2929         }
2930         return retVal;
2931 }
2932
2933 /**
2934  * @brief Add "Parent folder" ("..") item to directory view
2935  */
2936 void CDirView::AddParentFolderItem(bool bEnable)
2937 {
2938         AddNewItem(0, (DIFFITEM *)SPECIAL_ITEM_POS, bEnable ? DIFFIMG_DIRUP : DIFFIMG_DIRUP_DISABLE, 0);
2939 }
2940
2941 template <int flag>
2942 void CDirView::OnCtxtDirZip()
2943 {
2944         if (!HasZipSupport())
2945         {
2946                 LangMessageBox(IDS_NO_ZIP_SUPPORT, MB_ICONINFORMATION);
2947                 return;
2948         }
2949
2950         DirItemEnumerator
2951         (
2952                 this, LVNI_SELECTED | flag
2953         ).CompressArchive();
2954 }
2955
2956 void CDirView::ShowShellContextMenu(SIDE_TYPE stype)
2957 {
2958         CShellContextMenu *pContextMenu = nullptr;
2959         switch (stype)
2960         {
2961         case SIDE_LEFT:
2962                 if (m_pShellContextMenuLeft == nullptr)
2963                         m_pShellContextMenuLeft.reset(new CShellContextMenu(LeftCmdFirst, LeftCmdLast));
2964                 pContextMenu = m_pShellContextMenuLeft.get();
2965                 break;
2966         case SIDE_MIDDLE:
2967                 if (m_pShellContextMenuMiddle == nullptr)
2968                         m_pShellContextMenuMiddle.reset(new CShellContextMenu(MiddleCmdFirst, MiddleCmdLast));
2969                 pContextMenu = m_pShellContextMenuMiddle.get();
2970                 break;
2971         case SIDE_RIGHT:
2972                 if (m_pShellContextMenuRight == nullptr)
2973                         m_pShellContextMenuRight.reset(new CShellContextMenu(RightCmdFirst, RightCmdLast));
2974                 pContextMenu = m_pShellContextMenuRight.get();
2975                 break;
2976         }
2977         if (pContextMenu!=nullptr && ListShellContextMenu(stype))
2978         {
2979                 CPoint point;
2980                 GetCursorPos(&point);
2981                 HWND hWnd = GetSafeHwnd();
2982                 CFrameWnd *pFrame = GetTopLevelFrame();
2983                 ASSERT(pFrame != nullptr);
2984                 BOOL bAutoMenuEnableOld = pFrame->m_bAutoMenuEnable;
2985                 pFrame->m_bAutoMenuEnable = FALSE;
2986                 BOOL nCmd = TrackPopupMenu(pContextMenu->GetHMENU(), TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hWnd, nullptr);
2987                 if (nCmd)
2988                         pContextMenu->InvokeCommand(nCmd, hWnd);
2989                 pContextMenu->ReleaseShellContextMenu();
2990                 pFrame->m_bAutoMenuEnable = bAutoMenuEnableOld;
2991         }
2992 }
2993
2994 template <SIDE_TYPE stype>
2995 void CDirView::OnCtxtDirShellContextMenu()
2996 {
2997         ShowShellContextMenu(stype);
2998 }
2999
3000 /**
3001  * @brief Select all visible items in dir compare
3002  */
3003 void CDirView::OnSelectAll()
3004 {
3005         // While the user is renaming an item, select all the edited text.
3006         CEdit *pEdit = m_pList->GetEditControl();
3007         if (pEdit != nullptr)
3008         {
3009                 pEdit->SetSel(pEdit->GetWindowTextLength());
3010         }
3011         else
3012         {
3013                 int selCount = m_pList->GetItemCount();
3014
3015                 for (int i = 0; i < selCount; i++)
3016                 {
3017                         // Don't select special items (SPECIAL_ITEM_POS)
3018                         DIFFITEM *diffpos = GetItemKey(i);
3019                         if (diffpos != (DIFFITEM *)SPECIAL_ITEM_POS)
3020                                 m_pList->SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3021                 }
3022         }
3023 }
3024
3025 /**
3026  * @brief Update "Select All" item
3027  */
3028 void CDirView::OnUpdateSelectAll(CCmdUI* pCmdUI)
3029 {
3030         bool bEnable = (!IsLabelEdit()) || (m_pList->GetItemCount() > 0);
3031         pCmdUI->Enable(bEnable);
3032 }
3033
3034 /**
3035  * @brief Handle clicks in plugin context view in list
3036  */
3037 void CDirView::OnPluginPredifferMode(UINT nID)
3038 {
3039         ApplyPluginPrediffSetting(SelBegin(), SelEnd(), GetDiffContext(), 
3040                 (nID == ID_PREDIFF_AUTO) ? PLUGIN_MODE::PLUGIN_AUTO : PLUGIN_MODE::PLUGIN_MANUAL);
3041 }
3042
3043 /**
3044  * @brief Updates just before displaying plugin context view in list
3045  */
3046 void CDirView::OnUpdatePluginPredifferMode(CCmdUI* pCmdUI)
3047 {
3048         // 2004-04-03, Perry
3049         // CMainFrame::OnUpdatePluginUnpackMode handles this for global unpacking
3050         // and is the template to copy, but here, this is a bit tricky
3051         // as a group of files may be selected
3052         // and they may not all have the same setting
3053         // so I'm not trying this right now
3054
3055         pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
3056
3057         BCMenu *pPopup = static_cast<BCMenu*>(pCmdUI->m_pSubMenu);
3058         if (pPopup == nullptr)
3059                 return;
3060
3061         std::pair<int, int> counts = CountPredifferYesNo(SelBegin(), SelEnd(), GetDiffContext());
3062
3063         CheckContextMenu(pPopup, ID_PREDIFF_AUTO, (counts.first > 0));
3064         CheckContextMenu(pPopup, ID_PREDIFF_MANUAL, (counts.second > 0));
3065 }
3066
3067 /**
3068  * @brief Refresh cached options.
3069  */
3070 void CDirView::RefreshOptions()
3071 {
3072         m_nEscCloses = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
3073         m_bExpandSubdirs = GetOptionsMgr()->GetBool(OPT_DIRVIEW_EXPAND_SUBDIRS);
3074         Options::DirColors::Load(GetOptionsMgr(), m_cachedColors);
3075         m_bUseColors = GetOptionsMgr()->GetBool(OPT_DIRCLR_USE_COLORS);
3076         m_pList->SetBkColor(m_bUseColors ? m_cachedColors.clrDirMargin : GetSysColor(COLOR_WINDOW));
3077         Invalidate();
3078 }
3079
3080 /**
3081  * @brief Copy selected item left side paths (containing filenames) to clipboard.
3082  */
3083 template<SIDE_TYPE stype>
3084 void CDirView::OnCopyPathnames()
3085 {
3086         std::list<String> list;
3087         CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3088         PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3089 }
3090
3091 void CDirView::OnCopyBothPathnames()
3092 {
3093         std::list<String> list;
3094         CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3095         PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3096 }
3097
3098 /**
3099  * @brief Copy selected item filenames to clipboard.
3100  */
3101 void CDirView::OnCopyFilenames()
3102 {
3103         std::list<String> list;
3104         CopyFilenames(SelBegin(), SelEnd(), std::back_inserter(list));
3105         PutToClipboard(strutils::join(list.begin(), list.end(), _T("\r\n")), GetMainFrame()->GetSafeHwnd());
3106 }
3107
3108 /**
3109  * @brief Enable/Disable dirview Copy Filenames context menu item.
3110  */
3111 void CDirView::OnUpdateCopyFilenames(CCmdUI* pCmdUI)
3112 {
3113         pCmdUI->Enable(Count(&DirActions::IsItemFile).count > 0);
3114 }
3115
3116 /**
3117  * @brief Copy selected item left side to clipboard.
3118  */
3119 template<SIDE_TYPE stype>
3120 void CDirView::OnCopyToClipboard()
3121 {
3122         std::list<String> list;
3123         CopyPathnames(SelBegin(), SelEnd(), std::back_inserter(list), stype, GetDiffContext());
3124         PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3125 }
3126
3127 /**
3128  * @brief Copy selected item both side to clipboard.
3129  */
3130 void CDirView::OnCopyBothToClipboard()
3131 {
3132         std::list<String> list;
3133         CopyBothPathnames(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
3134         PutFilesToClipboard(list, GetMainFrame()->GetSafeHwnd());
3135 }
3136
3137 /**
3138  * @brief Rename a selected item on both sides.
3139  *
3140  */
3141 void CDirView::OnItemRename()
3142 {
3143         ASSERT(1 == m_pList->GetSelectedCount());
3144         int nSelItem = m_pList->GetNextItem(-1, LVNI_SELECTED);
3145         ASSERT(-1 != nSelItem);
3146         m_pList->EditLabel(nSelItem);
3147 }
3148
3149 /**
3150  * @brief Enable/Disable dirview Rename context menu item.
3151  *
3152  */
3153 void CDirView::OnUpdateItemRename(CCmdUI* pCmdUI)
3154 {
3155         bool bEnabled = (1 == m_pList->GetSelectedCount());
3156         pCmdUI->Enable(bEnabled && SelBegin() != SelEnd());
3157 }
3158
3159 /**
3160  * @brief hide selected item filenames (removes them from the ListView)
3161  */
3162 void CDirView::OnHideFilenames()
3163 {
3164         m_pList->SetRedraw(FALSE);      // Turn off updating (better performance)
3165         DirItemIterator it;
3166         while ((it = SelRevBegin()) != SelRevEnd())
3167         {
3168                 DIFFITEM &di = *it;
3169                 SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
3170                 DeleteItem(it.m_sel);
3171                 m_nHiddenItems++;
3172         }
3173         m_pList->SetRedraw(TRUE);       // Turn updating back on
3174 }
3175
3176 /**
3177  * @brief update menu item
3178  */
3179 void CDirView::OnUpdateHideFilenames(CCmdUI* pCmdUI)
3180 {
3181         pCmdUI->Enable(m_pList->GetSelectedCount() != 0);
3182 }
3183
3184 /// User chose (context menu) Move left to...
3185 template<SIDE_TYPE stype>
3186 void CDirView::OnCtxtDirMoveTo()
3187 {
3188         DoDirActionTo(stype, &DirActions::MoveTo<stype>, _("Moving files..."));
3189 }
3190
3191 /**
3192  * @brief Update "Move | Left to..." item
3193  */
3194 template<SIDE_TYPE stype>
3195 void CDirView::OnUpdateCtxtDirMoveTo(CCmdUI* pCmdUI)
3196 {
3197         Counts counts = Count(&DirActions::IsItemMovableToOn<stype>);
3198         pCmdUI->Enable(counts.count > 0);
3199         pCmdUI->SetText(FormatMenuItemStringTo(stype, counts.count, counts.total).c_str());
3200 }
3201
3202 /**
3203  * @brief Update title after window is resized.
3204  */
3205 void CDirView::OnSize(UINT nType, int cx, int cy)
3206 {
3207         CListView::OnSize(nType, cx, cy);
3208         GetDocument()->SetTitle(nullptr);
3209 }
3210
3211 /**
3212  * @brief Called when user selects 'Delete' from 'Merge' menu.
3213  */
3214 void CDirView::OnDelete()
3215 {
3216         DoDirAction(&DirActions::DeleteOnEitherOrBoth, _("Deleting files..."));
3217 }
3218
3219 /**
3220  * @brief Enables/disables 'Delete' item in 'Merge' menu.
3221  */
3222 void CDirView::OnUpdateDelete(CCmdUI* pCmdUI)
3223 {
3224         pCmdUI->Enable(Count(&DirActions::IsItemDeletableOnEitherOrBoth).count > 0);
3225 }
3226
3227 /**
3228  * @brief Called when item state is changed.
3229  *
3230  * Show count of selected items in statusbar.
3231  */
3232 void CDirView::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)
3233 {
3234         NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
3235
3236         // If item's selected state changed
3237         if ((pNMListView->uOldState & LVIS_SELECTED) !=
3238                         (pNMListView->uNewState & LVIS_SELECTED))
3239         {
3240                 if ((pNMListView->iItem % 5000) > 0)
3241                         SetTimer(STATUSBAR_UPDATE, 100, nullptr);
3242                 else
3243                         OnTimer(STATUSBAR_UPDATE);
3244         }
3245         *pResult = 0;
3246 }
3247
3248 /**
3249  * @brief Called before user start to item label edit.
3250  *
3251  * Disable label edit if initiated from a user double-click.
3252  */
3253 afx_msg void CDirView::OnBeginLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3254 {
3255         *pResult = (SelBegin() == SelEnd());
3256
3257         // If label edit is allowed.
3258         if (*pResult == FALSE)
3259         {
3260                 const NMLVDISPINFO *pdi = (NMLVDISPINFO*)pNMHDR;
3261                 ASSERT(pdi != nullptr);
3262
3263                 // Locate the edit box on the right column in case the user changed the
3264                 // column order.
3265                 const int nColPos = m_pColItems->ColLogToPhys(0);
3266
3267                 // Get text from the "File Name" column.
3268                 CString sText = m_pList->GetItemText(pdi->item.iItem, nColPos);
3269                 ASSERT(!sText.IsEmpty());
3270
3271                 // Keep only left file name (separated by '|'). This form occurs
3272                 // when two files exists with same name but not in same case.
3273                 int nPos = sText.Find('|');
3274                 if (-1 != nPos)
3275                 {
3276                         sText = sText.Left(nPos);
3277                 }
3278
3279                 // Set the edit control with the updated text.
3280                 CEdit *pEdit = m_pList->GetEditControl();
3281                 ASSERT(pEdit != nullptr);
3282                 pEdit->SetWindowText(sText);
3283
3284                 m_bUserCancelEdit = false;
3285         }
3286 }
3287
3288 /**
3289  * @brief Called when user done with item label edit.
3290  *
3291  */
3292 afx_msg void CDirView::OnEndLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
3293 {
3294         *pResult = FALSE;
3295
3296         // We can't use the normal condition of pszText==`nullptr` to know if the
3297         // user cancels editing when file names had different case (e.g.
3298         // "file.txt|FILE.txt"). The edit text was changed to "file.txt" and
3299         // if the user accept it as the new file name, pszText is `nullptr`.
3300
3301         if (!m_bUserCancelEdit)
3302         {
3303                 CEdit *pEdit = m_pList->GetEditControl();
3304                 ASSERT(pEdit != nullptr);
3305
3306                 CString sText;
3307                 pEdit->GetWindowText(sText);
3308
3309                 if (!sText.IsEmpty())
3310                 {
3311                         try {
3312                                 DirItemIterator it(m_pIList.get(), reinterpret_cast<NMLVDISPINFO *>(pNMHDR)->item.iItem);
3313                                 *pResult = DoItemRename(it, GetDiffContext(), String(sText));
3314                         } catch (ContentsChangedException& e) {
3315                                 AfxMessageBox(e.m_msg.c_str(), MB_ICONWARNING);
3316                         }
3317                 }
3318         }
3319 }
3320
3321 /**
3322  * @brief Called when item is marked for rescan.
3323  * This function marks selected items for rescan and rescans them.
3324  */
3325 void CDirView::OnMarkedRescan()
3326 {
3327         std::for_each(SelBegin(), SelEnd(), MarkForRescan);
3328         if (std::distance(SelBegin(), SelEnd()) > 0)
3329         {
3330                 m_pSavedTreeState.reset(SaveTreeState(GetDiffContext()));
3331                 GetDocument()->SetMarkedRescan();
3332                 GetDocument()->Rescan();
3333         }
3334 }
3335
3336 /**
3337  * @brief Called to update the item count in the status bar
3338  */
3339 void CDirView::OnUpdateStatusNum(CCmdUI* pCmdUI)
3340 {
3341         String s; // text to display
3342
3343         int count = m_pList->GetItemCount();
3344         int focusItem = GetFocusedItem();
3345
3346         if (focusItem == -1)
3347         {
3348                 // No item has focus
3349                 // "Items: %1"
3350                 s = strutils::format_string1(_("Items: %1"), strutils::to_str(count));
3351         }
3352         else
3353         {
3354                 // Don't show number to special items
3355                 DIFFITEM *pos = GetItemKey(focusItem);
3356                 if (pos != (DIFFITEM *)SPECIAL_ITEM_POS)
3357                 {
3358                         // If compare is non-recursive reduce special items count
3359                         bool bRecursive = GetDiffContext().m_bRecursive;
3360                         if (!bRecursive)
3361                         {
3362                                 --focusItem;
3363                                 --count;
3364                         }
3365                         // "Item %1 of %2"
3366                         s = strutils::format_string2(_("Item %1 of %2"), 
3367                                         strutils::to_str(focusItem + 1), strutils::to_str(count));
3368                 }
3369         }
3370         pCmdUI->SetText(s.c_str());
3371 }
3372
3373 /**
3374  * @brief Show all hidden items.
3375  */
3376 void CDirView::OnViewShowHiddenItems()
3377 {
3378         SetItemViewFlag(GetDiffContext(), ViewCustomFlags::VISIBLE, ViewCustomFlags::VISIBILITY);
3379         m_nHiddenItems = 0;
3380         Redisplay();
3381 }
3382
3383 /**
3384  * @brief Enable/Disable 'Show hidden items' menuitem.
3385  */
3386 void CDirView::OnUpdateViewShowHiddenItems(CCmdUI* pCmdUI)
3387 {
3388         pCmdUI->Enable(m_nHiddenItems > 0);
3389 }
3390
3391 /**
3392  * @brief Toggle Tree Mode
3393  */
3394 void CDirView::OnViewTreeMode()
3395 {
3396         m_bTreeMode = !m_bTreeMode;
3397         m_dirfilter.tree_mode = m_bTreeMode;
3398         GetOptionsMgr()->SaveOption(OPT_TREE_MODE, m_bTreeMode); // reverse
3399         Redisplay();
3400 }
3401
3402 /**
3403  * @brief Check/Uncheck 'Tree Mode' menuitem.
3404  */
3405 void CDirView::OnUpdateViewTreeMode(CCmdUI* pCmdUI)
3406 {
3407         // Don't show Tree Mode as 'checked' if the
3408         // menu item is greyed out (disabled).  Its very confusing.
3409         if( GetDocument()->GetDiffContext().m_bRecursive ) {
3410                 pCmdUI->SetCheck(m_bTreeMode);
3411                 pCmdUI->Enable(TRUE);
3412         } else {
3413                 pCmdUI->SetCheck(FALSE);
3414                 pCmdUI->Enable(FALSE);
3415         }
3416 }
3417
3418 /**
3419  * @brief Expand all subfolders
3420  */
3421 void CDirView::OnViewExpandAllSubdirs()
3422 {
3423         ExpandAllSubdirs(GetDiffContext());
3424         Redisplay();
3425 }
3426
3427 /**
3428  * @brief Update "Expand All Subfolders" item
3429  */
3430 void CDirView::OnUpdateViewExpandAllSubdirs(CCmdUI* pCmdUI)
3431 {
3432         pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3433 }
3434
3435 /**
3436  * @brief Collapse all subfolders
3437  */
3438 void CDirView::OnViewCollapseAllSubdirs()
3439 {
3440         CollapseAllSubdirs(GetDiffContext());
3441         Redisplay();
3442 }
3443
3444 /**
3445  * @brief Update "Collapse All Subfolders" item
3446  */
3447 void CDirView::OnUpdateViewCollapseAllSubdirs(CCmdUI* pCmdUI)
3448 {
3449         pCmdUI->Enable(m_bTreeMode && GetDiffContext().m_bRecursive);
3450 }
3451
3452 template <int pane1, int pane2>
3453 void CDirView::OnViewSwapPanes()
3454 {
3455         GetDocument()->Swap(pane1, pane2);
3456         Redisplay();
3457 }
3458
3459 template <int pane1, int pane2>
3460 void CDirView::OnUpdateViewSwapPanes(CCmdUI* pCmdUI)
3461 {
3462         pCmdUI->Enable(pane2 < GetDocument()->m_nDirs);
3463 }
3464
3465 /**
3466  * @brief Show/Hide different files/directories
3467  */
3468 void CDirView::OnOptionsShowDifferent() 
3469 {
3470         m_dirfilter.show_different = !m_dirfilter.show_different;
3471         GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT, m_dirfilter.show_different);
3472         Redisplay();
3473 }
3474
3475 /**
3476  * @brief Show/Hide identical files/directories
3477  */
3478 void CDirView::OnOptionsShowIdentical() 
3479 {
3480         m_dirfilter.show_identical = !m_dirfilter.show_identical;
3481         GetOptionsMgr()->SaveOption(OPT_SHOW_IDENTICAL, m_dirfilter.show_identical);
3482         Redisplay();
3483 }
3484
3485 /**
3486  * @brief Show/Hide left-only files/directories
3487  */
3488 void CDirView::OnOptionsShowUniqueLeft() 
3489 {
3490         m_dirfilter.show_unique_left = !m_dirfilter.show_unique_left;
3491         GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_LEFT, m_dirfilter.show_unique_left);
3492         Redisplay();
3493 }
3494
3495 /**
3496  * @brief Show/Hide middle-only files/directories
3497  */
3498 void CDirView::OnOptionsShowUniqueMiddle() 
3499 {
3500         m_dirfilter.show_unique_middle = !m_dirfilter.show_unique_middle;
3501         GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_MIDDLE, m_dirfilter.show_unique_middle);
3502         Redisplay();
3503 }
3504
3505 /**
3506  * @brief Show/Hide right-only files/directories
3507  */
3508 void CDirView::OnOptionsShowUniqueRight() 
3509 {
3510         m_dirfilter.show_unique_right = !m_dirfilter.show_unique_right;
3511         GetOptionsMgr()->SaveOption(OPT_SHOW_UNIQUE_RIGHT, m_dirfilter.show_unique_right);
3512         Redisplay();
3513 }
3514
3515 /**
3516  * @brief Show/Hide binary files
3517  */
3518 void CDirView::OnOptionsShowBinaries()
3519 {
3520         m_dirfilter.show_binaries = !m_dirfilter.show_binaries;
3521         GetOptionsMgr()->SaveOption(OPT_SHOW_BINARIES, m_dirfilter.show_binaries);
3522         Redisplay();
3523 }
3524
3525 /**
3526  * @brief Show/Hide skipped files/directories
3527  */
3528 void CDirView::OnOptionsShowSkipped()
3529 {
3530         m_dirfilter.show_skipped = !m_dirfilter.show_skipped;
3531         GetOptionsMgr()->SaveOption(OPT_SHOW_SKIPPED, m_dirfilter.show_skipped);
3532         Redisplay();
3533 }
3534
3535 /**
3536  * @brief Show/Hide different files/folders (Middle and right are identical)
3537  */
3538 void CDirView::OnOptionsShowDifferentLeftOnly() 
3539 {
3540         m_dirfilter.show_different_left_only = !m_dirfilter.show_different_left_only;
3541         GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_LEFT_ONLY, m_dirfilter.show_different_left_only);
3542         Redisplay();
3543 }
3544
3545 /**
3546  * @brief Show/Hide different files/folders (Left and right are identical)
3547  */
3548 void CDirView::OnOptionsShowDifferentMiddleOnly() 
3549 {
3550         m_dirfilter.show_different_middle_only = !m_dirfilter.show_different_middle_only;
3551         GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_MIDDLE_ONLY, m_dirfilter.show_different_middle_only);
3552         Redisplay();
3553 }
3554
3555 /**
3556  * @brief Show/Hide different files/folders (Left and middle are identical)
3557  */
3558 void CDirView::OnOptionsShowDifferentRightOnly() 
3559 {
3560         m_dirfilter.show_different_right_only = !m_dirfilter.show_different_right_only;
3561         GetOptionsMgr()->SaveOption(OPT_SHOW_DIFFERENT_RIGHT_ONLY, m_dirfilter.show_different_right_only);
3562         Redisplay();
3563 }
3564
3565 /**
3566  * @brief Show/Hide missing left only files/folders
3567  */
3568 void CDirView::OnOptionsShowMissingLeftOnly() 
3569 {
3570         m_dirfilter.show_missing_left_only = !m_dirfilter.show_missing_left_only;
3571         GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_LEFT_ONLY, m_dirfilter.show_missing_left_only);
3572         Redisplay();
3573 }
3574
3575 /**
3576  * @brief Show/Hide missing middle only files/folders
3577  */
3578 void CDirView::OnOptionsShowMissingMiddleOnly() 
3579 {
3580         m_dirfilter.show_missing_middle_only = !m_dirfilter.show_missing_middle_only;
3581         GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_MIDDLE_ONLY, m_dirfilter.show_missing_middle_only);
3582         Redisplay();
3583 }
3584
3585 /**
3586  * @brief Show/Hide missing right only files/folders
3587  */
3588 void CDirView::OnOptionsShowMissingRightOnly() 
3589 {
3590         m_dirfilter.show_missing_right_only = !m_dirfilter.show_missing_right_only;
3591         GetOptionsMgr()->SaveOption(OPT_SHOW_MISSING_RIGHT_ONLY, m_dirfilter.show_missing_right_only);
3592         Redisplay();
3593 }
3594
3595 void CDirView::OnUpdateOptionsShowdifferent(CCmdUI* pCmdUI) 
3596 {
3597         pCmdUI->SetCheck(m_dirfilter.show_different);
3598 }
3599
3600 void CDirView::OnUpdateOptionsShowidentical(CCmdUI* pCmdUI) 
3601 {
3602         pCmdUI->SetCheck(m_dirfilter.show_identical);
3603 }
3604
3605 void CDirView::OnUpdateOptionsShowuniqueleft(CCmdUI* pCmdUI) 
3606 {
3607         pCmdUI->SetCheck(m_dirfilter.show_unique_left);
3608 }
3609
3610 void CDirView::OnUpdateOptionsShowuniquemiddle(CCmdUI* pCmdUI) 
3611 {
3612         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3613         pCmdUI->SetCheck(m_dirfilter.show_unique_middle);
3614 }
3615
3616 void CDirView::OnUpdateOptionsShowuniqueright(CCmdUI* pCmdUI) 
3617 {
3618         pCmdUI->SetCheck(m_dirfilter.show_unique_right);
3619 }
3620
3621 void CDirView::OnUpdateOptionsShowBinaries(CCmdUI* pCmdUI) 
3622 {
3623         pCmdUI->SetCheck(m_dirfilter.show_binaries);
3624 }
3625
3626 void CDirView::OnUpdateOptionsShowSkipped(CCmdUI* pCmdUI)
3627 {
3628         pCmdUI->SetCheck(m_dirfilter.show_skipped);
3629 }
3630
3631 void CDirView::OnUpdateOptionsShowDifferentLeftOnly(CCmdUI* pCmdUI) 
3632 {
3633         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3634         pCmdUI->SetCheck(m_dirfilter.show_different_left_only);
3635 }
3636
3637 void CDirView::OnUpdateOptionsShowDifferentMiddleOnly(CCmdUI* pCmdUI) 
3638 {
3639         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3640         pCmdUI->SetCheck(m_dirfilter.show_different_middle_only);
3641 }
3642
3643 void CDirView::OnUpdateOptionsShowDifferentRightOnly(CCmdUI* pCmdUI) 
3644 {
3645         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3646         pCmdUI->SetCheck(m_dirfilter.show_different_right_only);
3647 }
3648
3649 void CDirView::OnUpdateOptionsShowMissingLeftOnly(CCmdUI* pCmdUI) 
3650 {
3651         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3652         pCmdUI->SetCheck(m_dirfilter.show_missing_left_only);
3653 }
3654
3655 void CDirView::OnUpdateOptionsShowMissingMiddleOnly(CCmdUI* pCmdUI) 
3656 {
3657         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3658         pCmdUI->SetCheck(m_dirfilter.show_missing_middle_only);
3659 }
3660
3661 void CDirView::OnUpdateOptionsShowMissingRightOnly(CCmdUI* pCmdUI) 
3662 {
3663         pCmdUI->Enable(GetDocument()->m_nDirs > 2);
3664         pCmdUI->SetCheck(m_dirfilter.show_missing_right_only);
3665 }
3666
3667 void CDirView::OnMergeCompare()
3668 {
3669         CWaitCursor waitstatus;
3670         OpenSelection();
3671 }
3672
3673 template<SELECTIONTYPE seltype>
3674 void CDirView::OnMergeCompare2()
3675 {
3676         CWaitCursor waitstatus;
3677         OpenSelection(seltype);
3678 }
3679
3680 void CDirView::OnMergeCompareNonHorizontally()
3681 {
3682         int sel1, sel2, sel3;
3683         if (!GetSelectedItems(&sel1, &sel2, &sel3))
3684                 return;
3685         DirSelectFilesDlg dlg;
3686         if (sel1 != -1)
3687                 dlg.m_pdi[0] = &GetDiffItem(sel1);
3688         if (sel2 != -1)
3689                 dlg.m_pdi[1] = &GetDiffItem(sel2);
3690         if (sel3 != -1)
3691                 dlg.m_pdi[2] = &GetDiffItem(sel3);
3692         if (dlg.DoModal() == IDOK && dlg.m_selectedButtons.size() > 0)
3693         {
3694                 CDirDoc *pDoc = GetDocument();
3695                 DWORD dwFlags[3] = {};
3696                 PathContext paths;
3697                 for (int nIndex = 0; nIndex < static_cast<int>(dlg.m_selectedButtons.size()); ++nIndex)
3698                 {
3699                         int n = dlg.m_selectedButtons[nIndex];
3700                         dwFlags[nIndex] = FFILEOPEN_NOMRU | (pDoc->GetReadOnly(n % 3) ? FFILEOPEN_READONLY : 0);
3701                         if (dlg.m_pdi[n / 3])
3702                                 paths.SetPath(nIndex, GetItemFileName(pDoc->GetDiffContext(), *dlg.m_pdi[n / 3], n % 3));
3703                 }
3704                 if (paths.GetSize() == 1)
3705                         paths.SetRight(_T(""));
3706                 Open(paths, dwFlags);
3707         }
3708 }
3709
3710 void CDirView::OnMergeCompareXML()
3711 {
3712         CWaitCursor waitstatus;
3713         PackingInfo packingInfo(PLUGIN_MODE::PLUGIN_BUILTIN_XML);
3714         OpenSelection(SELECTIONTYPE_NORMAL, &packingInfo, false);
3715 }
3716
3717 void CDirView::OnMergeCompareAs(UINT nID)
3718 {
3719         CWaitCursor waitstatus;
3720         OpenSelectionAs(nID);
3721 }
3722
3723 void CDirView::OnUpdateMergeCompare(CCmdUI *pCmdUI)
3724 {
3725         bool openableForDir = (pCmdUI->m_nID != ID_MERGE_COMPARE_XML &&
3726                                                    pCmdUI->m_nID != ID_MERGE_COMPARE_HEX &&
3727                                                    pCmdUI->m_nID != ID_MERGE_COMPARE_IMAGE);
3728
3729         DoUpdateOpen(SELECTIONTYPE_NORMAL, pCmdUI, openableForDir);
3730 }
3731
3732 template<SELECTIONTYPE seltype>
3733 void CDirView::OnUpdateMergeCompare2(CCmdUI *pCmdUI)
3734 {
3735         DoUpdateOpen(seltype, pCmdUI);
3736 }
3737
3738 void CDirView::OnViewCompareStatistics()
3739 {
3740         CompareStatisticsDlg dlg(GetDocument()->GetCompareStats());
3741         dlg.DoModal();
3742 }
3743
3744 /**
3745  * @brief Count left & right files, and number with editable text encoding
3746  * @param nLeft [out]  #files on left side selected
3747  * @param nLeftAffected [out]  #files on left side selected which can have text encoding changed
3748  * @param nRight [out]  #files on right side selected
3749  * @param nRightAffected [out]  #files on right side selected which can have text encoding changed
3750  *
3751  * Affected files include all except unicode files
3752  */
3753 void CDirView::FormatEncodingDialogDisplays(CLoadSaveCodepageDlg * dlg)
3754 {
3755         IntToIntMap currentCodepages = CountCodepages(SelBegin(), SelEnd(), GetDiffContext());
3756
3757         Counts left, middle, right;
3758         left = Count(&DirActions::IsItemEditableEncoding<SIDE_LEFT>);
3759         if (GetDocument()->m_nDirs > 2)
3760                 middle = Count(&DirActions::IsItemEditableEncoding<SIDE_MIDDLE>);
3761         right = Count(&DirActions::IsItemEditableEncoding<SIDE_RIGHT>);
3762
3763         // Format strings such as "25 of 30 Files Affected"
3764         String sLeftAffected = FormatFilesAffectedString(left.count, left.total);
3765         String sMiddleAffected = (GetDocument()->m_nDirs < 3) ? _T("") : FormatFilesAffectedString(middle.count, middle.total);
3766         String sRightAffected = FormatFilesAffectedString(right.count, right.total);
3767         dlg->SetLeftRightAffectStrings(sLeftAffected, sMiddleAffected, sRightAffected);
3768         int codepage = currentCodepages.FindMaxKey();
3769         dlg->SetCodepages(codepage);
3770 }
3771
3772 /**
3773  * @brief Display file encoding dialog to user & handle user's choices
3774  *
3775  * This handles DirView invocation, so multiple files may be affected
3776  */
3777 void CDirView::DoFileEncodingDialog()
3778 {
3779         CLoadSaveCodepageDlg dlg(GetDocument()->m_nDirs);
3780         // set up labels about what will be affected
3781         FormatEncodingDialogDisplays(&dlg);
3782         dlg.EnableSaveCodepage(false); // disallow setting a separate codepage for saving
3783
3784         // Invoke dialog
3785         if (dlg.DoModal() != IDOK)
3786                 return;
3787
3788         bool affected[3];
3789         affected[0] = dlg.DoesAffectLeft();
3790         affected[1] = dlg.DoesAffectMiddle();
3791         affected[SideToIndex(GetDiffContext(), SIDE_RIGHT)] = dlg.DoesAffectRight();
3792
3793         ApplyCodepage(SelBegin(), SelEnd(), GetDiffContext(), affected, dlg.GetLoadCodepage());
3794
3795         m_pList->InvalidateRect(nullptr);
3796         m_pList->UpdateWindow();
3797
3798         // TODO: We could loop through any active merge windows belonging to us
3799         // and see if any of their files are affected
3800         // but, if they've been edited, we cannot throw away the user's work?
3801 }
3802
3803 /**
3804  * @brief Display file encoding dialog & handle user's actions
3805  */
3806 void CDirView::OnFileEncoding()
3807 {
3808         DoFileEncodingDialog();
3809 }
3810
3811 /** @brief Open help from mainframe when user presses F1*/
3812 void CDirView::OnHelp()
3813 {
3814         theApp.ShowHelp(DirViewHelpLocation);
3815 }
3816
3817 /**
3818  * @brief true while user is editing a file name.
3819  */
3820 bool CDirView::IsLabelEdit() const
3821 {
3822         return (m_pList->GetEditControl() != nullptr);
3823 }
3824
3825 /**
3826  * @brief Allow edit "Paste" when renaming an item.
3827  */
3828 void CDirView::OnEditCopy()
3829 {
3830         CEdit *pEdit = m_pList->GetEditControl();
3831         if (pEdit != nullptr)
3832         {
3833                 pEdit->Copy();
3834         }
3835 }
3836
3837 /**
3838  * @brief Allow edit "Cut" when renaming an item.
3839  */
3840 void CDirView::OnEditCut()
3841 {
3842         CEdit *pEdit = m_pList->GetEditControl();
3843         if (pEdit != nullptr)
3844         {
3845                 pEdit->Cut();
3846         }
3847 }
3848
3849 /**
3850 * @brief Allow edit "Paste" when renaming an item.
3851  */
3852 void CDirView::OnEditPaste()
3853 {
3854         CEdit *pEdit = m_pList->GetEditControl();
3855         if (pEdit != nullptr)
3856         {
3857                 pEdit->Paste();
3858         }
3859 }
3860
3861 /**
3862  * @brief Allow edit "Undo" when renaming an item.
3863  */
3864 void CDirView::OnEditUndo()
3865 {
3866         CEdit *pEdit = m_pList->GetEditControl();
3867         if (pEdit != nullptr)
3868         {
3869                 pEdit->Undo();
3870         }
3871 }
3872
3873 /**
3874  * @brief Update the tool bar's "Undo" icon. It should be enabled when
3875  * renaming an item and undo is possible.
3876  */
3877 void CDirView::OnUpdateEditUndo(CCmdUI* pCmdUI)
3878 {
3879         CEdit *pEdit = m_pList->GetEditControl();
3880         pCmdUI->Enable(pEdit && pEdit->CanUndo());
3881 }
3882 /**
3883  * @brief Returns CShellContextMenu object that owns given HMENU.
3884  *
3885  * @param [in] hMenu Handle to the menu to check ownership of.
3886  * @return Either m_pShellContextMenuLeft, m_pShellContextMenuRight
3887  *   or `nullptr` if hMenu is not owned by these two.
3888  */
3889 CShellContextMenu* CDirView::GetCorrespondingShellContextMenu(HMENU hMenu) const
3890 {
3891         CShellContextMenu* pMenu = nullptr;
3892         if (m_pShellContextMenuLeft!=nullptr && hMenu == m_pShellContextMenuLeft->GetHMENU())
3893                 pMenu = m_pShellContextMenuLeft.get();
3894         else if (m_pShellContextMenuMiddle!=nullptr && hMenu == m_pShellContextMenuMiddle->GetHMENU())
3895                 pMenu = m_pShellContextMenuMiddle.get();
3896         else if (m_pShellContextMenuRight!=nullptr && hMenu == m_pShellContextMenuRight->GetHMENU())
3897                 pMenu = m_pShellContextMenuRight.get();
3898
3899         return pMenu;
3900 }
3901
3902 /**
3903  * @brief Handle messages related to correct menu working.
3904  *
3905  * We need to requery shell context menu each time we switch from context menu
3906  * for one side to context menu for other side. Here we check whether we need to
3907  * requery and call ShellContextMenuHandleMenuMessage.
3908  */
3909 LRESULT CDirView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
3910 {
3911         while (message == WM_INITMENUPOPUP)
3912         {
3913                 HMENU hMenu = (HMENU)wParam;
3914                 if (CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(hMenu))
3915                 {
3916                         if (m_hCurrentMenu != hMenu)
3917                         {
3918                                 // re-query context menu once more, because if context menu was queried for right
3919                                 // group of files and we are showing menu for left group (or vice versa) menu will
3920                                 // be shown incorrectly
3921                                 // also, if context menu was last queried for right group of files and we are
3922                                 // invoking command for left command will be executed for right group (the last
3923                                 // group that menu was requested for)
3924                                 // may be a "feature" of Shell
3925
3926                                 pMenu->RequeryShellContextMenu();
3927                                 m_hCurrentMenu = hMenu;
3928                         }
3929                 }
3930                 break;
3931         }
3932
3933         CShellContextMenu* pMenu = GetCorrespondingShellContextMenu(m_hCurrentMenu);
3934
3935         if (pMenu != nullptr)
3936         {
3937                 LRESULT res = 0;
3938                 pMenu->HandleMenuMessage(message, wParam, lParam, res);
3939         }
3940
3941         return CListView::WindowProc(message, wParam, lParam);
3942 }
3943
3944 /**
3945  * @brief Implement background item coloring
3946  */
3947 void CDirView::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult) 
3948 {
3949         if (!m_bUseColors) {
3950                 return;
3951         }
3952
3953         LPNMLISTVIEW pNM = (LPNMLISTVIEW)pNMHDR;
3954         *pResult = CDRF_DODEFAULT;
3955
3956         if (pNM->hdr.code == NM_CUSTOMDRAW)
3957         {
3958                 LPNMLVCUSTOMDRAW lpC = (LPNMLVCUSTOMDRAW)pNMHDR;
3959
3960                 if (lpC->nmcd.dwDrawStage == CDDS_PREPAINT)
3961                 {
3962                         *pResult =  CDRF_NOTIFYITEMDRAW;
3963                         return;
3964                 }
3965
3966                 if (lpC->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
3967                 {
3968                         *pResult = CDRF_NOTIFYITEMDRAW;
3969                         return;
3970                 }
3971
3972                 if (lpC->nmcd.dwDrawStage == (CDDS_ITEMPREPAINT | CDDS_SUBITEM ))
3973                 {
3974                         GetColors (static_cast<int>(lpC->nmcd.dwItemSpec), lpC->iSubItem, lpC->clrTextBk, lpC->clrText);
3975                 }
3976         }
3977 }
3978
3979 void CDirView::OnBnClickedComparisonStop()
3980 {
3981         if (m_pCmpProgressBar != nullptr)
3982                 m_pCmpProgressBar->EndUpdating();
3983         GetDocument()->AbortCurrentScan();
3984 }
3985
3986 void CDirView::OnBnClickedComparisonPause()
3987 {
3988         if (m_pCmpProgressBar != nullptr)
3989                 m_pCmpProgressBar->SetPaused(true);
3990         GetDocument()->PauseCurrentScan();
3991 }
3992
3993 void CDirView::OnBnClickedComparisonContinue()
3994 {
3995         if (m_pCmpProgressBar != nullptr)
3996                 m_pCmpProgressBar->SetPaused(false);
3997         GetDocument()->ContinueCurrentScan();
3998 }
3999
4000 /**
4001  * @brief Populate colors for items in view, depending on difference status
4002  */
4003 void CDirView::GetColors (int nRow, int nCol, COLORREF& clrBk, COLORREF& clrText) const
4004 {
4005         const DIFFITEM& di = GetDiffItem (nRow);
4006
4007         if (di.isEmpty())
4008         {
4009                 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4010                 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4011         }
4012         else if (di.diffcode.isResultFiltered())
4013         {
4014                 clrText = m_cachedColors.clrDirItemFilteredText;
4015                 clrBk = m_cachedColors.clrDirItemFiltered;
4016         }
4017         else if (!IsItemExistAll(GetDiffContext(), di))
4018         {
4019                 clrText = m_cachedColors.clrDirItemNotExistAllText;
4020                 clrBk = m_cachedColors.clrDirItemNotExistAll;
4021         }
4022         else if (di.diffcode.isResultDiff())
4023         {
4024                 clrText = m_cachedColors.clrDirItemDiffText;
4025                 clrBk = m_cachedColors.clrDirItemDiff;
4026         }
4027         else if (di.diffcode.isResultSame())
4028         {
4029                 clrText = m_cachedColors.clrDirItemEqualText;
4030                 clrBk = m_cachedColors.clrDirItemEqual;
4031         }
4032         else
4033         {
4034                 clrText = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_NORMALTEXT);
4035                 clrBk = theApp.GetMainSyntaxColors()->GetColor(COLORINDEX_BKGND);
4036         }
4037 }
4038
4039 void CDirView::OnSearch()
4040 {
4041         CDirDoc *pDoc = GetDocument();
4042         m_pList->SetRedraw(FALSE);      // Turn off updating (better performance)
4043         int nRows = m_pList->GetItemCount();
4044         for (int currRow = nRows - 1; currRow >= 0; currRow--)
4045         {
4046                 DIFFITEM *pos = GetItemKey(currRow);
4047                 if (pos == (DIFFITEM *)SPECIAL_ITEM_POS)
4048                         continue;
4049
4050                 bool bFound = false;
4051                 DIFFITEM &di = GetDiffItem(currRow);
4052                 PathContext paths;
4053                 for (int i = 0; i < pDoc->m_nDirs; i++)
4054                 {
4055                         if (di.diffcode.exists(i) && !di.diffcode.isDirectory())
4056                         {
4057                                 GetItemFileNames(currRow, &paths);
4058                                 UniMemFile ufile;
4059                                 if (!ufile.OpenReadOnly(paths[i]))
4060                                         continue;
4061
4062                                 ufile.SetUnicoding(di.diffFileInfo[i].encoding.m_unicoding);
4063                                 ufile.SetBom(di.diffFileInfo[i].encoding.m_bom);
4064                                 ufile.SetCodepage(di.diffFileInfo[i].encoding.m_codepage);
4065
4066                                 ufile.ReadBom();
4067
4068                                 String line;
4069                                 for (;;)
4070                                 {
4071                                         bool lossy = false;
4072                                         if (!ufile.ReadString(line, &lossy))
4073                                                 break;
4074                                         
4075                                         if (_tcsstr(line.c_str(), _T("DirView")))
4076                                         {
4077                                                 bFound = true;
4078                                                 break;
4079                                         }
4080                                 }
4081
4082                                 ufile.Close();
4083                                 if (bFound)
4084                                         break;
4085                         }
4086                 }
4087                 if (!bFound)
4088                 {
4089                         SetItemViewFlag(di, ViewCustomFlags::HIDDEN, ViewCustomFlags::VISIBILITY);
4090                         DeleteItem(currRow);
4091                         m_nHiddenItems++;
4092                 }
4093         }
4094         m_pList->SetRedraw(TRUE);       // Turn updating back on
4095 }
4096
4097 /**
4098  * @brief Drag files/directories from folder compare listing view.
4099  */
4100 void CDirView::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult) 
4101 {
4102         COleDataSource *DropData = new COleDataSource();
4103
4104         std::list<String> list;
4105         CopyPathnamesForDragAndDrop(SelBegin(), SelEnd(), std::back_inserter(list), GetDiffContext());
4106         String filesForDroping = strutils::join(list.begin(), list.end(), _T("\n")) + _T("\n");
4107
4108         CSharedFile file(GMEM_DDESHARE | GMEM_MOVEABLE | GMEM_ZEROINIT);
4109         file.Write(filesForDroping.data(), static_cast<unsigned>((filesForDroping.length() + 1) * sizeof(TCHAR)));
4110         
4111         HGLOBAL hMem = GlobalReAlloc(file.Detach(), (filesForDroping.length() + 1) * sizeof(TCHAR), 0);
4112         if (hMem != nullptr) 
4113         {
4114                 DropData->CacheGlobalData(CF_UNICODETEXT, hMem);
4115                 DROPEFFECT de = DropData->DoDragDrop(DROPEFFECT_COPY | DROPEFFECT_MOVE, nullptr);
4116         }
4117
4118         *pResult = 0;
4119 }
4120
4121 /// Assign column name, using string resource & current column ordering
4122 void CDirView::NameColumn(const DirColInfo *col, int subitem)
4123 {
4124         int phys = m_pColItems->ColLogToPhys(subitem);
4125         if (phys>=0)
4126         {
4127                 String s = tr(col->idNameContext, col->idName);
4128                 LV_COLUMN lvc;
4129                 lvc.mask = LVCF_TEXT;
4130                 lvc.pszText = const_cast<LPTSTR>(s.c_str());
4131                 m_pList->SetColumn(phys, &lvc);
4132         }
4133 }
4134
4135 /// Load column names from string table
4136 void CDirView::UpdateColumnNames()
4137 {
4138         int ncols = m_pColItems->GetColCount();
4139         for (int i=0; i<ncols; ++i)
4140         {
4141                 const DirColInfo* col = m_pColItems->GetDirColInfo(i);
4142                 NameColumn(col, i);
4143         }
4144 }
4145
4146 /**
4147  * @brief Set alignment of columns.
4148  */
4149 void CDirView::SetColAlignments()
4150 {
4151         int ncols = m_pColItems->GetColCount();
4152         for (int i=0; i<ncols; ++i)
4153         {
4154                 const DirColInfo * col = m_pColItems->GetDirColInfo(i);
4155                 LVCOLUMN lvc;
4156                 lvc.mask = LVCF_FMT;
4157                 lvc.fmt = col->alignment;
4158                 m_pList->SetColumn(m_pColItems->ColLogToPhys(i), &lvc);
4159         }
4160 }
4161
4162 CDirView::CompareState::CompareState(const CDiffContext *pCtxt, const DirViewColItems *pColItems, int sortCol, bool bSortAscending, bool bTreeMode)
4163 : pCtxt(pCtxt)
4164 , pColItems(pColItems)
4165 , sortCol(sortCol)
4166 , bSortAscending(bSortAscending)
4167 , bTreeMode(bTreeMode)
4168 {
4169 }
4170
4171 /// Compare two specified rows during a sort operation (windows callback)
4172 int CALLBACK CDirView::CompareState::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
4173 {
4174         CompareState *pThis = reinterpret_cast<CompareState*>(lParamSort);
4175         // Sort special items always first in dir view
4176         if (lParam1 == -1)
4177                 return -1;
4178         if (lParam2 == -1)
4179                 return 1;
4180
4181         DIFFITEM *diffposl = (DIFFITEM *)lParam1;
4182         DIFFITEM *diffposr = (DIFFITEM *)lParam2;
4183         const DIFFITEM &ldi = pThis->pCtxt->GetDiffAt(diffposl);
4184         const DIFFITEM &rdi = pThis->pCtxt->GetDiffAt(diffposr);
4185         // compare 'left' and 'right' parameters as appropriate
4186         int retVal = pThis->pColItems->ColSort(pThis->pCtxt, pThis->sortCol, ldi, rdi, pThis->bTreeMode);
4187         // return compare result, considering sort direction
4188         return pThis->bSortAscending ? retVal : -retVal;
4189 }
4190
4191 /// Add new item to list view
4192 int CDirView::AddNewItem(int i, DIFFITEM *diffpos, int iImage, int iIndent)
4193 {
4194         LV_ITEM lvItem;
4195         lvItem.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE | LVIF_INDENT;
4196         lvItem.iItem = i;
4197         lvItem.iIndent = iIndent;
4198         lvItem.iSubItem = 0;
4199         lvItem.pszText = LPSTR_TEXTCALLBACK;
4200         lvItem.lParam = (LPARAM)diffpos;
4201         lvItem.iImage = iImage;
4202         return GetListCtrl().InsertItem(&lvItem);
4203 }
4204
4205 /**
4206  * @brief Update listview display of details for specified row
4207  * @note Customising shownd data should be done here
4208  */
4209 void CDirView::UpdateDiffItemStatus(UINT nIdx)
4210 {
4211         GetListCtrl().RedrawItems(nIdx, nIdx);
4212         const DIFFITEM& di = GetDiffItem(nIdx);
4213         if (di.diffcode.isDirectory())
4214         {
4215                 DirItemIterator it;
4216                 for (it = RevBegin(); it != RevEnd(); )
4217                 {
4218                         DIFFITEM& di2 = *it;
4219                         int cursel = it.m_sel;
4220                         ++it;
4221                         if (di2.IsAncestor(&di))
4222                         {
4223                                 if ((di2.diffcode.diffcode & DIFFCODE::SIDEFLAGS) == 0)
4224                                         DeleteItem(cursel, true);
4225                                 else
4226                                         GetListCtrl().RedrawItems(cursel, cursel);
4227                         }
4228                 }
4229         }
4230 }
4231
4232 static String rgDispinfoText[2]; // used in function below
4233
4234 /**
4235  * @brief Allocate a text buffer to assign to NMLVDISPINFO::item::pszText
4236  * Quoting from SDK Docs:
4237  *      If the LVITEM structure is receiving item text, the pszText and cchTextMax
4238  *      members specify the address and size of a buffer. You can either copy text to
4239  *      the buffer or assign the address of a string to the pszText member. In the
4240  *      latter case, you must not change or delete the string until the corresponding
4241  *      item text is deleted or two additional LVN_GETDISPINFO messages have been sent.
4242  */
4243 static LPTSTR NTAPI AllocDispinfoText(const String &s)
4244 {
4245         static int i = 0;
4246         LPCTSTR pszText = (rgDispinfoText[i] = s).c_str();
4247         i ^= 1;
4248         return (LPTSTR)pszText;
4249 }
4250
4251 /**
4252  * @brief Respond to LVN_GETDISPINFO message
4253  */
4254 void CDirView::ReflectGetdispinfo(NMLVDISPINFO *pParam)
4255 {
4256         int nIdx = pParam->item.iItem;
4257         int i = m_pColItems->ColPhysToLog(pParam->item.iSubItem);
4258         DIFFITEM *key = GetItemKey(nIdx);
4259         if (key == (DIFFITEM *)SPECIAL_ITEM_POS)
4260         {
4261                 if (m_pColItems->IsColName(i))
4262                 {
4263                         pParam->item.pszText = _T("..");
4264                 }
4265                 return;
4266         }
4267         if (!GetDocument()->HasDiffs())
4268                 return;
4269         const CDiffContext &ctxt = GetDiffContext();
4270         const DIFFITEM &di = ctxt.GetDiffAt(key);
4271         if (pParam->item.mask & LVIF_TEXT)
4272         {
4273                 String s = m_pColItems->ColGetTextToDisplay(&ctxt, i, di);
4274                 pParam->item.pszText = AllocDispinfoText(s);
4275         }
4276         if (pParam->item.mask & LVIF_IMAGE)
4277         {
4278                 pParam->item.iImage = GetColImage(di);
4279         }
4280 }
4281
4282 /**
4283  * @brief User examines & edits which columns are displayed in dirview, and in which order
4284  */
4285 void CDirView::OnEditColumns()
4286 {
4287         CDirColsDlg dlg;
4288         // List all the currently displayed columns
4289         for (int col=0; col<GetListCtrl().GetHeaderCtrl()->GetItemCount(); ++col)
4290         {
4291                 int l = m_pColItems->ColPhysToLog(col);
4292                 dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l, col);
4293         }
4294         // Now add all the columns not currently displayed
4295         int l=0;
4296         for (l=0; l<m_pColItems->GetColCount(); ++l)
4297         {
4298                 if (m_pColItems->ColLogToPhys(l)==-1)
4299                 {
4300                         dlg.AddColumn(m_pColItems->GetColDisplayName(l), m_pColItems->GetColDescription(l), l);
4301                 }
4302         }
4303
4304         // Add default order of columns for resetting to defaults
4305         for (l = 0; l < m_pColItems->GetColCount(); ++l)
4306         {
4307                 int phy = m_pColItems->GetColDefaultOrder(l);
4308                 dlg.AddDefColumn(m_pColItems->GetColDisplayName(l), l, phy);
4309         }
4310
4311         if (dlg.DoModal() != IDOK)
4312                 return;
4313
4314         const String keyname = GetDocument()->m_nDirs < 3 ? OPT_DIRVIEW_COLUMN_WIDTHS : OPT_DIRVIEW3_COLUMN_WIDTHS;
4315         GetOptionsMgr()->SaveOption(keyname,
4316                 (dlg.m_bReset ? m_pColItems->ResetColumnWidths(GetDefColumnWidth()) :
4317                                 m_pColItems->SaveColumnWidths(std::bind(&CListCtrl::GetColumnWidth, m_pList, _1))));
4318
4319         // Reset our data to reflect the new data from the dialog
4320         const CDirColsDlg::ColumnArray & cols = dlg.GetColumns();
4321         m_pColItems->ClearColumnOrders();
4322         const int sortColumn = GetOptionsMgr()->GetInt((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4323         std::vector<int> colorder(m_pColItems->GetColCount(), -1);
4324         for (CDirColsDlg::ColumnArray::const_iterator iter = cols.begin();
4325                 iter != cols.end(); ++iter)
4326         {
4327                 int log = iter->log_col; 
4328                 int phy = iter->phy_col;
4329                 colorder[log] = phy;
4330
4331                 // If sorted column was hidden, reset sorting
4332                 if (log == sortColumn && phy < 0)
4333                 {
4334                         GetOptionsMgr()->Reset((GetDocument()->m_nDirs < 3) ? OPT_DIRVIEW_SORT_COLUMN : OPT_DIRVIEW_SORT_COLUMN3);
4335                         GetOptionsMgr()->Reset(OPT_DIRVIEW_SORT_ASCENDING);
4336                 }
4337         }
4338
4339         m_pColItems->SetColumnOrdering(&colorder[0]);
4340
4341         if (m_pColItems->GetDispColCount() < 1)
4342         {
4343                 // Ignore them if they didn't leave a column showing
4344                 m_pColItems->ResetColumnOrdering();
4345         }
4346         else
4347         {
4348                 ReloadColumns();
4349                 Redisplay();
4350         }
4351 }
4352
4353 DirActions CDirView::MakeDirActions(DirActions::method_type func) const
4354 {
4355         const CDirDoc *pDoc = GetDocument();
4356         return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), func);
4357 }
4358
4359 DirActions CDirView::MakeDirActions(DirActions::method_type2 func) const
4360 {
4361         const CDirDoc *pDoc = GetDocument();
4362         return DirActions(pDoc->GetDiffContext(), pDoc->GetReadOnly(), nullptr, func);
4363 }
4364
4365 const CDiffContext& CDirView::GetDiffContext() const
4366 {
4367         return GetDocument()->GetDiffContext();
4368 }
4369
4370 CDiffContext& CDirView::GetDiffContext()
4371 {
4372         return GetDocument()->GetDiffContext();
4373 }