OSDN Git Service

Merge pull request #8 from WinMerge/master
[winmerge-jp/winmerge-jp.git] / Src / Merge.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  Merge.cpp
9  *
10  * @brief Defines the class behaviors for the application.
11  *
12  */
13
14 #include "stdafx.h"
15 #include "Merge.h"
16 #include "Constants.h"
17 #include "UnicodeString.h"
18 #include "unicoder.h"
19 #include "Environment.h"
20 #include "OptionsMgr.h"
21 #include "OptionsInit.h"
22 #include "RegOptionsMgr.h"
23 #include "OpenDoc.h"
24 #include "OpenFrm.h"
25 #include "OpenView.h"
26 #include "HexMergeDoc.h"
27 #include "HexMergeFrm.h"
28 #include "HexMergeView.h"
29 #include "AboutDlg.h"
30 #include "MainFrm.h"
31 #include "MergeEditFrm.h"
32 #include "DirFrame.h"
33 #include "MergeDoc.h"
34 #include "DirDoc.h"
35 #include "DirView.h"
36 #include "PropBackups.h"
37 #include "FileOrFolderSelect.h"
38 #include "paths.h"
39 #include "FileFilterHelper.h"
40 #include "LineFiltersList.h"
41 #include "FilterCommentsManager.h"
42 #include "SyntaxColors.h"
43 #include "CCrystalTextMarkers.h"
44 #include "OptionsSyntaxColors.h"
45 #include "Plugins.h"
46 #include "ProjectFile.h"
47 #include "MergeEditSplitterView.h"
48 #include "LanguageSelect.h"
49 #include "OptionsDef.h"
50 #include "MergeCmdLineInfo.h"
51 #include "ConflictFileParser.h"
52 #include "JumpList.h"
53 #include "stringdiffs.h"
54 #include "TFile.h"
55 #include "paths.h"
56 #include "CompareStats.h"
57 #include "TestMain.h"
58 #include "charsets.h" // For shutdown cleanup
59
60 #ifdef _DEBUG
61 #define new DEBUG_NEW
62 #endif
63
64 /** @brief Location for command line help to open. */
65 static const TCHAR CommandLineHelpLocation[] = _T("::/htmlhelp/Command_line.html");
66
67 /** @brief Backup file extension. */
68 static const TCHAR BACKUP_FILE_EXT[] = _T("bak");
69
70 /////////////////////////////////////////////////////////////////////////////
71 // CMergeApp
72
73 BEGIN_MESSAGE_MAP(CMergeApp, CWinApp)
74         //{{AFX_MSG_MAP(CMergeApp)
75         ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
76         ON_COMMAND(ID_HELP, OnHelp)
77         ON_COMMAND_EX_RANGE(ID_FILE_PROJECT_MRU_FIRST, ID_FILE_PROJECT_MRU_LAST, OnOpenRecentFile)
78         ON_UPDATE_COMMAND_UI(ID_FILE_PROJECT_MRU_FIRST, CWinApp::OnUpdateRecentFileMenu)
79         ON_COMMAND(ID_FILE_MERGINGMODE, OnMergingMode)
80         ON_UPDATE_COMMAND_UI(ID_FILE_MERGINGMODE, OnUpdateMergingMode)
81         ON_UPDATE_COMMAND_UI(ID_STATUS_MERGINGMODE, OnUpdateMergingStatus)
82         //}}AFX_MSG_MAP
83         // Standard file based document commands
84         //ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
85         //ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
86         // Standard print setup command
87         ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
88 END_MESSAGE_MAP()
89
90 /////////////////////////////////////////////////////////////////////////////
91 // CMergeApp construction
92
93 CMergeApp::CMergeApp() :
94   m_bNeedIdleTimer(false)
95 , m_pOpenTemplate(nullptr)
96 , m_pDiffTemplate(nullptr)
97 , m_pHexMergeTemplate(nullptr)
98 , m_pDirTemplate(nullptr)
99 , m_mainThreadScripts(nullptr)
100 , m_nLastCompareResult(0)
101 , m_bNonInteractive(false)
102 , m_pOptions(new CRegOptionsMgr())
103 , m_pGlobalFileFilter(new FileFilterHelper())
104 , m_nActiveOperations(0)
105 , m_pLangDlg(new CLanguageSelect())
106 , m_bEscShutdown(false)
107 , m_bExitIfNoDiff(MergeCmdLineInfo::Disabled)
108 , m_pLineFilters(new LineFiltersList())
109 , m_pFilterCommentsManager(new FilterCommentsManager())
110 , m_pSyntaxColors(new SyntaxColors())
111 , m_pMarkers(new CCrystalTextMarkers())
112 , m_bMergingMode(false)
113 {
114         // add construction code here,
115         // Place all significant initialization in InitInstance
116 }
117
118 CMergeApp::~CMergeApp()
119 {
120         strdiff::Close();
121 }
122 /////////////////////////////////////////////////////////////////////////////
123 // The one and only CMergeApp object
124
125 CMergeApp theApp;
126
127 /////////////////////////////////////////////////////////////////////////////
128 // CMergeApp initialization
129
130 /**
131  * @brief Initialize WinMerge application instance.
132  * @return TRUE if application initialization succeeds (and we'll run it),
133  *   FALSE if something failed and we exit the instance.
134  * @todo We could handle these failure situations more gratefully, i.e. show
135  *  at least some error message to the user..
136  */
137 BOOL CMergeApp::InitInstance()
138 {
139         // Prevents DLL hijacking
140         HMODULE hLibrary = GetModuleHandle(_T("kernel32.dll"));
141         BOOL (WINAPI *pfnSetSearchPathMode)(DWORD) = (BOOL (WINAPI *)(DWORD))GetProcAddress(hLibrary, "SetSearchPathMode");
142         if (pfnSetSearchPathMode != nullptr)
143                 pfnSetSearchPathMode(0x00000001L /*BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE*/ | 0x00008000L /*BASE_SEARCH_PATH_PERMANENT*/);
144         BOOL (WINAPI *pfnSetDllDirectoryA)(LPCSTR) = (BOOL (WINAPI *)(LPCSTR))GetProcAddress(hLibrary, "SetDllDirectoryA");
145         if (pfnSetDllDirectoryA != nullptr)
146                 pfnSetDllDirectoryA("");
147
148         JumpList::SetCurrentProcessExplicitAppUserModelID(L"Thingamahoochie.WinMerge");
149
150         InitCommonControls();    // initialize common control library
151         CWinApp::InitInstance(); // call parent class method
152
153         m_imageForInitializingGdiplus.Load((IStream*)nullptr); // initialize GDI+
154
155         // Runtime switch so programmer may set this in interactive debugger
156         int dbgmem = 0;
157         if (dbgmem)
158         {
159                 // get current setting
160                 int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
161                 // Keep freed memory blocks in the heap's linked list and mark them as freed
162                 tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
163                 // Call _CrtCheckMemory at every allocation and deallocation request.
164                 // WARNING: This slows down WinMerge *A LOT*
165                 tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
166                 // Set the new state for the flag
167                 _CrtSetDbgFlag( tmpFlag );
168         }
169
170         // CCrystalEdit Drag and Drop functionality needs AfxOleInit.
171         if(!AfxOleInit())
172         {
173                 TRACE(_T("AfxOleInitFailed. OLE functionality disabled"));
174         }
175
176         // Standard initialization
177         // If you are not using these features and wish to reduce the size
178         //  of your final executable, you should remove from the following
179         //  the specific initialization routines you do not need.
180
181         // Revoke the standard OLE Message Filter to avoid drawing frame while loading files.
182         COleMessageFilter* pOldFilter = AfxOleGetMessageFilter();
183         pOldFilter->Revoke();
184
185         // Load registry keys from WinMerge.reg if existing WinMerge.reg
186         env::LoadRegistryFromFile(paths::ConcatPath(env::GetProgPath(), _T("WinMerge.reg")));
187
188         // Parse command-line arguments.
189 #ifdef TEST_WINMERGE
190         MergeCmdLineInfo cmdInfo(_T(""));
191 #else
192         MergeCmdLineInfo cmdInfo(GetCommandLine());
193 #endif
194         if (cmdInfo.m_bNoPrefs)
195                 m_pOptions->SetSerializing(false); // Turn off serializing to registry.
196
197         Options::CopyHKLMValues();
198         Options::Init(m_pOptions.get()); // Implementation in OptionsInit.cpp
199         ApplyCommandLineConfigOptions(cmdInfo);
200         if (cmdInfo.m_sErrorMessages.size() > 0)
201         {
202                 if (AttachConsole(ATTACH_PARENT_PROCESS))
203                 {
204                         DWORD dwWritten;
205                         for (auto& msg : cmdInfo.m_sErrorMessages)
206                         {
207                                 String line = _T("WinMerge: ") + msg + _T("\n");
208                                 WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), line.c_str(), static_cast<DWORD>(line.length()), &dwWritten, nullptr);
209                         }
210                         FreeConsole();
211                 }
212         }
213
214         // Initialize temp folder
215         SetupTempPath();
216
217         // If paths were given to commandline we consider this being an invoke from
218         // commandline (from other application, shellextension etc).
219         bool bCommandLineInvoke = cmdInfo.m_Files.GetSize() > 0;
220
221         // WinMerge registry settings are stored under HKEY_CURRENT_USER/Software/Thingamahoochie
222         // This is the name of the company of the original author (Dean Grimm)
223         SetRegistryKey(_T("Thingamahoochie"));
224
225         bool bSingleInstance = GetOptionsMgr()->GetBool(OPT_SINGLE_INSTANCE) ||
226                 (true == cmdInfo.m_bSingleInstance);
227
228         // Create exclusion mutex name
229         TCHAR szDesktopName[MAX_PATH] = _T("Win9xDesktop");
230         DWORD dwLengthNeeded;
231         GetUserObjectInformation(GetThreadDesktop(GetCurrentThreadId()), UOI_NAME, 
232                 szDesktopName, sizeof(szDesktopName), &dwLengthNeeded);
233         TCHAR szMutexName[MAX_PATH + 40];
234         // Combine window class name and desktop name to form a unique mutex name.
235         // As the window class name is decorated to distinguish between ANSI and
236         // UNICODE build, so will be the mutex name.
237         wsprintf(szMutexName, _T("%s-%s"), CMainFrame::szClassName, szDesktopName);
238         HANDLE hMutex = CreateMutex(nullptr, FALSE, szMutexName);
239         if (hMutex != nullptr)
240                 WaitForSingleObject(hMutex, INFINITE);
241         if (bSingleInstance && GetLastError() == ERROR_ALREADY_EXISTS)
242         {
243                 // Activate previous instance and send commandline to it
244                 HWND hWnd = FindWindow(CMainFrame::szClassName, nullptr);
245                 if (hWnd != nullptr)
246                 {
247                         if (IsIconic(hWnd))
248                                 ShowWindow(hWnd, SW_RESTORE);
249                         SetForegroundWindow(GetLastActivePopup(hWnd));
250                         LPTSTR cmdLine = GetCommandLine();
251                         COPYDATASTRUCT data = { 0, (lstrlen(cmdLine) + 1) * sizeof(TCHAR), cmdLine};
252                         if (::SendMessage(hWnd, WM_COPYDATA, NULL, (LPARAM)&data))
253                         {
254                                 ReleaseMutex(hMutex);
255                                 CloseHandle(hMutex);
256                                 return FALSE;
257                         }
258                 }
259         }
260
261         LoadStdProfileSettings(GetOptionsMgr()->GetInt(OPT_MRU_MAX));  // Load standard INI file options (including MRU)
262
263         InitializeFileFilters();
264
265         // Read last used filter from registry
266         // If filter fails to set, reset to default
267         const String filterString = m_pOptions->GetString(OPT_FILEFILTER_CURRENT);
268         bool bFilterSet = m_pGlobalFileFilter->SetFilter(filterString);
269         if (!bFilterSet)
270         {
271                 String filter = m_pGlobalFileFilter->GetFilterNameOrMask();
272                 m_pOptions->SaveOption(OPT_FILEFILTER_CURRENT, filter);
273         }
274
275         charsets_init();
276         UpdateCodepageModule();
277
278         FileTransform::g_UnpackerMode = static_cast<PLUGIN_MODE>(GetOptionsMgr()->GetInt(OPT_PLUGINS_UNPACKER_MODE));
279         FileTransform::g_PredifferMode = static_cast<PLUGIN_MODE>(GetOptionsMgr()->GetInt(OPT_PLUGINS_PREDIFFER_MODE));
280
281         NONCLIENTMETRICS ncm = { sizeof NONCLIENTMETRICS };
282         if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof NONCLIENTMETRICS, &ncm, 0))
283         {
284                 const int lfHeight = -MulDiv(9, CClientDC(CWnd::GetDesktopWindow()).GetDeviceCaps(LOGPIXELSY), 72);
285                 if (abs(ncm.lfMenuFont.lfHeight) > abs(lfHeight))
286                         ncm.lfMenuFont.lfHeight = lfHeight;
287                 if (wcscmp(ncm.lfMenuFont.lfFaceName, L"Meiryo") == 0 || wcscmp(ncm.lfMenuFont.lfFaceName, L"\U000030e1\U000030a4\U000030ea\U000030aa"/* "Meiryo" in Japanese */) == 0)
288                         wcscpy_s(ncm.lfMenuFont.lfFaceName, L"Meiryo UI");
289                 m_fontGUI.CreateFontIndirect(&ncm.lfMenuFont);
290         }
291
292         if (m_pSyntaxColors != nullptr)
293                 Options::SyntaxColors::Init(GetOptionsMgr(), m_pSyntaxColors.get());
294
295         if (m_pMarkers != nullptr)
296                 m_pMarkers->LoadFromRegistry();
297
298         CCrystalTextView::SetRenderingModeDefault(static_cast<CCrystalTextView::RENDERING_MODE>(GetOptionsMgr()->GetInt(OPT_RENDERING_MODE)));
299
300         if (m_pLineFilters != nullptr)
301                 m_pLineFilters->Initialize(GetOptionsMgr());
302
303         // If there are no filters loaded, and there is filter string in previous
304         // option string, import old filters to new place.
305         if (m_pLineFilters->GetCount() == 0)
306         {
307                 String oldFilter = theApp.GetProfileString(_T("Settings"), _T("RegExps"));
308                 if (!oldFilter.empty())
309                         m_pLineFilters->Import(oldFilter);
310         }
311
312         // Check if filter folder is set, and create it if not
313         String pathMyFolders = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
314         if (pathMyFolders.empty())
315         {
316                 // No filter path, set it to default and make sure it exists.
317                 pathMyFolders = GetOptionsMgr()->GetDefault<String>(OPT_FILTER_USERPATH);
318                 GetOptionsMgr()->SaveOption(OPT_FILTER_USERPATH, pathMyFolders);
319                 theApp.m_pGlobalFileFilter->SetUserFilterPath(pathMyFolders);
320         }
321         if (!paths::CreateIfNeeded(pathMyFolders))
322         {
323                 // Failed to create a folder, check it didn't already
324                 // exist.
325                 DWORD errCode = GetLastError();
326                 if (errCode != ERROR_ALREADY_EXISTS)
327                 {
328                         // Failed to create a folder for filters, fallback to
329                         // "My Documents"-folder. It is not worth the trouble to
330                         // bother user about this or user more clever solutions.
331                         GetOptionsMgr()->SaveOption(OPT_FILTER_USERPATH, env::GetMyDocuments());
332                 }
333         }
334
335         strdiff::Init(); // String diff init
336         strdiff::SetBreakChars(GetOptionsMgr()->GetString(OPT_BREAK_SEPARATORS).c_str());
337
338         m_bMergingMode = GetOptionsMgr()->GetBool(OPT_MERGE_MODE);
339
340         // Initialize i18n (multiple language) support
341
342         m_pLangDlg->InitializeLanguage((WORD)GetOptionsMgr()->GetInt(OPT_SELECTED_LANGUAGE));
343
344         m_mainThreadScripts = new CAssureScriptsForThread;
345
346         // Register the application's document templates.  Document templates
347         //  serve as the connection between documents, frame windows and views.
348
349         // Open view
350         m_pOpenTemplate = new CMultiDocTemplate(
351                 IDR_MAINFRAME,
352                 RUNTIME_CLASS(COpenDoc),
353                 RUNTIME_CLASS(COpenFrame), // custom MDI child frame
354                 RUNTIME_CLASS(COpenView));
355         AddDocTemplate(m_pOpenTemplate);
356
357         // Merge Edit view
358         m_pDiffTemplate = new CMultiDocTemplate(
359                 IDR_MERGEDOCTYPE,
360                 RUNTIME_CLASS(CMergeDoc),
361                 RUNTIME_CLASS(CMergeEditFrame), // custom MDI child frame
362                 RUNTIME_CLASS(CMergeEditSplitterView));
363         AddDocTemplate(m_pDiffTemplate);
364
365         // Merge Edit view
366         m_pHexMergeTemplate = new CMultiDocTemplate(
367                 IDR_MERGEDOCTYPE,
368                 RUNTIME_CLASS(CHexMergeDoc),
369                 RUNTIME_CLASS(CHexMergeFrame), // custom MDI child frame
370                 RUNTIME_CLASS(CHexMergeView));
371         AddDocTemplate(m_pHexMergeTemplate);
372
373         // Directory view
374         m_pDirTemplate = new CMultiDocTemplate(
375                 IDR_DIRDOCTYPE,
376                 RUNTIME_CLASS(CDirDoc),
377                 RUNTIME_CLASS(CDirFrame), // custom MDI child frame
378                 RUNTIME_CLASS(CDirView));
379         AddDocTemplate(m_pDirTemplate);
380
381         // create main MDI Frame window
382         CMainFrame* pMainFrame = new CMainFrame;
383         if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
384         {
385                 if (hMutex != nullptr)
386                 {
387                         ReleaseMutex(hMutex);
388                         CloseHandle(hMutex);
389                 }
390                 return FALSE;
391         }
392         m_pMainWnd = pMainFrame;
393
394         // Init menus -- hMenuDefault is for MainFrame
395         pMainFrame->m_hMenuDefault = pMainFrame->NewDefaultMenu();
396
397         // Set the menu
398         // Note : for Windows98 compatibility, use FromHandle and not Attach/Detach
399         CMenu * pNewMenu = CMenu::FromHandle(pMainFrame->m_hMenuDefault);
400         pMainFrame->MDISetMenu(pNewMenu, nullptr);
401
402         // The main window has been initialized, so activate it.
403         pMainFrame->ActivateFrame(cmdInfo.m_nCmdShow);
404
405         // Since this function actually opens paths for compare it must be
406         // called after initializing CMainFrame!
407         bool bContinue = true;
408         if (!ParseArgsAndDoOpen(cmdInfo, pMainFrame) && bCommandLineInvoke)
409                 bContinue = false;
410
411         if (hMutex != nullptr)
412                 ReleaseMutex(hMutex);
413
414         // If user wants to cancel the compare, close WinMerge
415         if (!bContinue)
416         {
417                 pMainFrame->PostMessage(WM_CLOSE, 0, 0);
418         }
419
420 #ifdef TEST_WINMERGE
421         WinMergeTest::TestAll();
422 #endif
423
424         return bContinue;
425 }
426
427 static void OpenContributersFile(int&)
428 {
429         theApp.OpenFileToExternalEditor(paths::ConcatPath(env::GetProgPath(), ContributorsPath));
430 }
431
432 // App command to run the dialog
433 void CMergeApp::OnAppAbout()
434 {
435         CAboutDlg aboutDlg;
436         aboutDlg.m_onclick_contributers += Poco::delegate(OpenContributersFile);
437         aboutDlg.DoModal();
438         aboutDlg.m_onclick_contributers.clear();
439 }
440
441 /////////////////////////////////////////////////////////////////////////////
442 // CMergeApp commands
443
444 /**
445  * @brief Called when application is about to exit.
446  * This functions is called when application is exiting, so this is
447  * good place to do cleanups.
448  * @return Application's exit value (returned from WinMain()).
449  */
450 int CMergeApp::ExitInstance() 
451 {
452         charsets_cleanup();
453
454         //  Save registry keys if existing WinMerge.reg
455         env::SaveRegistryToFile(paths::ConcatPath(env::GetProgPath(), _T("WinMerge.reg")), RegDir);
456
457         // Remove tempfolder
458         const String temp = env::GetTemporaryPath();
459         ClearTempfolder(temp);
460
461         // Cleanup left over tempfiles from previous instances.
462         // Normally this should not neet to do anything - but if for some reason
463         // WinMerge did not delete temp files this makes sure they are removed.
464         CleanupWMtemp();
465
466         delete m_mainThreadScripts;
467         CWinApp::ExitInstance();
468         return 0;
469 }
470
471 int CMergeApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt)
472 {
473         // This is a convenient point for breakpointing !!!
474
475         // Create a handle to store the parent window of the message box.
476         CWnd* pParentWnd = CWnd::GetActiveWindow();
477
478         // Check whether an active window was retrieved successfully.
479         if (pParentWnd == nullptr)
480         {
481                 // Try to retrieve a handle to the last active popup.
482                 CWnd * mainwnd = GetMainWnd();
483                 if (mainwnd != nullptr)
484                         pParentWnd = mainwnd->GetLastActivePopup();
485         }
486
487         // Use our own message box implementation, which adds the
488         // do not show again checkbox, and implements it on subsequent calls
489         // (if caller set the style)
490
491         if (m_bNonInteractive)
492         {
493                 if (AttachConsole(ATTACH_PARENT_PROCESS))
494                 {
495                         DWORD dwWritten;
496                         String line = _T("WinMerge: ") + String(lpszPrompt) + _T("\n");
497                         WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), line.c_str(), static_cast<DWORD>(line.length()), &dwWritten, nullptr);
498                         FreeConsole();
499                 }
500                 return IDCANCEL;
501         }
502
503         // Create the message box dialog.
504         CMessageBoxDialog dlgMessage(pParentWnd, lpszPrompt, _T(""), nType | MB_RIGHT_ALIGN,
505                 nIDPrompt);
506         
507         if (m_pMainWnd->IsIconic())
508                 m_pMainWnd->ShowWindow(SW_RESTORE);
509
510         // Display the message box dialog and return the result.
511         return static_cast<int>(dlgMessage.DoModal());
512 }
513
514 bool CMergeApp::IsReallyIdle() const
515 {
516         bool idle = true;
517         POSITION pos = m_pDirTemplate->GetFirstDocPosition();
518         while (pos != nullptr)
519         {
520                 CDirDoc *pDirDoc = static_cast<CDirDoc *>(m_pDirTemplate->GetNextDoc(pos));
521                 if (const CompareStats *pCompareStats = pDirDoc->GetCompareStats())
522                 {
523                         if (!pCompareStats->IsCompareDone() || pDirDoc->GetGeneratingReport())
524                                 idle = false;
525                 }
526         }
527     return idle;
528 }
529
530 BOOL CMergeApp::OnIdle(LONG lCount) 
531 {
532         if (CWinApp::OnIdle(lCount))
533                 return TRUE;
534
535         // If anyone has requested notification when next idle occurs, send it
536         if (m_bNeedIdleTimer)
537         {
538                 m_bNeedIdleTimer = false;
539                 m_pMainWnd->SendMessageToDescendants(WM_TIMER, IDLE_TIMER, lCount, TRUE, FALSE);
540         }
541
542         if (m_bNonInteractive && IsReallyIdle())
543                 m_pMainWnd->PostMessage(WM_CLOSE, 0, 0);
544
545         static_cast<CRegOptionsMgr *>(GetOptionsMgr())->CloseKeys();
546
547         return FALSE;
548 }
549
550 /**
551  * @brief Load any known file filters.
552  *
553  * This function loads filter files from paths we know contain them.
554  * @note User's filter location may not be set yet.
555  */
556 void CMergeApp::InitializeFileFilters()
557 {
558         String filterPath = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
559
560         if (!filterPath.empty())
561         {
562                 m_pGlobalFileFilter->SetUserFilterPath(filterPath);
563         }
564         m_pGlobalFileFilter->LoadAllFileFilters();
565 }
566
567 void CMergeApp::ApplyCommandLineConfigOptions(MergeCmdLineInfo& cmdInfo)
568 {
569         if (cmdInfo.m_bNoPrefs)
570                 m_pOptions->SetSerializing(false); // Turn off serializing to registry.
571
572         for (const auto& it : cmdInfo.m_Options)
573         {
574                 if (m_pOptions->Set(it.first, it.second) == COption::OPT_NOTFOUND)
575                 {
576                         String longname = m_pOptions->ExpandShortName(it.first);
577                         if (!longname.empty())
578                         {
579                                 m_pOptions->Set(longname, it.second);
580                         }
581                         else
582                         {
583                                 cmdInfo.m_sErrorMessages.push_back(strutils::format_string1(_T("Invalid key '%1' specified in /config option"), it.first));
584                         }
585                 }
586         }
587 }
588
589 /** @brief Read command line arguments and open files for comparison.
590  *
591  * The name of the function is a legacy code from the time that this function
592  * actually parsed the command line. Today the parsing is done using the
593  * MergeCmdLineInfo class.
594  * @param [in] cmdInfo Commandline parameters info.
595  * @param [in] pMainFrame Pointer to application main frame.
596  * @return `true` if we opened the compare, `false` if the compare was canceled.
597  */
598 bool CMergeApp::ParseArgsAndDoOpen(MergeCmdLineInfo& cmdInfo, CMainFrame* pMainFrame)
599 {
600         bool bCompared = false;
601         String strDesc[3];
602         std::unique_ptr<PackingInfo> infoUnpacker;
603
604         m_bNonInteractive = cmdInfo.m_bNonInteractive;
605
606         if (!cmdInfo.m_sUnpacker.empty())
607         {
608                 infoUnpacker.reset(new PackingInfo(PLUGIN_MODE::PLUGIN_MANUAL));
609                 infoUnpacker->m_PluginName = cmdInfo.m_sUnpacker;
610         }
611
612         // Set the global file filter.
613         if (!cmdInfo.m_sFileFilter.empty())
614         {
615                 m_pGlobalFileFilter->SetFilter(cmdInfo.m_sFileFilter);
616         }
617
618         // Set codepage.
619         if (cmdInfo.m_nCodepage)
620         {
621                 UpdateDefaultCodepage(2,cmdInfo.m_nCodepage);
622         }
623
624         // Unless the user has requested to see WinMerge's usage open files for
625         // comparison.
626         if (cmdInfo.m_bShowUsage)
627         {
628                 ShowHelp(CommandLineHelpLocation);
629         }
630         else
631         {
632                 // Set the required information we need from the command line:
633
634                 m_bExitIfNoDiff = cmdInfo.m_bExitIfNoDiff;
635                 m_bEscShutdown = cmdInfo.m_bEscShutdown;
636
637                 m_strSaveAsPath = cmdInfo.m_sOutputpath;
638
639                 strDesc[0] = cmdInfo.m_sLeftDesc;
640                 if (cmdInfo.m_Files.GetSize() < 3)
641                 {
642                         strDesc[1] = cmdInfo.m_sRightDesc;
643                 }
644                 else
645                 {
646                         strDesc[1] = cmdInfo.m_sMiddleDesc;
647                         strDesc[2] = cmdInfo.m_sRightDesc;
648                 }
649
650                 if (cmdInfo.m_Files.GetSize() > 2)
651                 {
652                         cmdInfo.m_dwLeftFlags |= FFILEOPEN_CMDLINE;
653                         cmdInfo.m_dwMiddleFlags |= FFILEOPEN_CMDLINE;
654                         cmdInfo.m_dwRightFlags |= FFILEOPEN_CMDLINE;
655                         DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwMiddleFlags, cmdInfo.m_dwRightFlags};
656                         bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
657                                 dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr,
658                                 cmdInfo.m_sPreDiffer, infoUnpacker.get());
659                 }
660                 else if (cmdInfo.m_Files.GetSize() > 1)
661                 {
662                         DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
663                         bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
664                                 dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr,
665                                 cmdInfo.m_sPreDiffer, infoUnpacker.get());
666                 }
667                 else if (cmdInfo.m_Files.GetSize() == 1)
668                 {
669                         String sFilepath = cmdInfo.m_Files[0];
670                         if (IsProjectFile(sFilepath))
671                         {
672                                 bCompared = LoadAndOpenProjectFile(sFilepath);
673                         }
674                         else if (IsConflictFile(sFilepath))
675                         {
676                                 //For a conflict file, load the descriptions in their respective positions:  (they will be reordered as needed)
677                                 strDesc[0] = cmdInfo.m_sLeftDesc;
678                                 strDesc[1] = cmdInfo.m_sMiddleDesc;
679                                 strDesc[2] = cmdInfo.m_sRightDesc;
680                                 bCompared = pMainFrame->DoOpenConflict(sFilepath, strDesc);
681                         }
682                         else
683                         {
684                                 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
685                                 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
686                                         dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr, 
687                                         cmdInfo.m_sPreDiffer, infoUnpacker.get());
688                         }
689                 }
690                 else if (cmdInfo.m_Files.GetSize() == 0) // if there are no input args, we can check the display file dialog flag
691                 {
692                         bool showFiles = m_pOptions->GetBool(OPT_SHOW_SELECT_FILES_AT_STARTUP);
693                         if (showFiles)
694                                 pMainFrame->DoFileOpen();
695                 }
696         }
697         return bCompared;
698 }
699
700 void CMergeApp::UpdateDefaultCodepage(int cpDefaultMode, int cpCustomCodepage)
701 {
702         int wLangId;
703
704         switch (cpDefaultMode)
705         {
706                 case 0:
707                         ucr::setDefaultCodepage(GetACP());
708                         break;
709                 case 1:
710                         TCHAR buff[32];
711                         wLangId = GetLangId();
712                         if (GetLocaleInfo(wLangId, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof(buff)/sizeof(buff[0])))
713                                 ucr::setDefaultCodepage(_ttol(buff));
714                         else
715                                 ucr::setDefaultCodepage(GetACP());
716                         break;
717                 case 2:
718                         ucr::setDefaultCodepage(cpCustomCodepage);
719                         break;
720                 default:
721                         // no other valid option
722                         assert (false);
723                         ucr::setDefaultCodepage(GetACP());
724         }
725 }
726
727 /**
728  * @brief Send current option settings into codepage module
729  */
730 void CMergeApp::UpdateCodepageModule()
731 {
732         // Get current codepage settings from the options module
733         // and push them into the codepage module
734         UpdateDefaultCodepage(GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_MODE), GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_CUSTOM));
735 }
736
737 /** @brief Open help from mainframe when user presses F1*/
738 void CMergeApp::OnHelp()
739 {
740         ShowHelp();
741 }
742
743 /**
744  * @brief Open given file to external editor specified in options.
745  * @param [in] file Full path to file to open.
746  *
747  * Opens file to defined (in Options/system), Notepad by default,
748  * external editor. Path is decorated with quotation marks if needed
749  * (contains spaces). Also '$file' in editor path is replaced by
750  * filename to open.
751  * @param [in] file Full path to file to open.
752  * @param [in] nLineNumber Line number to go to.
753  */
754 void CMergeApp::OpenFileToExternalEditor(const String& file, int nLineNumber/* = 1*/)
755 {
756         String sCmd = GetOptionsMgr()->GetString(OPT_EXT_EDITOR_CMD);
757         String sFile(file);
758         strutils::replace(sCmd, _T("$linenum"), strutils::to_str(nLineNumber));
759
760         size_t nIndex = sCmd.find(_T("$file"));
761         if (nIndex != String::npos)
762         {
763                 sFile.insert(0, _T("\""));
764                 strutils::replace(sCmd, _T("$file"), sFile);
765                 nIndex = sCmd.find(' ', nIndex + sFile.length());
766                 if (nIndex != String::npos)
767                         sCmd.insert(nIndex, _T("\""));
768                 else
769                         sCmd += '"';
770         }
771         else
772         {
773                 sCmd += _T(" \"");
774                 sCmd += sFile;
775                 sCmd += _T("\"");
776         }
777
778         bool retVal = false;
779         STARTUPINFO stInfo = { sizeof STARTUPINFO };
780         PROCESS_INFORMATION processInfo;
781
782         retVal = !!CreateProcess(nullptr, (LPTSTR)sCmd.c_str(),
783                 nullptr, nullptr, FALSE, CREATE_DEFAULT_ERROR_MODE, nullptr, nullptr,
784                 &stInfo, &processInfo);
785
786         if (!retVal)
787         {
788                 // Error invoking external editor
789                 String msg = strutils::format_string1(_("Failed to execute external editor: %1"), sCmd);
790                 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
791         }
792         else
793         {
794                 CloseHandle(processInfo.hThread);
795                 CloseHandle(processInfo.hProcess);
796         }
797 }
798
799 /**
800  * @brief Open file, if it exists, else open url
801  */
802 void CMergeApp::OpenFileOrUrl(LPCTSTR szFile, LPCTSTR szUrl)
803 {
804         if (paths::DoesPathExist(szFile) == paths::IS_EXISTING_FILE)
805                 ShellExecute(nullptr, _T("open"), _T("notepad.exe"), szFile, nullptr, SW_SHOWNORMAL);
806         else
807                 ShellExecute(nullptr, _T("open"), szUrl, nullptr, nullptr, SW_SHOWNORMAL);
808 }
809
810 /**
811  * @brief Show Help - this is for opening help from outside mainframe.
812  * @param [in] helpLocation Location inside help, if `nullptr` main help is opened.
813  */
814 void CMergeApp::ShowHelp(LPCTSTR helpLocation /*= nullptr*/)
815 {
816         String name, ext;
817         LANGID LangId = GetLangId();
818         paths::SplitFilename(m_pLangDlg->GetFileName(LangId), nullptr, &name, &ext);
819         String sPath = paths::ConcatPath(env::GetProgPath(), strutils::format(DocsPath, name.c_str()));
820         if (paths::DoesPathExist(sPath) != paths::IS_EXISTING_FILE)
821                 sPath = paths::ConcatPath(env::GetProgPath(), strutils::format(DocsPath, _T("")));
822         if (helpLocation == nullptr)
823         {
824                 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
825                         ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOC, NULL);
826                 else
827                         ShellExecute(nullptr, _T("open"), DocsURL, nullptr, nullptr, SW_SHOWNORMAL);
828         }
829         else
830         {
831                 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
832                 {
833                         sPath += helpLocation;
834                         ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOPIC, NULL);
835                 }
836         }
837 }
838
839 /**
840  * @brief Creates backup before file is saved or copied over.
841  * This function handles formatting correct path and filename for
842  * backup file. Formatting is done based on several options available
843  * for users in Options/Backups dialog. After path is formatted, file
844  * is simply just copied. Not much error checking, just if copying
845  * succeeded or failed.
846  * @param [in] bFolder Are we creating backup in folder compare?
847  * @param [in] pszPath Full path to file to backup.
848  * @return `true` if backup succeeds, or isn't just done.
849  */
850 bool CMergeApp::CreateBackup(bool bFolder, const String& pszPath)
851 {
852         // If user doesn't want to backups in folder compare, return
853         // success so operations don't abort.
854         if (bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FOLDERCMP)))
855                 return true;
856         // Likewise if user doesn't want backups in file compare
857         else if (!bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FILECMP)))
858                 return true;
859
860         // create backup copy of file if destination file exists
861         if (paths::DoesPathExist(pszPath) == paths::IS_EXISTING_FILE)
862         {
863                 String bakPath;
864                 String path;
865                 String filename;
866                 String ext;
867         
868                 paths::SplitFilename(paths::GetLongPath(pszPath), &path, &filename, &ext);
869
870                 // Determine backup folder
871                 if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
872                         PropBackups::FOLDER_ORIGINAL)
873                 {
874                         // Put backups to same folder than original file
875                         bakPath = path;
876                 }
877                 else if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
878                         PropBackups::FOLDER_GLOBAL)
879                 {
880                         // Put backups to global folder defined in options
881                         bakPath = GetOptionsMgr()->GetString(OPT_BACKUP_GLOBALFOLDER);
882                         if (bakPath.empty())
883                                 bakPath = path;
884                         else
885                                 bakPath = paths::GetLongPath(bakPath);
886                 }
887                 else
888                 {
889                         _RPTF0(_CRT_ERROR, "Unknown backup location!");
890                 }
891
892                 bool success = false;
893                 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_BAK))
894                 {
895                         // Don't add dot if there is no existing extension
896                         if (ext.size() > 0)
897                                 ext += _T(".");
898                         ext += BACKUP_FILE_EXT;
899                 }
900
901                 // Append time to filename if wanted so
902                 // NOTE just adds timestamp at the moment as I couldn't figure out
903                 // nice way to add a real time (invalid chars etc).
904                 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_TIME))
905                 {
906                         struct tm tm;
907                         time_t curtime = 0;
908                         time(&curtime);
909                         ::localtime_s(&tm, &curtime);
910                         CString timestr;
911                         timestr.Format(_T("%04d%02d%02d%02d%02d%02d"), tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
912                         filename += _T("-");
913                         filename += timestr;
914                 }
915
916                 // Append filename and extension (+ optional .bak) to path
917                 if ((bakPath.length() + filename.length() + ext.length())
918                         < MAX_PATH_FULL)
919                 {
920                         success = true;
921                         bakPath = paths::ConcatPath(bakPath, filename);
922                         bakPath += _T(".");
923                         bakPath += ext;
924                 }
925
926                 if (success)
927                 {
928                         success = !!CopyFileW(TFile(pszPath).wpath().c_str(), TFile(bakPath).wpath().c_str(), FALSE);
929                 }
930                 
931                 if (!success)
932                 {
933                         String msg = strutils::format_string1(
934                                 _("Unable to backup original file:\n%1\n\nContinue anyway?"),
935                                 pszPath);
936                         if (AfxMessageBox(msg.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN) != IDYES)
937                                 return false;
938                 }
939                 return true;
940         }
941
942         // we got here because we're either not backing up of there was nothing to backup
943         return true;
944 }
945
946 /**
947  * @brief Checks if path (file/folder) is read-only and asks overwriting it.
948  *
949  * @param strSavePath [in,out] Path where to save (file or folder)
950  * @param bMultiFile [in] Single file or multiple files/folder
951  * @param bApplyToAll [in,out] Apply last user selection for all items?
952  * @return Users selection:
953  * - IDOK: Item was not readonly, no actions
954  * - IDYES/IDYESTOALL: Overwrite readonly item
955  * - IDNO: User selected new filename (single file) or user wants to skip
956  * - IDCANCEL: Cancel operation
957  * @sa CMainFrame::SyncFileToVCS()
958  * @sa CMergeDoc::DoSave()
959  */
960 int CMergeApp::HandleReadonlySave(String& strSavePath, bool bMultiFile,
961                 bool &bApplyToAll)
962 {
963         CFileStatus status;
964         int nRetVal = IDOK;
965         bool bFileRO = false;
966         bool bFileExists = false;
967         String s;
968         String str;
969         CString title;
970
971         if (!strSavePath.empty())
972         {
973                 try
974                 {
975                         TFile file(strSavePath);
976                         bFileExists = file.exists();
977                         if (bFileExists)
978                                 bFileRO = !file.canWrite();
979                 }
980                 catch (...)
981                 {
982                 }
983         }
984
985         if (bFileExists && bFileRO)
986         {
987                 UINT userChoice = 0;
988                 
989                 // Don't ask again if its already asked
990                 if (bApplyToAll)
991                         userChoice = IDYES;
992                 else
993                 {
994                         // Prompt for user choice
995                         if (bMultiFile)
996                         {
997                                 // Multiple files or folder
998                                 str = strutils::format_string1(_("%1\nis marked read-only. Would you like to override the read-only item?"), strSavePath);
999                                 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1000                                                 MB_ICONWARNING | MB_DEFBUTTON3 | MB_DONT_ASK_AGAIN |
1001                                                 MB_YES_TO_ALL, IDS_SAVEREADONLY_MULTI);
1002                         }
1003                         else
1004                         {
1005                                 // Single file
1006                                 str = strutils::format_string1(_("%1 is marked read-only. Would you like to override the read-only file ? (No to save as new filename.)"), strSavePath);
1007                                 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1008                                                 MB_ICONWARNING | MB_DEFBUTTON2 | MB_DONT_ASK_AGAIN,
1009                                                 IDS_SAVEREADONLY_FMT);
1010                         }
1011                 }
1012                 switch (userChoice)
1013                 {
1014                 // Overwrite read-only file
1015                 case IDYESTOALL:
1016                         bApplyToAll = true;  // Don't ask again (no break here)
1017                 case IDYES:
1018                         CFile::GetStatus(strSavePath.c_str(), status);
1019                         status.m_mtime = 0;             // Avoid unwanted changes
1020                         status.m_attribute &= ~CFile::readOnly;
1021                         CFile::SetStatus(strSavePath.c_str(), status);
1022                         nRetVal = IDYES;
1023                         break;
1024                 
1025                 // Save to new filename (single) /skip this item (multiple)
1026                 case IDNO:
1027                         if (!bMultiFile)
1028                         {
1029                                 if (SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, false, strSavePath.c_str()))
1030                                 {
1031                                         strSavePath = s;
1032                                         nRetVal = IDNO;
1033                                 }
1034                                 else
1035                                         nRetVal = IDCANCEL;
1036                         }
1037                         else
1038                                 nRetVal = IDNO;
1039                         break;
1040
1041                 // Cancel saving
1042                 case IDCANCEL:
1043                         nRetVal = IDCANCEL;
1044                         break;
1045                 }
1046         }
1047         return nRetVal;
1048 }
1049
1050 /**
1051  * @brief Is specified file a project file?
1052  * @param [in] filepath Full path to file to check.
1053  * @return true if file is a projectfile.
1054  */
1055 bool CMergeApp::IsProjectFile(const String& filepath) const
1056 {
1057         String ext;
1058         paths::SplitFilename(filepath, nullptr, nullptr, &ext);
1059         if (strutils::compare_nocase(ext, ProjectFile::PROJECTFILE_EXT) == 0)
1060                 return true;
1061         else
1062                 return false;
1063 }
1064
1065 bool CMergeApp::LoadProjectFile(const String& sProject, ProjectFile &project)
1066 {
1067         if (sProject.empty())
1068                 return false;
1069
1070         try
1071         {
1072         project.Read(sProject);
1073         }
1074         catch (Poco::Exception& e)
1075         {
1076                 String sErr = _("Unknown error attempting to open project file");
1077                 sErr += ucr::toTString(e.displayText());
1078                 String msg = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1079                 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1080                 return false;
1081         }
1082
1083         return true;
1084 }
1085
1086 bool CMergeApp::SaveProjectFile(const String& sProject, const ProjectFile &project)
1087 {
1088         try
1089         {
1090                 project.Save(sProject);
1091         }
1092         catch (Poco::Exception& e)
1093         {
1094                 String sErr = _("Unknown error attempting to save project file");
1095                 sErr += ucr::toTString(e.displayText());
1096                 String msg = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1097                 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1098                 return false;
1099         }
1100
1101         return true;
1102 }
1103
1104 /** 
1105  * @brief Read project and perform comparison specified
1106  * @param [in] sProject Full path to project file.
1107  * @return `true` if loading project file and starting compare succeeded.
1108  */
1109 bool CMergeApp::LoadAndOpenProjectFile(const String& sProject, const String& sReportFile)
1110 {
1111         ProjectFile project;
1112         if (!LoadProjectFile(sProject, project))
1113                 return false;
1114         
1115         bool rtn = true;
1116         for (auto& projItem : project.Items())
1117         {
1118                 PathContext tFiles;
1119                 bool bRecursive = false;
1120                 projItem.GetPaths(tFiles, bRecursive);
1121                 for (int i = 0; i < tFiles.GetSize(); ++i)
1122                 {
1123                         if (!paths::IsPathAbsolute(tFiles[i]))
1124                         {
1125                                 String sProjectDir = paths::GetParentPath(sProject);
1126                                 if (tFiles[i].substr(0, 1) == _T("\\"))
1127                                 {
1128                                         if (sProjectDir.length() > 1 && sProjectDir[1] == ':')
1129                                                 tFiles[i] = paths::ConcatPath(sProjectDir.substr(0, 2), tFiles[i]);
1130                                 }
1131                                 else
1132                                         tFiles[i] = paths::ConcatPath(sProjectDir, tFiles[i]);
1133                         }
1134                 }
1135                 bool bLeftReadOnly = projItem.GetLeftReadOnly();
1136                 bool bMiddleReadOnly = projItem.GetMiddleReadOnly();
1137                 bool bRightReadOnly = projItem.GetRightReadOnly();
1138                 if (projItem.HasFilter())
1139                 {
1140                         String filter = projItem.GetFilter();
1141                         filter = strutils::trim_ws(filter);
1142                         m_pGlobalFileFilter->SetFilter(filter);
1143                 }
1144                 if (projItem.HasSubfolders())
1145                         bRecursive = projItem.GetSubfolders() > 0;
1146
1147                 DWORD dwFlags[3] = {
1148                         static_cast<DWORD>(tFiles.GetPath(0).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT),
1149                         static_cast<DWORD>(tFiles.GetPath(1).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT),
1150                         static_cast<DWORD>(tFiles.GetPath(2).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT)
1151                 };
1152                 if (bLeftReadOnly)
1153                         dwFlags[0] |= FFILEOPEN_READONLY;
1154                 if (tFiles.GetSize() == 2)
1155                 {
1156                         if (bRightReadOnly)
1157                                 dwFlags[1] |= FFILEOPEN_READONLY;
1158                 }
1159                 else
1160                 {
1161                         if (bMiddleReadOnly)
1162                                 dwFlags[1] |= FFILEOPEN_READONLY;
1163                         if (bRightReadOnly)
1164                                 dwFlags[2] |= FFILEOPEN_READONLY;
1165                 }
1166
1167                 GetOptionsMgr()->SaveOption(OPT_CMP_INCLUDE_SUBDIRS, bRecursive);
1168
1169                 rtn &= GetMainFrame()->DoFileOpen(&tFiles, dwFlags, nullptr, sReportFile, bRecursive);
1170         }
1171
1172         AddToRecentProjectsMRU(sProject.c_str());
1173         return rtn;
1174 }
1175
1176 /**
1177  * @brief Return windows language ID of current WinMerge GUI language
1178  */
1179 WORD CMergeApp::GetLangId() const
1180 {
1181         return m_pLangDlg->GetLangId();
1182 }
1183
1184 /**
1185  * @brief Lang aware version of CStatusBar::SetIndicators()
1186  */
1187 void CMergeApp::SetIndicators(CStatusBar &sb, const UINT *rgid, int n) const
1188 {
1189         m_pLangDlg->SetIndicators(sb, rgid, n);
1190 }
1191
1192 /**
1193  * @brief Translate menu to current WinMerge GUI language
1194  */
1195 void CMergeApp::TranslateMenu(HMENU h) const
1196 {
1197         m_pLangDlg->TranslateMenu(h);
1198 }
1199
1200 /**
1201  * @brief Translate dialog to current WinMerge GUI language
1202  */
1203 void CMergeApp::TranslateDialog(HWND h) const
1204 {
1205         CWnd *pWnd = CWnd::FromHandle(h);
1206         pWnd->SetFont(const_cast<CFont *>(&m_fontGUI));
1207         pWnd->SendMessageToDescendants(WM_SETFONT, (WPARAM)m_fontGUI.m_hObject, MAKELPARAM(FALSE, 0), TRUE);
1208
1209         m_pLangDlg->TranslateDialog(h);
1210 }
1211
1212 /**
1213  * @brief Load string and translate to current WinMerge GUI language
1214  */
1215 String CMergeApp::LoadString(UINT id) const
1216 {
1217         return m_pLangDlg->LoadString(id);
1218 }
1219
1220 bool CMergeApp::TranslateString(const std::string& str, String& translated_str) const
1221 {
1222         return m_pLangDlg->TranslateString(str, translated_str);
1223 }
1224
1225 /**
1226  * @brief Load dialog caption and translate to current WinMerge GUI language
1227  */
1228 std::wstring CMergeApp::LoadDialogCaption(LPCTSTR lpDialogTemplateID) const
1229 {
1230         return m_pLangDlg->LoadDialogCaption(lpDialogTemplateID);
1231 }
1232
1233 /**
1234  * @brief Adds specified file to the recent projects list.
1235  * @param [in] sPathName Path to project file
1236  */
1237 void CMergeApp::AddToRecentProjectsMRU(LPCTSTR sPathName)
1238 {
1239         // sPathName will be added to the top of the MRU list. 
1240         // If sPathName already exists in the MRU list, it will be moved to the top
1241         if (m_pRecentFileList != nullptr)    {
1242                 m_pRecentFileList->Add(sPathName);
1243                 m_pRecentFileList->WriteList();
1244         }
1245 }
1246
1247 void CMergeApp::SetupTempPath()
1248 {
1249         String instTemp = env::GetPerInstanceString(TempFolderPrefix);
1250         if (GetOptionsMgr()->GetBool(OPT_USE_SYSTEM_TEMP_PATH))
1251                 env::SetTemporaryPath(paths::ConcatPath(env::GetSystemTempPath(), instTemp));
1252         else
1253                 env::SetTemporaryPath(paths::ConcatPath(GetOptionsMgr()->GetString(OPT_CUSTOM_TEMP_PATH), instTemp));
1254 }
1255
1256 /**
1257  * @brief Handles menu selection from recent projects list
1258  * @param [in] nID Menu ID of the selected item
1259  */
1260 BOOL CMergeApp::OnOpenRecentFile(UINT nID)
1261 {
1262         return LoadAndOpenProjectFile(static_cast<const TCHAR *>(m_pRecentFileList->m_arrNames[nID-ID_FILE_PROJECT_MRU_FIRST]));
1263 }
1264
1265 /**
1266  * @brief Return if doc is in Merging/Editing mode
1267  */
1268 bool CMergeApp::GetMergingMode() const
1269 {
1270         return m_bMergingMode;
1271 }
1272
1273 /**
1274  * @brief Set doc to Merging/Editing mode
1275  */
1276 void CMergeApp::SetMergingMode(bool bMergingMode)
1277 {
1278         m_bMergingMode = bMergingMode;
1279         GetOptionsMgr()->SaveOption(OPT_MERGE_MODE, m_bMergingMode);
1280 }
1281
1282 /**
1283  * @brief Switch Merging/Editing mode and update
1284  * buffer read-only states accordingly
1285  */
1286 void CMergeApp::OnMergingMode()
1287 {
1288         bool bMergingMode = GetMergingMode();
1289
1290         if (!bMergingMode)
1291                 LangMessageBox(IDS_MERGE_MODE, MB_ICONINFORMATION | MB_DONT_DISPLAY_AGAIN);
1292         SetMergingMode(!bMergingMode);
1293 }
1294
1295 /**
1296  * @brief Update Menuitem for Merging Mode
1297  */
1298 void CMergeApp::OnUpdateMergingMode(CCmdUI* pCmdUI)
1299 {
1300         pCmdUI->Enable(true);
1301         pCmdUI->SetCheck(GetMergingMode());
1302 }
1303
1304 /**
1305  * @brief Update MergingMode UI in statusbar
1306  */
1307 void CMergeApp::OnUpdateMergingStatus(CCmdUI *pCmdUI)
1308 {
1309         String text = theApp.LoadString(IDS_MERGEMODE_MERGING);
1310         pCmdUI->SetText(text.c_str());
1311         pCmdUI->Enable(GetMergingMode());
1312 }
1313
1314 UINT CMergeApp::GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault)
1315 {
1316         COptionsMgr *pOptions = GetOptionsMgr();
1317         String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1318         if (!pOptions->Get(name).IsInt())
1319                 pOptions->InitOption(name, nDefault);
1320         return pOptions->GetInt(name);
1321 }
1322
1323 BOOL CMergeApp::WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue)
1324 {
1325         COptionsMgr *pOptions = GetOptionsMgr();
1326         String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1327         if (!pOptions->Get(name).IsInt())
1328                 pOptions->InitOption(name, nValue);
1329         return pOptions->SaveOption(name, nValue) == COption::OPT_OK;
1330 }
1331
1332 CString CMergeApp::GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault)
1333 {
1334         COptionsMgr *pOptions = GetOptionsMgr();
1335         String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1336         if (!pOptions->Get(name).IsString())
1337                 pOptions->InitOption(name, lpszDefault ? lpszDefault : _T(""));
1338         return pOptions->GetString(name).c_str();
1339 }
1340
1341 BOOL CMergeApp::WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue)
1342 {
1343         COptionsMgr *pOptions = GetOptionsMgr();
1344         if (lpszEntry != nullptr)
1345         {
1346                 String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1347                 if (!pOptions->Get(name).IsString())
1348                         pOptions->InitOption(name, lpszValue ? lpszValue : _T(""));
1349                 return pOptions->SaveOption(name, lpszValue ? lpszValue : _T("")) == COption::OPT_OK;
1350         }
1351         else
1352         {
1353                 String name = strutils::format(_T("%s/"), lpszSection);
1354                 pOptions->RemoveOption(name);
1355         }
1356         return TRUE;
1357 }