OSDN Git Service

246258dd5bd4048dbfe3397bb54408190303a755
[winmerge-jp/winmerge-jp.git] / Src / MainFrm.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  MainFrm.cpp
9  *
10  * @brief Implementation of the CMainFrame class
11  */
12
13 #include "StdAfx.h"
14 #include "MainFrm.h"
15 #include <vector>
16 #include <afxinet.h>
17 #include <boost/range/mfc.hpp>
18 #include "Constants.h"
19 #include "Merge.h"
20 #include "FileFilterHelper.h"
21 #include "UnicodeString.h"
22 #include "BCMenu.h"
23 #include "OpenFrm.h"
24 #include "DirFrame.h"           // Include type information
25 #include "MergeEditFrm.h"
26 #include "HexMergeFrm.h"
27 #include "DirView.h"
28 #include "DirDoc.h"
29 #include "OpenDoc.h"
30 #include "MergeDoc.h"
31 #include "MergeEditView.h"
32 #include "HexMergeDoc.h"
33 #include "HexMergeView.h"
34 #include "ImgMergeFrm.h"
35 #include "LineFiltersList.h"
36 #include "SubstitutionFiltersList.h"
37 #include "ConflictFileParser.h"
38 #include "LineFiltersDlg.h"
39 #include "SubstitutionFiltersDlg.h"
40 #include "paths.h"
41 #include "Environment.h"
42 #include "PatchTool.h"
43 #include "Plugins.h"
44 #include "ConfigLog.h"
45 #include "7zCommon.h"
46 #include "Merge7zFormatMergePluginImpl.h"
47 #include "FileFiltersDlg.h"
48 #include "OptionsMgr.h"
49 #include "OptionsDef.h"
50 #include "codepage_detect.h"
51 #include "unicoder.h"
52 #include "PreferencesDlg.h"
53 #include "FileOrFolderSelect.h"
54 #include "PluginsListDlg.h"
55 #include "SelectPluginDlg.h"
56 #include "stringdiffs.h"
57 #include "MergeCmdLineInfo.h"
58 #include "OptionsFont.h"
59 #include "JumpList.h"
60 #include "DropHandler.h"
61 #include "LanguageSelect.h"
62 #include "VersionInfo.h"
63 #include "Bitmap.h"
64 #include "CCrystalTextMarkers.h"
65 #include "utils/hqbitmap.h"
66 #include "UniFile.h"
67 #include "TFile.h"
68 #include "Shell.h"
69 #include "WindowsManagerDialog.h"
70
71 using std::vector;
72 using boost::begin;
73 using boost::end;
74
75 #ifdef _DEBUG
76 #define new DEBUG_NEW
77 #endif
78
79 static void LoadToolbarImageList(int orgImageWidth, int newImageHeight, UINT nIDResource, bool bGrayscale, CImageList& ImgList);
80 static CPtrList &GetDocList(CMultiDocTemplate *pTemplate);
81 template<class DocClass>
82 DocClass * GetMergeDocForDiff(CMultiDocTemplate *pTemplate, CDirDoc *pDirDoc, int nFiles, bool bMakeVisible = true);
83
84 /**
85  * @brief A table associating menuitem id, icon and menus to apply.
86  */
87 const CMainFrame::MENUITEM_ICON CMainFrame::m_MenuIcons[] = {
88         { ID_FILE_OPENCONFLICT,                 IDB_FILE_OPENCONFLICT,                  CMainFrame::MENU_ALL },
89         { ID_FILE_NEW_TABLE,                    IDB_FILE_NEW_TABLE,                             CMainFrame::MENU_ALL },
90         { ID_FILE_NEW_HEX,                              IDB_FILE_NEW_HEX,                               CMainFrame::MENU_ALL },
91         { ID_FILE_NEW_IMAGE,                    IDB_FILE_NEW_IMAGE,                             CMainFrame::MENU_ALL },
92         { ID_FILE_NEW3,                                 IDB_FILE_NEW3,                                  CMainFrame::MENU_ALL },
93         { ID_FILE_NEW3_TABLE,                   IDB_FILE_NEW3_TABLE,                    CMainFrame::MENU_ALL },
94         { ID_FILE_NEW3_HEX,                             IDB_FILE_NEW3_HEX,                              CMainFrame::MENU_ALL },
95         { ID_FILE_NEW3_IMAGE,                   IDB_FILE_NEW3_IMAGE,                    CMainFrame::MENU_ALL },
96         { ID_EDIT_COPY,                                 IDB_EDIT_COPY,                                  CMainFrame::MENU_ALL },
97         { ID_EDIT_CUT,                                  IDB_EDIT_CUT,                                   CMainFrame::MENU_ALL },
98         { ID_EDIT_PASTE,                                IDB_EDIT_PASTE,                                 CMainFrame::MENU_ALL },
99         { ID_EDIT_FIND,                                 IDB_EDIT_SEARCH,                                CMainFrame::MENU_ALL },
100         { ID_WINDOW_CASCADE,                    IDB_WINDOW_CASCADE,                             CMainFrame::MENU_ALL },
101         { ID_WINDOW_TILE_HORZ,                  IDB_WINDOW_HORIZONTAL,                  CMainFrame::MENU_ALL },
102         { ID_WINDOW_TILE_VERT,                  IDB_WINDOW_VERTICAL,                    CMainFrame::MENU_ALL },
103         { ID_FILE_CLOSE,                                IDB_WINDOW_CLOSE,                               CMainFrame::MENU_ALL },
104         { ID_WINDOW_CHANGE_PANE,                IDB_WINDOW_CHANGEPANE,                  CMainFrame::MENU_ALL },
105         { ID_EDIT_WMGOTO,                               IDB_EDIT_GOTO,                                  CMainFrame::MENU_ALL },
106         { ID_EDIT_REPLACE,                              IDB_EDIT_REPLACE,                               CMainFrame::MENU_ALL },
107         { ID_VIEW_SELECTFONT,                   IDB_VIEW_SELECTFONT,                    CMainFrame::MENU_ALL },
108         { ID_APP_EXIT,                                  IDB_FILE_EXIT,                                  CMainFrame::MENU_ALL },
109         { ID_HELP_CONTENTS,                             IDB_HELP_CONTENTS,                              CMainFrame::MENU_ALL },
110         { ID_EDIT_SELECT_ALL,                   IDB_EDIT_SELECTALL,                             CMainFrame::MENU_ALL },
111         { ID_TOOLS_FILTERS,                             IDB_TOOLS_FILTERS,                              CMainFrame::MENU_ALL },
112         { ID_TOOLS_CUSTOMIZECOLUMNS,    IDB_TOOLS_COLUMNS,                              CMainFrame::MENU_ALL },
113         { ID_TOOLS_GENERATEPATCH,               IDB_TOOLS_GENERATEPATCH,                CMainFrame::MENU_ALL },
114         { ID_PLUGINS_LIST,                              IDB_PLUGINS_LIST,                               CMainFrame::MENU_ALL },
115         { ID_FILE_PRINT,                                IDB_FILE_PRINT,                                 CMainFrame::MENU_FILECMP },
116         { ID_TOOLS_GENERATEREPORT,              IDB_TOOLS_GENERATEREPORT,               CMainFrame::MENU_FILECMP },
117         { ID_EDIT_TOGGLE_BOOKMARK,              IDB_EDIT_TOGGLE_BOOKMARK,               CMainFrame::MENU_FILECMP },
118         { ID_EDIT_GOTO_NEXT_BOOKMARK,   IDB_EDIT_GOTO_NEXT_BOOKMARK,    CMainFrame::MENU_FILECMP },
119         { ID_EDIT_GOTO_PREV_BOOKMARK,   IDB_EDIT_GOTO_PREV_BOOKMARK,    CMainFrame::MENU_FILECMP },
120         { ID_EDIT_CLEAR_ALL_BOOKMARKS,  IDB_EDIT_CLEAR_ALL_BOOKMARKS,   CMainFrame::MENU_FILECMP },
121         { ID_VIEW_ZOOMIN,                               IDB_VIEW_ZOOMIN,                                CMainFrame::MENU_FILECMP },
122         { ID_VIEW_ZOOMOUT,                              IDB_VIEW_ZOOMOUT,                               CMainFrame::MENU_FILECMP },
123         { ID_COPY_FROM_LEFT,                    IDB_COPY_FROM_LEFT,                             CMainFrame::MENU_FILECMP },
124         { ID_COPY_FROM_RIGHT,                   IDB_COPY_FROM_RIGHT,                    CMainFrame::MENU_FILECMP },
125         { ID_LINES_R2L,                                 IDB_COPY_SELECTED_LINES_TO_LEFT,        CMainFrame::MENU_FILECMP },
126         { ID_LINES_L2R,                                 IDB_COPY_SELECTED_LINES_TO_RIGHT,       CMainFrame::MENU_FILECMP },
127         { ID_COPY_LINES_FROM_LEFT,              IDB_COPY_SELECTED_LINES_FROM_LEFT,      CMainFrame::MENU_FILECMP },
128         { ID_COPY_LINES_FROM_RIGHT,             IDB_COPY_SELECTED_LINES_FROM_RIGHT,     CMainFrame::MENU_FILECMP },
129         { ID_MERGE_COMPARE,                             IDB_MERGE_COMPARE,                              CMainFrame::MENU_FOLDERCMP },
130         { ID_MERGE_COMPARE_LEFT1_LEFT2,         IDB_MERGE_COMPARE_LEFT1_LEFT2,  CMainFrame::MENU_FOLDERCMP },
131         { ID_MERGE_COMPARE_RIGHT1_RIGHT2,       IDB_MERGE_COMPARE_RIGHT1_RIGHT2,CMainFrame::MENU_FOLDERCMP },
132         { ID_MERGE_COMPARE_LEFT1_RIGHT2,        IDB_MERGE_COMPARE_LEFT1_RIGHT2, CMainFrame::MENU_FOLDERCMP },
133         { ID_MERGE_COMPARE_LEFT2_RIGHT1,        IDB_MERGE_COMPARE_LEFT2_RIGHT1, CMainFrame::MENU_FOLDERCMP },
134         { ID_MERGE_DELETE,                              IDB_MERGE_DELETE,                               CMainFrame::MENU_FOLDERCMP },
135         { ID_TOOLS_GENERATEREPORT,              IDB_TOOLS_GENERATEREPORT,               CMainFrame::MENU_FOLDERCMP },
136         { ID_DIR_COPY_LEFT_TO_RIGHT,    IDB_LEFT_TO_RIGHT,                              CMainFrame::MENU_FOLDERCMP },
137         { ID_DIR_COPY_LEFT_TO_MIDDLE,   IDB_LEFT_TO_MIDDLE,                             CMainFrame::MENU_FOLDERCMP },
138         { ID_DIR_COPY_RIGHT_TO_LEFT,    IDB_RIGHT_TO_LEFT,                              CMainFrame::MENU_FOLDERCMP },
139         { ID_DIR_COPY_RIGHT_TO_MIDDLE,  IDB_RIGHT_TO_MIDDLE,                    CMainFrame::MENU_FOLDERCMP },
140         { ID_DIR_COPY_MIDDLE_TO_LEFT,   IDB_MIDDLE_TO_LEFT,                             CMainFrame::MENU_FOLDERCMP },
141         { ID_DIR_COPY_MIDDLE_TO_RIGHT,  IDB_MIDDLE_TO_RIGHT,                    CMainFrame::MENU_FOLDERCMP },
142         { ID_DIR_COPY_LEFT_TO_BROWSE,   IDB_LEFT_TO_BROWSE,                             CMainFrame::MENU_FOLDERCMP },
143         { ID_DIR_COPY_MIDDLE_TO_BROWSE, IDB_MIDDLE_TO_BROWSE,                   CMainFrame::MENU_FOLDERCMP },
144         { ID_DIR_COPY_RIGHT_TO_BROWSE,  IDB_RIGHT_TO_BROWSE,                    CMainFrame::MENU_FOLDERCMP },
145         { ID_DIR_MOVE_LEFT_TO_BROWSE,   IDB_MOVE_LEFT_TO_BROWSE,                CMainFrame::MENU_FOLDERCMP },
146         { ID_DIR_MOVE_MIDDLE_TO_BROWSE, IDB_MOVE_MIDDLE_TO_BROWSE,              CMainFrame::MENU_FOLDERCMP },
147         { ID_DIR_MOVE_RIGHT_TO_BROWSE,  IDB_MOVE_RIGHT_TO_BROWSE,               CMainFrame::MENU_FOLDERCMP },
148         { ID_DIR_DEL_LEFT,                              IDB_LEFT,                                               CMainFrame::MENU_FOLDERCMP },
149         { ID_DIR_DEL_MIDDLE,                    IDB_MIDDLE,                                             CMainFrame::MENU_FOLDERCMP },
150         { ID_DIR_DEL_RIGHT,                             IDB_RIGHT,                                              CMainFrame::MENU_FOLDERCMP },
151         { ID_DIR_DEL_BOTH,                              IDB_BOTH,                                               CMainFrame::MENU_FOLDERCMP },
152         { ID_DIR_DEL_ALL,                               IDB_ALL,                                                CMainFrame::MENU_FOLDERCMP },
153         { ID_DIR_COPY_PATHNAMES_LEFT,   IDB_LEFT,                                               CMainFrame::MENU_FOLDERCMP },
154         { ID_DIR_COPY_PATHNAMES_MIDDLE, IDB_MIDDLE,                                             CMainFrame::MENU_FOLDERCMP },
155         { ID_DIR_COPY_PATHNAMES_RIGHT,  IDB_RIGHT,                                              CMainFrame::MENU_FOLDERCMP },
156         { ID_DIR_COPY_PATHNAMES_BOTH,   IDB_BOTH,                                               CMainFrame::MENU_FOLDERCMP },
157         { ID_DIR_COPY_PATHNAMES_ALL,    IDB_ALL,                                                CMainFrame::MENU_FOLDERCMP },
158         { ID_DIR_COPY_LEFT_TO_CLIPBOARD, IDB_LEFT,                                              CMainFrame::MENU_FOLDERCMP },
159         { ID_DIR_COPY_MIDDLE_TO_CLIPBOARD, IDB_MIDDLE,                                  CMainFrame::MENU_FOLDERCMP },
160         { ID_DIR_COPY_RIGHT_TO_CLIPBOARD, IDB_RIGHT,                                    CMainFrame::MENU_FOLDERCMP },
161         { ID_DIR_COPY_BOTH_TO_CLIPBOARD, IDB_BOTH,                                              CMainFrame::MENU_FOLDERCMP },
162         { ID_DIR_COPY_ALL_TO_CLIPBOARD, IDB_ALL,                                                CMainFrame::MENU_FOLDERCMP },
163         { ID_DIR_ZIP_LEFT,                              IDB_LEFT,                                               CMainFrame::MENU_FOLDERCMP },
164         { ID_DIR_ZIP_MIDDLE,                    IDB_MIDDLE,                                             CMainFrame::MENU_FOLDERCMP },
165         { ID_DIR_ZIP_RIGHT,                             IDB_RIGHT,                                              CMainFrame::MENU_FOLDERCMP },
166         { ID_DIR_ZIP_BOTH,                              IDB_BOTH,                                               CMainFrame::MENU_FOLDERCMP },
167         { ID_DIR_ZIP_ALL,                               IDB_ALL,                                                CMainFrame::MENU_FOLDERCMP }
168 };
169
170
171 /////////////////////////////////////////////////////////////////////////////
172 // CMainFrame
173
174 IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
175
176 BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
177         //{{AFX_MSG_MAP(CMainFrame)
178         ON_WM_MENUCHAR()
179         ON_WM_MEASUREITEM()
180         ON_WM_INITMENUPOPUP()
181         ON_WM_INITMENU()
182         ON_WM_CREATE()
183         ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
184         ON_COMMAND(ID_HELP_GNULICENSE, OnHelpGnulicense)
185         ON_COMMAND(ID_OPTIONS, OnOptions)
186         ON_COMMAND(ID_VIEW_SELECTFONT, OnViewSelectfont)
187         ON_COMMAND(ID_VIEW_USEDEFAULTFONT, OnViewUsedefaultfont)
188         ON_COMMAND(ID_HELP_CONTENTS, OnHelpContents)
189         ON_WM_CLOSE()
190         ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
191         ON_WM_TIMER()
192         ON_WM_DESTROY()
193         ON_COMMAND_RANGE(ID_UNPACK_MANUAL, ID_UNPACK_AUTO, OnPluginUnpackMode)
194         ON_UPDATE_COMMAND_UI_RANGE(ID_UNPACK_MANUAL, ID_UNPACK_AUTO, OnUpdatePluginUnpackMode)
195         ON_COMMAND_RANGE(ID_PREDIFFER_MANUAL, ID_PREDIFFER_AUTO, OnPluginPrediffMode)
196         ON_UPDATE_COMMAND_UI_RANGE(ID_PREDIFFER_MANUAL, ID_PREDIFFER_AUTO, OnUpdatePluginPrediffMode)
197         ON_UPDATE_COMMAND_UI(ID_OPEN_WITH_UNPACKER, OnUpdatePluginRelatedMenu)
198         ON_UPDATE_COMMAND_UI(ID_APPLY_PREDIFFER, OnUpdatePluginRelatedMenu)
199         ON_UPDATE_COMMAND_UI(ID_TRANSFORM_WITH_SCRIPT, OnUpdatePluginRelatedMenu)
200         ON_UPDATE_COMMAND_UI(ID_RELOAD_PLUGINS, OnUpdatePluginRelatedMenu)
201         ON_COMMAND(ID_RELOAD_PLUGINS, OnReloadPlugins)
202         ON_COMMAND(ID_HELP_GETCONFIG, OnSaveConfigData)
203         ON_COMMAND(ID_FILE_NEW, (OnFileNew<2, FRAME_FILE>))
204         ON_COMMAND(ID_FILE_NEW_TABLE, (OnFileNew<2, FRAME_FILE, true>))
205         ON_COMMAND(ID_FILE_NEW_HEX, (OnFileNew<2, FRAME_HEXFILE>))
206         ON_COMMAND(ID_FILE_NEW_IMAGE, (OnFileNew<2, FRAME_IMGFILE>))
207         ON_COMMAND(ID_FILE_NEW3, (OnFileNew<3, FRAME_FILE>))
208         ON_COMMAND(ID_FILE_NEW3_TABLE, (OnFileNew<2, FRAME_FILE, true>))
209         ON_COMMAND(ID_FILE_NEW3_HEX, (OnFileNew<3, FRAME_HEXFILE>))
210         ON_COMMAND(ID_FILE_NEW3_IMAGE, (OnFileNew<3, FRAME_IMGFILE>))
211         ON_COMMAND(ID_TOOLS_FILTERS, OnToolsFilters)
212         ON_COMMAND(ID_VIEW_STATUS_BAR, OnViewStatusBar)
213         ON_UPDATE_COMMAND_UI(ID_VIEW_TAB_BAR, OnUpdateViewTabBar)
214         ON_COMMAND(ID_VIEW_TAB_BAR, OnViewTabBar)
215         ON_UPDATE_COMMAND_UI(ID_VIEW_RESIZE_PANES, OnUpdateResizePanes)
216         ON_COMMAND(ID_VIEW_RESIZE_PANES, OnResizePanes)
217         ON_COMMAND(ID_FILE_OPENPROJECT, OnFileOpenProject)
218         ON_MESSAGE(WM_COPYDATA, OnCopyData)
219         ON_MESSAGE(WM_USER+1, OnUser1)
220         ON_COMMAND(ID_WINDOW_CLOSEALL, OnWindowCloseAll)
221         ON_UPDATE_COMMAND_UI(ID_WINDOW_CLOSEALL, OnUpdateWindowCloseAll)
222         ON_COMMAND(ID_FILE_SAVEPROJECT, OnSaveProject)
223         ON_WM_ACTIVATEAPP()
224         ON_COMMAND_RANGE(ID_TOOLBAR_NONE, ID_TOOLBAR_HUGE, OnToolbarSize)
225         ON_UPDATE_COMMAND_UI_RANGE(ID_TOOLBAR_NONE, ID_TOOLBAR_HUGE, OnUpdateToolbarSize)
226         ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText)
227         ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText)
228         ON_COMMAND(ID_HELP_RELEASENOTES, OnHelpReleasenotes)
229         ON_COMMAND(ID_HELP_TRANSLATIONS, OnHelpTranslations)
230         ON_COMMAND(ID_FILE_OPENCONFLICT, OnFileOpenConflict)
231         ON_COMMAND(ID_PLUGINS_LIST, OnPluginsList)
232         ON_UPDATE_COMMAND_UI(ID_STATUS_PLUGIN, OnUpdatePluginName)
233         ON_NOTIFY(TBN_DROPDOWN, AFX_IDW_TOOLBAR, OnToolbarButtonDropDown)
234         ON_COMMAND_RANGE(ID_DIFF_OPTIONS_WHITESPACE_COMPARE, ID_DIFF_OPTIONS_WHITESPACE_IGNOREALL, OnDiffWhitespace)
235         ON_UPDATE_COMMAND_UI_RANGE(ID_DIFF_OPTIONS_WHITESPACE_COMPARE, ID_DIFF_OPTIONS_WHITESPACE_IGNOREALL, OnUpdateDiffWhitespace)
236         ON_COMMAND(ID_DIFF_OPTIONS_IGNORE_BLANKLINES, OnDiffIgnoreBlankLines)
237         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_IGNORE_BLANKLINES, OnUpdateDiffIgnoreBlankLines)
238         ON_COMMAND(ID_DIFF_OPTIONS_IGNORE_CASE, OnDiffIgnoreCase)
239         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_IGNORE_CASE, OnUpdateDiffIgnoreCase)
240         ON_COMMAND(ID_DIFF_OPTIONS_IGNORE_EOL, OnDiffIgnoreEOL)
241         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_IGNORE_EOL, OnUpdateDiffIgnoreEOL)
242         ON_COMMAND(ID_DIFF_OPTIONS_IGNORE_CODEPAGE, OnDiffIgnoreCP)
243         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_IGNORE_CODEPAGE, OnUpdateDiffIgnoreCP)
244         ON_COMMAND(ID_DIFF_OPTIONS_IGNORE_COMMENTS, OnDiffIgnoreComments)
245         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_IGNORE_COMMENTS, OnUpdateDiffIgnoreComments)
246         ON_COMMAND(ID_DIFF_OPTIONS_INCLUDE_SUBFOLDERS, OnIncludeSubfolders)
247         ON_UPDATE_COMMAND_UI(ID_DIFF_OPTIONS_INCLUDE_SUBFOLDERS, OnUpdateIncludeSubfolders)
248         ON_COMMAND_RANGE(ID_DIFF_OPTIONS_COMPMETHOD_FULL_CONTENTS, ID_DIFF_OPTIONS_COMPMETHOD_SIZE, OnCompareMethod)
249         ON_UPDATE_COMMAND_UI_RANGE(ID_DIFF_OPTIONS_COMPMETHOD_FULL_CONTENTS, ID_DIFF_OPTIONS_COMPMETHOD_SIZE, OnUpdateCompareMethod)
250         ON_COMMAND_RANGE(ID_MRU_FIRST, ID_MRU_LAST, OnMRUs)
251         ON_UPDATE_COMMAND_UI(ID_MRU_FIRST, OnUpdateNoMRUs)
252         ON_UPDATE_COMMAND_UI(ID_NO_MRU, OnUpdateNoMRUs)
253         ON_COMMAND(ID_FIRSTFILE, OnFirstFile)
254         ON_UPDATE_COMMAND_UI(ID_FIRSTFILE, OnUpdateFirstFile)
255         ON_COMMAND(ID_PREVFILE, OnPrevFile)
256         ON_UPDATE_COMMAND_UI(ID_PREVFILE, OnUpdatePrevFile)
257         ON_COMMAND(ID_NEXTFILE, OnNextFile)
258         ON_UPDATE_COMMAND_UI(ID_NEXTFILE, OnUpdateNextFile)
259         ON_COMMAND(ID_LASTFILE, OnLastFile)
260         ON_UPDATE_COMMAND_UI(ID_LASTFILE, OnUpdateLastFile)
261         ON_COMMAND(ID_ACCEL_QUIT, &CMainFrame::OnAccelQuit)
262         ON_MESSAGE(WMU_CHILDFRAMEADDED, &CMainFrame::OnChildFrameAdded)
263         ON_MESSAGE(WMU_CHILDFRAMEREMOVED, &CMainFrame::OnChildFrameRemoved)
264         ON_MESSAGE(WMU_CHILDFRAMEACTIVATE, &CMainFrame::OnChildFrameActivate)
265         ON_MESSAGE(WMU_CHILDFRAMEACTIVATED, &CMainFrame::OnChildFrameActivated)
266         //}}AFX_MSG_MAP
267 END_MESSAGE_MAP()
268
269 /**
270  * @brief MainFrame statusbar panels/indicators
271  */
272 static UINT StatusbarIndicators[] =
273 {
274         ID_SEPARATOR,           // Plugin name
275         ID_SEPARATOR,           // status line indicator
276         ID_SEPARATOR,           // Merge mode
277         ID_SEPARATOR,           // Diff number
278         ID_INDICATOR_CAPS,      // Caps Lock
279         ID_INDICATOR_NUM,       // Num Lock
280         ID_INDICATOR_OVR,       // Insert
281 };
282
283 /**
284   * @brief Return a const reference to a CMultiDocTemplate's list of documents.
285   */
286 static CPtrList &GetDocList(CMultiDocTemplate *pTemplate)
287 {
288         struct Template : public CMultiDocTemplate
289         {
290         public:
291                 using CMultiDocTemplate::m_docList;
292         };
293         return static_cast<struct Template *>(pTemplate)->m_docList;
294 }
295
296 /////////////////////////////////////////////////////////////////////////////
297 // CMainFrame construction/destruction
298
299 /**
300  * @brief MainFrame constructor. Loads settings from registry.
301  * @todo Preference for logging?
302  */
303 CMainFrame::CMainFrame()
304 : m_bFirstTime(true)
305 , m_pDropHandler(nullptr)
306 , m_bShowErrors(false)
307 , m_lfDiff(Options::Font::Load(GetOptionsMgr(), OPT_FONT_FILECMP))
308 , m_lfDir(Options::Font::Load(GetOptionsMgr(), OPT_FONT_DIRCMP))
309 {
310 }
311
312 CMainFrame::~CMainFrame()
313 {
314         GetOptionsMgr()->SaveOption(OPT_TABBAR_AUTO_MAXWIDTH, m_wndTabBar.GetAutoMaxWidth());
315         strdiff::Close();
316
317         m_arrChild.RemoveAll();
318 }
319
320 const TCHAR CMainFrame::szClassName[] = _T("WinMergeWindowClassW");
321
322 /**
323  * @brief Change MainFrame window class name
324  *        see http://support.microsoft.com/kb/403825/ja
325  */
326 BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
327 {
328         WNDCLASS wndcls;
329         BOOL bRes = CMDIFrameWnd::PreCreateWindow(cs);
330         HINSTANCE hInst = AfxGetInstanceHandle();
331         // see if the class already exists
332         if (!::GetClassInfo(hInst, szClassName, &wndcls))
333         {
334                 // get default stuff
335                 ::GetClassInfo(hInst, cs.lpszClass, &wndcls);
336                 // register a new class
337                 wndcls.lpszClassName = szClassName;
338                 wndcls.hIcon = ::LoadIcon(hInst, MAKEINTRESOURCE(IDR_MAINFRAME));
339                 ::RegisterClass(&wndcls);
340         }
341         cs.lpszClass = szClassName;
342         return bRes;
343 }
344
345 int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
346 {
347         if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
348                 return -1;
349
350         m_wndMDIClient.SubclassWindow(m_hWndMDIClient);
351
352         if (!CreateToolbar())
353         {
354                 TRACE0("Failed to create toolbar\n");
355                 return -1;      // fail to create
356         }
357         
358         if (!m_wndTabBar.Create(this))
359         {
360                 TRACE0("Failed to create tab bar\n");
361                 return -1;      // fail to create
362         }
363         m_wndTabBar.SetAutoMaxWidth(GetOptionsMgr()->GetBool(OPT_TABBAR_AUTO_MAXWIDTH));
364
365         if (!GetOptionsMgr()->GetBool(OPT_SHOW_TABBAR))
366                 CMDIFrameWnd::ShowControlBar(&m_wndTabBar, false, 0);
367
368         if (!m_wndStatusBar.Create(this))
369         {
370                 TRACE0("Failed to create status bar\n");
371                 return -1;      // fail to create
372         }
373         theApp.SetIndicators(m_wndStatusBar, StatusbarIndicators,
374                         static_cast<int>(std::size(StatusbarIndicators)));
375
376         const int lpx = CClientDC(this).GetDeviceCaps(LOGPIXELSX);
377         auto pointToPixel = [lpx](int point) { return MulDiv(point, lpx, 72); };
378         m_wndStatusBar.SetPaneInfo(0, 0, SBPS_STRETCH | SBPS_NOBORDERS, 0);
379         m_wndStatusBar.SetPaneInfo(1, ID_STATUS_PLUGIN, 0, pointToPixel(225));
380         m_wndStatusBar.SetPaneInfo(2, ID_STATUS_MERGINGMODE, 0, pointToPixel(75)); 
381         m_wndStatusBar.SetPaneInfo(3, ID_STATUS_DIFFNUM, 0, pointToPixel(112)); 
382
383         if (!GetOptionsMgr()->GetBool(OPT_SHOW_STATUSBAR))
384                 CMDIFrameWnd::ShowControlBar(&m_wndStatusBar, false, 0);
385
386         m_pDropHandler = new DropHandler(std::bind(&CMainFrame::OnDropFiles, this, std::placeholders::_1));
387         RegisterDragDrop(m_hWnd, m_pDropHandler);
388
389         m_wndMDIClient.ModifyStyleEx(WS_EX_CLIENTEDGE, 0);
390
391         return 0;
392 }
393
394 void CMainFrame::OnTimer(UINT_PTR nIDEvent)
395 {
396         CMDIFrameWnd::OnTimer(nIDEvent);
397
398         if (nIDEvent == IDT_UPDATEMAINMENU)
399         {
400                 KillTimer(nIDEvent);
401
402                 BOOL bMaximized;
403                 MDIGetActive(&bMaximized);
404
405                 // When MDI maximized the window icon is drawn on the menu bar, so we
406                 // need to notify it that our icon has changed.
407                 if (bMaximized)
408                         DrawMenuBar();
409
410                 OnUpdateFrameTitle(FALSE);
411         }
412 }
413
414 void CMainFrame::OnDestroy(void)
415 {
416         if (m_pDropHandler != nullptr)
417                 RevokeDragDrop(m_hWnd);
418 }
419
420 static HMENU GetSubmenu(HMENU menu, int nthSubmenu)
421 {
422         for (int nth = 0, i = 0; i < ::GetMenuItemCount(menu); i++)
423         {
424                 if (::GetSubMenu(menu, i) != nullptr)
425                 {
426                         if (nth == nthSubmenu)
427                                 return ::GetSubMenu(menu, i);
428                         nth++;
429                 }
430         }
431         // error, submenu not found
432         return nullptr;
433 }
434
435 static HMENU GetSubmenu(HMENU mainMenu, UINT nIDFirstMenuItem, int nthSubmenu)
436 {
437         int i;
438         for (i = 0 ; i < ::GetMenuItemCount(mainMenu) ; i++)
439                 if (::GetMenuItemID(::GetSubMenu(mainMenu, i), 0) == nIDFirstMenuItem)
440                         break;
441         HMENU menu = ::GetSubMenu(mainMenu, i);
442         if (!menu)
443                 return nullptr;
444         return GetSubmenu(menu, nthSubmenu);
445 }
446
447 /**
448  * @brief Find the scripts submenu from the main menu
449  * As now this is the first submenu in "Plugins" menu
450  * We find the "Plugins" menu by looking for a menu 
451  *  starting with ID_UNPACK_MANUAL.
452  */
453 HMENU CMainFrame::GetPrediffersSubmenu(HMENU mainMenu)
454 {
455         return GetSubmenu(mainMenu, ID_PLUGINS_LIST, 1);
456 }
457
458 /**
459  * @brief Create a new menu for the view..
460  * @param [in] view Menu view either MENU_DEFAULT, MENU_MERGEVIEW or MENU_DIRVIEW.
461  * @param [in] ID Menu's resource ID.
462  * @return Menu for the view.
463  */
464 HMENU CMainFrame::NewMenu(int view, int ID)
465 {
466         int menu_view;
467         if (m_pMenus[view] == nullptr)
468         {
469                 m_pMenus[view].reset(new BCMenu());
470                 if (m_pMenus[view] == nullptr)
471                         return nullptr;
472         }
473
474         switch (view)
475         {
476         case MENU_MERGEVIEW:
477                 menu_view = MENU_FILECMP;
478                 break;
479         case MENU_DIRVIEW:
480                 menu_view = MENU_FOLDERCMP;
481                 break;
482         case MENU_DEFAULT:
483         default:
484                 menu_view = MENU_MAINFRM;
485                 break;
486         };
487
488         if (!m_pMenus[view]->LoadMenu(ID))
489         {
490                 ASSERT(false);
491                 return nullptr;
492         }
493
494         if (view == MENU_IMGMERGEVIEW)
495         {
496                 m_pImageMenu.reset(new BCMenu);
497                 m_pImageMenu->LoadMenu(MAKEINTRESOURCE(IDR_POPUP_IMGMERGEVIEW));
498                 m_pMenus[view]->InsertMenu(4, MF_BYPOSITION | MF_POPUP, (UINT_PTR)m_pImageMenu->GetSubMenu(0)->m_hMenu, const_cast<TCHAR *>(LoadResString(IDS_IMAGE_MENU).c_str())); 
499         }
500
501         // Load bitmaps to menuitems
502         for (auto& menu_icon: m_MenuIcons)
503         {
504                 if (menu_view == (menu_icon.menusToApply & menu_view))
505                 {
506                         m_pMenus[view]->ModifyODMenu(nullptr, menu_icon.menuitemID, menu_icon.iconResID);
507                 }
508         }
509
510         m_pMenus[view]->LoadToolbar(IDR_MAINFRAME);
511
512         theApp.TranslateMenu(m_pMenus[view]->m_hMenu);
513
514         return (m_pMenus[view]->Detach());
515
516 }
517 /** 
518 * @brief Create new default (CMainFrame) menu.
519 */
520 HMENU CMainFrame::NewDefaultMenu(int ID /*=0*/)
521 {
522         if (ID == 0)
523                 ID = IDR_MAINFRAME;
524         return NewMenu( MENU_DEFAULT, ID );
525 }
526
527 /**
528  * @brief Create new File compare (CMergeEditView) menu.
529  */
530 HMENU CMainFrame::NewMergeViewMenu()
531 {
532         return NewMenu( MENU_MERGEVIEW, IDR_MERGEDOCTYPE);
533 }
534
535 /**
536  * @brief Create new Dir compare (CDirView) menu
537  */
538 HMENU CMainFrame::NewDirViewMenu()
539 {
540         return NewMenu(MENU_DIRVIEW, IDR_DIRDOCTYPE );
541 }
542
543 /**
544  * @brief Create new File compare (CHexMergeView) menu.
545  */
546 HMENU CMainFrame::NewHexMergeViewMenu()
547 {
548         return NewMenu( MENU_HEXMERGEVIEW, IDR_MERGEDOCTYPE);
549 }
550
551 /**
552  * @brief Create new Image compare (CImgMergeView) menu.
553  */
554 HMENU CMainFrame::NewImgMergeViewMenu()
555 {
556         return NewMenu( MENU_IMGMERGEVIEW, IDR_MERGEDOCTYPE);
557 }
558
559 /**
560  * @brief Create new File compare (COpenView) menu.
561  */
562 HMENU CMainFrame::NewOpenViewMenu()
563 {
564         return NewMenu( MENU_OPENVIEW, IDR_MAINFRAME);
565 }
566
567 /**
568  * @brief This handler ensures that the popup menu items are drawn correctly.
569  */
570 void CMainFrame::OnMeasureItem(int nIDCtl,
571         LPMEASUREITEMSTRUCT lpMeasureItemStruct)
572 {
573         bool setflag = false;
574         if (lpMeasureItemStruct->CtlType == ODT_MENU)
575         {
576                 if (IsMenu(reinterpret_cast<HMENU>(static_cast<uintptr_t>(lpMeasureItemStruct->itemID))))
577                 {
578                         CMenu* cmenu =
579                                 CMenu::FromHandle(reinterpret_cast<HMENU>(static_cast<uintptr_t>(lpMeasureItemStruct->itemID)));
580
581                         if (m_pMenus[MENU_DEFAULT]->IsMenu(cmenu))
582                         {
583                                 m_pMenus[MENU_DEFAULT]->MeasureItem(lpMeasureItemStruct);
584                                 setflag = true;
585                         }
586                 }
587         }
588
589         if (!setflag)
590                 CMDIFrameWnd::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
591 }
592
593 /**
594  * @brief This handler ensures that keyboard shortcuts work.
595  */
596 LRESULT CMainFrame::OnMenuChar(UINT nChar, UINT nFlags, 
597         CMenu* pMenu) 
598 {
599         LRESULT lresult;
600         if(m_pMenus[MENU_DEFAULT]->IsMenu(pMenu))
601                 lresult=BCMenu::FindKeyboardShortcut(nChar, nFlags, pMenu);
602         else
603                 lresult=CMDIFrameWnd::OnMenuChar(nChar, nFlags, pMenu);
604         return lresult;
605 }
606
607 /**
608  * @brief This handler updates the menus from time to time.
609  */
610 void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) 
611 {
612         if (!bSysMenu)
613         {
614                 if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
615                 {
616                         PathContext paths;
617                         for (int i = 0; i < pMergeDoc->GetFileCount(); ++i)
618                                 paths.SetPath(i, pMergeDoc->GetPath(i));
619                         String filteredFilenames = strutils::join(paths.begin(), paths.end(), _T("|"));
620                         unsigned topMenuId = pPopupMenu->GetMenuItemID(0);
621                         if (topMenuId == ID_NO_PREDIFFER)
622                         {
623                                 UpdatePrediffersMenu();
624                         }
625                         else if (topMenuId == ID_MERGE_COMPARE_TEXT)
626                         {
627                                 CMenu* pMenu = pPopupMenu;
628                                 // empty the menu
629                                 for (int i = pMenu->GetMenuItemCount() - 1; i > (ID_MERGE_COMPARE_IMAGE - ID_MERGE_COMPARE_TEXT); --i)
630                                         pMenu->DeleteMenu(i, MF_BYPOSITION);
631
632                                 CMainFrame::AppendPluginMenus(pMenu, filteredFilenames, FileTransform::UnpackerEventNames, true, ID_UNPACKERS_FIRST);
633                         }
634                         else if (topMenuId == ID_NO_EDIT_SCRIPTS)
635                         {
636                                 CMenu* pMenu = pPopupMenu;
637                                 ASSERT(pMenu != nullptr);
638
639                                 // empty the menu
640                                 int i = pMenu->GetMenuItemCount();
641                                 while (i--)
642                                         pMenu->DeleteMenu(0, MF_BYPOSITION);
643
644                                 CMainFrame::AppendPluginMenus(pMenu, filteredFilenames, FileTransform::EditorScriptEventNames, false, ID_SCRIPT_FIRST);
645                         }
646                         else if (topMenuId == ID_PLUGINS_LIST)
647                         {
648                                 for (int j = 0; j < 2; j++)
649                                 {
650                                         CMenu* pMenu = pPopupMenu->GetSubMenu((j == 0) ? 8 : (pPopupMenu->GetMenuItemCount() - 4));
651                                         ASSERT(pMenu != nullptr);
652
653                                         // empty the menu
654                                         int i = pMenu->GetMenuItemCount();
655                                         while (i--)
656                                                 pMenu->DeleteMenu(0, MF_BYPOSITION);
657
658                                         if (j == 0)
659                                                 CMainFrame::AppendPluginMenus(pMenu, filteredFilenames, FileTransform::UnpackerEventNames, false, ID_UNPACKERS_FIRST);
660                                         else
661                                                 CMainFrame::AppendPluginMenus(pMenu, filteredFilenames, FileTransform::EditorScriptEventNames, false, ID_SCRIPT_FIRST);
662                                 }
663                         }
664                 }
665
666                 CMDIFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
667                 if (BCMenu::IsMenu(pPopupMenu))
668                 {
669                         BCMenu::UpdateMenu(pPopupMenu);
670                 }
671         }
672         else
673         {
674                 CMDIFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
675         }
676 }
677
678 /////////////////////////////////////////////////////////////////////////////
679 // CMainFrame message handlers
680
681 void CMainFrame::OnFileOpen() 
682 {
683         DoFileOpen();
684 }
685
686 /**
687  * @brief Check for BOM, and also, if bGuessEncoding, try to deduce codepage
688  *
689  * Unpacks info from FileLocation & delegates all work to codepage_detect module
690  */
691 static void
692 FileLocationGuessEncodings(FileLocation & fileloc, int iGuessEncoding)
693 {
694         fileloc.encoding = codepage_detect::Guess(fileloc.filepath, iGuessEncoding);
695 }
696
697 bool CMainFrame::ShowAutoMergeDoc(CDirDoc * pDirDoc,
698         int nFiles, const FileLocation ifileloc[],
699         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
700         const PackingInfo * infoUnpacker /*= nullptr*/, int line /*= -1*/)
701 {
702         ASSERT(pDirDoc != nullptr);
703
704         if (sReportFile.empty() && pDirDoc->CompareFilesIfFilesAreLarge(nFiles, ifileloc))
705                 return false;
706
707         String unpackedFileExtension;
708         if (infoUnpacker && GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
709         {
710                 std::vector<String> filepaths(nFiles);
711                 std::transform(ifileloc, ifileloc + nFiles, filepaths.begin(),
712                         [](auto& file) { return file.filepath; });
713                 String filteredFilenames = strutils::join(filepaths.begin(), filepaths.end(), _T("|"));
714                 unpackedFileExtension = infoUnpacker->GetUnpackedFileExtension(filteredFilenames);
715         }
716         FileFilterHelper filterImg, filterBin;
717         filterImg.UseMask(true);
718         filterImg.SetMask(GetOptionsMgr()->GetString(OPT_CMP_IMG_FILEPATTERNS));
719         filterBin.UseMask(true);
720         filterBin.SetMask(GetOptionsMgr()->GetString(OPT_CMP_BIN_FILEPATTERNS));
721         for (int pane = 0; pane < nFiles; ++pane)
722         {
723                 String filepath = ifileloc[pane].filepath + unpackedFileExtension;
724                 if (filterImg.includeFile(filepath) && CImgMergeFrame::IsLoadable())
725                         return ShowImgMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags, strDesc, sReportFile, infoUnpacker);
726                 else if (filterBin.includeFile(filepath) && CHexMergeView::IsLoadable())
727                         return ShowHexMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags, strDesc, sReportFile, infoUnpacker);
728         }
729         return ShowTextOrTableMergeDoc({}, pDirDoc, nFiles, ifileloc, dwFlags, strDesc, sReportFile, infoUnpacker, line);
730 }
731
732 bool CMainFrame::ShowMergeDoc(UINT nID, CDirDoc* pDirDoc,
733         int nFiles, const FileLocation ifileloc[],
734         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
735         const PackingInfo* infoUnpacker /*= nullptr*/, int line /*= -1*/)
736 {
737         switch (nID)
738         {
739         case ID_MERGE_COMPARE_TEXT:
740                 return ShowTextMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags,
741                         strDesc, sReportFile, infoUnpacker, line);
742         case ID_MERGE_COMPARE_TABLE:
743                 return ShowTableMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags,
744                         strDesc, sReportFile, infoUnpacker, line);
745         case ID_MERGE_COMPARE_HEX:
746                 return ShowHexMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags,
747                         strDesc, sReportFile, infoUnpacker);
748         case ID_MERGE_COMPARE_IMAGE:
749                 return ShowImgMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags,
750                         strDesc, sReportFile, infoUnpacker);
751         default:
752                 return ShowAutoMergeDoc(pDirDoc, nFiles, ifileloc, dwFlags,
753                         strDesc, sReportFile, infoUnpacker, line);
754         }
755 }
756
757 std::array<bool, 3> GetROFromFlags(int nFiles, const DWORD dwFlags[])
758 {
759         std::array<bool, 3> bRO = { false, false, false };
760         for (int pane = 0; pane < nFiles; pane++)
761         {
762                 if (dwFlags)
763                         bRO[pane] = ((dwFlags[pane] & FFILEOPEN_READONLY) > 0);
764         }
765         return bRO;
766 }
767
768 int GetActivePaneFromFlags(int nFiles, const DWORD dwFlags[])
769 {
770         int nActivePane = -1;
771         for (int pane = 0; pane < nFiles; ++pane)
772         {
773                 if (dwFlags && (dwFlags[pane] & FFILEOPEN_SETFOCUS))
774                         nActivePane = pane;
775         }
776         return nActivePane;
777 }
778
779 /**
780  * @brief Creates new MergeDoc instance and shows documents.
781  * @param [in] pDirDoc Dir compare document to create a new Merge document for.
782  * @param [in] ifilelocLeft Left side file location info.
783  * @param [in] ifilelocRight Right side file location info.
784  * @param [in] dwLeftFlags Left side flags.
785  * @param [in] dwRightFlags Right side flags.
786  * @param [in] infoUnpacker Plugin info.
787  * @return success/failure
788  */
789 bool CMainFrame::ShowTextOrTableMergeDoc(std::optional<bool> table, CDirDoc * pDirDoc,
790         int nFiles, const FileLocation ifileloc[],
791         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
792         const PackingInfo * infoUnpacker /*= nullptr*/, int line /*= -1*/)
793 {
794         if (m_pMenus[MENU_MERGEVIEW] == nullptr)
795                 theApp.m_pDiffTemplate->m_hMenuShared = NewMergeViewMenu();
796         CMergeDoc * pMergeDoc = GetMergeDocForDiff<CMergeDoc>(theApp.m_pDiffTemplate, pDirDoc, nFiles, false);
797
798         // Make local copies, so we can change encoding if we guess it below
799         FileLocation fileloc[3];
800         std::copy_n(ifileloc, nFiles, fileloc);
801
802         ASSERT(pMergeDoc != nullptr);           // must ASSERT to get an answer to the question below ;-)
803         if (pMergeDoc == nullptr)
804                 return false; // when does this happen ?
805
806         // if an unpacker is selected, it must be used during LoadFromFile
807         // MergeDoc must memorize it for SaveToFile
808         // Warning : this unpacker may differ from the pDirDoc one
809         // (through menu : "Plugins"->"Open with unpacker")
810         pMergeDoc->SetUnpacker(infoUnpacker);
811
812         // detect codepage
813         int iGuessEncodingType = GetOptionsMgr()->GetInt(OPT_CP_DETECT);
814         for (int pane = 0; pane < nFiles; pane++)
815         {
816                 if (fileloc[pane].encoding.m_unicoding == -1)
817                         fileloc[pane].encoding.m_unicoding = ucr::NONE;
818                 if (fileloc[pane].encoding.m_unicoding == ucr::NONE && fileloc[pane].encoding.m_codepage == -1)
819                 {
820                         FileLocationGuessEncodings(fileloc[pane], iGuessEncodingType);
821                 }
822         }
823
824         pMergeDoc->SetEnableTableEditing(table);
825
826         // Note that OpenDocs() takes care of closing compare window when needed.
827         bool bResult = pMergeDoc->OpenDocs(nFiles, fileloc, GetROFromFlags(nFiles, dwFlags).data(), strDesc);
828         if (bResult)
829         {
830                 if (CMergeEditFrame *pFrame = pMergeDoc->GetParentFrame())
831                         if (!pFrame->IsActivated())
832                                 pFrame->InitialUpdateFrame(pMergeDoc, true);
833         }
834         else
835         {
836                 return false;
837         }
838
839         for (int pane = 0; pane < nFiles; pane++)
840         {
841                 if (dwFlags)
842                 {
843                         bool bModified = (dwFlags[pane] & FFILEOPEN_MODIFIED) > 0;
844                         if (bModified)
845                         {
846                                 pMergeDoc->m_ptBuf[pane]->SetModified(true);
847                                 pMergeDoc->UpdateHeaderPath(pane);
848                         }
849                         if (dwFlags[pane] & FFILEOPEN_AUTOMERGE)
850                         {
851                                 pMergeDoc->DoAutoMerge(pane);
852                         }
853                 }
854         }
855
856         pMergeDoc->MoveOnLoad(GetActivePaneFromFlags(nFiles, dwFlags), line, true);
857
858         if (!sReportFile.empty())
859                 pMergeDoc->GenerateReport(sReportFile);
860
861         return true;
862 }
863
864 bool CMainFrame::ShowTextMergeDoc(CDirDoc* pDirDoc,
865         int nFiles, const FileLocation ifileloc[],
866         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
867         const PackingInfo* infoUnpacker /*= nullptr*/, int line /*= -1*/)
868 {
869         return ShowTextOrTableMergeDoc(false, pDirDoc, nFiles, ifileloc, dwFlags, strDesc, sReportFile, infoUnpacker, line);
870 }
871
872 bool CMainFrame::ShowTableMergeDoc(CDirDoc* pDirDoc,
873         int nFiles, const FileLocation ifileloc[],
874         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
875         const PackingInfo* infoUnpacker /*= nullptr*/, int line /*= -1*/)
876 {
877         return ShowTextOrTableMergeDoc(true, pDirDoc, nFiles, ifileloc, dwFlags, strDesc, sReportFile, infoUnpacker, line);
878 }
879
880 bool CMainFrame::ShowHexMergeDoc(CDirDoc * pDirDoc, int nFiles, const FileLocation fileloc[],
881         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
882         const PackingInfo * infoUnpacker /*= nullptr*/)
883 {
884         if (m_pMenus[MENU_HEXMERGEVIEW] == nullptr)
885                 theApp.m_pHexMergeTemplate->m_hMenuShared = NewHexMergeViewMenu();
886         CHexMergeDoc *pHexMergeDoc = GetMergeDocForDiff<CHexMergeDoc>(theApp.m_pHexMergeTemplate, pDirDoc, nFiles);
887         if (pHexMergeDoc == nullptr)
888                 return false;
889
890         pHexMergeDoc->SetUnpacker(infoUnpacker);
891
892         if (!pHexMergeDoc->OpenDocs(nFiles, fileloc, GetROFromFlags(nFiles, dwFlags).data(), strDesc))
893                 return false;
894
895         pHexMergeDoc->MoveOnLoad(GetActivePaneFromFlags(nFiles, dwFlags));
896         
897         if (!sReportFile.empty())
898                 pHexMergeDoc->GenerateReport(sReportFile);
899
900         return true;
901 }
902
903 bool CMainFrame::ShowImgMergeDoc(CDirDoc * pDirDoc, int nFiles, const FileLocation fileloc[],
904         const DWORD dwFlags[], const String strDesc[], const String& sReportFile /*= _T("")*/,
905         const PackingInfo * infoUnpacker /*= nullptr*/)
906 {
907         CImgMergeFrame *pImgMergeFrame = new CImgMergeFrame();
908         if (!CImgMergeFrame::menu.m_hMenu)
909                 CImgMergeFrame::menu.m_hMenu = NewImgMergeViewMenu();
910         pImgMergeFrame->SetSharedMenu(CImgMergeFrame::menu.m_hMenu);
911         pImgMergeFrame->SetUnpacker(infoUnpacker);
912         pImgMergeFrame->SetDirDoc(pDirDoc);
913         pDirDoc->AddMergeDoc(pImgMergeFrame);
914                 
915         if (!pImgMergeFrame->OpenDocs(nFiles, fileloc, GetROFromFlags(nFiles, dwFlags).data(), strDesc, this))
916                 return false;
917
918         for (int pane = 0; pane < nFiles; pane++)
919         {
920                 if (dwFlags && (dwFlags[pane] & FFILEOPEN_AUTOMERGE))
921                         pImgMergeFrame->DoAutoMerge(pane);
922         }
923
924         pImgMergeFrame->MoveOnLoad(GetActivePaneFromFlags(nFiles, dwFlags));
925
926         if (!sReportFile.empty())
927                 pImgMergeFrame->GenerateReport(sReportFile);
928
929         return true;
930 }
931
932 bool CMainFrame::ShowTextMergeDoc(CDirDoc* pDirDoc, int nBuffers, const String text[],
933                 const String strDesc[], const String& strFileExt, int line /*= -1*/)
934 {
935         FileLocation fileloc[3];
936         DWORD dwFlags[3] = {};
937         CDirDoc* pDirDoc2 = pDirDoc->GetMainView() ? pDirDoc :
938                 static_cast<CDirDoc*>(theApp.m_pDirTemplate->CreateNewDocument());
939         for (int nBuffer = 0; nBuffer < nBuffers; ++nBuffer)
940         {
941                 TempFilePtr wTemp(new TempFile());
942                 String workFile = wTemp->Create(_T("text_"), strFileExt);
943                 m_tempFiles.push_back(wTemp);
944                 wTemp->Create(_T(""), strFileExt);
945                 UniStdioFile file;
946                 if (file.OpenCreateUtf8(workFile))
947                 {
948                         file.WriteString(text[nBuffer]);
949                 }
950                 fileloc[nBuffer].setPath(workFile);
951         }
952         return ShowTextMergeDoc(pDirDoc2, nBuffers, fileloc, dwFlags, strDesc, _T(""), nullptr, line);
953 }
954
955 /**
956  * @brief Show GNU licence information in notepad (local file) or in Web Browser
957  */
958 void CMainFrame::OnHelpGnulicense() 
959 {
960         const String spath = paths::ConcatPath(env::GetProgPath(), LicenseFile);
961         shell::OpenFileOrUrl(spath.c_str(), LicenceUrl);
962 }
963
964 /**
965  * @brief Opens Options-dialog and saves changed options
966  */
967 void CMainFrame::OnOptions() 
968 {
969         // Using singleton shared syntax colors
970         CPreferencesDlg dlg(GetOptionsMgr(), theApp.GetMainSyntaxColors());
971         INT_PTR rv = dlg.DoModal();
972
973         if (rv == IDOK)
974         {
975                 LANGID lang = static_cast<LANGID>(GetOptionsMgr()->GetInt(OPT_SELECTED_LANGUAGE));
976                 if (lang != theApp.m_pLangDlg->GetLangId())
977                 {
978                         theApp.m_pLangDlg->SetLanguage(lang, true);
979         
980                         // Update status bar inicator texts
981                         theApp.SetIndicators(m_wndStatusBar, 0, 0);
982         
983                         // Update the current menu
984                         ReloadMenu();
985         
986                         // update the title text of the document
987                         UpdateDocTitle();
988
989                         UpdateResources();
990                 }
991
992                 // Set new temporary path
993                 theApp.SetupTempPath();
994
995                 // Set new filterpath
996                 String filterPath = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
997                 theApp.m_pGlobalFileFilter->SetUserFilterPath(filterPath);
998
999                 CCrystalTextView::RENDERING_MODE nRenderingMode = static_cast<CCrystalTextView::RENDERING_MODE>(GetOptionsMgr()->GetInt(OPT_RENDERING_MODE));
1000                 CCrystalTextView::SetRenderingModeDefault(nRenderingMode);
1001
1002                 theApp.UpdateCodepageModule();
1003
1004                 strdiff::SetBreakChars(GetOptionsMgr()->GetString(OPT_BREAK_SEPARATORS).c_str());
1005
1006                 // make an attempt at rescanning any open diff sessions
1007                 ApplyDiffOptions();
1008
1009                 // Update all dirdoc settings
1010                 for (auto pDirDoc : GetAllDirDocs())
1011                         pDirDoc->RefreshOptions();
1012                 for (auto pOpenDoc : GetAllOpenDocs())
1013                         pOpenDoc->RefreshOptions();
1014                 for (auto pMergeDoc : GetAllHexMergeDocs())
1015                         pMergeDoc->RefreshOptions();
1016         }
1017 }
1018
1019 static bool AddToRecentDocs(const PathContext& paths, const unsigned flags[], bool recurse, const String& filter)
1020 {
1021         String params, title;
1022         for (int nIndex = 0; nIndex < paths.GetSize(); ++nIndex)
1023         {
1024                 if (flags && (flags[nIndex] & FFILEOPEN_READONLY))
1025                 {
1026                         switch (nIndex)
1027                         {
1028                         case 0: params += _T("/wl "); break;
1029                         case 1: params += paths.GetSize() == 2 ? _T("/wr ") : _T("/wm "); break;
1030                         case 2: params += _T("/wr "); break;
1031                         }
1032                 }
1033                 params += _T("\"") + paths[nIndex] + _T("\" ");
1034
1035                 String path = paths[nIndex];
1036                 paths::normalize(path);
1037                 title += paths::FindFileName(path);
1038                 if (nIndex < paths.GetSize() - 1)
1039                         title += _T(" - ");
1040         }
1041         if (recurse)
1042                 params += _T("/r ");
1043         if (!filter.empty())
1044                 params += _T("/f \"") + filter + _T("\" ");
1045
1046         Concurrent::CreateTask([params, title](){
1047                         CoInitialize(nullptr);
1048                         JumpList::AddToRecentDocs(_T(""), params, title, params, 0);
1049                         CoUninitialize();
1050                         return 0;
1051                 });
1052         return true;
1053 }
1054 /**
1055  * @brief Begin a diff: open dirdoc if it is directories, else open a mergedoc for editing.
1056  * @param [in] pszLeft Left-side path.
1057  * @param [in] pszRight Right-side path.
1058  * @param [in] dwLeftFlags Left-side flags.
1059  * @param [in] dwRightFlags Right-side flags.
1060  * @param [in] bRecurse Do we run recursive (folder) compare?
1061  * @param [in] pDirDoc Dir compare document to use.
1062  * @param [in] infoUnpacker Unpacker plugin name.
1063  * @param [in] infoPrediffer Prediffer plugin name.
1064  * @return `true` if opening files and compare succeeded, `false` otherwise.
1065  */
1066 bool CMainFrame::DoFileOpen(const PathContext * pFiles /*= nullptr*/,
1067         const DWORD dwFlags[] /*= nullptr*/, const String strDesc[] /*= nullptr*/, const String& sReportFile /*= T("")*/,
1068         bool bRecurse /*= false*/, CDirDoc* pDirDoc/*= nullptr*/,
1069         const PackingInfo *infoUnpacker /*= nullptr*/, const PrediffingInfo *infoPrediffer /*= nullptr*/,
1070         UINT nID /*= 0*/, int line /*= -1*/)
1071 {
1072         if (pDirDoc != nullptr && !pDirDoc->CloseMergeDocs())
1073                 return false;
1074
1075         FileTransform::AutoUnpacking = GetOptionsMgr()->GetBool(OPT_PLUGINS_UNPACKER_MODE);
1076         FileTransform::AutoPrediffing = GetOptionsMgr()->GetBool(OPT_PLUGINS_PREDIFFER_MODE);
1077
1078         Merge7zFormatMergePluginScope scope(infoUnpacker);
1079
1080         PathContext tFiles;
1081         if (pFiles != nullptr)
1082                 tFiles = *pFiles;
1083         bool bRO[3] = {0};
1084         if (dwFlags)
1085         {
1086                 bRO[0] = (dwFlags[0] & FFILEOPEN_READONLY) != 0;
1087                 bRO[1] = (dwFlags[1] & FFILEOPEN_READONLY) != 0;
1088                 bRO[2] = (dwFlags[2] & FFILEOPEN_READONLY) != 0;
1089         };
1090
1091         // pop up dialog unless arguments exist (and are compatible)
1092         paths::PATH_EXISTENCE pathsType = paths::GetPairComparability(tFiles, IsArchiveFile);
1093         if (pathsType == paths::DOES_NOT_EXIST)
1094         {
1095                 if (m_pMenus[MENU_OPENVIEW] == nullptr)
1096                         theApp.m_pOpenTemplate->m_hMenuShared = NewOpenViewMenu();
1097                 COpenDoc *pOpenDoc = static_cast<COpenDoc *>(theApp.m_pOpenTemplate->CreateNewDocument());
1098                 if (dwFlags)
1099                 {
1100                         pOpenDoc->m_dwFlags[0] = dwFlags[0];
1101                         pOpenDoc->m_dwFlags[1] = dwFlags[1];
1102                         pOpenDoc->m_dwFlags[2] = dwFlags[2];
1103                 }
1104                 pOpenDoc->m_files = tFiles;
1105                 pOpenDoc->m_bRecurse = bRecurse;
1106                 if (infoUnpacker)
1107                         pOpenDoc->m_strUnpackerPipeline = infoUnpacker->GetPluginPipeline();
1108                 CFrameWnd *pFrame = theApp.m_pOpenTemplate->CreateNewFrame(pOpenDoc, nullptr);
1109                 theApp.m_pOpenTemplate->InitialUpdateFrame(pFrame, pOpenDoc);
1110                 return true;
1111         }
1112         else
1113         {
1114                 // Add trailing '\' for directories if its missing
1115                 if (pathsType == paths::IS_EXISTING_DIR)
1116                 {
1117                         if (!paths::EndsWithSlash(tFiles[0]) && !IsArchiveFile(tFiles[0]))
1118                                 tFiles[0] = paths::AddTrailingSlash(tFiles[0]);
1119                         if (!paths::EndsWithSlash(tFiles[1]) && !IsArchiveFile(tFiles[1]))
1120                                 tFiles[1] = paths::AddTrailingSlash(tFiles[1]);
1121                         if (tFiles.GetSize() == 3 && !paths::EndsWithSlash(tFiles[2]) && !IsArchiveFile(tFiles[1]))
1122                                 tFiles[2] = paths::AddTrailingSlash(tFiles[2]);
1123                 }
1124
1125                 //save the MRU left and right files.
1126                 if (dwFlags)
1127                 {
1128                         if (!(dwFlags[0] & FFILEOPEN_NOMRU))
1129                                 addToMru(tFiles[0].c_str(), _T("Files\\Left"));
1130                         if (!(dwFlags[1] & FFILEOPEN_NOMRU))
1131                                 addToMru(tFiles[1].c_str(), _T("Files\\Right"));
1132                         if (tFiles.GetSize() == 3 && !(dwFlags[2] & FFILEOPEN_NOMRU))
1133                                 addToMru(tFiles[2].c_str(), _T("Files\\Option"));
1134                 }
1135         }
1136
1137         CTempPathContext *pTempPathContext = nullptr;
1138         if (nID == 0 && pathsType == paths::IS_EXISTING_DIR)
1139         {
1140                 DecompressResult res= DecompressArchive(m_hWnd, tFiles);
1141                 if (res.pTempPathContext)
1142                 {
1143                         pathsType = res.pathsType;
1144                         tFiles = res.files;
1145                         pTempPathContext = res.pTempPathContext;
1146                 }
1147         }
1148
1149         // Determine if we want a new dirview open, now that we know if it was
1150         // an archive. Don't open a new dirview if we are comparing files.
1151         if (pDirDoc == nullptr)
1152         {
1153                 if (nID == 0 && pathsType == paths::IS_EXISTING_DIR)
1154                 {
1155                         CDirDoc::m_nDirsTemp = tFiles.GetSize();
1156                         if (m_pMenus[MENU_DIRVIEW] == nullptr)
1157                                 theApp.m_pDirTemplate->m_hMenuShared = NewDirViewMenu();
1158                         pDirDoc = static_cast<CDirDoc*>(theApp.m_pDirTemplate->OpenDocumentFile(nullptr));
1159                 }
1160                 else
1161                 {
1162                         pDirDoc = static_cast<CDirDoc*>(theApp.m_pDirTemplate->CreateNewDocument());
1163                 }
1164         }
1165
1166         // open the diff
1167         if (nID == 0 && pathsType == paths::IS_EXISTING_DIR)
1168         {
1169                 if (pDirDoc != nullptr)
1170                 {
1171                         // Anything that can go wrong inside InitCompare() will yield an
1172                         // exception. There is no point in checking return value.
1173                         pDirDoc->InitCompare(tFiles, bRecurse, pTempPathContext);
1174
1175                         pDirDoc->SetReportFile(sReportFile);
1176                         pDirDoc->SetDescriptions(strDesc);
1177                         pDirDoc->SetTitle(nullptr);
1178                         for (int nIndex = 0; nIndex < tFiles.GetSize(); nIndex++)
1179                                 pDirDoc->SetReadOnly(nIndex, bRO[nIndex]);
1180
1181                         pDirDoc->Rescan();
1182                 }
1183         }
1184         else
1185         {               
1186                 FileLocation fileloc[3];
1187
1188                 for (int nPane = 0; nPane < tFiles.GetSize(); nPane++)
1189                         fileloc[nPane].setPath(tFiles[nPane]);
1190
1191                 if (infoPrediffer && !infoPrediffer->GetPluginPipeline().empty())
1192                 {
1193                         String strBothFilenames = strutils::join(tFiles.begin(), tFiles.end(), _T("|"));
1194                         pDirDoc->GetPluginManager().SetPrediffer(strBothFilenames, infoPrediffer->GetPluginPipeline());
1195                 }
1196
1197                 ShowMergeDoc(nID, pDirDoc, tFiles.GetSize(), fileloc, dwFlags, strDesc, sReportFile,
1198                                 infoUnpacker, line);
1199         }
1200
1201         if (pFiles != nullptr && (!dwFlags || !(dwFlags[0] & FFILEOPEN_NOMRU)))
1202         {
1203                 String filter = GetOptionsMgr()->GetString(OPT_FILEFILTER_CURRENT);
1204                 AddToRecentDocs(*pFiles, (unsigned *)dwFlags, bRecurse, filter);
1205         }
1206
1207         return true;
1208 }
1209
1210 bool CMainFrame::DoFileOpen(UINT nID, const PathContext* pFiles /*= nullptr*/,
1211         const DWORD dwFlags[] /*= nullptr*/, const String strDesc[] /*= nullptr*/,
1212         const String& sReportFile /*= _T("")*/, const PackingInfo *infoUnpacker /*= nullptr*/, int line /*= -1*/)
1213 {
1214         CDirDoc* pDirDoc = static_cast<CDirDoc*>(theApp.m_pDirTemplate->CreateNewDocument());
1215         FileLocation fileloc[3];
1216         for (int pane = 0; pane < pFiles->GetSize(); pane++)
1217                 fileloc[pane].setPath((*pFiles)[pane]);
1218         return ShowMergeDoc(nID, pDirDoc, pFiles->GetSize(), fileloc,
1219                 dwFlags, strDesc, sReportFile, infoUnpacker, line);
1220 }
1221
1222 void CMainFrame::UpdateFont(FRAMETYPE frame)
1223 {
1224         if (frame == FRAME_FOLDER)
1225         {
1226                 for (auto pDoc : GetAllDirDocs())
1227                 {
1228                         if (pDoc != nullptr)
1229                         {
1230                                 CDirView *pView = pDoc->GetMainView();
1231                                 if (pView != nullptr)
1232                                         pView->SetFont(m_lfDir);
1233                         }
1234                 }
1235         }
1236         else
1237         {
1238                 for (auto pDoc : GetAllMergeDocs())
1239                 {
1240                         CMergeDoc *pMergeDoc = dynamic_cast<CMergeDoc *>(pDoc);
1241                         if (pMergeDoc != nullptr)
1242                                 for (auto& pView: pMergeDoc->GetViewList())
1243                                         pView->SetFont(m_lfDiff);
1244                 }
1245         }
1246 }
1247
1248 /**
1249  * @brief Select font for Merge/Dir view
1250  * 
1251  * Shows font selection dialog to user, sets current font and saves
1252  * selected font properties to registry. Selects fon type to active
1253  * view (Merge/Dir compare). If there is no open views, then font
1254  * is selected for Merge view (for example user may want to change to
1255  * unicode font before comparing files).
1256  */
1257 void CMainFrame::OnViewSelectfont() 
1258 {
1259         FRAMETYPE frame = GetFrameType(GetActiveFrame());
1260         CHOOSEFONT cf = { sizeof CHOOSEFONT };
1261         LOGFONT *lf = nullptr;
1262         cf.Flags = CF_INITTOLOGFONTSTRUCT|CF_FORCEFONTEXIST|CF_SCREENFONTS;
1263         if (frame == FRAME_FILE)
1264                 cf.Flags |= CF_FIXEDPITCHONLY; // Only fixed-width fonts for merge view
1265
1266         // CF_FIXEDPITCHONLY = 0x00004000L
1267         // in case you are a developer and want to disable it to test with, eg, a Chinese capable font
1268         if (frame == FRAME_FOLDER)
1269                 lf = &m_lfDir;
1270         else
1271                 lf = &m_lfDiff;
1272
1273         cf.lpLogFont = lf;
1274
1275         if (ChooseFont(&cf))
1276         {
1277                 Options::Font::Save(GetOptionsMgr(), frame == FRAME_FOLDER ? OPT_FONT_DIRCMP : OPT_FONT_FILECMP, lf, true);
1278                 UpdateFont(frame);
1279         }
1280 }
1281
1282 /**
1283  * @brief Use default font for active view type
1284  *
1285  * Disable user-selected font for active view type (Merge/Dir compare).
1286  * If there is no open views, then Merge view font is changed.
1287  */
1288 void CMainFrame::OnViewUsedefaultfont() 
1289 {
1290         FRAMETYPE frame = GetFrameType(GetActiveFrame());
1291
1292         if (frame == FRAME_FOLDER)
1293         {
1294                 Options::Font::Reset(GetOptionsMgr(), OPT_FONT_DIRCMP);
1295                 m_lfDir = Options::Font::Load(GetOptionsMgr(), OPT_FONT_DIRCMP);
1296                 Options::Font::Save(GetOptionsMgr(), OPT_FONT_DIRCMP, &m_lfDir, false);
1297         }
1298         else
1299         {
1300                 Options::Font::Reset(GetOptionsMgr(), OPT_FONT_FILECMP);
1301                 m_lfDiff = Options::Font::Load(GetOptionsMgr(), OPT_FONT_FILECMP);
1302                 Options::Font::Save(GetOptionsMgr(), OPT_FONT_FILECMP, &m_lfDiff, false);
1303         }
1304
1305         UpdateFont(frame);
1306 }
1307
1308 /**
1309  * @brief Update any resources necessary after a GUI language change
1310  */
1311 void CMainFrame::UpdateResources()
1312 {
1313         m_wndStatusBar.SetPaneText(0, theApp.LoadString(AFX_IDS_IDLEMESSAGE).c_str());
1314
1315         for (auto pDoc : GetAllDirDocs())
1316                 pDoc->UpdateResources();
1317         for (auto pDoc : GetAllMergeDocs())
1318                 pDoc->UpdateResources();
1319         for (auto pDoc : GetAllOpenDocs())
1320                 pDoc->UpdateResources();
1321         for (auto pFrame: GetAllImgMergeFrames())
1322                 pFrame->UpdateResources();
1323 }
1324
1325 /**
1326  * @brief Open WinMerge help.
1327  *
1328  * If local HTMLhelp file is found, open it, otherwise open HTML page from web.
1329  */
1330 void CMainFrame::OnHelpContents()
1331 {
1332         theApp.ShowHelp();
1333 }
1334
1335 /**
1336  * @brief Handle translation of default messages on the status bar
1337  */
1338 void CMainFrame::GetMessageString(UINT nID, CString& rMessage) const
1339 {
1340         // load appropriate string
1341         const String s = theApp.LoadString(nID);
1342         if (s.length() > 0)
1343                 AfxExtractSubString(rMessage, s.c_str(), 0);
1344 }
1345
1346 void CMainFrame::ActivateFrame(int nCmdShow) 
1347 {
1348         if (!m_bFirstTime)
1349         {
1350                 CMDIFrameWnd::ActivateFrame(nCmdShow);
1351                 return;
1352         }
1353
1354         m_bFirstTime = false;
1355
1356         WINDOWPLACEMENT wp = {};
1357         wp.length = sizeof(WINDOWPLACEMENT);
1358         GetWindowPlacement(&wp);
1359         wp.rcNormalPosition.left=theApp.GetProfileInt(_T("Settings"), _T("MainLeft"),0);
1360         wp.rcNormalPosition.top=theApp.GetProfileInt(_T("Settings"), _T("MainTop"),0);
1361         wp.rcNormalPosition.right=theApp.GetProfileInt(_T("Settings"), _T("MainRight"),0);
1362         wp.rcNormalPosition.bottom=theApp.GetProfileInt(_T("Settings"), _T("MainBottom"),0);
1363         if (nCmdShow != SW_MINIMIZE && theApp.GetProfileInt(_T("Settings"), _T("MainMax"), FALSE))
1364                 wp.showCmd = SW_MAXIMIZE;
1365         else
1366                 wp.showCmd = nCmdShow;
1367
1368         CRect dsk_rc,rc(wp.rcNormalPosition);
1369
1370         dsk_rc.left = ::GetSystemMetrics(SM_XVIRTUALSCREEN);
1371         dsk_rc.top = ::GetSystemMetrics(SM_YVIRTUALSCREEN);
1372         dsk_rc.right = dsk_rc.left + ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
1373         dsk_rc.bottom = dsk_rc.top + ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
1374         if (rc.Width() != 0 && rc.Height() != 0)
1375         {
1376                 // Ensure top-left corner is on visible area,
1377                 // 20 points margin is added to prevent "lost" window
1378                 CPoint ptTopLeft(rc.TopLeft());
1379                 ptTopLeft += CPoint(20, 20);
1380
1381                 if (dsk_rc.PtInRect(ptTopLeft))
1382                         SetWindowPlacement(&wp);
1383                 else
1384                         CMDIFrameWnd::ActivateFrame(nCmdShow);
1385         }
1386         else
1387                 CMDIFrameWnd::ActivateFrame(nCmdShow);
1388 }
1389
1390 /**
1391  * @brief Called when mainframe is about to be closed.
1392  * This function is called when mainframe is to be closed (not for
1393  * file/compare windows.
1394  */
1395 void CMainFrame::OnClose()
1396 {
1397         if (theApp.GetActiveOperations())
1398                 return;
1399
1400         // Check if there are multiple windows open and ask for closing them
1401         bool bAskClosing = GetOptionsMgr()->GetBool(OPT_ASK_MULTIWINDOW_CLOSE);
1402         if (bAskClosing)
1403         {
1404                 bool quit = AskCloseConfirmation();
1405                 if (!quit)
1406                         return;
1407         }
1408
1409         // Save last selected filter
1410         String filter = theApp.m_pGlobalFileFilter->GetFilterNameOrMask();
1411         GetOptionsMgr()->SaveOption(OPT_FILEFILTER_CURRENT, filter);
1412
1413         // save main window position
1414         WINDOWPLACEMENT wp = {};
1415         wp.length = sizeof(WINDOWPLACEMENT);
1416         GetWindowPlacement(&wp);
1417         theApp.WriteProfileInt(_T("Settings"), _T("MainLeft"),wp.rcNormalPosition.left);
1418         theApp.WriteProfileInt(_T("Settings"), _T("MainTop"),wp.rcNormalPosition.top);
1419         theApp.WriteProfileInt(_T("Settings"), _T("MainRight"),wp.rcNormalPosition.right);
1420         theApp.WriteProfileInt(_T("Settings"), _T("MainBottom"),wp.rcNormalPosition.bottom);
1421         theApp.WriteProfileInt(_T("Settings"), _T("MainMax"), (wp.showCmd == SW_MAXIMIZE));
1422
1423         for (auto pFrame: GetAllImgMergeFrames())
1424         {
1425                 if (!pFrame->CloseNow())
1426                         return;
1427         }
1428
1429         CMDIFrameWnd::OnClose();
1430 }
1431
1432 /**
1433  * @brief Utility function to update CSuperComboBox format MRU
1434  */
1435 void CMainFrame::addToMru(LPCTSTR szItem, LPCTSTR szRegSubKey, UINT nMaxItems)
1436 {
1437         std::vector<CString> list;
1438         CString s;
1439         UINT cnt = AfxGetApp()->GetProfileInt(szRegSubKey, _T("Count"), 0);
1440         list.push_back(szItem);
1441         for (UINT i=0 ; i<cnt; ++i)
1442         {
1443                 s = AfxGetApp()->GetProfileString(szRegSubKey, strutils::format(_T("Item_%d"), i).c_str());
1444                 if (s != szItem)
1445                         list.push_back(s);
1446         }
1447         cnt = list.size() > nMaxItems ? nMaxItems : static_cast<UINT>(list.size());
1448         for (UINT i=0 ; i<cnt; ++i)
1449                 AfxGetApp()->WriteProfileString(szRegSubKey, strutils::format(_T("Item_%d"), i).c_str(), list[i]);
1450         // update count
1451         AfxGetApp()->WriteProfileInt(szRegSubKey, _T("Count"), cnt);
1452 }
1453
1454 void CMainFrame::ApplyDiffOptions() 
1455 {
1456         for (auto pMergeDoc : GetAllMergeDocs())
1457         {
1458                 // Re-read MergeDoc settings (also updates view settings)
1459                 // and rescan using new options
1460                 pMergeDoc->RefreshOptions();
1461                 pMergeDoc->FlushAndRescan(true);
1462         }
1463 }
1464
1465 /// Get list of OpenDocs (documents underlying edit sessions)
1466 OpenDocList &CMainFrame::GetAllOpenDocs()
1467 {
1468         return static_cast<OpenDocList &>(GetDocList(theApp.m_pOpenTemplate));
1469 }
1470
1471 /// Get list of MergeDocs (documents underlying edit sessions)
1472 MergeDocList &CMainFrame::GetAllMergeDocs()
1473 {
1474         return static_cast<MergeDocList &>(GetDocList(theApp.m_pDiffTemplate));
1475 }
1476
1477 /// Get list of DirDocs (documents underlying a scan)
1478 DirDocList &CMainFrame::GetAllDirDocs()
1479 {
1480         return static_cast<DirDocList &>(GetDocList(theApp.m_pDirTemplate));
1481 }
1482
1483 /// Get list of HexMergeDocs (documents underlying edit sessions)
1484 HexMergeDocList &CMainFrame::GetAllHexMergeDocs()
1485 {
1486         return static_cast<HexMergeDocList &>(GetDocList(theApp.m_pHexMergeTemplate));
1487 }
1488
1489 std::list<CImgMergeFrame *> CMainFrame::GetAllImgMergeFrames()
1490 {
1491         std::list<CImgMergeFrame *> list;
1492         // Close Non-Document/View frame with confirmation
1493         CMDIChildWnd *pChild = static_cast<CMDIChildWnd *>(CWnd::FromHandle(m_hWndMDIClient)->GetWindow(GW_CHILD));
1494         while (pChild != nullptr)
1495         {
1496                 CMDIChildWnd *pNextChild = static_cast<CMDIChildWnd *>(pChild->GetWindow(GW_HWNDNEXT));
1497                 if (GetFrameType(pChild) == FRAME_IMGFILE)
1498                         list.push_back(static_cast<CImgMergeFrame *>(pChild));
1499                 pChild = pNextChild;
1500         }
1501         return list;
1502 }
1503
1504 /**
1505  * @brief Obtain a merge doc to display a difference in files.
1506  * @return Pointer to CMergeDoc to use. 
1507  */
1508 template<class DocClass>
1509 DocClass * GetMergeDocForDiff(CMultiDocTemplate *pTemplate, CDirDoc *pDirDoc, int nFiles, bool bMakeVisible)
1510 {
1511         // Create a new merge doc
1512         DocClass::m_nBuffersTemp = nFiles;
1513         DocClass *pMergeDoc = static_cast<DocClass*>(pTemplate->OpenDocumentFile(nullptr, bMakeVisible));
1514         if (pMergeDoc != nullptr)
1515         {
1516                 pDirDoc->AddMergeDoc(pMergeDoc);
1517                 pMergeDoc->SetDirDoc(pDirDoc);
1518         }
1519         return pMergeDoc;
1520 }
1521
1522 // Clear the item count in the main status pane
1523 void CMainFrame::ClearStatusbarItemCount()
1524 {
1525         m_wndStatusBar.SetPaneText(2, _T(""));
1526 }
1527
1528 /**
1529  * @brief Generate patch from files selected.
1530  *
1531  * Creates a patch from selected files in active directory compare, or
1532  * active file compare. Files in file compare must be saved before
1533  * creating a patch.
1534  */
1535 void CMainFrame::OnToolsGeneratePatch()
1536 {
1537         CPatchTool patcher;
1538         patcher.CreatePatch();
1539 }
1540
1541 void CMainFrame::OnDropFiles(const std::vector<String>& dropped_files)
1542 {
1543         PathContext tFiles(dropped_files);
1544         const size_t fileCount = tFiles.GetSize();
1545
1546         bool recurse = GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS);
1547         // Do a reverse comparison with the current 'Include Subfolders' settings when pressing Control key
1548         if (::GetAsyncKeyState(VK_CONTROL) & 0x8000)
1549                 recurse = !recurse;
1550
1551         // If user has <Shift> pressed with one file selected,
1552         // assume it is an archive and set filenames to same
1553         if (::GetAsyncKeyState(VK_SHIFT) < 0 && fileCount == 1)
1554         {
1555                 tFiles.SetRight(tFiles[0]);
1556         }
1557
1558         // Check if they dropped a project file
1559         DWORD dwFlags[3] = {FFILEOPEN_NONE, FFILEOPEN_NONE, FFILEOPEN_NONE};
1560         if (fileCount == 1)
1561         {
1562                 if (theApp.IsProjectFile(tFiles[0]))
1563                 {
1564                         theApp.LoadAndOpenProjectFile(tFiles[0]);
1565                         return;
1566                 }
1567                 if (IsConflictFile(tFiles[0]))
1568                 {
1569                         DoOpenConflict(tFiles[0], nullptr, true);
1570                         return;
1571                 }
1572         }
1573
1574         DoFileOpen(&tFiles, dwFlags, nullptr, _T(""), recurse);
1575 }
1576
1577 void CMainFrame::OnPluginUnpackMode(UINT nID )
1578 {
1579         switch (nID)
1580         {
1581         case ID_UNPACK_MANUAL:
1582                 FileTransform::AutoUnpacking = false;
1583                 break;
1584         case ID_UNPACK_AUTO:
1585                 FileTransform::AutoUnpacking = true;
1586                 break;
1587         }
1588         for (auto pDirDoc : GetAllDirDocs())
1589         {
1590                 pDirDoc->GetPluginManager().SetUnpackerSettingAll(FileTransform::AutoUnpacking);
1591                 pDirDoc->UpdateAllViews(nullptr);
1592         }
1593         GetOptionsMgr()->SaveOption(OPT_PLUGINS_UNPACKER_MODE, static_cast<int>(FileTransform::AutoUnpacking));
1594 }
1595
1596 void CMainFrame::OnUpdatePluginUnpackMode(CCmdUI* pCmdUI) 
1597 {
1598         pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
1599
1600         if (pCmdUI->m_nID == ID_UNPACK_MANUAL)
1601                 pCmdUI->SetRadio(!FileTransform::AutoUnpacking);
1602         if (pCmdUI->m_nID == ID_UNPACK_AUTO)
1603                 pCmdUI->SetRadio(FileTransform::AutoUnpacking);
1604 }
1605
1606 void CMainFrame::OnPluginPrediffMode(UINT nID )
1607 {
1608         switch (nID)
1609         {
1610         case ID_PREDIFFER_MANUAL:
1611                 FileTransform::AutoPrediffing = false;
1612                 break;
1613         case ID_PREDIFFER_AUTO:
1614                 FileTransform::AutoPrediffing = true;
1615                 break;
1616         }
1617         PrediffingInfo infoPrediffer;
1618         for (auto pMergeDoc : GetAllMergeDocs())
1619                 pMergeDoc->SetPrediffer(&infoPrediffer);
1620         for (auto pDirDoc : GetAllDirDocs())
1621         {
1622                 pDirDoc->GetPluginManager().SetPrediffSettingAll(FileTransform::AutoPrediffing);
1623                 pDirDoc->UpdateAllViews(nullptr);
1624         }
1625         GetOptionsMgr()->SaveOption(OPT_PLUGINS_PREDIFFER_MODE, FileTransform::AutoPrediffing);
1626 }
1627
1628 void CMainFrame::OnUpdatePluginPrediffMode(CCmdUI* pCmdUI) 
1629 {
1630         pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
1631
1632         if (pCmdUI->m_nID == ID_PREDIFFER_MANUAL)
1633                 pCmdUI->SetRadio(!FileTransform::AutoPrediffing);
1634         if (pCmdUI->m_nID == ID_PREDIFFER_AUTO)
1635                 pCmdUI->SetRadio(FileTransform::AutoPrediffing);
1636 }
1637 /**
1638  * @brief Called when "Reload Plugins" item is updated
1639  */
1640 void CMainFrame::OnUpdatePluginRelatedMenu(CCmdUI* pCmdUI)
1641 {
1642         bool enabled = GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED);
1643         if (enabled && (pCmdUI->m_nID == ID_APPLY_PREDIFFER || pCmdUI->m_nID == ID_TRANSFORM_WITH_SCRIPT))
1644                 enabled = GetFrameType(GetActiveFrame()) == FRAME_FILE;
1645         pCmdUI->Enable(enabled);
1646 }
1647
1648 void CMainFrame::OnReloadPlugins()
1649 {
1650         UpdatePrediffersMenu();
1651 }
1652
1653 /** @brief Return active merge edit view, if can figure it out/is available */
1654 CMergeEditView * CMainFrame::GetActiveMergeEditView()
1655 {
1656         // NB: GetActiveDocument does not return the Merge Doc 
1657         //     even when the merge edit view is in front
1658         // NB: CMergeEditFrame::GetActiveView returns `nullptr` when location view active
1659         // So we have this rather complicated logic to try to get a merge edit view
1660         // We look at the front child window, which should be a frame
1661         // and we can get a MergeEditView from it, if it is a CMergeEditFrame
1662         // (DirViews use a different frame type)
1663         CMergeEditFrame * pFrame = dynamic_cast<CMergeEditFrame *>(GetActiveFrame());
1664         if (pFrame == nullptr) return nullptr;
1665         // Try to get the active MergeEditView (ie, left or right)
1666         if (pFrame->GetActiveView() != nullptr && pFrame->GetActiveView()->IsKindOf(RUNTIME_CLASS(CMergeEditView)))
1667         {
1668                 return dynamic_cast<CMergeEditView *>(pFrame->GetActiveView());
1669         }
1670         return pFrame->GetMergeDoc()->GetActiveMergeView();
1671 }
1672
1673 void CMainFrame::UpdatePrediffersMenu()
1674 {
1675         CMenu* menu = GetMenu();
1676         if (menu == nullptr)
1677         {
1678                 return;
1679         }
1680
1681         HMENU hMainMenu = menu->m_hMenu;
1682         HMENU prediffersSubmenu = GetPrediffersSubmenu(hMainMenu);
1683         if (prediffersSubmenu != nullptr)
1684         {
1685                 CMergeEditView * pEditView = GetActiveMergeEditView();
1686                 if (pEditView != nullptr)
1687                         pEditView->GetDocument()->createPrediffersSubmenu(prediffersSubmenu);
1688                 else
1689                 {
1690                         // no view or dir view : display an empty submenu
1691                         int i = GetMenuItemCount(prediffersSubmenu);
1692                         while (i --)
1693                                 ::DeleteMenu(prediffersSubmenu, 0, MF_BYPOSITION);
1694                         ::AppendMenu(prediffersSubmenu, MF_SEPARATOR, 0, nullptr);
1695                 }
1696         }
1697 }
1698
1699 /**
1700  * @brief Save WinMerge configuration and info to file
1701  */
1702 void CMainFrame::OnSaveConfigData()
1703 {
1704         CConfigLog configLog;
1705         String sError;
1706
1707         if (configLog.WriteLogFile(sError))
1708         {
1709                 String sFileName = configLog.GetFileName();
1710                 CMergeApp::OpenFileToExternalEditor(sFileName);
1711         }
1712         else
1713         {
1714                 String sFileName = configLog.GetFileName();
1715                 String msg = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), sFileName, sError);
1716                 AfxMessageBox(msg.c_str(), MB_OK | MB_ICONSTOP);
1717         }
1718 }
1719
1720 /**
1721  * @brief Open two new empty docs, 'Scratchpads'
1722  * 
1723  * Allows user to open two empty docs, to paste text to
1724  * compare from clipboard.
1725  * @note File filenames are set emptys and filedescriptors
1726  * are loaded from resource.
1727  * @sa CMergeDoc::OpenDocs()
1728  * @sa CMergeDoc::TrySaveAs()
1729  */
1730 void CMainFrame::FileNew(int nPanes, FRAMETYPE frameType, bool table) 
1731 {
1732         CDirDoc *pDirDoc = static_cast<CDirDoc*>(theApp.m_pDirTemplate->CreateNewDocument());
1733         
1734         // Load emptyfile descriptors and open empty docs
1735         // Use default codepage
1736         DWORD dwFlags[3] = {0, 0, 0};
1737         String strDesc[3];
1738         FileLocation fileloc[3];
1739         if (nPanes == 2)
1740         {
1741                 strDesc[0] = _("Untitled left");
1742                 strDesc[1] = _("Untitled right");
1743                 fileloc[0].encoding.SetCodepage(ucr::getDefaultCodepage());
1744                 fileloc[1].encoding.SetCodepage(ucr::getDefaultCodepage());
1745         }
1746         else
1747         {
1748                 strDesc[0] = _("Untitled left");
1749                 strDesc[1] = _("Untitled middle");
1750                 strDesc[2] = _("Untitled right");
1751                 fileloc[0].encoding.SetCodepage(ucr::getDefaultCodepage());
1752                 fileloc[1].encoding.SetCodepage(ucr::getDefaultCodepage());
1753                 fileloc[2].encoding.SetCodepage(ucr::getDefaultCodepage());
1754         }
1755         UINT nID = ID_MERGE_COMPARE_TEXT;
1756         switch (frameType)
1757         {
1758         case FRAME_FILE: nID = !table ? ID_MERGE_COMPARE_TEXT : ID_MERGE_COMPARE_TABLE; break;
1759         case FRAME_HEXFILE: nID = ID_MERGE_COMPARE_HEX; break;
1760         case FRAME_IMGFILE: nID = ID_MERGE_COMPARE_IMAGE; break;
1761         }
1762         ShowMergeDoc(nID, pDirDoc, nPanes, fileloc, dwFlags, strDesc);
1763 }
1764
1765 /**
1766  * @brief Open two new empty docs, 'Scratchpads'
1767  * 
1768  * Allows user to open two empty docs, to paste text to
1769  * compare from clipboard.
1770  * @note File filenames are set emptys and filedescriptors
1771  * are loaded from resource.
1772  * @sa CMergeDoc::OpenDocs()
1773  * @sa CMergeDoc::TrySaveAs()
1774  */
1775 template <int nFiles, CMainFrame::FRAMETYPE frameType, bool table>
1776 void CMainFrame::OnFileNew() 
1777 {
1778         FileNew(nFiles, frameType, table);
1779 }
1780
1781 /**
1782  * @brief Open Filters dialog
1783  */
1784 void CMainFrame::OnToolsFilters()
1785 {
1786         String title = _("Filters");
1787         CPropertySheet sht(title.c_str());
1788         LineFiltersDlg lineFiltersDlg;
1789         SubstitutionFiltersDlg substitutionFiltersDlg;
1790         FileFiltersDlg fileFiltersDlg;
1791         std::unique_ptr<LineFiltersList> lineFilters(new LineFiltersList());
1792         std::unique_ptr<SubstitutionFiltersList> SubstitutionFilters(new SubstitutionFiltersList());
1793         String selectedFilter;
1794         const String origFilter = theApp.m_pGlobalFileFilter->GetFilterNameOrMask();
1795         sht.AddPage(&fileFiltersDlg);
1796         sht.AddPage(&lineFiltersDlg);
1797         sht.AddPage(&substitutionFiltersDlg);
1798         sht.m_psh.dwFlags |= PSH_NOAPPLYNOW; // Hide 'Apply' button since we don't need it
1799
1800         // Make sure all filters are up-to-date
1801         theApp.m_pGlobalFileFilter->ReloadUpdatedFilters();
1802
1803         fileFiltersDlg.SetFilterArray(theApp.m_pGlobalFileFilter->GetFileFilters(selectedFilter));
1804         fileFiltersDlg.SetSelected(selectedFilter);
1805         const bool lineFiltersEnabledOrig = GetOptionsMgr()->GetBool(OPT_LINEFILTER_ENABLED);
1806         lineFiltersDlg.m_bIgnoreRegExp = lineFiltersEnabledOrig;
1807
1808         lineFilters->CloneFrom(theApp.m_pLineFilters.get());
1809         lineFiltersDlg.SetList(lineFilters.get());
1810
1811         SubstitutionFilters->CloneFrom(theApp.m_pSubstitutionFiltersList.get());
1812         substitutionFiltersDlg.SetList(SubstitutionFilters.get());
1813
1814         sht.SetActivePage(AfxGetApp()->GetProfileInt(_T("Settings"), _T("FilterStartPage"), 0));
1815
1816         if (sht.DoModal() == IDOK)
1817         {
1818                 String strNone = _("<None>");
1819                 String path = fileFiltersDlg.GetSelected();
1820                 if (path.find(strNone) != String::npos)
1821                 {
1822                         // Don't overwrite mask we already have
1823                         if (!theApp.m_pGlobalFileFilter->IsUsingMask())
1824                         {
1825                                 String sFilter(_T("*.*"));
1826                                 theApp.m_pGlobalFileFilter->SetFilter(sFilter);
1827                                 GetOptionsMgr()->SaveOption(OPT_FILEFILTER_CURRENT, sFilter);
1828                         }
1829                 }
1830                 else
1831                 {
1832                         theApp.m_pGlobalFileFilter->SetFileFilterPath(path);
1833                         theApp.m_pGlobalFileFilter->UseMask(false);
1834                         String sFilter = theApp.m_pGlobalFileFilter->GetFilterNameOrMask();
1835                         GetOptionsMgr()->SaveOption(OPT_FILEFILTER_CURRENT, sFilter);
1836                 }
1837                 bool linefiltersEnabled = lineFiltersDlg.m_bIgnoreRegExp;
1838                 GetOptionsMgr()->SaveOption(OPT_LINEFILTER_ENABLED, linefiltersEnabled);
1839
1840                 // Check if compare documents need rescanning
1841                 bool bFileCompareRescan = false;
1842                 bool bFolderCompareRescan = false;
1843                 CFrameWnd * pFrame = GetActiveFrame();
1844                 FRAMETYPE frame = GetFrameType(pFrame);
1845                 if (frame == FRAME_FILE)
1846                 {
1847                         if
1848                         (
1849                                    linefiltersEnabled != lineFiltersEnabledOrig
1850                                 || !lineFilters->Compare(theApp.m_pLineFilters.get())
1851                                 || !SubstitutionFilters->Compare(theApp.m_pSubstitutionFiltersList.get())
1852                         )
1853                         {
1854                                 bFileCompareRescan = true;
1855                         }
1856                 }
1857                 else if (frame == FRAME_FOLDER)
1858                 {
1859                         const String newFilter = theApp.m_pGlobalFileFilter->GetFilterNameOrMask();
1860                         if (lineFiltersEnabledOrig != linefiltersEnabled || 
1861                                         !theApp.m_pLineFilters->Compare(lineFilters.get()) || origFilter != newFilter)
1862                         {
1863                                 int res = LangMessageBox(IDS_FILTERCHANGED, MB_ICONWARNING | MB_YESNO);
1864                                 if (res == IDYES)
1865                                         bFolderCompareRescan = true;
1866                         }
1867                 }
1868
1869                 // Save new filters before (possibly) rescanning
1870                 theApp.m_pLineFilters->CloneFrom(lineFilters.get());
1871                 theApp.m_pLineFilters->SaveFilters();
1872
1873                 theApp.m_pSubstitutionFiltersList->CloneFrom(SubstitutionFilters.get());
1874                 theApp.m_pSubstitutionFiltersList->SaveFilters();
1875
1876                 if (bFileCompareRescan)
1877                 {
1878                         for (auto pMergeDoc : GetAllMergeDocs())
1879                                 pMergeDoc->FlushAndRescan(true);
1880                 }
1881                 else if (bFolderCompareRescan)
1882                 {
1883                         for (auto pDirDoc : GetAllDirDocs())
1884                                 pDirDoc->Rescan();
1885                 }
1886         }
1887 }
1888
1889 /**
1890  * @brief Open Filters dialog.
1891  */
1892 void CMainFrame::SelectFilter()
1893 {
1894         OnToolsFilters();
1895 }
1896
1897 /**
1898  * @brief Closes application with ESC.
1899  *
1900  * Application is closed if:
1901  * - 'Close Windows with ESC' option is enabled and
1902  *    there is no open document windows
1903  * - '-e' commandline switch is given
1904  */
1905 BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
1906 {
1907         // Check if we got 'ESC pressed' -message
1908         if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_ESCAPE))
1909         {
1910                 if (theApp.m_bEscShutdown && m_wndTabBar.GetItemCount() <= 1)
1911                 {
1912                         AfxGetMainWnd()->SendMessage(WM_COMMAND, ID_APP_EXIT);
1913                         return TRUE;
1914                 }
1915                 else if (GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC) == 1 && m_wndTabBar.GetItemCount() == 0)
1916                 {
1917                         AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_APP_EXIT);
1918                         return FALSE;
1919                 }
1920         }
1921
1922         if (WM_KEYDOWN == pMsg->message && VK_TAB == pMsg->wParam && GetAsyncKeyState(VK_CONTROL) < 0 && m_arrChild.GetSize() > 1)
1923         {
1924                 CWindowsManagerDialog* pDlg = new CWindowsManagerDialog;
1925                 pDlg->Create(CWindowsManagerDialog::IDD, this);
1926                 pDlg->ShowWindow(SW_SHOW);
1927                 return TRUE;
1928         }
1929
1930         return CMDIFrameWnd::PreTranslateMessage(pMsg);
1931 }
1932
1933 /**
1934  * @brief Show/hide statusbar.
1935  */
1936 void CMainFrame::OnViewStatusBar()
1937 {
1938         bool bShow = !GetOptionsMgr()->GetBool(OPT_SHOW_STATUSBAR);
1939         GetOptionsMgr()->SaveOption(OPT_SHOW_STATUSBAR, bShow);
1940
1941         CMDIFrameWnd::ShowControlBar(&m_wndStatusBar, bShow, 0);
1942 }
1943
1944 /**
1945  * @brief Updates "Show Tabbar" menuitem.
1946  */
1947 void CMainFrame::OnUpdateViewTabBar(CCmdUI* pCmdUI) 
1948 {
1949         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_SHOW_TABBAR));
1950 }
1951
1952 /**
1953  * @brief Show/hide tabbar.
1954  */
1955 void CMainFrame::OnViewTabBar()
1956 {
1957         bool bShow = !GetOptionsMgr()->GetBool(OPT_SHOW_TABBAR);
1958         GetOptionsMgr()->SaveOption(OPT_SHOW_TABBAR, bShow);
1959
1960         CMDIFrameWnd::ShowControlBar(&m_wndTabBar, bShow, 0);
1961 }
1962
1963 /**
1964  * @brief Updates "Automatically Resize Panes" menuitem.
1965  */
1966 void CMainFrame::OnUpdateResizePanes(CCmdUI* pCmdUI)
1967 {
1968         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_RESIZE_PANES));
1969 }
1970
1971
1972 /**
1973  * @brief Enable/disable automatic pane resizing.
1974  */
1975 void CMainFrame::OnResizePanes()
1976 {
1977         bool bResize = !GetOptionsMgr()->GetBool(OPT_RESIZE_PANES);
1978         GetOptionsMgr()->SaveOption(OPT_RESIZE_PANES, bResize);
1979         // TODO: Introduce a common merge frame superclass?
1980         CFrameWnd *pActiveFrame = GetActiveFrame();
1981         if (CMergeEditFrame *pFrame = DYNAMIC_DOWNCAST(CMergeEditFrame, pActiveFrame))
1982         {
1983                 pFrame->UpdateAutoPaneResize();
1984                 if (bResize)
1985                         pFrame->UpdateSplitter();
1986         }
1987         else if (CHexMergeFrame *pFrame1 = DYNAMIC_DOWNCAST(CHexMergeFrame, pActiveFrame))
1988         {
1989                 pFrame1->UpdateAutoPaneResize();
1990                 if (bResize)
1991                         pFrame1->UpdateSplitter();
1992         }
1993 }
1994
1995 /**
1996  * @brief Open project-file.
1997  */
1998 void CMainFrame::OnFileOpenProject()
1999 {
2000         String sFilepath;
2001         
2002         // get the default projects path
2003         String strProjectPath = GetOptionsMgr()->GetString(OPT_PROJECTS_PATH);
2004         if (!SelectFile(GetSafeHwnd(), sFilepath, true, strProjectPath.c_str(), _T(""),
2005                         _("WinMerge Project Files (*.WinMerge)|*.WinMerge||")))
2006                 return;
2007         
2008         strProjectPath = paths::GetParentPath(sFilepath);
2009         // store this as the new project path
2010         GetOptionsMgr()->SaveOption(OPT_PROJECTS_PATH, strProjectPath);
2011
2012         theApp.LoadAndOpenProjectFile(sFilepath);
2013 }
2014
2015 /**
2016  * @brief Receive command line from another instance.
2017  *
2018  * This function receives command line when only single-instance
2019  * is allowed. New instance tried to start sends its command line
2020  * to here so we can open paths it was meant to.
2021  */
2022 LRESULT CMainFrame::OnCopyData(WPARAM wParam, LPARAM lParam)
2023 {
2024         COPYDATASTRUCT *pCopyData = (COPYDATASTRUCT*)lParam;
2025         LPCTSTR pchData = (LPCTSTR)pCopyData->lpData;
2026         // Bail out if data isn't zero-terminated
2027         DWORD cchData = pCopyData->cbData / sizeof(TCHAR);
2028         if (cchData == 0 || pchData[cchData - 1] != _T('\0'))
2029                 return FALSE;
2030         ReplyMessage(TRUE);
2031         MergeCmdLineInfo cmdInfo(pchData);
2032         theApp.ApplyCommandLineConfigOptions(cmdInfo);
2033         theApp.ParseArgsAndDoOpen(cmdInfo, this);
2034         return TRUE;
2035 }
2036
2037 LRESULT CMainFrame::OnUser1(WPARAM wParam, LPARAM lParam)
2038 {
2039         if (IMergeDoc *pMergeDoc = GetActiveIMergeDoc())
2040                 pMergeDoc->CheckFileChanged();
2041         return 0;
2042 }
2043
2044 /**
2045  * @brief Close all open windows.
2046  * 
2047  * Asks about saving unsaved files and then closes all open windows.
2048  */
2049 void CMainFrame::OnWindowCloseAll()
2050 {
2051         CMDIChildWnd *pChild = MDIGetActive();
2052         while (pChild != nullptr)
2053         {
2054                 CDocument* pDoc;
2055                 if ((pDoc = pChild->GetActiveDocument()) != nullptr)
2056                 {
2057                         if (!pDoc->SaveModified())
2058                                 return;
2059                         pDoc->OnCloseDocument();
2060                 }
2061                 else if (GetFrameType(pChild) == FRAME_IMGFILE)
2062                 {
2063                         if (!static_cast<CImgMergeFrame *>(pChild)->CloseNow())
2064                                 return;
2065                 }
2066                 else
2067                 {
2068                         pChild->DestroyWindow();
2069                 }
2070                 pChild = MDIGetActive();
2071         }
2072         return;
2073 }
2074
2075 /**
2076  * @brief Enables Window/Close All item if there are open windows.
2077  */ 
2078 void CMainFrame::OnUpdateWindowCloseAll(CCmdUI* pCmdUI)
2079 {
2080         pCmdUI->Enable(MDIGetActive() != nullptr);
2081 }
2082
2083 /**
2084  * @brief Access to the singleton main frame (where we have some globals)
2085  */
2086 CMainFrame * GetMainFrame()
2087 {
2088         CWnd * mainwnd = AfxGetMainWnd();
2089         ASSERT(mainwnd != nullptr);
2090         CMainFrame *pMainframe = dynamic_cast<CMainFrame*>(mainwnd);
2091         ASSERT(pMainframe != nullptr);
2092         return pMainframe;
2093 }
2094
2095 /**
2096  * @brief Opens dialog for user to Load, edit and save project files.
2097  * This dialog gets current compare paths and filter (+other properties
2098  * possible in project files) and initializes the dialog with them.
2099  */
2100 void CMainFrame::OnSaveProject()
2101 {
2102         if (m_pMenus[MENU_OPENVIEW] == nullptr)
2103                 theApp.m_pOpenTemplate->m_hMenuShared = NewOpenViewMenu();
2104         COpenDoc *pOpenDoc = static_cast<COpenDoc *>(theApp.m_pOpenTemplate->CreateNewDocument());
2105
2106         CFrameWnd * pFrame = GetActiveFrame();
2107         FRAMETYPE frame = pFrame ? GetFrameType(pFrame) : FRAME_OTHER;
2108
2109         if (frame == FRAME_FILE || frame == FRAME_HEXFILE || frame == FRAME_IMGFILE)
2110         {
2111                 if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2112                 {
2113                         PathContext paths;
2114                         for (int pane = 0; pane < pMergeDoc->GetFileCount(); ++pane)
2115                         {
2116                                 pOpenDoc->m_dwFlags[pane] = FFILEOPEN_PROJECT | (pMergeDoc->GetReadOnly(pane) ? FFILEOPEN_READONLY : 0);
2117                                 paths.SetPath(pane, pMergeDoc->GetPath(pane));
2118                         }
2119                         pOpenDoc->m_files = paths;
2120                         pOpenDoc->m_bRecurse = GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS);
2121                         pOpenDoc->m_strExt = theApp.m_pGlobalFileFilter->GetFilterNameOrMask();
2122                         pOpenDoc->m_strUnpackerPipeline = pMergeDoc->GetUnpacker()->GetPluginPipeline();
2123                 }
2124         }
2125         else if (frame == FRAME_FOLDER)
2126         {
2127                 // Get paths currently in compare
2128                 if (const CDirDoc* pDoc = static_cast<const CDirDoc*>(pFrame->GetActiveDocument()))
2129                 {
2130                         const CDiffContext& ctxt = pDoc->GetDiffContext();
2131
2132                         // Set-up the dialog
2133                         for (int pane = 0; pane < ctxt.GetCompareDirs(); ++pane)
2134                         {
2135                                 pOpenDoc->m_dwFlags[pane] = FFILEOPEN_PROJECT | (pDoc->GetReadOnly(pane) ? FFILEOPEN_READONLY : 0);
2136                                 pOpenDoc->m_files.SetPath(pane, paths::AddTrailingSlash(ctxt.GetNormalizedPath(pane)));
2137                         }
2138                         pOpenDoc->m_bRecurse = ctxt.m_bRecursive;
2139                         pOpenDoc->m_strExt = static_cast<FileFilterHelper*>(ctxt.m_piFilterGlobal)->GetFilterNameOrMask();
2140                 }
2141         }
2142
2143         CFrameWnd *pOpenFrame = theApp.m_pOpenTemplate->CreateNewFrame(pOpenDoc, nullptr);
2144         theApp.m_pOpenTemplate->InitialUpdateFrame(pOpenFrame, pOpenDoc);
2145 }
2146
2147 /** 
2148  * @brief Start flashing window if window is inactive.
2149  */
2150 void CMainFrame::StartFlashing()
2151 {
2152         CWnd * activeWindow = GetActiveWindow();
2153         if (activeWindow != this)
2154                 FlashWindowEx(FLASHW_ALL | FLASHW_TIMERNOFG, 3, 0);
2155 }
2156
2157 #if _MFC_VER > 0x0600
2158 void CMainFrame::OnActivateApp(BOOL bActive, DWORD dwThreadID)
2159 #else
2160 void CMainFrame::OnActivateApp(BOOL bActive, HTASK hTask)
2161 #endif
2162 {
2163 #if _MFC_VER > 0x0600
2164         CMDIFrameWnd::OnActivateApp(bActive, dwThreadID);
2165 #else
2166         CMDIFrameWnd::OnActivateApp(bActive, hTask);
2167 #endif
2168
2169         if (IMergeDoc *pMergeDoc = GetActiveIMergeDoc())
2170                 PostMessage(WM_USER+1);
2171 }
2172
2173 BOOL CMainFrame::CreateToolbar()
2174 {
2175         if (!m_wndToolBar.CreateEx(this) ||
2176                 !m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
2177         {
2178                 return FALSE;
2179         }
2180
2181         if (!m_wndReBar.Create(this, RBS_BANDBORDERS,
2182                 WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_ALIGN_TOP))
2183         {
2184                 return FALSE;
2185         }
2186
2187         VERIFY(m_wndToolBar.ModifyStyle(0, TBSTYLE_FLAT|TBSTYLE_TRANSPARENT));
2188
2189         // Remove this if you don't want tool tips or a resizable toolbar
2190         m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
2191                 CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
2192         m_wndToolBar.GetToolBarCtrl().SetExtendedStyle(TBSTYLE_EX_DRAWDDARROWS);
2193
2194         m_wndReBar.AddBar(&m_wndToolBar);
2195
2196         LoadToolbarImages();
2197
2198         UINT nID, nStyle;
2199         for (auto cmd : { ID_OPTIONS, ID_FILE_NEW, ID_FILE_OPEN, ID_FILE_SAVE })
2200         {
2201                 int iImage;
2202                 int index = m_wndToolBar.GetToolBarCtrl().CommandToIndex(cmd);
2203                 m_wndToolBar.GetButtonInfo(index, nID, nStyle, iImage);
2204                 nStyle |= TBSTYLE_DROPDOWN;
2205                 m_wndToolBar.SetButtonInfo(index, nID, nStyle, iImage);
2206         }
2207
2208         if (!GetOptionsMgr()->GetBool(OPT_SHOW_TOOLBAR))
2209         {
2210                 CMDIFrameWnd::ShowControlBar(&m_wndToolBar, false, 0);
2211         }
2212
2213         return TRUE;
2214 }
2215
2216 /** @brief Load toolbar images from the resource. */
2217 void CMainFrame::LoadToolbarImages()
2218 {
2219         const int toolbarNewImgSize = MulDiv(16, GetSystemMetrics(SM_CXSMICON), 16) * (1 + GetOptionsMgr()->GetInt(OPT_TOOLBAR_SIZE));
2220         const int toolbarOrgImgSize = toolbarNewImgSize <= 20 ? 16 : 32;
2221         CToolBarCtrl& BarCtrl = m_wndToolBar.GetToolBarCtrl();
2222
2223         m_ToolbarImages[TOOLBAR_IMAGES_ENABLED].Detach();
2224         m_ToolbarImages[TOOLBAR_IMAGES_DISABLED].Detach();
2225         CSize sizeButton(0, 0);
2226
2227         LoadToolbarImageList(toolbarOrgImgSize, toolbarNewImgSize,
2228                 toolbarOrgImgSize <= 16 ? IDB_TOOLBAR_ENABLED : IDB_TOOLBAR_ENABLED32,
2229                 false, m_ToolbarImages[TOOLBAR_IMAGES_ENABLED]);
2230         LoadToolbarImageList(toolbarOrgImgSize, toolbarNewImgSize,
2231                 toolbarOrgImgSize <= 16 ? IDB_TOOLBAR_ENABLED : IDB_TOOLBAR_ENABLED32,
2232                 true, m_ToolbarImages[TOOLBAR_IMAGES_DISABLED]);
2233
2234         sizeButton = CSize(toolbarNewImgSize + 8, toolbarNewImgSize + 8);
2235
2236         BarCtrl.SetButtonSize(sizeButton);
2237         if (CImageList *pImgList = BarCtrl.SetImageList(&m_ToolbarImages[TOOLBAR_IMAGES_ENABLED]))
2238                 pImgList->DeleteImageList();
2239         if (CImageList *pImgList = BarCtrl.SetDisabledImageList(&m_ToolbarImages[TOOLBAR_IMAGES_DISABLED]))
2240                 pImgList->DeleteImageList();
2241
2242         // resize the rebar.
2243         REBARBANDINFO rbbi = { sizeof REBARBANDINFO };
2244         rbbi.fMask = RBBIM_CHILDSIZE;
2245         rbbi.cyMinChild = sizeButton.cy;
2246         m_wndReBar.GetReBarCtrl().SetBandInfo(0, &rbbi);
2247 }
2248
2249
2250 /**
2251  * @brief Load a transparent 32-bit color image list.
2252  */
2253 static void LoadHiColImageList(UINT nIDResource, int nWidth, int nHeight, int nNewWidth, int nNewHeight, int nCount, bool bGrayscale, CImageList& ImgList)
2254 {
2255         CBitmap bm;
2256         bm.Attach(LoadBitmapAndConvertTo32bit(AfxGetInstanceHandle(), nIDResource, nNewWidth * nCount, nNewHeight, bGrayscale, RGB(0xff, 0, 0xff)));
2257
2258         VERIFY(ImgList.Create(nNewWidth, nNewHeight, ILC_COLOR32, nCount, 0));
2259         int nIndex = ImgList.Add(&bm, nullptr);
2260         ASSERT(-1 != nIndex);
2261 }
2262
2263 /**
2264  * @brief Load toolbar image list.
2265  */
2266 static void LoadToolbarImageList(int orgImageWidth, int newImageWidth, UINT nIDResource, bool bGrayscale, CImageList& ImgList)
2267 {
2268         const int ImageCount = 26;
2269         const int orgImageHeight = orgImageWidth - 1;
2270         const int newImageHeight = newImageWidth - 1;
2271         LoadHiColImageList(nIDResource, orgImageWidth, orgImageHeight, newImageWidth, newImageHeight, ImageCount, bGrayscale, ImgList);
2272 }
2273
2274 /**
2275  * @brief Called when the document title is modified.
2276  */
2277 void CMainFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
2278 {
2279         CFrameWnd::OnUpdateFrameTitle(bAddToTitle);
2280         
2281         if (m_wndTabBar.m_hWnd != nullptr)
2282                 m_wndTabBar.UpdateTabs();
2283 }
2284
2285 /** @brief Show none/small/big/huge toolbar. */
2286 void CMainFrame::OnToolbarSize(UINT id)
2287 {
2288         if (id == ID_TOOLBAR_NONE)
2289         {
2290                 GetOptionsMgr()->SaveOption(OPT_SHOW_TOOLBAR, false);
2291                 CMDIFrameWnd::ShowControlBar(&m_wndToolBar, false, 0);
2292         }
2293         else
2294         {
2295                 GetOptionsMgr()->SaveOption(OPT_SHOW_TOOLBAR, true);
2296                 GetOptionsMgr()->SaveOption(OPT_TOOLBAR_SIZE, id - ID_TOOLBAR_SMALL);
2297
2298                 LoadToolbarImages();
2299
2300                 CMDIFrameWnd::ShowControlBar(&m_wndToolBar, true, 0);
2301         }
2302 }
2303
2304 /** @brief Show none/small/big/huge toolbar. */
2305 void CMainFrame::OnUpdateToolbarSize(CCmdUI *pCmdUI)
2306 {
2307         if (!GetOptionsMgr()->GetBool(OPT_SHOW_TOOLBAR))
2308                 pCmdUI->SetRadio(pCmdUI->m_nID == ID_TOOLBAR_NONE);
2309         else
2310                 pCmdUI->SetRadio((pCmdUI->m_nID - ID_TOOLBAR_SMALL) == static_cast<UINT>(GetOptionsMgr()->GetInt(OPT_TOOLBAR_SIZE)));
2311 }
2312
2313 /** @brief Lang aware version of CFrameWnd::OnToolTipText() */
2314 BOOL CMainFrame::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
2315 {
2316         ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);
2317
2318         // need to handle both ANSI and UNICODE versions of the message
2319         TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
2320         TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
2321         String strFullText;
2322         CString strTipText;
2323         UINT_PTR nID = pNMHDR->idFrom;
2324         if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
2325                 pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
2326         {
2327                 // idFrom is actually the HWND of the tool
2328                 nID = ::GetDlgCtrlID((HWND)nID);
2329         }
2330
2331         if (nID != 0) // will be zero on a separator
2332         {
2333                 strFullText = theApp.LoadString(static_cast<UINT>(nID));
2334                 // don't handle the message if no string resource found
2335                 if (strFullText.empty())
2336                         return FALSE;
2337
2338                 // this is the command id, not the button index
2339                 AfxExtractSubString(strTipText, strFullText.c_str(), 1, '\n');
2340         }
2341         if (pNMHDR->code == TTN_NEEDTEXTA)
2342                 _wcstombsz(pTTTA->szText, strTipText, static_cast<ULONG>(std::size(pTTTA->szText)));
2343         else
2344                 lstrcpyn(pTTTW->szText, strTipText, static_cast<int>(std::size(pTTTW->szText)));
2345         *pResult = 0;
2346
2347         // bring the tooltip window above other popup windows
2348         ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,
2349                 SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER);
2350
2351         return TRUE;    // message was handled
2352 }
2353
2354 /**
2355  * @brief Ask user for close confirmation when closing the mainframe.
2356  * This function asks if user wants to close multiple open windows when user
2357  * selects (perhaps accidentally) to close WinMerge (application).
2358  * @return true if user agreeds to close all windows.
2359  */
2360 bool CMainFrame::AskCloseConfirmation()
2361 {
2362         const DirDocList &dirdocs = GetAllDirDocs();
2363         const MergeDocList &mergedocs = GetAllMergeDocs();
2364
2365         int ret = IDYES;
2366         const size_t count = dirdocs.GetCount() + mergedocs.GetCount();
2367         if (count > 1)
2368         {
2369                 // Check that we don't have one empty dirdoc + mergedoc situation.
2370                 // That happens since we open "hidden" dirdoc for every file compare.
2371                 if (dirdocs.GetCount() == 1)
2372                 {
2373                         CDirDoc *pDoc = dirdocs.GetHead();
2374                         if (!pDoc->HasDiffs())
2375                                 return true;
2376                 }
2377                 ret = LangMessageBox(IDS_CLOSEALL_WINDOWS, MB_YESNO | MB_ICONWARNING);
2378         }
2379         return (ret == IDYES);
2380 }
2381
2382 /**
2383  * @brief Shows the release notes for user.
2384  * This function opens release notes HTML document into browser.
2385  */
2386 void CMainFrame::OnHelpReleasenotes()
2387 {
2388         const String sPath = paths::ConcatPath(env::GetProgPath(), RelNotes);
2389         shell::Open(sPath.c_str());
2390 }
2391
2392 /**
2393  * @brief Shows the translations page.
2394  * This function opens translations page URL into browser.
2395  */
2396 void CMainFrame::OnHelpTranslations()
2397 {
2398         shell::Open(TranslationsUrl);
2399 }
2400
2401 /**
2402  * @brief Called when user selects File/Open Conflict...
2403  */
2404 void CMainFrame::OnFileOpenConflict()
2405 {
2406         String conflictFile;
2407         if (SelectFile(GetSafeHwnd(), conflictFile))
2408         {
2409                 DoOpenConflict(conflictFile);
2410         }
2411 }
2412
2413 /**
2414  * @brief Select and open conflict file for resolving.
2415  * This function lets user to select conflict file to resolve.
2416  * Then we parse conflict file to two files to "merge" and
2417  * save resulting file over original file.
2418  *
2419  * Set left-side file read-only as it is the repository file which cannot
2420  * be modified anyway. Right-side file is user's file which is set as
2421  * modified by default so user can just save it and accept workspace
2422  * file as resolved file.
2423  * @param [in] conflictFile Full path to conflict file to open.
2424  * @param [in] checked If true, do not check if it really is project file.
2425  * @return `true` if conflict file was opened for resolving.
2426  */
2427 bool CMainFrame::DoOpenConflict(const String& conflictFile, const String strDesc[] /*= nullptr*/, bool checked /*= false*/)
2428 {
2429         bool conflictCompared = false;
2430
2431         if (!checked)
2432         {
2433                 bool confFile = IsConflictFile(conflictFile);
2434                 if (!confFile)
2435                 {
2436                         String message = strutils::format_string1(_("The file\n%1\nis not a conflict file."), conflictFile);
2437                         AfxMessageBox(message.c_str(), MB_ICONSTOP);
2438                         return false;
2439                 }
2440         }
2441
2442         // Create temp files and put them into the list,
2443         // from where they get deleted when MainFrame is deleted.
2444         String ext = paths::FindExtension(conflictFile);
2445         TempFilePtr wTemp(new TempFile());
2446         String workFile = wTemp->Create(_T("confw_"), ext);
2447         m_tempFiles.push_back(wTemp);
2448         TempFilePtr vTemp(new TempFile());
2449         String revFile = vTemp->Create(_T("confv_"), ext);
2450         m_tempFiles.push_back(vTemp);
2451         TempFilePtr bTemp(new TempFile());
2452         String baseFile = vTemp->Create(_T("confb_"), ext);
2453         m_tempFiles.push_back(bTemp);
2454
2455         // Parse conflict file into two files.
2456         bool inners, threeWay;
2457         int iGuessEncodingType = GetOptionsMgr()->GetInt(OPT_CP_DETECT);
2458         bool success = ParseConflictFile(conflictFile, workFile, revFile, baseFile, iGuessEncodingType, inners, threeWay);
2459
2460         if (success)
2461         {
2462                 // Open two parsed files to WinMerge, telling WinMerge to
2463                 // save over original file (given as third filename).
2464                 theApp.m_strSaveAsPath = conflictFile;
2465                 if (!threeWay)
2466                 {
2467                         String strDesc2[2] = { 
2468                                 (strDesc && !strDesc[0].empty()) ? strDesc[0] : _("Theirs File"),
2469                                 (strDesc && !strDesc[2].empty()) ? strDesc[2] : _("Mine File") };
2470                         DWORD dwFlags[2] = {FFILEOPEN_READONLY | FFILEOPEN_NOMRU, FFILEOPEN_NOMRU | FFILEOPEN_MODIFIED};
2471                         PathContext tmpPathContext(revFile, workFile);
2472                         conflictCompared = DoFileOpen(&tmpPathContext, dwFlags, strDesc2);
2473                 }
2474                 else
2475                 {
2476                         String strDesc3[3] = {
2477                                 (strDesc && !strDesc[0].empty()) ? strDesc[0] : _("Base File"),
2478                                 (strDesc && !strDesc[1].empty()) ? strDesc[1] : _("Theirs File"),
2479                                 (strDesc && !strDesc[2].empty()) ? strDesc[2] : _("Mine File") };
2480                         PathContext tmpPathContext(baseFile, revFile, workFile);
2481                         DWORD dwFlags[3] = {FFILEOPEN_READONLY | FFILEOPEN_NOMRU, FFILEOPEN_READONLY | FFILEOPEN_NOMRU, FFILEOPEN_NOMRU | FFILEOPEN_MODIFIED};
2482                         conflictCompared = DoFileOpen(&tmpPathContext, dwFlags, strDesc3);
2483                 }
2484         }
2485         else
2486         {
2487                 LangMessageBox(IDS_ERROR_CONF_RESOLVE, MB_ICONSTOP);
2488         }
2489         return conflictCompared;
2490 }
2491
2492 bool CMainFrame::DoSelfCompare(UINT nID, const String& file, const String strDesc[] /*= nullptr*/,
2493         const PackingInfo *infoUnpacker /*= nullptr*/, int line /*= -1*/)
2494 {
2495         String ext = paths::FindExtension(file);
2496         TempFilePtr wTemp(new TempFile());
2497         String copiedFile = wTemp->Create(_T("self-compare_"), ext);
2498         m_tempFiles.push_back(wTemp);
2499
2500         TFile(file).copyTo(copiedFile);
2501
2502         String strDesc2[2] = { 
2503                 (strDesc && !strDesc[0].empty()) ? strDesc[0] : _("Original File"),
2504                 (strDesc && !strDesc[1].empty()) ? strDesc[1] : _("") };
2505         DWORD dwFlags[2] = {FFILEOPEN_READONLY | FFILEOPEN_NOMRU, FFILEOPEN_NOMRU};
2506         PathContext tmpPathContext(copiedFile, file);
2507         return DoFileOpen(nID, &tmpPathContext, dwFlags, strDesc2, _T(""), infoUnpacker, line);
2508 }
2509
2510 /**
2511  * @brief Get type of frame (File/Folder compare).
2512  * @param [in] pFrame Pointer to frame to check.
2513  * @return FRAMETYPE of the given frame.
2514 */
2515 CMainFrame::FRAMETYPE CMainFrame::GetFrameType(const CFrameWnd * pFrame)
2516 {
2517         bool bMergeFrame = !!pFrame->IsKindOf(RUNTIME_CLASS(CMergeEditFrame));
2518         bool bHexMergeFrame = !!pFrame->IsKindOf(RUNTIME_CLASS(CHexMergeFrame));
2519         bool bImgMergeFrame = !!pFrame->IsKindOf(RUNTIME_CLASS(CImgMergeFrame));
2520         bool bDirFrame = !!pFrame->IsKindOf(RUNTIME_CLASS(CDirFrame));
2521
2522         if (bMergeFrame)
2523                 return FRAME_FILE;
2524         else if (bHexMergeFrame)
2525                 return FRAME_HEXFILE;
2526         else if (bImgMergeFrame)
2527                 return FRAME_IMGFILE;
2528         else if (bDirFrame)
2529                 return FRAME_FOLDER;
2530         else
2531                 return FRAME_OTHER;
2532 }
2533
2534 /**
2535  * @brief Show the plugins list dialog.
2536  */
2537 void CMainFrame::OnPluginsList()
2538 {
2539         PluginsListDlg dlg;
2540         dlg.DoModal();
2541 }
2542
2543 void CMainFrame::OnToolbarButtonDropDown(NMHDR* pNMHDR, LRESULT* pResult)
2544 {
2545         LPNMTOOLBAR pToolBar = reinterpret_cast<LPNMTOOLBAR>(pNMHDR);
2546         ClientToScreen(&(pToolBar->rcButton));
2547         BCMenu menu;
2548         int id;
2549         switch (pToolBar->iItem)
2550         {
2551         case ID_FILE_NEW:
2552                 id = IDR_POPUP_NEW;
2553                 break;
2554         case ID_FILE_OPEN:
2555                 id = IDR_POPUP_OPEN;
2556                 break;
2557         case ID_FILE_SAVE:
2558                 id = IDR_POPUP_SAVE;
2559                 break;
2560         default:
2561                 id = IDR_POPUP_DIFF_OPTIONS;
2562                 break;
2563         }
2564         VERIFY(menu.LoadMenu(id));
2565         theApp.TranslateMenu(menu.m_hMenu);
2566         CMenu* pPopup = menu.GetSubMenu(0);
2567         if (pPopup != nullptr)
2568         {
2569                 pPopup->TrackPopupMenu(TPM_RIGHTALIGN | TPM_RIGHTBUTTON, 
2570                         pToolBar->rcButton.right, pToolBar->rcButton.bottom, this);
2571         }
2572         *pResult = 0;
2573 }
2574 void CMainFrame::OnDiffWhitespace(UINT nID)
2575 {
2576         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_WHITESPACE, nID - ID_DIFF_OPTIONS_WHITESPACE_COMPARE);
2577         ApplyDiffOptions();
2578 }
2579
2580 void CMainFrame::OnUpdateDiffWhitespace(CCmdUI* pCmdUI)
2581 {
2582         pCmdUI->SetRadio((pCmdUI->m_nID - ID_DIFF_OPTIONS_WHITESPACE_COMPARE) == static_cast<UINT>(GetOptionsMgr()->GetInt(OPT_CMP_IGNORE_WHITESPACE)));
2583         pCmdUI->Enable();
2584 }
2585
2586 void CMainFrame::OnDiffIgnoreBlankLines()
2587 {
2588         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_BLANKLINES, !GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_BLANKLINES));
2589         ApplyDiffOptions();
2590 }
2591
2592 void CMainFrame::OnUpdateDiffIgnoreBlankLines(CCmdUI* pCmdUI)
2593 {
2594         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_BLANKLINES));
2595         pCmdUI->Enable();
2596 }
2597
2598 void CMainFrame::OnDiffIgnoreCase()
2599 {
2600         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_CASE, !GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CASE));
2601         ApplyDiffOptions();
2602 }
2603
2604 void CMainFrame::OnUpdateDiffIgnoreCase(CCmdUI* pCmdUI)
2605 {
2606         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CASE));
2607         pCmdUI->Enable();
2608 }
2609
2610 void CMainFrame::OnDiffIgnoreEOL()
2611 {
2612         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_EOL, !GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_EOL));
2613         ApplyDiffOptions();
2614 }
2615
2616 void CMainFrame::OnUpdateDiffIgnoreEOL(CCmdUI* pCmdUI)
2617 {
2618         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_EOL));
2619         pCmdUI->Enable();
2620 }
2621
2622 void CMainFrame::OnDiffIgnoreCP()
2623 {
2624         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_CODEPAGE, !GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CODEPAGE));
2625         ApplyDiffOptions();
2626 }
2627
2628 void CMainFrame::OnUpdateDiffIgnoreCP(CCmdUI* pCmdUI)
2629 {
2630         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CODEPAGE));
2631         pCmdUI->Enable();
2632 }
2633
2634 void CMainFrame::OnDiffIgnoreComments()
2635 {
2636         GetOptionsMgr()->SaveOption(OPT_CMP_FILTER_COMMENTLINES, !GetOptionsMgr()->GetBool(OPT_CMP_FILTER_COMMENTLINES));
2637         ApplyDiffOptions();
2638 }
2639
2640 void CMainFrame::OnUpdateDiffIgnoreComments(CCmdUI* pCmdUI)
2641 {
2642         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_FILTER_COMMENTLINES));
2643         pCmdUI->Enable();
2644 }
2645
2646 void CMainFrame::OnIncludeSubfolders()
2647 {
2648         GetOptionsMgr()->SaveOption(OPT_CMP_INCLUDE_SUBDIRS, !GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS));
2649         // Update all dirdoc settings
2650         for (auto pDirDoc : GetAllDirDocs())
2651                 pDirDoc->RefreshOptions();
2652         for (auto pOpenDoc : GetAllOpenDocs())
2653                 pOpenDoc->RefreshOptions();
2654 }
2655
2656 void CMainFrame::OnUpdateIncludeSubfolders(CCmdUI* pCmdUI)
2657 {
2658         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS));
2659         pCmdUI->Enable();
2660 }
2661
2662 void CMainFrame::OnCompareMethod(UINT nID)
2663
2664         GetOptionsMgr()->SaveOption(OPT_CMP_METHOD, nID - ID_DIFF_OPTIONS_COMPMETHOD_FULL_CONTENTS);
2665 }
2666
2667 void CMainFrame::OnUpdateCompareMethod(CCmdUI* pCmdUI)
2668 {
2669         pCmdUI->SetRadio((pCmdUI->m_nID - ID_DIFF_OPTIONS_COMPMETHOD_FULL_CONTENTS) == static_cast<UINT>(GetOptionsMgr()->GetInt(OPT_CMP_METHOD)));
2670         pCmdUI->Enable();
2671 }
2672
2673 void CMainFrame::OnMRUs(UINT nID)
2674 {
2675         std::vector<JumpList::Item> mrus = JumpList::GetRecentDocs(GetOptionsMgr()->GetInt(OPT_MRU_MAX));
2676         const size_t idx = static_cast<size_t>(nID) - ID_MRU_FIRST;
2677         if (idx < mrus.size())
2678         {
2679                 MergeCmdLineInfo cmdInfo((_T("\"") + mrus[idx].path + _T("\" ") + mrus[idx].params).c_str());
2680                 theApp.ParseArgsAndDoOpen(cmdInfo, this);
2681         }
2682 }
2683
2684 void CMainFrame::OnUpdateNoMRUs(CCmdUI* pCmdUI)
2685 {
2686         // append the MRU submenu
2687         CMenu *pMenu = pCmdUI->m_pSubMenu ? pCmdUI->m_pSubMenu : pCmdUI->m_pMenu;
2688         if (pMenu == nullptr)
2689                 return;
2690         HMENU hMenu = pMenu->m_hMenu;
2691         
2692         // empty the menu
2693         size_t i = ::GetMenuItemCount(hMenu);
2694         while (i --)
2695                 ::DeleteMenu(hMenu, 0, MF_BYPOSITION);
2696
2697         std::vector<JumpList::Item> mrus = JumpList::GetRecentDocs(GetOptionsMgr()->GetInt(OPT_MRU_MAX));
2698
2699         if (mrus.size() == 0)
2700         {
2701                 // no script : create a <empty> entry
2702                 ::AppendMenu(hMenu, MF_STRING, ID_NO_EDIT_SCRIPTS, theApp.LoadString(IDS_NO_EDIT_SCRIPTS).c_str());
2703         }
2704         else
2705         {
2706                 // or fill in the submenu with the scripts names
2707                 int ID = ID_MRU_FIRST;  // first ID in menu
2708                 for (i = 0 ; i < mrus.size() ; i++, ID++)
2709                         ::AppendMenu(hMenu, MF_STRING, ID, 
2710                                 ((i < 9 ? strutils::format(_T("&%d "), i+1) : strutils::format(_T("&%c "), 'a' + i - 9)) 
2711                                         + mrus[i].title).c_str());
2712         }
2713
2714         pCmdUI->Enable(true);
2715 }
2716
2717 /**
2718  * @brief Update plugin name
2719  * @param [in] pCmdUI UI component to update.
2720  */
2721 void CMainFrame::OnUpdatePluginName(CCmdUI* pCmdUI)
2722 {
2723         if (auto pMergeDoc = GetActiveIMergeDoc())
2724         {
2725                 String pluginNames;
2726                 const PackingInfo* infoUnpacker = pMergeDoc->GetUnpacker();
2727                 if (infoUnpacker && !infoUnpacker->GetPluginPipeline().empty())
2728                         pluginNames += infoUnpacker->GetPluginPipeline() + _T("&");
2729                 const PrediffingInfo* infoPrediffer = pMergeDoc->GetPrediffer();
2730                 if (infoPrediffer && !infoPrediffer->GetPluginPipeline().empty())
2731                         pluginNames += infoPrediffer->GetPluginPipeline() + _T("&");
2732                 pCmdUI->SetText(pluginNames.substr(0, pluginNames.length() - 1).c_str());
2733         }
2734         else
2735                 pCmdUI->SetText(_T(""));
2736 }
2737
2738 /**
2739  * @brief Move to next file
2740  */
2741 void CMainFrame::OnNextFile()
2742 {
2743         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2744                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2745                         pDirDoc->MoveToNextFile(pMergeDoc);
2746 }
2747
2748 /**
2749  * @brief Called when Move to next file is updated
2750  */
2751 void CMainFrame::OnUpdateNextFile(CCmdUI* pCmdUI)
2752 {
2753         bool enabled = false;
2754         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2755                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2756                         enabled = !pDirDoc->IsLastFile();
2757         pCmdUI->Enable(enabled);
2758 }
2759
2760 /**
2761  * @brief Move to previous file
2762  */
2763 void CMainFrame::OnPrevFile()
2764 {
2765         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2766                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2767                         pDirDoc->MoveToPrevFile(pMergeDoc);
2768 }
2769
2770 /**
2771  * @brief Called when Move to previous file is updated
2772  */
2773 void CMainFrame::OnUpdatePrevFile(CCmdUI* pCmdUI)
2774 {
2775         bool enabled = false;
2776         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2777                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2778                         enabled = !pDirDoc->IsFirstFile();
2779         pCmdUI->Enable(enabled);
2780 }
2781
2782 /**
2783  * @brief Move to first file
2784  */
2785 void CMainFrame::OnFirstFile()
2786 {
2787         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2788                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2789                         pDirDoc->MoveToFirstFile(pMergeDoc);
2790 }
2791
2792 /**
2793  * @brief Called when Move to first file is updated
2794  */
2795 void CMainFrame::OnUpdateFirstFile(CCmdUI* pCmdUI)
2796 {
2797         bool enabled = false;
2798         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2799                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2800                         enabled = !pDirDoc->IsFirstFile();
2801         pCmdUI->Enable(enabled);
2802 }
2803
2804 /**
2805  * @brief Move to last file
2806  */
2807 void CMainFrame::OnLastFile()
2808 {
2809         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2810                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2811                         pDirDoc->MoveToLastFile(pMergeDoc);
2812 }
2813
2814 /**
2815  * @brief Called when Move to last file item is updated
2816  */
2817 void CMainFrame::OnUpdateLastFile(CCmdUI* pCmdUI)
2818 {
2819         bool enabled = false;
2820         if (IMergeDoc* pMergeDoc = GetActiveIMergeDoc())
2821                 if (CDirDoc* pDirDoc = pMergeDoc->GetDirDoc())
2822                         enabled = !pDirDoc->IsLastFile();
2823         pCmdUI->Enable(enabled);
2824 }
2825
2826 void CMainFrame::ReloadMenu()
2827 {
2828         // set the menu of the main frame window
2829         UINT idMenu = IDR_MAINFRAME;
2830         CMergeApp *pApp = dynamic_cast<CMergeApp *> (AfxGetApp());
2831         CMainFrame * pMainFrame = dynamic_cast<CMainFrame *> ((CFrameWnd*)pApp->m_pMainWnd);
2832         HMENU hNewDefaultMenu = pMainFrame->NewDefaultMenu(idMenu);
2833         HMENU hNewMergeMenu = pMainFrame->NewMergeViewMenu();
2834         HMENU hNewImgMergeMenu = pMainFrame->NewImgMergeViewMenu();
2835         HMENU hNewDirMenu = pMainFrame->NewDirViewMenu();
2836         if (hNewDefaultMenu != nullptr && hNewMergeMenu != nullptr && hNewDirMenu != nullptr)
2837         {
2838                 // Note : for Windows98 compatibility, use FromHandle and not Attach/Detach
2839                 CMenu * pNewDefaultMenu = CMenu::FromHandle(hNewDefaultMenu);
2840                 CMenu * pNewMergeMenu = CMenu::FromHandle(hNewMergeMenu);
2841                 CMenu * pNewImgMergeMenu = CMenu::FromHandle(hNewImgMergeMenu);
2842                 CMenu * pNewDirMenu = CMenu::FromHandle(hNewDirMenu);
2843
2844                 CWnd *pFrame = CWnd::FromHandle(::GetWindow(pMainFrame->m_hWndMDIClient, GW_CHILD));
2845                 while (pFrame != nullptr)
2846                 {
2847                         if (pFrame->IsKindOf(RUNTIME_CLASS(CMergeEditFrame)))
2848                                 static_cast<CMergeEditFrame *>(pFrame)->SetSharedMenu(hNewMergeMenu);
2849                         if (pFrame->IsKindOf(RUNTIME_CLASS(CHexMergeFrame)))
2850                                 static_cast<CHexMergeFrame *>(pFrame)->SetSharedMenu(hNewMergeMenu);
2851                         if (pFrame->IsKindOf(RUNTIME_CLASS(CImgMergeFrame)))
2852                                 static_cast<CImgMergeFrame *>(pFrame)->SetSharedMenu(hNewImgMergeMenu);
2853                         else if (pFrame->IsKindOf(RUNTIME_CLASS(COpenFrame)))
2854                                 static_cast<COpenFrame *>(pFrame)->SetSharedMenu(hNewDefaultMenu);
2855                         else if (pFrame->IsKindOf(RUNTIME_CLASS(CDirFrame)))
2856                                 static_cast<CDirFrame *>(pFrame)->SetSharedMenu(hNewDirMenu);
2857                         pFrame = pFrame->GetNextWindow();
2858                 }
2859
2860                 CFrameWnd *pActiveFrame = pMainFrame->GetActiveFrame();
2861                 if (pActiveFrame != nullptr)
2862                 {
2863                         if (pActiveFrame->IsKindOf(RUNTIME_CLASS(CMergeEditFrame)))
2864                                 pMainFrame->MDISetMenu(pNewMergeMenu, nullptr);
2865                         else if (pActiveFrame->IsKindOf(RUNTIME_CLASS(CHexMergeFrame)))
2866                                 pMainFrame->MDISetMenu(pNewMergeMenu, nullptr);
2867                         else if (pActiveFrame->IsKindOf(RUNTIME_CLASS(CImgMergeFrame)))
2868                                 pMainFrame->MDISetMenu(pNewImgMergeMenu, nullptr);
2869                         else if (pActiveFrame->IsKindOf(RUNTIME_CLASS(CDirFrame)))
2870                                 pMainFrame->MDISetMenu(pNewDirMenu, nullptr);
2871                         else
2872                                 pMainFrame->MDISetMenu(pNewDefaultMenu, nullptr);
2873                 }
2874                 else
2875                         pMainFrame->MDISetMenu(pNewDefaultMenu, nullptr);
2876
2877                 // Don't delete the old menu
2878                 // There is a bug in BCMenu or in Windows98 : the new menu does not
2879                 // appear correctly if we destroy the old one
2880                 //                      if (pOldDefaultMenu != nullptr)
2881                 //                              pOldDefaultMenu->DestroyMenu();
2882                 //                      if (pOldMergeMenu != nullptr)
2883                 //                              pOldMergeMenu->DestroyMenu();
2884                 //                      if (pOldDirMenu = nullptr)
2885                 //                              pOldDirMenu->DestroyMenu();
2886
2887                 // m_hMenuDefault is used to redraw the main menu when we close a child frame
2888                 // if this child frame had a different menu
2889                 pMainFrame->m_hMenuDefault = hNewDefaultMenu;
2890                 pApp->m_pOpenTemplate->m_hMenuShared = hNewDefaultMenu;
2891                 pApp->m_pDiffTemplate->m_hMenuShared = hNewMergeMenu;
2892                 pApp->m_pDirTemplate->m_hMenuShared = hNewDirMenu;
2893
2894                 // force redrawing the menu bar
2895                 pMainFrame->DrawMenuBar();
2896         }
2897 }
2898
2899 void CMainFrame::AppendPluginMenus(CMenu *pMenu, const String& filteredFilenames,
2900         const std::vector<std::wstring>& events, bool addAllMenu, unsigned baseId)
2901 {
2902         if (!GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED))
2903                 return;
2904
2905         auto [suggestedPlugins, allPlugins] = FileTransform::CreatePluginMenuInfos(filteredFilenames, events, baseId);
2906
2907         if (!addAllMenu)
2908         {
2909                 pMenu->AppendMenu(MF_STRING, ID_SUGGESTED_PLUGINS, _("Suggested plugins").c_str());
2910         }
2911
2912         for (const auto& [caption, name, id, plugin] : suggestedPlugins)
2913                 pMenu->AppendMenu(MF_STRING, id, caption.c_str());
2914
2915         CMenu* pMenu2 = pMenu;
2916         CMenu popupAll;
2917         if (addAllMenu)
2918         {
2919                 popupAll.CreatePopupMenu();
2920                 pMenu->AppendMenu(MF_POPUP, reinterpret_cast<UINT_PTR>(popupAll.m_hMenu), _("Al&l").c_str());
2921                 pMenu2 = &popupAll;
2922         }
2923         else
2924         {
2925                 pMenu->AppendMenu(MF_SEPARATOR, 0);
2926                 pMenu->AppendMenu(MF_STRING, ID_NOT_SUGGESTED_PLUGINS, _("Other plugins").c_str());
2927         }
2928
2929         std::vector<String> processTypes;
2930         for (const auto& [processType, pluginList] : allPlugins)
2931                 processTypes.push_back(processType);
2932         auto it = std::find(processTypes.begin(), processTypes.end(), _("&Others"));
2933         if (it != processTypes.end())
2934         {
2935                 processTypes.erase(it);
2936                 processTypes.push_back(_("&Others"));
2937         }
2938
2939         for (const auto& processType: processTypes)
2940         {
2941                 CMenu popup;
2942                 popup.CreatePopupMenu();
2943                 if (processType.empty())
2944                 {
2945                         for (const auto& [caption, name, id, plugin] : allPlugins[processType])
2946                                 pMenu2->AppendMenu(MF_STRING, id, caption.c_str());
2947                 }
2948                 else
2949                 {
2950                         for (const auto& [caption, name, id, plugin] : allPlugins[processType])
2951                                 popup.AppendMenu(MF_STRING, id, caption.c_str());
2952                         pMenu2->AppendMenu(MF_POPUP, reinterpret_cast<UINT_PTR>(popup.m_hMenu), processType.c_str());
2953                 }
2954                 popup.Detach();
2955         }
2956
2957         if (addAllMenu)
2958         {
2959                 if (baseId == ID_UNPACKERS_FIRST)
2960                         pMenu2->AppendMenu(MF_STRING, ID_OPEN_WITH_UNPACKER, _("&Select...").c_str());
2961                 else if (baseId == ID_PREDIFFERS_FIRST)
2962                         pMenu2->AppendMenu(MF_STRING, ID_APPLY_PREDIFFER, _("&Select...").c_str());
2963         }
2964         popupAll.Detach();
2965 }
2966
2967 String CMainFrame::GetPluginPipelineByMenuId(unsigned idSearch, const std::vector<std::wstring>& events, unsigned baseId)
2968 {
2969         PluginInfo* pluginFound = nullptr;
2970         String pluginName;
2971         auto [suggestedPlugins, allPlugins] = FileTransform::CreatePluginMenuInfos(_T(""), events, baseId);
2972         for (const auto& [processType, pluginList] : allPlugins)
2973         {
2974                 for (const auto& [caption, name, id, plugin] : pluginList)
2975                 {
2976                         if (id == idSearch)
2977                         {
2978                                 pluginName = name;
2979                                 pluginFound = plugin;
2980                                 break;
2981                         }
2982                 }
2983         }
2984         if (pluginFound)
2985         {
2986                 if (!pluginFound->GetExtendedPropertyValue(_T("ArgumentsRequired")).has_value() && 
2987                     !pluginFound->GetExtendedPropertyValue(pluginName + _T(".ArgumentsRequired")).has_value())
2988                         return pluginName;
2989                 CSelectPluginDlg dlg(pluginName, _T(""), 
2990                         (baseId == ID_UNPACKERS_FIRST)  ? CSelectPluginDlg::PluginType::Unpacker    : (
2991                         (baseId == ID_PREDIFFERS_FIRST) ? CSelectPluginDlg::PluginType::Prediffer   : 
2992                                                           CSelectPluginDlg::PluginType::EditorScript), true);
2993                 if (dlg.DoModal() != IDOK)
2994                         return {};
2995                 return dlg.GetPluginPipeline();
2996         }
2997         return {};
2998 }
2999
3000 IMergeDoc* CMainFrame::GetActiveIMergeDoc()
3001 {
3002         CFrameWnd* pFrame = GetActiveFrame();
3003         if (!pFrame)
3004                 return nullptr;
3005         IMergeDoc* pMergeDoc = dynamic_cast<IMergeDoc*>(pFrame->GetActiveDocument());
3006         if (!pMergeDoc)
3007                 pMergeDoc = dynamic_cast<IMergeDoc *>(pFrame);
3008         return pMergeDoc;
3009 }
3010
3011 void CMainFrame::UpdateDocTitle()
3012 {
3013         CDocManager* pDocManager = AfxGetApp()->m_pDocManager;
3014         POSITION posTemplate = pDocManager->GetFirstDocTemplatePosition();
3015         ASSERT(posTemplate != nullptr);
3016
3017         while (posTemplate != nullptr)
3018         {
3019                 CDocTemplate* pTemplate = pDocManager->GetNextDocTemplate(posTemplate);
3020
3021                 ASSERT(pTemplate != nullptr);
3022
3023                 for (auto pDoc : GetDocList(static_cast<CMultiDocTemplate *>(pTemplate)))
3024                 {
3025                         static_cast<CDocument *>(const_cast<void *>(pDoc))->SetTitle(nullptr);
3026                         ((CFrameWnd*)AfxGetApp()->m_pMainWnd)->OnUpdateFrameTitle(TRUE);
3027                 }
3028         }
3029 }
3030
3031 void CMainFrame::OnAccelQuit()
3032 {
3033         // TODO: Add your command handler code here
3034
3035         SendMessage(WM_CLOSE);
3036 }
3037
3038 LRESULT CMainFrame::OnChildFrameAdded(WPARAM wParam, LPARAM lParam)
3039 {
3040         for (int i = 0; i < m_arrChild.GetSize(); ++i)
3041         {
3042                 if (reinterpret_cast<CMDIChildWnd*>(lParam) == m_arrChild.GetAt(i))
3043                 {
3044                         return 0;
3045                 }
3046         }
3047
3048         m_arrChild.InsertAt(0, (CMDIChildWnd*)lParam);
3049
3050         return 1;
3051 }
3052
3053 LRESULT CMainFrame::OnChildFrameRemoved(WPARAM wParam, LPARAM lParam)
3054 {
3055         for (int i = 0; i < m_arrChild.GetSize(); ++i)
3056         {
3057                 if (reinterpret_cast<CMDIChildWnd*>(lParam) == m_arrChild.GetAt(i))
3058                 {
3059                         m_arrChild.RemoveAt(i);
3060                         break;
3061                 }
3062         }
3063
3064         return 1;
3065 }
3066
3067 LRESULT CMainFrame::OnChildFrameActivate(WPARAM wParam, LPARAM lParam)
3068 {
3069         for (int i = 0; i < m_arrChild.GetSize(); ++i)
3070         {
3071                 if (reinterpret_cast<CMDIChildWnd*>(lParam) == m_arrChild.GetAt(i))
3072                 {
3073                         CMDIChildWnd* pMDIChild = m_arrChild.GetAt(i);
3074                         if (pMDIChild->IsIconic())
3075                                 pMDIChild->ShowWindow(SW_RESTORE);
3076                         MDIActivate(pMDIChild);
3077                         break;
3078                 }
3079         }
3080
3081         return 1;
3082 }
3083 // put lParam as index 0 in m_arrChild
3084 LRESULT CMainFrame::OnChildFrameActivated(WPARAM wParam, LPARAM lParam)
3085 {
3086         for (int i = 0; i < m_arrChild.GetSize(); ++i)
3087         {
3088                 if (reinterpret_cast<CMDIChildWnd*>(lParam) == m_arrChild.GetAt(i))
3089                 {
3090                         m_arrChild.RemoveAt(i);
3091                         break;
3092                 }
3093         }
3094
3095         m_arrChild.InsertAt(0, (CMDIChildWnd*)lParam);
3096
3097         return 1;
3098 }