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 "FilterCommentsManager.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_pFilterCommentsManager(new FilterCommentsManager())
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 bool bSingleInstance = GetOptionsMgr()->GetBool(OPT_SINGLE_INSTANCE) ||
226 (true == cmdInfo.m_bSingleInstance);
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)
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);
261 LoadStdProfileSettings(GetOptionsMgr()->GetInt(OPT_MRU_MAX)); // Load standard INI file options (including MRU)
263 InitializeFileFilters();
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);
271 String filter = m_pGlobalFileFilter->GetFilterNameOrMask();
272 m_pOptions->SaveOption(OPT_FILEFILTER_CURRENT, filter);
276 UpdateCodepageModule();
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));
281 NONCLIENTMETRICS ncm = { sizeof NONCLIENTMETRICS };
282 if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof NONCLIENTMETRICS, &ncm, 0))
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);
292 if (m_pSyntaxColors != nullptr)
293 Options::SyntaxColors::Init(GetOptionsMgr(), m_pSyntaxColors.get());
295 if (m_pMarkers != nullptr)
296 m_pMarkers->LoadFromRegistry();
298 CCrystalTextView::SetRenderingModeDefault(static_cast<CCrystalTextView::RENDERING_MODE>(GetOptionsMgr()->GetInt(OPT_RENDERING_MODE)));
300 if (m_pLineFilters != nullptr)
301 m_pLineFilters->Initialize(GetOptionsMgr());
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)
307 String oldFilter = theApp.GetProfileString(_T("Settings"), _T("RegExps"));
308 if (!oldFilter.empty())
309 m_pLineFilters->Import(oldFilter);
312 // Check if filter folder is set, and create it if not
313 String pathMyFolders = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
314 if (pathMyFolders.empty())
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);
321 if (!paths::CreateIfNeeded(pathMyFolders))
323 // Failed to create a folder, check it didn't already
325 DWORD errCode = GetLastError();
326 if (errCode != ERROR_ALREADY_EXISTS)
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());
335 strdiff::Init(); // String diff init
336 strdiff::SetBreakChars(GetOptionsMgr()->GetString(OPT_BREAK_SEPARATORS).c_str());
338 m_bMergingMode = GetOptionsMgr()->GetBool(OPT_MERGE_MODE);
340 // Initialize i18n (multiple language) support
342 m_pLangDlg->InitializeLanguage((WORD)GetOptionsMgr()->GetInt(OPT_SELECTED_LANGUAGE));
344 m_mainThreadScripts = new CAssureScriptsForThread;
346 // Register the application's document templates. Document templates
347 // serve as the connection between documents, frame windows and views.
350 m_pOpenTemplate = new CMultiDocTemplate(
352 RUNTIME_CLASS(COpenDoc),
353 RUNTIME_CLASS(COpenFrame), // custom MDI child frame
354 RUNTIME_CLASS(COpenView));
355 AddDocTemplate(m_pOpenTemplate);
358 m_pDiffTemplate = new CMultiDocTemplate(
360 RUNTIME_CLASS(CMergeDoc),
361 RUNTIME_CLASS(CMergeEditFrame), // custom MDI child frame
362 RUNTIME_CLASS(CMergeEditSplitterView));
363 AddDocTemplate(m_pDiffTemplate);
366 m_pHexMergeTemplate = new CMultiDocTemplate(
368 RUNTIME_CLASS(CHexMergeDoc),
369 RUNTIME_CLASS(CHexMergeFrame), // custom MDI child frame
370 RUNTIME_CLASS(CHexMergeView));
371 AddDocTemplate(m_pHexMergeTemplate);
374 m_pDirTemplate = new CMultiDocTemplate(
376 RUNTIME_CLASS(CDirDoc),
377 RUNTIME_CLASS(CDirFrame), // custom MDI child frame
378 RUNTIME_CLASS(CDirView));
379 AddDocTemplate(m_pDirTemplate);
381 // create main MDI Frame window
382 CMainFrame* pMainFrame = new CMainFrame;
383 if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
385 if (hMutex != nullptr)
387 ReleaseMutex(hMutex);
392 m_pMainWnd = pMainFrame;
394 // Init menus -- hMenuDefault is for MainFrame
395 pMainFrame->m_hMenuDefault = pMainFrame->NewDefaultMenu();
398 // Note : for Windows98 compatibility, use FromHandle and not Attach/Detach
399 CMenu * pNewMenu = CMenu::FromHandle(pMainFrame->m_hMenuDefault);
400 pMainFrame->MDISetMenu(pNewMenu, nullptr);
402 // The main window has been initialized, so activate it.
403 pMainFrame->ActivateFrame(cmdInfo.m_nCmdShow);
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)
411 if (hMutex != nullptr)
412 ReleaseMutex(hMutex);
414 // If user wants to cancel the compare, close WinMerge
417 pMainFrame->PostMessage(WM_CLOSE, 0, 0);
421 WinMergeTest::TestAll();
427 static void OpenContributersFile(int&)
429 theApp.OpenFileToExternalEditor(paths::ConcatPath(env::GetProgPath(), ContributorsPath));
432 // App command to run the dialog
433 void CMergeApp::OnAppAbout()
436 aboutDlg.m_onclick_contributers += Poco::delegate(OpenContributersFile);
438 aboutDlg.m_onclick_contributers.clear();
441 /////////////////////////////////////////////////////////////////////////////
442 // CMergeApp commands
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()).
450 int CMergeApp::ExitInstance()
454 // Save registry keys if existing WinMerge.reg
455 env::SaveRegistryToFile(paths::ConcatPath(env::GetProgPath(), _T("WinMerge.reg")), RegDir);
458 const String temp = env::GetTemporaryPath();
459 ClearTempfolder(temp);
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.
466 delete m_mainThreadScripts;
467 CWinApp::ExitInstance();
471 int CMergeApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt)
473 // This is a convenient point for breakpointing !!!
475 // Create a handle to store the parent window of the message box.
476 CWnd* pParentWnd = CWnd::GetActiveWindow();
478 // Check whether an active window was retrieved successfully.
479 if (pParentWnd == nullptr)
481 // Try to retrieve a handle to the last active popup.
482 CWnd * mainwnd = GetMainWnd();
483 if (mainwnd != nullptr)
484 pParentWnd = mainwnd->GetLastActivePopup();
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)
491 if (m_bNonInteractive)
493 if (AttachConsole(ATTACH_PARENT_PROCESS))
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);
503 // Create the message box dialog.
504 CMessageBoxDialog dlgMessage(pParentWnd, lpszPrompt, _T(""), nType | MB_RIGHT_ALIGN,
507 if (m_pMainWnd->IsIconic())
508 m_pMainWnd->ShowWindow(SW_RESTORE);
510 // Display the message box dialog and return the result.
511 return static_cast<int>(dlgMessage.DoModal());
514 bool CMergeApp::IsReallyIdle() const
517 POSITION pos = m_pDirTemplate->GetFirstDocPosition();
518 while (pos != nullptr)
520 CDirDoc *pDirDoc = static_cast<CDirDoc *>(m_pDirTemplate->GetNextDoc(pos));
521 if (const CompareStats *pCompareStats = pDirDoc->GetCompareStats())
523 if (!pCompareStats->IsCompareDone() || pDirDoc->GetGeneratingReport())
530 BOOL CMergeApp::OnIdle(LONG lCount)
532 if (CWinApp::OnIdle(lCount))
535 // If anyone has requested notification when next idle occurs, send it
536 if (m_bNeedIdleTimer)
538 m_bNeedIdleTimer = false;
539 m_pMainWnd->SendMessageToDescendants(WM_TIMER, IDLE_TIMER, lCount, TRUE, FALSE);
542 if (m_bNonInteractive && IsReallyIdle())
543 m_pMainWnd->PostMessage(WM_CLOSE, 0, 0);
545 static_cast<CRegOptionsMgr *>(GetOptionsMgr())->CloseKeys();
551 * @brief Load any known file filters.
553 * This function loads filter files from paths we know contain them.
554 * @note User's filter location may not be set yet.
556 void CMergeApp::InitializeFileFilters()
558 String filterPath = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
560 if (!filterPath.empty())
562 m_pGlobalFileFilter->SetUserFilterPath(filterPath);
564 m_pGlobalFileFilter->LoadAllFileFilters();
567 void CMergeApp::ApplyCommandLineConfigOptions(MergeCmdLineInfo& cmdInfo)
569 if (cmdInfo.m_bNoPrefs)
570 m_pOptions->SetSerializing(false); // Turn off serializing to registry.
572 for (const auto& it : cmdInfo.m_Options)
574 if (m_pOptions->Set(it.first, it.second) == COption::OPT_NOTFOUND)
576 String longname = m_pOptions->ExpandShortName(it.first);
577 if (!longname.empty())
579 m_pOptions->Set(longname, it.second);
583 cmdInfo.m_sErrorMessages.push_back(strutils::format_string1(_T("Invalid key '%1' specified in /config option"), it.first));
589 /** @brief Read command line arguments and open files for comparison.
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.
598 bool CMergeApp::ParseArgsAndDoOpen(MergeCmdLineInfo& cmdInfo, CMainFrame* pMainFrame)
600 bool bCompared = false;
602 std::unique_ptr<PackingInfo> infoUnpacker;
604 m_bNonInteractive = cmdInfo.m_bNonInteractive;
606 if (!cmdInfo.m_sUnpacker.empty())
608 infoUnpacker.reset(new PackingInfo(PLUGIN_MODE::PLUGIN_MANUAL));
609 infoUnpacker->m_PluginName = cmdInfo.m_sUnpacker;
612 // Set the global file filter.
613 if (!cmdInfo.m_sFileFilter.empty())
615 m_pGlobalFileFilter->SetFilter(cmdInfo.m_sFileFilter);
619 if (cmdInfo.m_nCodepage)
621 UpdateDefaultCodepage(2,cmdInfo.m_nCodepage);
624 // Unless the user has requested to see WinMerge's usage open files for
626 if (cmdInfo.m_bShowUsage)
628 ShowHelp(CommandLineHelpLocation);
632 // Set the required information we need from the command line:
634 m_bExitIfNoDiff = cmdInfo.m_bExitIfNoDiff;
635 m_bEscShutdown = cmdInfo.m_bEscShutdown;
637 m_strSaveAsPath = cmdInfo.m_sOutputpath;
639 strDesc[0] = cmdInfo.m_sLeftDesc;
640 if (cmdInfo.m_Files.GetSize() < 3)
642 strDesc[1] = cmdInfo.m_sRightDesc;
646 strDesc[1] = cmdInfo.m_sMiddleDesc;
647 strDesc[2] = cmdInfo.m_sRightDesc;
650 if (cmdInfo.m_Files.GetSize() > 2)
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());
660 else if (cmdInfo.m_Files.GetSize() > 1)
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());
667 else if (cmdInfo.m_Files.GetSize() == 1)
669 String sFilepath = cmdInfo.m_Files[0];
670 if (IsProjectFile(sFilepath))
672 bCompared = LoadAndOpenProjectFile(sFilepath);
674 else if (IsConflictFile(sFilepath))
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);
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());
690 else if (cmdInfo.m_Files.GetSize() == 0) // if there are no input args, we can check the display file dialog flag
692 bool showFiles = m_pOptions->GetBool(OPT_SHOW_SELECT_FILES_AT_STARTUP);
694 pMainFrame->DoFileOpen();
700 void CMergeApp::UpdateDefaultCodepage(int cpDefaultMode, int cpCustomCodepage)
704 switch (cpDefaultMode)
707 ucr::setDefaultCodepage(GetACP());
711 wLangId = GetLangId();
712 if (GetLocaleInfo(wLangId, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof(buff)/sizeof(buff[0])))
713 ucr::setDefaultCodepage(_ttol(buff));
715 ucr::setDefaultCodepage(GetACP());
718 ucr::setDefaultCodepage(cpCustomCodepage);
721 // no other valid option
723 ucr::setDefaultCodepage(GetACP());
728 * @brief Send current option settings into codepage module
730 void CMergeApp::UpdateCodepageModule()
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));
737 /** @brief Open help from mainframe when user presses F1*/
738 void CMergeApp::OnHelp()
744 * @brief Open given file to external editor specified in options.
745 * @param [in] file Full path to file to open.
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
751 * @param [in] file Full path to file to open.
752 * @param [in] nLineNumber Line number to go to.
754 void CMergeApp::OpenFileToExternalEditor(const String& file, int nLineNumber/* = 1*/)
756 String sCmd = GetOptionsMgr()->GetString(OPT_EXT_EDITOR_CMD);
758 strutils::replace(sCmd, _T("$linenum"), strutils::to_str(nLineNumber));
760 size_t nIndex = sCmd.find(_T("$file"));
761 if (nIndex != String::npos)
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("\""));
779 STARTUPINFO stInfo = { sizeof STARTUPINFO };
780 PROCESS_INFORMATION processInfo;
782 retVal = !!CreateProcess(nullptr, (LPTSTR)sCmd.c_str(),
783 nullptr, nullptr, FALSE, CREATE_DEFAULT_ERROR_MODE, nullptr, nullptr,
784 &stInfo, &processInfo);
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);
794 CloseHandle(processInfo.hThread);
795 CloseHandle(processInfo.hProcess);
800 * @brief Open file, if it exists, else open url
802 void CMergeApp::OpenFileOrUrl(LPCTSTR szFile, LPCTSTR szUrl)
804 if (paths::DoesPathExist(szFile) == paths::IS_EXISTING_FILE)
805 ShellExecute(nullptr, _T("open"), _T("notepad.exe"), szFile, nullptr, SW_SHOWNORMAL);
807 ShellExecute(nullptr, _T("open"), szUrl, nullptr, nullptr, SW_SHOWNORMAL);
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.
814 void CMergeApp::ShowHelp(LPCTSTR helpLocation /*= nullptr*/)
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)
824 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
825 ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOC, NULL);
827 ShellExecute(nullptr, _T("open"), DocsURL, nullptr, nullptr, SW_SHOWNORMAL);
831 if (paths::DoesPathExist(sPath) == paths::IS_EXISTING_FILE)
833 sPath += helpLocation;
834 ::HtmlHelp(nullptr, sPath.c_str(), HH_DISPLAY_TOPIC, NULL);
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.
850 bool CMergeApp::CreateBackup(bool bFolder, const String& pszPath)
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)))
856 // Likewise if user doesn't want backups in file compare
857 else if (!bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FILECMP)))
860 // create backup copy of file if destination file exists
861 if (paths::DoesPathExist(pszPath) == paths::IS_EXISTING_FILE)
868 paths::SplitFilename(paths::GetLongPath(pszPath), &path, &filename, &ext);
870 // Determine backup folder
871 if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
872 PropBackups::FOLDER_ORIGINAL)
874 // Put backups to same folder than original file
877 else if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
878 PropBackups::FOLDER_GLOBAL)
880 // Put backups to global folder defined in options
881 bakPath = GetOptionsMgr()->GetString(OPT_BACKUP_GLOBALFOLDER);
885 bakPath = paths::GetLongPath(bakPath);
889 _RPTF0(_CRT_ERROR, "Unknown backup location!");
892 bool success = false;
893 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_BAK))
895 // Don't add dot if there is no existing extension
898 ext += BACKUP_FILE_EXT;
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))
909 ::localtime_s(&tm, &curtime);
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);
916 // Append filename and extension (+ optional .bak) to path
917 if ((bakPath.length() + filename.length() + ext.length())
921 bakPath = paths::ConcatPath(bakPath, filename);
928 success = !!CopyFileW(TFile(pszPath).wpath().c_str(), TFile(bakPath).wpath().c_str(), FALSE);
933 String msg = strutils::format_string1(
934 _("Unable to backup original file:\n%1\n\nContinue anyway?"),
936 if (AfxMessageBox(msg.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN) != IDYES)
942 // we got here because we're either not backing up of there was nothing to backup
947 * @brief Checks if path (file/folder) is read-only and asks overwriting it.
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()
960 int CMergeApp::HandleReadonlySave(String& strSavePath, bool bMultiFile,
965 bool bFileRO = false;
966 bool bFileExists = false;
971 if (!strSavePath.empty())
975 TFile file(strSavePath);
976 bFileExists = file.exists();
978 bFileRO = !file.canWrite();
985 if (bFileExists && bFileRO)
989 // Don't ask again if its already asked
994 // Prompt for user choice
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);
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);
1014 // Overwrite read-only file
1016 bApplyToAll = true; // Don't ask again (no break here)
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);
1025 // Save to new filename (single) /skip this item (multiple)
1029 if (SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, false, strSavePath.c_str()))
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.
1055 bool CMergeApp::IsProjectFile(const String& filepath) const
1058 paths::SplitFilename(filepath, nullptr, nullptr, &ext);
1059 if (strutils::compare_nocase(ext, ProjectFile::PROJECTFILE_EXT) == 0)
1065 bool CMergeApp::LoadProjectFile(const String& sProject, ProjectFile &project)
1067 if (sProject.empty())
1072 project.Read(sProject);
1074 catch (Poco::Exception& e)
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);
1086 bool CMergeApp::SaveProjectFile(const String& sProject, const ProjectFile &project)
1090 project.Save(sProject);
1092 catch (Poco::Exception& e)
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);
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.
1109 bool CMergeApp::LoadAndOpenProjectFile(const String& sProject, const String& sReportFile)
1111 ProjectFile project;
1112 if (!LoadProjectFile(sProject, project))
1116 for (auto& projItem : project.Items())
1119 bool bRecursive = false;
1120 projItem.GetPaths(tFiles, bRecursive);
1121 for (int i = 0; i < tFiles.GetSize(); ++i)
1123 if (!paths::IsPathAbsolute(tFiles[i]))
1125 String sProjectDir = paths::GetParentPath(sProject);
1126 if (tFiles[i].substr(0, 1) == _T("\\"))
1128 if (sProjectDir.length() > 1 && sProjectDir[1] == ':')
1129 tFiles[i] = paths::ConcatPath(sProjectDir.substr(0, 2), tFiles[i]);
1132 tFiles[i] = paths::ConcatPath(sProjectDir, tFiles[i]);
1135 bool bLeftReadOnly = projItem.GetLeftReadOnly();
1136 bool bMiddleReadOnly = projItem.GetMiddleReadOnly();
1137 bool bRightReadOnly = projItem.GetRightReadOnly();
1138 if (projItem.HasFilter())
1140 String filter = projItem.GetFilter();
1141 filter = strutils::trim_ws(filter);
1142 m_pGlobalFileFilter->SetFilter(filter);
1144 if (projItem.HasSubfolders())
1145 bRecursive = projItem.GetSubfolders() > 0;
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)
1153 dwFlags[0] |= FFILEOPEN_READONLY;
1154 if (tFiles.GetSize() == 2)
1157 dwFlags[1] |= FFILEOPEN_READONLY;
1161 if (bMiddleReadOnly)
1162 dwFlags[1] |= FFILEOPEN_READONLY;
1164 dwFlags[2] |= FFILEOPEN_READONLY;
1167 GetOptionsMgr()->SaveOption(OPT_CMP_INCLUDE_SUBDIRS, bRecursive);
1169 rtn &= GetMainFrame()->DoFileOpen(&tFiles, dwFlags, nullptr, sReportFile, bRecursive);
1172 AddToRecentProjectsMRU(sProject.c_str());
1177 * @brief Return windows language ID of current WinMerge GUI language
1179 WORD CMergeApp::GetLangId() const
1181 return m_pLangDlg->GetLangId();
1185 * @brief Lang aware version of CStatusBar::SetIndicators()
1187 void CMergeApp::SetIndicators(CStatusBar &sb, const UINT *rgid, int n) const
1189 m_pLangDlg->SetIndicators(sb, rgid, n);
1193 * @brief Translate menu to current WinMerge GUI language
1195 void CMergeApp::TranslateMenu(HMENU h) const
1197 m_pLangDlg->TranslateMenu(h);
1201 * @brief Translate dialog to current WinMerge GUI language
1203 void CMergeApp::TranslateDialog(HWND h) const
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);
1209 m_pLangDlg->TranslateDialog(h);
1213 * @brief Load string and translate to current WinMerge GUI language
1215 String CMergeApp::LoadString(UINT id) const
1217 return m_pLangDlg->LoadString(id);
1220 bool CMergeApp::TranslateString(const std::string& str, String& translated_str) const
1222 return m_pLangDlg->TranslateString(str, translated_str);
1226 * @brief Load dialog caption and translate to current WinMerge GUI language
1228 std::wstring CMergeApp::LoadDialogCaption(LPCTSTR lpDialogTemplateID) const
1230 return m_pLangDlg->LoadDialogCaption(lpDialogTemplateID);
1234 * @brief Adds specified file to the recent projects list.
1235 * @param [in] sPathName Path to project file
1237 void CMergeApp::AddToRecentProjectsMRU(LPCTSTR sPathName)
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();
1247 void CMergeApp::SetupTempPath()
1249 String instTemp = env::GetPerInstanceString(TempFolderPrefix);
1250 if (GetOptionsMgr()->GetBool(OPT_USE_SYSTEM_TEMP_PATH))
1251 env::SetTemporaryPath(paths::ConcatPath(env::GetSystemTempPath(), instTemp));
1253 env::SetTemporaryPath(paths::ConcatPath(GetOptionsMgr()->GetString(OPT_CUSTOM_TEMP_PATH), instTemp));
1257 * @brief Handles menu selection from recent projects list
1258 * @param [in] nID Menu ID of the selected item
1260 BOOL CMergeApp::OnOpenRecentFile(UINT nID)
1262 return LoadAndOpenProjectFile(static_cast<const TCHAR *>(m_pRecentFileList->m_arrNames[nID-ID_FILE_PROJECT_MRU_FIRST]));
1266 * @brief Return if doc is in Merging/Editing mode
1268 bool CMergeApp::GetMergingMode() const
1270 return m_bMergingMode;
1274 * @brief Set doc to Merging/Editing mode
1276 void CMergeApp::SetMergingMode(bool bMergingMode)
1278 m_bMergingMode = bMergingMode;
1279 GetOptionsMgr()->SaveOption(OPT_MERGE_MODE, m_bMergingMode);
1283 * @brief Switch Merging/Editing mode and update
1284 * buffer read-only states accordingly
1286 void CMergeApp::OnMergingMode()
1288 bool bMergingMode = GetMergingMode();
1291 LangMessageBox(IDS_MERGE_MODE, MB_ICONINFORMATION | MB_DONT_DISPLAY_AGAIN);
1292 SetMergingMode(!bMergingMode);
1296 * @brief Update Menuitem for Merging Mode
1298 void CMergeApp::OnUpdateMergingMode(CCmdUI* pCmdUI)
1300 pCmdUI->Enable(true);
1301 pCmdUI->SetCheck(GetMergingMode());
1305 * @brief Update MergingMode UI in statusbar
1307 void CMergeApp::OnUpdateMergingStatus(CCmdUI *pCmdUI)
1309 String text = theApp.LoadString(IDS_MERGEMODE_MERGING);
1310 pCmdUI->SetText(text.c_str());
1311 pCmdUI->Enable(GetMergingMode());
1314 UINT CMergeApp::GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault)
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);
1323 BOOL CMergeApp::WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue)
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;
1332 CString CMergeApp::GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault)
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();
1341 BOOL CMergeApp::WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue)
1343 COptionsMgr *pOptions = GetOptionsMgr();
1344 if (lpszEntry != nullptr)
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;
1353 String name = strutils::format(_T("%s/"), lpszSection);
1354 pOptions->RemoveOption(name);