1 /////////////////////////////////////////////////////////////////////////////
2 // WinMerge: an interactive diff/merge utility
3 // Copyright (C) 1997-2000 Thingamahoochie Software
5 // SPDX-License-Identifier: GPL-2.0-or-later
6 /////////////////////////////////////////////////////////////////////////////
10 * @brief Defines the class behaviors for the application.
16 #include "Constants.h"
17 #include "UnicodeString.h"
19 #include "Environment.h"
20 #include "OptionsMgr.h"
21 #include "OptionsInit.h"
22 #include "RegOptionsMgr.h"
26 #include "HexMergeDoc.h"
27 #include "HexMergeFrm.h"
28 #include "HexMergeView.h"
31 #include "MergeEditFrm.h"
36 #include "PropBackups.h"
37 #include "FileOrFolderSelect.h"
39 #include "FileFilterHelper.h"
40 #include "LineFiltersList.h"
41 #include "SubstitutionFiltersList.h"
42 #include "SyntaxColors.h"
43 #include "CCrystalTextMarkers.h"
44 #include "OptionsSyntaxColors.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"
53 #include "stringdiffs.h"
56 #include "CompareStats.h"
58 #include "charsets.h" // For shutdown cleanup
64 /** @brief Location for command line help to open. */
65 static const TCHAR CommandLineHelpLocation[] = _T("::/htmlhelp/Command_line.html");
67 /** @brief Backup file extension. */
68 static const TCHAR BACKUP_FILE_EXT[] = _T("bak");
70 /////////////////////////////////////////////////////////////////////////////
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)
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)
90 /////////////////////////////////////////////////////////////////////////////
91 // CMergeApp construction
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_pSubstitutionFiltersList(new SubstitutionFiltersList())
110 , m_pSyntaxColors(new SyntaxColors())
111 , m_pMarkers(new CCrystalTextMarkers())
112 , m_bMergingMode(false)
114 // add construction code here,
115 // Place all significant initialization in InitInstance
118 CMergeApp::~CMergeApp()
122 /////////////////////////////////////////////////////////////////////////////
123 // The one and only CMergeApp object
127 /////////////////////////////////////////////////////////////////////////////
128 // CMergeApp initialization
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..
137 BOOL CMergeApp::InitInstance()
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("");
148 JumpList::SetCurrentProcessExplicitAppUserModelID(L"Thingamahoochie.WinMerge");
150 InitCommonControls(); // initialize common control library
151 CWinApp::InitInstance(); // call parent class method
153 m_imageForInitializingGdiplus.Load((IStream*)nullptr); // initialize GDI+
155 // Runtime switch so programmer may set this in interactive debugger
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 );
170 // CCrystalEdit Drag and Drop functionality needs AfxOleInit.
173 TRACE(_T("AfxOleInitFailed. OLE functionality disabled"));
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.
181 // Revoke the standard OLE Message Filter to avoid drawing frame while loading files.
182 COleMessageFilter* pOldFilter = AfxOleGetMessageFilter();
183 pOldFilter->Revoke();
185 // Load registry keys from WinMerge.reg if existing WinMerge.reg
186 env::LoadRegistryFromFile(paths::ConcatPath(env::GetProgPath(), _T("WinMerge.reg")));
188 // Parse command-line arguments.
190 MergeCmdLineInfo cmdInfo(_T(""));
192 MergeCmdLineInfo cmdInfo(GetCommandLine());
194 if (cmdInfo.m_bNoPrefs)
195 m_pOptions->SetSerializing(false); // Turn off serializing to registry.
197 Options::CopyHKLMValues();
198 Options::Init(m_pOptions.get()); // Implementation in OptionsInit.cpp
199 ApplyCommandLineConfigOptions(cmdInfo);
200 if (cmdInfo.m_sErrorMessages.size() > 0)
202 if (AttachConsole(ATTACH_PARENT_PROCESS))
205 for (auto& msg : cmdInfo.m_sErrorMessages)
207 String line = _T("WinMerge: ") + msg + _T("\n");
208 WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), line.c_str(), static_cast<DWORD>(line.length()), &dwWritten, nullptr);
214 // Initialize temp folder
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;
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"));
225 int nSingleInstance = cmdInfo.m_nSingleInstance.has_value() ?
226 *cmdInfo.m_nSingleInstance : GetOptionsMgr()->GetInt(OPT_SINGLE_INSTANCE);
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 (nSingleInstance != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
243 // Activate previous instance and send commandline to it
244 HWND hWnd = FindWindow(CMainFrame::szClassName, nullptr);
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))
254 ReleaseMutex(hMutex);
256 if (nSingleInstance > 1)
258 DWORD dwProcessId = 0;
259 GetWindowThreadProcessId(hWnd, &dwProcessId);
260 HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, dwProcessId);
262 WaitForSingleObject(hProcess, INFINITE);
269 LoadStdProfileSettings(GetOptionsMgr()->GetInt(OPT_MRU_MAX)); // Load standard INI file options (including MRU)
271 InitializeFileFilters();
273 // Read last used filter from registry
274 // If filter fails to set, reset to default
275 const String filterString = m_pOptions->GetString(OPT_FILEFILTER_CURRENT);
276 bool bFilterSet = m_pGlobalFileFilter->SetFilter(filterString);
279 String filter = m_pGlobalFileFilter->GetFilterNameOrMask();
280 m_pOptions->SaveOption(OPT_FILEFILTER_CURRENT, filter);
284 UpdateCodepageModule();
286 FileTransform::g_UnpackerMode = static_cast<PLUGIN_MODE>(GetOptionsMgr()->GetInt(OPT_PLUGINS_UNPACKER_MODE));
287 FileTransform::g_PredifferMode = static_cast<PLUGIN_MODE>(GetOptionsMgr()->GetInt(OPT_PLUGINS_PREDIFFER_MODE));
289 NONCLIENTMETRICS ncm = { sizeof NONCLIENTMETRICS };
290 if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof NONCLIENTMETRICS, &ncm, 0))
292 const int lfHeight = -MulDiv(9, CClientDC(CWnd::GetDesktopWindow()).GetDeviceCaps(LOGPIXELSY), 72);
293 if (abs(ncm.lfMenuFont.lfHeight) > abs(lfHeight))
294 ncm.lfMenuFont.lfHeight = lfHeight;
295 if (wcscmp(ncm.lfMenuFont.lfFaceName, L"Meiryo") == 0 || wcscmp(ncm.lfMenuFont.lfFaceName, L"\U000030e1\U000030a4\U000030ea\U000030aa"/* "Meiryo" in Japanese */) == 0)
296 wcscpy_s(ncm.lfMenuFont.lfFaceName, L"Meiryo UI");
297 m_fontGUI.CreateFontIndirect(&ncm.lfMenuFont);
300 if (m_pSyntaxColors != nullptr)
301 Options::SyntaxColors::Init(GetOptionsMgr(), m_pSyntaxColors.get());
303 if (m_pMarkers != nullptr)
304 m_pMarkers->LoadFromRegistry();
306 CCrystalTextView::SetRenderingModeDefault(static_cast<CCrystalTextView::RENDERING_MODE>(GetOptionsMgr()->GetInt(OPT_RENDERING_MODE)));
308 if (m_pLineFilters != nullptr)
309 m_pLineFilters->Initialize(GetOptionsMgr());
311 // If there are no filters loaded, and there is filter string in previous
312 // option string, import old filters to new place.
313 if (m_pLineFilters->GetCount() == 0)
315 String oldFilter = theApp.GetProfileString(_T("Settings"), _T("RegExps"));
316 if (!oldFilter.empty())
317 m_pLineFilters->Import(oldFilter);
320 if (m_pSubstitutionFiltersList != nullptr)
321 m_pSubstitutionFiltersList->Initialize(GetOptionsMgr());
323 // Check if filter folder is set, and create it if not
324 String pathMyFolders = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
325 if (pathMyFolders.empty())
327 // No filter path, set it to default and make sure it exists.
328 pathMyFolders = GetOptionsMgr()->GetDefault<String>(OPT_FILTER_USERPATH);
329 GetOptionsMgr()->SaveOption(OPT_FILTER_USERPATH, pathMyFolders);
330 theApp.m_pGlobalFileFilter->SetUserFilterPath(pathMyFolders);
332 if (!paths::CreateIfNeeded(pathMyFolders))
334 // Failed to create a folder, check it didn't already
336 DWORD errCode = GetLastError();
337 if (errCode != ERROR_ALREADY_EXISTS)
339 // Failed to create a folder for filters, fallback to
340 // "My Documents"-folder. It is not worth the trouble to
341 // bother user about this or user more clever solutions.
342 GetOptionsMgr()->SaveOption(OPT_FILTER_USERPATH, env::GetMyDocuments());
346 strdiff::Init(); // String diff init
347 strdiff::SetBreakChars(GetOptionsMgr()->GetString(OPT_BREAK_SEPARATORS).c_str());
349 m_bMergingMode = GetOptionsMgr()->GetBool(OPT_MERGE_MODE);
351 // Initialize i18n (multiple language) support
353 m_pLangDlg->InitializeLanguage((WORD)GetOptionsMgr()->GetInt(OPT_SELECTED_LANGUAGE));
355 m_mainThreadScripts = new CAssureScriptsForThread;
357 // Register the application's document templates. Document templates
358 // serve as the connection between documents, frame windows and views.
361 m_pOpenTemplate = new CMultiDocTemplate(
363 RUNTIME_CLASS(COpenDoc),
364 RUNTIME_CLASS(COpenFrame), // custom MDI child frame
365 RUNTIME_CLASS(COpenView));
366 AddDocTemplate(m_pOpenTemplate);
369 m_pDiffTemplate = new CMultiDocTemplate(
371 RUNTIME_CLASS(CMergeDoc),
372 RUNTIME_CLASS(CMergeEditFrame), // custom MDI child frame
373 RUNTIME_CLASS(CMergeEditSplitterView));
374 AddDocTemplate(m_pDiffTemplate);
377 m_pHexMergeTemplate = new CMultiDocTemplate(
379 RUNTIME_CLASS(CHexMergeDoc),
380 RUNTIME_CLASS(CHexMergeFrame), // custom MDI child frame
381 RUNTIME_CLASS(CHexMergeView));
382 AddDocTemplate(m_pHexMergeTemplate);
385 m_pDirTemplate = new CMultiDocTemplate(
387 RUNTIME_CLASS(CDirDoc),
388 RUNTIME_CLASS(CDirFrame), // custom MDI child frame
389 RUNTIME_CLASS(CDirView));
390 AddDocTemplate(m_pDirTemplate);
392 // create main MDI Frame window
393 CMainFrame* pMainFrame = new CMainFrame;
394 if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
396 if (hMutex != nullptr)
398 ReleaseMutex(hMutex);
403 m_pMainWnd = pMainFrame;
405 // Init menus -- hMenuDefault is for MainFrame
406 pMainFrame->m_hMenuDefault = pMainFrame->NewDefaultMenu();
409 // Note : for Windows98 compatibility, use FromHandle and not Attach/Detach
410 CMenu * pNewMenu = CMenu::FromHandle(pMainFrame->m_hMenuDefault);
411 pMainFrame->MDISetMenu(pNewMenu, nullptr);
413 // The main window has been initialized, so activate it.
414 pMainFrame->ActivateFrame(cmdInfo.m_nCmdShow);
416 // Since this function actually opens paths for compare it must be
417 // called after initializing CMainFrame!
418 bool bContinue = true;
419 if (!ParseArgsAndDoOpen(cmdInfo, pMainFrame) && bCommandLineInvoke)
422 if (hMutex != nullptr)
423 ReleaseMutex(hMutex);
425 // If user wants to cancel the compare, close WinMerge
428 pMainFrame->PostMessage(WM_CLOSE, 0, 0);
432 WinMergeTest::TestAll();
438 static void OpenContributersFile(int&)
440 theApp.OpenFileToExternalEditor(paths::ConcatPath(env::GetProgPath(), ContributorsPath));
443 // App command to run the dialog
444 void CMergeApp::OnAppAbout()
447 aboutDlg.m_onclick_contributers += Poco::delegate(OpenContributersFile);
449 aboutDlg.m_onclick_contributers.clear();
452 /////////////////////////////////////////////////////////////////////////////
453 // CMergeApp commands
456 * @brief Called when application is about to exit.
457 * This functions is called when application is exiting, so this is
458 * good place to do cleanups.
459 * @return Application's exit value (returned from WinMain()).
461 int CMergeApp::ExitInstance()
465 // Save registry keys if existing WinMerge.reg
466 env::SaveRegistryToFile(paths::ConcatPath(env::GetProgPath(), _T("WinMerge.reg")), RegDir);
469 const String temp = env::GetTemporaryPath();
470 ClearTempfolder(temp);
472 // Cleanup left over tempfiles from previous instances.
473 // Normally this should not need to do anything - but if for some reason
474 // WinMerge did not delete temp files this makes sure they are removed.
477 delete m_mainThreadScripts;
478 CWinApp::ExitInstance();
482 int CMergeApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt)
484 // This is a convenient point for breakpointing !!!
486 // Create a handle to store the parent window of the message box.
487 CWnd* pParentWnd = CWnd::GetActiveWindow();
489 // Check whether an active window was retrieved successfully.
490 if (pParentWnd == nullptr)
492 // Try to retrieve a handle to the last active popup.
493 CWnd * mainwnd = GetMainWnd();
494 if (mainwnd != nullptr)
495 pParentWnd = mainwnd->GetLastActivePopup();
498 // Use our own message box implementation, which adds the
499 // do not show again checkbox, and implements it on subsequent calls
500 // (if caller set the style)
502 if (m_bNonInteractive)
504 if (AttachConsole(ATTACH_PARENT_PROCESS))
507 String line = _T("WinMerge: ") + String(lpszPrompt) + _T("\n");
508 WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), line.c_str(), static_cast<DWORD>(line.length()), &dwWritten, nullptr);
514 // Create the message box dialog.
515 CMessageBoxDialog dlgMessage(pParentWnd, lpszPrompt, _T(""), nType | MB_RIGHT_ALIGN,
518 if (m_pMainWnd->IsIconic())
519 m_pMainWnd->ShowWindow(SW_RESTORE);
521 // Display the message box dialog and return the result.
522 return static_cast<int>(dlgMessage.DoModal());
525 bool CMergeApp::IsReallyIdle() const
528 POSITION pos = m_pDirTemplate->GetFirstDocPosition();
529 while (pos != nullptr)
531 CDirDoc *pDirDoc = static_cast<CDirDoc *>(m_pDirTemplate->GetNextDoc(pos));
532 if (const CompareStats *pCompareStats = pDirDoc->GetCompareStats())
534 if (!pCompareStats->IsCompareDone() || pDirDoc->GetGeneratingReport())
541 BOOL CMergeApp::OnIdle(LONG lCount)
543 if (CWinApp::OnIdle(lCount))
546 // If anyone has requested notification when next idle occurs, send it
547 if (m_bNeedIdleTimer)
549 m_bNeedIdleTimer = false;
550 m_pMainWnd->SendMessageToDescendants(WM_TIMER, IDLE_TIMER, lCount, TRUE, FALSE);
553 if (m_bNonInteractive && IsReallyIdle())
554 m_pMainWnd->PostMessage(WM_CLOSE, 0, 0);
556 static_cast<CRegOptionsMgr *>(GetOptionsMgr())->CloseKeys();
562 * @brief Load any known file filters.
564 * This function loads filter files from paths we know contain them.
565 * @note User's filter location may not be set yet.
567 void CMergeApp::InitializeFileFilters()
569 String filterPath = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
571 if (!filterPath.empty())
573 m_pGlobalFileFilter->SetUserFilterPath(filterPath);
575 m_pGlobalFileFilter->LoadAllFileFilters();
578 void CMergeApp::ApplyCommandLineConfigOptions(MergeCmdLineInfo& cmdInfo)
580 if (cmdInfo.m_bNoPrefs)
581 m_pOptions->SetSerializing(false); // Turn off serializing to registry.
583 for (const auto& it : cmdInfo.m_Options)
585 if (m_pOptions->Set(it.first, it.second) == COption::OPT_NOTFOUND)
587 String longname = m_pOptions->ExpandShortName(it.first);
588 if (!longname.empty())
590 m_pOptions->Set(longname, it.second);
594 cmdInfo.m_sErrorMessages.push_back(strutils::format_string1(_T("Invalid key '%1' specified in /config option"), it.first));
600 /** @brief Read command line arguments and open files for comparison.
602 * The name of the function is a legacy code from the time that this function
603 * actually parsed the command line. Today the parsing is done using the
604 * MergeCmdLineInfo class.
605 * @param [in] cmdInfo Commandline parameters info.
606 * @param [in] pMainFrame Pointer to application main frame.
607 * @return `true` if we opened the compare, `false` if the compare was canceled.
609 bool CMergeApp::ParseArgsAndDoOpen(MergeCmdLineInfo& cmdInfo, CMainFrame* pMainFrame)
611 bool bCompared = false;
613 std::unique_ptr<PackingInfo> infoUnpacker;
615 m_bNonInteractive = cmdInfo.m_bNonInteractive;
617 if (!cmdInfo.m_sUnpacker.empty())
619 infoUnpacker.reset(new PackingInfo(PLUGIN_MODE::PLUGIN_MANUAL));
620 infoUnpacker->m_PluginName = cmdInfo.m_sUnpacker;
623 // Set the global file filter.
624 if (!cmdInfo.m_sFileFilter.empty())
626 m_pGlobalFileFilter->SetFilter(cmdInfo.m_sFileFilter);
630 if (cmdInfo.m_nCodepage)
632 UpdateDefaultCodepage(2,cmdInfo.m_nCodepage);
635 // Set compare method
636 if (cmdInfo.m_nCompMethod.has_value())
637 GetOptionsMgr()->Set(OPT_CMP_METHOD, *cmdInfo.m_nCompMethod);
639 // Unless the user has requested to see WinMerge's usage open files for
641 if (cmdInfo.m_bShowUsage)
643 ShowHelp(CommandLineHelpLocation);
647 // Set the required information we need from the command line:
649 m_bExitIfNoDiff = cmdInfo.m_bExitIfNoDiff;
650 m_bEscShutdown = cmdInfo.m_bEscShutdown;
652 m_strSaveAsPath = cmdInfo.m_sOutputpath;
654 strDesc[0] = cmdInfo.m_sLeftDesc;
655 if (cmdInfo.m_Files.GetSize() < 3)
657 strDesc[1] = cmdInfo.m_sRightDesc;
661 strDesc[1] = cmdInfo.m_sMiddleDesc;
662 strDesc[2] = cmdInfo.m_sRightDesc;
665 if (cmdInfo.m_Files.GetSize() > 2)
667 cmdInfo.m_dwLeftFlags |= FFILEOPEN_CMDLINE;
668 cmdInfo.m_dwMiddleFlags |= FFILEOPEN_CMDLINE;
669 cmdInfo.m_dwRightFlags |= FFILEOPEN_CMDLINE;
670 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwMiddleFlags, cmdInfo.m_dwRightFlags};
671 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
672 dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr,
673 cmdInfo.m_sPreDiffer, infoUnpacker.get());
675 else if (cmdInfo.m_Files.GetSize() > 1)
677 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
678 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
679 dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr,
680 cmdInfo.m_sPreDiffer, infoUnpacker.get());
682 else if (cmdInfo.m_Files.GetSize() == 1)
684 String sFilepath = cmdInfo.m_Files[0];
685 if (IsProjectFile(sFilepath))
687 bCompared = LoadAndOpenProjectFile(sFilepath);
689 else if (IsConflictFile(sFilepath))
691 //For a conflict file, load the descriptions in their respective positions: (they will be reordered as needed)
692 strDesc[0] = cmdInfo.m_sLeftDesc;
693 strDesc[1] = cmdInfo.m_sMiddleDesc;
694 strDesc[2] = cmdInfo.m_sRightDesc;
695 bCompared = pMainFrame->DoOpenConflict(sFilepath, strDesc);
699 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
700 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
701 dwFlags, strDesc, cmdInfo.m_sReportFile, cmdInfo.m_bRecurse, nullptr,
702 cmdInfo.m_sPreDiffer, infoUnpacker.get());
705 else if (cmdInfo.m_Files.GetSize() == 0) // if there are no input args, we can check the display file dialog flag
707 bool showFiles = m_pOptions->GetBool(OPT_SHOW_SELECT_FILES_AT_STARTUP);
709 pMainFrame->DoFileOpen();
715 void CMergeApp::UpdateDefaultCodepage(int cpDefaultMode, int cpCustomCodepage)
719 switch (cpDefaultMode)
722 ucr::setDefaultCodepage(GetACP());
726 wLangId = GetLangId();
727 if (GetLocaleInfo(wLangId, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof(buff)/sizeof(buff[0])))
728 ucr::setDefaultCodepage(_ttol(buff));
730 ucr::setDefaultCodepage(GetACP());
733 ucr::setDefaultCodepage(cpCustomCodepage);
736 // no other valid option
738 ucr::setDefaultCodepage(GetACP());
743 * @brief Send current option settings into codepage module
745 void CMergeApp::UpdateCodepageModule()
747 // Get current codepage settings from the options module
748 // and push them into the codepage module
749 UpdateDefaultCodepage(GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_MODE), GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_CUSTOM));
752 /** @brief Open help from mainframe when user presses F1*/
753 void CMergeApp::OnHelp()
759 * @brief Open given file to external editor specified in options.
760 * @param [in] file Full path to file to open.
762 * Opens file to defined (in Options/system), Notepad by default,
763 * external editor. Path is decorated with quotation marks if needed
764 * (contains spaces). Also '$file' in editor path is replaced by
766 * @param [in] file Full path to file to open.
767 * @param [in] nLineNumber Line number to go to.
769 void CMergeApp::OpenFileToExternalEditor(const String& file, int nLineNumber/* = 1*/)
771 String sCmd = GetOptionsMgr()->GetString(OPT_EXT_EDITOR_CMD);
773 strutils::replace(sCmd, _T("$linenum"), strutils::to_str(nLineNumber));
775 size_t nIndex = sCmd.find(_T("$file"));
776 if (nIndex != String::npos)
778 sFile.insert(0, _T("\""));
779 strutils::replace(sCmd, _T("$file"), sFile);
780 nIndex = sCmd.find(' ', nIndex + sFile.length());
781 if (nIndex != String::npos)
782 sCmd.insert(nIndex, _T("\""));
794 STARTUPINFO stInfo = { sizeof STARTUPINFO };
795 PROCESS_INFORMATION processInfo;
797 retVal = !!CreateProcess(nullptr, (LPTSTR)sCmd.c_str(),
798 nullptr, nullptr, FALSE, CREATE_DEFAULT_ERROR_MODE, nullptr, nullptr,
799 &stInfo, &processInfo);
803 // Error invoking external editor
804 String msg = strutils::format_string1(_("Failed to execute external editor: %1"), sCmd);
805 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
809 CloseHandle(processInfo.hThread);
810 CloseHandle(processInfo.hProcess);
815 * @brief Open file, if it exists, else open url
817 void CMergeApp::OpenFileOrUrl(LPCTSTR szFile, LPCTSTR szUrl)
819 if (paths::DoesPathExist(szFile) == paths::IS_EXISTING_FILE)
820 ShellExecute(nullptr, _T("open"), _T("notepad.exe"), szFile, nullptr, SW_SHOWNORMAL);
822 ShellExecute(nullptr, _T("open"), szUrl, nullptr, nullptr, SW_SHOWNORMAL);
826 * @brief Show Help - this is for opening help from outside mainframe.
827 * @param [in] helpLocation Location inside help, if `nullptr` main help is opened.
829 void CMergeApp::ShowHelp(LPCTSTR helpLocation /*= nullptr*/)
832 LANGID LangId = GetLangId();
833 paths::SplitFilename(m_pLangDlg->GetFileName(LangId), nullptr, &name, &ext);
834 String sPath = paths::ConcatPath(env::GetProgPath(), strutils::format(DocsPath, name.c_str()));
835 if (paths::DoesPathExist(sPath) != paths::IS_EXISTING_FILE)
836 sPath = paths::ConcatPath(env::GetProgPath(), strutils::format(DocsPath, _T("")));
837 if (helpLocation == nullptr)
839 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
840 ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOC, NULL);
842 ShellExecute(nullptr, _T("open"), DocsURL, nullptr, nullptr, SW_SHOWNORMAL);
846 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
848 sPath += helpLocation;
849 ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOPIC, NULL);
855 * @brief Creates backup before file is saved or copied over.
856 * This function handles formatting correct path and filename for
857 * backup file. Formatting is done based on several options available
858 * for users in Options/Backups dialog. After path is formatted, file
859 * is simply just copied. Not much error checking, just if copying
860 * succeeded or failed.
861 * @param [in] bFolder Are we creating backup in folder compare?
862 * @param [in] pszPath Full path to file to backup.
863 * @return `true` if backup succeeds, or isn't just done.
865 bool CMergeApp::CreateBackup(bool bFolder, const String& pszPath)
867 // If user doesn't want to backups in folder compare, return
868 // success so operations don't abort.
869 if (bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FOLDERCMP)))
871 // Likewise if user doesn't want backups in file compare
872 else if (!bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FILECMP)))
875 // create backup copy of file if destination file exists
876 if (paths::DoesPathExist(pszPath) == paths::IS_EXISTING_FILE)
883 paths::SplitFilename(paths::GetLongPath(pszPath), &path, &filename, &ext);
885 // Determine backup folder
886 if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
887 PropBackups::FOLDER_ORIGINAL)
889 // Put backups to same folder than original file
892 else if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
893 PropBackups::FOLDER_GLOBAL)
895 // Put backups to global folder defined in options
896 bakPath = GetOptionsMgr()->GetString(OPT_BACKUP_GLOBALFOLDER);
900 bakPath = paths::GetLongPath(bakPath);
904 _RPTF0(_CRT_ERROR, "Unknown backup location!");
907 bool success = false;
908 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_BAK))
910 // Don't add dot if there is no existing extension
913 ext += BACKUP_FILE_EXT;
916 // Append time to filename if wanted so
917 // NOTE just adds timestamp at the moment as I couldn't figure out
918 // nice way to add a real time (invalid chars etc).
919 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_TIME))
924 ::localtime_s(&tm, &curtime);
926 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);
931 // Append filename and extension (+ optional .bak) to path
932 if ((bakPath.length() + filename.length() + ext.length())
936 bakPath = paths::ConcatPath(bakPath, filename);
943 success = !!CopyFileW(TFile(pszPath).wpath().c_str(), TFile(bakPath).wpath().c_str(), FALSE);
948 String msg = strutils::format_string1(
949 _("Unable to backup original file:\n%1\n\nContinue anyway?"),
951 if (AfxMessageBox(msg.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN) != IDYES)
957 // we got here because we're either not backing up of there was nothing to backup
962 * @brief Checks if path (file/folder) is read-only and asks overwriting it.
964 * @param strSavePath [in,out] Path where to save (file or folder)
965 * @param bMultiFile [in] Single file or multiple files/folder
966 * @param bApplyToAll [in,out] Apply last user selection for all items?
967 * @return Users selection:
968 * - IDOK: Item was not readonly, no actions
969 * - IDYES/IDYESTOALL: Overwrite readonly item
970 * - IDNO: User selected new filename (single file) or user wants to skip
971 * - IDCANCEL: Cancel operation
972 * @sa CMainFrame::SyncFileToVCS()
973 * @sa CMergeDoc::DoSave()
975 int CMergeApp::HandleReadonlySave(String& strSavePath, bool bMultiFile,
980 bool bFileRO = false;
981 bool bFileExists = false;
986 if (!strSavePath.empty())
990 TFile file(strSavePath);
991 bFileExists = file.exists();
993 bFileRO = !file.canWrite();
1000 if (bFileExists && bFileRO)
1002 UINT userChoice = 0;
1004 // Don't ask again if its already asked
1009 // Prompt for user choice
1012 // Multiple files or folder
1013 str = strutils::format_string1(_("%1\nis marked read-only. Would you like to override the read-only item?"), strSavePath);
1014 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1015 MB_ICONWARNING | MB_DEFBUTTON3 | MB_DONT_ASK_AGAIN |
1016 MB_YES_TO_ALL, IDS_SAVEREADONLY_MULTI);
1021 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);
1022 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1023 MB_ICONWARNING | MB_DEFBUTTON2 | MB_DONT_ASK_AGAIN,
1024 IDS_SAVEREADONLY_FMT);
1029 // Overwrite read-only file
1031 bApplyToAll = true; // Don't ask again (no break here)
1033 CFile::GetStatus(strSavePath.c_str(), status);
1034 status.m_mtime = 0; // Avoid unwanted changes
1035 status.m_attribute &= ~CFile::readOnly;
1036 CFile::SetStatus(strSavePath.c_str(), status);
1040 // Save to new filename (single) /skip this item (multiple)
1044 if (SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, false, strSavePath.c_str()))
1066 * @brief Is specified file a project file?
1067 * @param [in] filepath Full path to file to check.
1068 * @return true if file is a projectfile.
1070 bool CMergeApp::IsProjectFile(const String& filepath) const
1073 paths::SplitFilename(filepath, nullptr, nullptr, &ext);
1074 if (strutils::compare_nocase(ext, ProjectFile::PROJECTFILE_EXT) == 0)
1080 bool CMergeApp::LoadProjectFile(const String& sProject, ProjectFile &project)
1082 if (sProject.empty())
1087 project.Read(sProject);
1089 catch (Poco::Exception& e)
1091 String sErr = _("Unknown error attempting to open project file.");
1092 sErr += ucr::toTString(e.displayText());
1093 String msg = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1094 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1101 bool CMergeApp::SaveProjectFile(const String& sProject, const ProjectFile &project)
1105 project.Save(sProject);
1107 catch (Poco::Exception& e)
1109 String sErr = _("Unknown error attempting to save project file.");
1110 sErr += ucr::toTString(e.displayText());
1111 String msg = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1112 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1120 * @brief Read project and perform comparison specified
1121 * @param [in] sProject Full path to project file.
1122 * @return `true` if loading project file and starting compare succeeded.
1124 bool CMergeApp::LoadAndOpenProjectFile(const String& sProject, const String& sReportFile)
1126 ProjectFile project;
1127 if (!LoadProjectFile(sProject, project))
1131 for (auto& projItem : project.Items())
1134 bool bRecursive = false;
1135 projItem.GetPaths(tFiles, bRecursive);
1136 for (int i = 0; i < tFiles.GetSize(); ++i)
1138 if (!paths::IsPathAbsolute(tFiles[i]))
1140 String sProjectDir = paths::GetParentPath(sProject);
1141 if (tFiles[i].substr(0, 1) == _T("\\"))
1143 if (sProjectDir.length() > 1 && sProjectDir[1] == ':')
1144 tFiles[i] = paths::ConcatPath(sProjectDir.substr(0, 2), tFiles[i]);
1147 tFiles[i] = paths::ConcatPath(sProjectDir, tFiles[i]);
1150 bool bLeftReadOnly = projItem.GetLeftReadOnly();
1151 bool bMiddleReadOnly = projItem.GetMiddleReadOnly();
1152 bool bRightReadOnly = projItem.GetRightReadOnly();
1153 if (projItem.HasFilter())
1155 String filter = projItem.GetFilter();
1156 filter = strutils::trim_ws(filter);
1157 m_pGlobalFileFilter->SetFilter(filter);
1159 if (projItem.HasSubfolders())
1160 bRecursive = projItem.GetSubfolders() > 0;
1162 DWORD dwFlags[3] = {
1163 static_cast<DWORD>(tFiles.GetPath(0).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT),
1164 static_cast<DWORD>(tFiles.GetPath(1).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT),
1165 static_cast<DWORD>(tFiles.GetPath(2).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT)
1168 dwFlags[0] |= FFILEOPEN_READONLY;
1169 if (tFiles.GetSize() == 2)
1172 dwFlags[1] |= FFILEOPEN_READONLY;
1176 if (bMiddleReadOnly)
1177 dwFlags[1] |= FFILEOPEN_READONLY;
1179 dwFlags[2] |= FFILEOPEN_READONLY;
1182 GetOptionsMgr()->SaveOption(OPT_CMP_INCLUDE_SUBDIRS, bRecursive);
1184 rtn &= GetMainFrame()->DoFileOpen(&tFiles, dwFlags, nullptr, sReportFile, bRecursive);
1187 AddToRecentProjectsMRU(sProject.c_str());
1192 * @brief Return windows language ID of current WinMerge GUI language
1194 WORD CMergeApp::GetLangId() const
1196 return m_pLangDlg->GetLangId();
1200 * @brief Lang aware version of CStatusBar::SetIndicators()
1202 void CMergeApp::SetIndicators(CStatusBar &sb, const UINT *rgid, int n) const
1204 m_pLangDlg->SetIndicators(sb, rgid, n);
1208 * @brief Translate menu to current WinMerge GUI language
1210 void CMergeApp::TranslateMenu(HMENU h) const
1212 m_pLangDlg->TranslateMenu(h);
1216 * @brief Translate dialog to current WinMerge GUI language
1218 void CMergeApp::TranslateDialog(HWND h) const
1220 CWnd *pWnd = CWnd::FromHandle(h);
1221 pWnd->SetFont(const_cast<CFont *>(&m_fontGUI));
1222 pWnd->SendMessageToDescendants(WM_SETFONT, (WPARAM)m_fontGUI.m_hObject, MAKELPARAM(FALSE, 0), TRUE);
1224 m_pLangDlg->TranslateDialog(h);
1228 * @brief Load string and translate to current WinMerge GUI language
1230 String CMergeApp::LoadString(UINT id) const
1232 return m_pLangDlg->LoadString(id);
1235 bool CMergeApp::TranslateString(const std::string& str, String& translated_str) const
1237 return m_pLangDlg->TranslateString(str, translated_str);
1241 * @brief Load dialog caption and translate to current WinMerge GUI language
1243 std::wstring CMergeApp::LoadDialogCaption(LPCTSTR lpDialogTemplateID) const
1245 return m_pLangDlg->LoadDialogCaption(lpDialogTemplateID);
1249 * @brief Adds specified file to the recent projects list.
1250 * @param [in] sPathName Path to project file
1252 void CMergeApp::AddToRecentProjectsMRU(LPCTSTR sPathName)
1254 // sPathName will be added to the top of the MRU list.
1255 // If sPathName already exists in the MRU list, it will be moved to the top
1256 if (m_pRecentFileList != nullptr) {
1257 m_pRecentFileList->Add(sPathName);
1258 m_pRecentFileList->WriteList();
1262 void CMergeApp::SetupTempPath()
1264 String instTemp = env::GetPerInstanceString(TempFolderPrefix);
1265 if (GetOptionsMgr()->GetBool(OPT_USE_SYSTEM_TEMP_PATH))
1266 env::SetTemporaryPath(paths::ConcatPath(env::GetSystemTempPath(), instTemp));
1268 env::SetTemporaryPath(paths::ConcatPath(GetOptionsMgr()->GetString(OPT_CUSTOM_TEMP_PATH), instTemp));
1272 * @brief Handles menu selection from recent projects list
1273 * @param [in] nID Menu ID of the selected item
1275 BOOL CMergeApp::OnOpenRecentFile(UINT nID)
1277 return LoadAndOpenProjectFile(static_cast<const TCHAR *>(m_pRecentFileList->m_arrNames[nID-ID_FILE_PROJECT_MRU_FIRST]));
1281 * @brief Return if doc is in Merging/Editing mode
1283 bool CMergeApp::GetMergingMode() const
1285 return m_bMergingMode;
1289 * @brief Set doc to Merging/Editing mode
1291 void CMergeApp::SetMergingMode(bool bMergingMode)
1293 m_bMergingMode = bMergingMode;
1294 GetOptionsMgr()->SaveOption(OPT_MERGE_MODE, m_bMergingMode);
1298 * @brief Switch Merging/Editing mode and update
1299 * buffer read-only states accordingly
1301 void CMergeApp::OnMergingMode()
1303 bool bMergingMode = GetMergingMode();
1306 LangMessageBox(IDS_MERGE_MODE, MB_ICONINFORMATION | MB_DONT_DISPLAY_AGAIN);
1307 SetMergingMode(!bMergingMode);
1311 * @brief Update Menuitem for Merging Mode
1313 void CMergeApp::OnUpdateMergingMode(CCmdUI* pCmdUI)
1315 pCmdUI->Enable(true);
1316 pCmdUI->SetCheck(GetMergingMode());
1320 * @brief Update MergingMode UI in statusbar
1322 void CMergeApp::OnUpdateMergingStatus(CCmdUI *pCmdUI)
1324 String text = theApp.LoadString(IDS_MERGEMODE_MERGING);
1325 pCmdUI->SetText(text.c_str());
1326 pCmdUI->Enable(GetMergingMode());
1329 UINT CMergeApp::GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault)
1331 COptionsMgr *pOptions = GetOptionsMgr();
1332 String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1333 if (!pOptions->Get(name).IsInt())
1334 pOptions->InitOption(name, nDefault);
1335 return pOptions->GetInt(name);
1338 BOOL CMergeApp::WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue)
1340 COptionsMgr *pOptions = GetOptionsMgr();
1341 String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1342 if (!pOptions->Get(name).IsInt())
1343 pOptions->InitOption(name, nValue);
1344 return pOptions->SaveOption(name, nValue) == COption::OPT_OK;
1347 CString CMergeApp::GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault)
1349 COptionsMgr *pOptions = GetOptionsMgr();
1350 String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1351 if (!pOptions->Get(name).IsString())
1352 pOptions->InitOption(name, lpszDefault ? lpszDefault : _T(""));
1353 return pOptions->GetString(name).c_str();
1356 BOOL CMergeApp::WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue)
1358 COptionsMgr *pOptions = GetOptionsMgr();
1359 if (lpszEntry != nullptr)
1361 String name = strutils::format(_T("%s/%s"), lpszSection, lpszEntry);
1362 if (!pOptions->Get(name).IsString())
1363 pOptions->InitOption(name, lpszValue ? lpszValue : _T(""));
1364 return pOptions->SaveOption(name, lpszValue ? lpszValue : _T("")) == COption::OPT_OK;
1368 String name = strutils::format(_T("%s/"), lpszSection);
1369 pOptions->RemoveOption(name);