1 /////////////////////////////////////////////////////////////////////////////
2 // WinMerge: an interactive diff/merge utility
3 // Copyright (C) 1997-2000 Thingamahoochie Software
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2 of the License, or
9 // (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /////////////////////////////////////////////////////////////////////////////
24 * @brief Defines the class behaviors for the application.
30 #include "Constants.h"
31 #include "UnicodeString.h"
33 #include "Environment.h"
34 #include "OptionsMgr.h"
35 #include "RegOptionsMgr.h"
39 #include "HexMergeDoc.h"
40 #include "HexMergeFrm.h"
41 #include "HexMergeView.h"
49 #include "PropBackups.h"
50 #include "FileOrFolderSelect.h"
52 #include "FileFilterHelper.h"
53 #include "LineFiltersList.h"
54 #include "SyntaxColors.h"
55 #include "OptionsSyntaxColors.h"
57 #include "ProjectFile.h"
58 #include "MergeEditView.h"
59 #include "LanguageSelect.h"
60 #include "OptionsDef.h"
61 #include "MergeCmdLineInfo.h"
62 #include "ConflictFileParser.h"
66 #include "stringdiffs.h"
68 #include "SourceControl.h"
70 #include "Constants.h"
72 // For shutdown cleanup
78 static char THIS_FILE[] = __FILE__;
83 /** @brief Location for command line help to open. */
84 static TCHAR CommandLineHelpLocation[] = _T("::/htmlhelp/Command_line.html");
86 // registry dir to WinMerge
87 static String f_RegDir = _T("Software\\Thingamahoochie\\WinMerge");
89 /** @brief Backup file extension. */
90 static const TCHAR BACKUP_FILE_EXT[] = _T("bak");
94 * @brief Turn STL exceptions into MFC exceptions.
95 * Based on the article "Visual C++ Exception-Handling Instrumentation"
96 * by Eugene Gershnik, published at http://www.drdobbs.com/184416600.
97 * Rethrow fix inspired by http://www.spinics.net/lists/wine/msg05996.html.
100 namespace Turn_STL_exceptions_into_MFC_exceptions
102 # ifndef _STATIC_CPPLIB
103 # error This hack only works with _STATIC_CPPLIB defined.
106 class CDisguisedSTLException : public CException
109 std::exception *m_pSTLException;
111 CDisguisedSTLException(std::exception *pSTLException)
112 : m_pSTLException(pSTLException)
115 virtual BOOL GetErrorMessage(LPTSTR lpszError, UINT nMaxError, PUINT)
117 _sntprintf(lpszError, nMaxError, _T("%hs"), m_pSTLException->what());
122 const DWORD CPP_EXCEPTION = 0xE06D7363;
123 const DWORD MS_MAGIC = 0x19930520;
125 extern "C" void __stdcall _CxxThrowException(void *pObject, _s__ThrowInfo const *pObjectInfo)
127 __declspec(thread) static ULONG_PTR args[3] = { MS_MAGIC, 0, 0 };
130 pObject = reinterpret_cast<void *>(args[1]);
131 pObjectInfo = reinterpret_cast<_s__ThrowInfo const *>(args[2]);
135 args[1] = (ULONG_PTR)pObject;
136 args[2] = (ULONG_PTR)pObjectInfo;
139 if (pObjectInfo->pCatchableTypeArray && (i = pObjectInfo->pCatchableTypeArray->nCatchableTypes))
141 const char *name = typeid(std::exception).raw_name();
142 if (pObjectInfo->pCatchableTypeArray->arrayOfCatchableTypes[i - 1]->pType->name == name)
144 throw new CDisguisedSTLException(static_cast<std::exception *>(pObject));
147 RaiseException(CPP_EXCEPTION, EXCEPTION_NONCONTINUABLE, sizeof(args)/sizeof(args[0]), args);
153 /////////////////////////////////////////////////////////////////////////////
156 BEGIN_MESSAGE_MAP(CMergeApp, CWinApp)
157 //{{AFX_MSG_MAP(CMergeApp)
158 ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
159 ON_COMMAND(ID_HELP, OnHelp)
160 ON_COMMAND_EX_RANGE(ID_FILE_MRU_FILE1, ID_FILE_MRU_FILE16, OnOpenRecentFile)
161 ON_COMMAND(ID_FILE_MERGINGMODE, OnMergingMode)
162 ON_UPDATE_COMMAND_UI(ID_FILE_MERGINGMODE, OnUpdateMergingMode)
163 ON_UPDATE_COMMAND_UI(ID_STATUS_MERGINGMODE, OnUpdateMergingStatus)
165 // Standard file based document commands
166 //ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
167 //ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
168 // Standard print setup command
169 ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
172 static void AddEnglishResourceHook();
175 * @brief Mapping from command line argument name (eg, ignorews) to WinMerge
176 * option name (eg, Settings/IgnoreSpace).
178 * These arguments take an optional colon and number, like so:
180 * "/ignoreblanklines" (makes WinMerge ignore blank lines)
181 * "/ignoreblanklines:1" (makes WinMerge ignore blank lines)
182 * "/ignoreblanklines:0" (makes WinMerge not ignore blank lines)
187 LPCTSTR WinMergeOptionName;
191 /////////////////////////////////////////////////////////////////////////////
192 // CMergeApp construction
194 CMergeApp::CMergeApp() :
195 m_bNeedIdleTimer(FALSE)
198 , m_pHexMergeTemplate(0)
200 , m_mainThreadScripts(NULL)
201 , m_nLastCompareResult(0)
202 , m_bNonInteractive(false)
203 , m_pOptions(new CRegOptionsMgr())
204 , m_pGlobalFileFilter(new FileFilterHelper())
205 , m_nActiveOperations(0)
206 , m_pLangDlg(new CLanguageSelect())
207 , m_bEscShutdown(FALSE)
208 , m_bClearCaseTool(FALSE)
209 , m_bExitIfNoDiff(MergeCmdLineInfo::Disabled)
210 , m_pLineFilters(new LineFiltersList())
211 , m_pSyntaxColors(new SyntaxColors())
212 , m_pSourceControl(new SourceControl())
213 , m_bMergingMode(FALSE)
215 // add construction code here,
216 // Place all significant initialization in InitInstance
219 CMergeApp::~CMergeApp()
223 /////////////////////////////////////////////////////////////////////////////
224 // The one and only CMergeApp object
228 /////////////////////////////////////////////////////////////////////////////
229 // CMergeApp initialization
232 * @brief Initialize WinMerge application instance.
233 * @return TRUE if application initialization succeeds (and we'll run it),
234 * FALSE if something failed and we exit the instance.
235 * @todo We could handle these failure situations more gratefully, i.e. show
236 * at least some error message to the user..
238 BOOL CMergeApp::InitInstance()
240 // Prevents DLL hijacking
241 HMODULE hLibrary = GetModuleHandle(_T("kernel32.dll"));
242 BOOL (WINAPI *pfnSetSearchPathMode)(DWORD) = (BOOL (WINAPI *)(DWORD))GetProcAddress(hLibrary, "SetSearchPathMode");
243 if (pfnSetSearchPathMode)
244 pfnSetSearchPathMode(0x00000001L /*BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE*/ | 0x00008000L /*BASE_SEARCH_PATH_PERMANENT*/);
245 BOOL (WINAPI *pfnSetDllDirectoryA)(LPCSTR) = (BOOL (WINAPI *)(LPCSTR))GetProcAddress(hLibrary, "SetDllDirectoryA");
246 if (pfnSetDllDirectoryA)
247 pfnSetDllDirectoryA("");
249 JumpList::SetCurrentProcessExplicitAppUserModelID(L"Thingamahoochie.WinMerge");
251 InitCommonControls(); // initialize common control library
252 CWinApp::InitInstance(); // call parent class method
254 // Runtime switch so programmer may set this in interactive debugger
258 // get current setting
259 int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
260 // Keep freed memory blocks in the heap's linked list and mark them as freed
261 tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
262 // Call _CrtCheckMemory at every allocation and deallocation request.
263 // WARNING: This slows down WinMerge *A LOT*
264 tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
265 // Set the new state for the flag
266 _CrtSetDbgFlag( tmpFlag );
269 // CCrystalEdit Drag and Drop functionality needs AfxOleInit.
272 TRACE(_T("AfxOleInitFailed. OLE functionality disabled"));
275 // Standard initialization
276 // If you are not using these features and wish to reduce the size
277 // of your final executable, you should remove from the following
278 // the specific initialization routines you do not need.
280 // Revoke the standard OLE Message Filter to avoid drawing frame while loading files.
281 COleMessageFilter* pOldFilter = AfxOleGetMessageFilter();
282 pOldFilter->Revoke();
284 // Load registry keys from WinMerge.reg if existing WinMerge.reg
285 env_LoadRegistryFromFile(paths_ConcatPath(env_GetProgPath(), _T("WinMerge.reg")));
287 OptionsInit(); // Implementation in OptionsInit.cpp
289 // Initialize temp folder
292 // Cleanup left over tempfiles from previous instances.
293 // Normally this should not neet to do anything - but if for some reason
294 // WinMerge did not delete temp files this makes sure they are removed.
297 // Parse command-line arguments.
298 MergeCmdLineInfo cmdInfo = GetCommandLine();
300 // If paths were given to commandline we consider this being an invoke from
301 // commandline (from other application, shellextension etc).
302 BOOL bCommandLineInvoke = cmdInfo.m_Files.GetSize() > 0;
304 // WinMerge registry settings are stored under HKEY_CURRENT_USER/Software/Thingamahoochie
305 // This is the name of the company of the original author (Dean Grimm)
306 SetRegistryKey(_T("Thingamahoochie"));
308 BOOL bSingleInstance = GetOptionsMgr()->GetBool(OPT_SINGLE_INSTANCE) ||
309 (true == cmdInfo.m_bSingleInstance);
311 // Create exclusion mutex name
312 TCHAR szDesktopName[MAX_PATH] = _T("Win9xDesktop");
313 DWORD dwLengthNeeded;
314 GetUserObjectInformation(GetThreadDesktop(GetCurrentThreadId()), UOI_NAME,
315 szDesktopName, sizeof(szDesktopName), &dwLengthNeeded);
316 TCHAR szMutexName[MAX_PATH + 40];
317 // Combine window class name and desktop name to form a unique mutex name.
318 // As the window class name is decorated to distinguish between ANSI and
319 // UNICODE build, so will be the mutex name.
320 wsprintf(szMutexName, _T("%s-%s"), CMainFrame::szClassName, szDesktopName);
321 HANDLE hMutex = CreateMutex(NULL, FALSE, szMutexName);
323 WaitForSingleObject(hMutex, INFINITE);
324 if (bSingleInstance && GetLastError() == ERROR_ALREADY_EXISTS)
326 // Activate previous instance and send commandline to it
327 HWND hWnd = FindWindow(CMainFrame::szClassName, NULL);
331 ShowWindow(hWnd, SW_RESTORE);
332 SetForegroundWindow(GetLastActivePopup(hWnd));
333 LPTSTR cmdLine = GetCommandLine();
334 COPYDATASTRUCT data = { 0, (lstrlen(cmdLine) + 1) * sizeof(TCHAR), cmdLine};
335 if (SendMessage(hWnd, WM_COPYDATA, NULL, (LPARAM)&data))
337 ReleaseMutex(hMutex);
344 LoadStdProfileSettings(8); // Load standard INI file options (including MRU)
346 InitializeFileFilters();
348 // Read last used filter from registry
349 // If filter fails to set, reset to default
350 const String filterString = m_pOptions->GetString(OPT_FILEFILTER_CURRENT);
351 BOOL bFilterSet = m_pGlobalFileFilter->SetFilter(filterString.c_str());
354 String filter = m_pGlobalFileFilter->GetFilterNameOrMask();
355 m_pOptions->SaveOption(OPT_FILEFILTER_CURRENT, filter);
358 UpdateCodepageModule();
360 if (m_pSourceControl)
361 m_pSourceControl->InitializeSourceControlMembers();
363 g_bUnpackerMode = theApp.GetProfileInt(_T("Settings"), _T("UnpackerMode"), PLUGIN_MANUAL);
364 g_bPredifferMode = theApp.GetProfileInt(_T("Settings"), _T("PredifferMode"), PLUGIN_MANUAL);
366 NONCLIENTMETRICS ncm = { sizeof NONCLIENTMETRICS };
367 if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof NONCLIENTMETRICS, &ncm, 0))
369 HDC hdc = ::GetDC(NULL);
370 int lfHeight = -MulDiv(9, GetDeviceCaps(hdc, LOGPIXELSY), 72);
371 ::ReleaseDC(NULL, hdc);
372 if (abs(ncm.lfMenuFont.lfHeight) > abs(lfHeight))
373 ncm.lfMenuFont.lfHeight = lfHeight;
374 if (wcscmp(ncm.lfMenuFont.lfFaceName, L"Meiryo") == 0 || wcscmp(ncm.lfMenuFont.lfFaceName, L"\U000030e1\U000030a4\U000030ea\U000030aa"/* "Meiryo" in Japanese */) == 0)
375 wcscpy_s(ncm.lfMenuFont.lfFaceName, L"Meiryo UI");
376 m_fontGUI.CreateFontIndirect(&ncm.lfMenuFont);
380 Options::SyntaxColors::Load(m_pSyntaxColors.get());
383 m_pLineFilters->Initialize(GetOptionsMgr());
385 // If there are no filters loaded, and there is filter string in previous
386 // option string, import old filters to new place.
387 if (m_pLineFilters->GetCount() == 0)
389 String oldFilter = theApp.GetProfileString(_T("Settings"), _T("RegExps"));
390 if (!oldFilter.empty())
391 m_pLineFilters->Import(oldFilter);
394 // Check if filter folder is set, and create it if not
395 String pathMyFolders = GetOptionsMgr()->GetString(OPT_FILTER_USERPATH);
396 if (pathMyFolders.empty())
398 // No filter path, set it to default and make sure it exists.
399 String pathFilters = GetDefaultFilterUserPath(TRUE);
400 GetOptionsMgr()->SaveOption(OPT_FILTER_USERPATH, pathFilters);
401 theApp.m_pGlobalFileFilter->SetFileFilterPath(pathFilters.c_str());
404 sd_Init(); // String diff init
405 sd_SetBreakChars(GetOptionsMgr()->GetString(OPT_BREAK_SEPARATORS).c_str());
407 m_bMergingMode = GetOptionsMgr()->GetBool(OPT_MERGE_MODE);
409 // Initialize i18n (multiple language) support
411 m_pLangDlg->InitializeLanguage((WORD)GetOptionsMgr()->GetInt(OPT_SELECTED_LANGUAGE));
413 AddEnglishResourceHook(); // Use English string when l10n (foreign) string missing
415 m_mainThreadScripts = new CAssureScriptsForThread;
417 // Register the application's document templates. Document templates
418 // serve as the connection between documents, frame windows and views.
421 m_pOpenTemplate = new CMultiDocTemplate(
423 RUNTIME_CLASS(COpenDoc),
424 RUNTIME_CLASS(COpenFrame), // custom MDI child frame
425 RUNTIME_CLASS(COpenView));
426 AddDocTemplate(m_pOpenTemplate);
429 m_pDiffTemplate = new CMultiDocTemplate(
431 RUNTIME_CLASS(CMergeDoc),
432 RUNTIME_CLASS(CChildFrame), // custom MDI child frame
433 RUNTIME_CLASS(CMergeEditView));
434 AddDocTemplate(m_pDiffTemplate);
437 m_pHexMergeTemplate = new CMultiDocTemplate(
439 RUNTIME_CLASS(CHexMergeDoc),
440 RUNTIME_CLASS(CHexMergeFrame), // custom MDI child frame
441 RUNTIME_CLASS(CHexMergeView));
442 AddDocTemplate(m_pHexMergeTemplate);
445 m_pDirTemplate = new CMultiDocTemplate(
447 RUNTIME_CLASS(CDirDoc),
448 RUNTIME_CLASS(CDirFrame), // custom MDI child frame
449 RUNTIME_CLASS(CDirView));
450 AddDocTemplate(m_pDirTemplate);
452 // create main MDI Frame window
453 CMainFrame* pMainFrame = new CMainFrame;
454 if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
458 ReleaseMutex(hMutex);
463 m_pMainWnd = pMainFrame;
465 // Init menus -- hMenuDefault is for MainFrame
466 pMainFrame->m_hMenuDefault = pMainFrame->NewDefaultMenu();
469 // Note : for Windows98 compatibility, use FromHandle and not Attach/Detach
470 CMenu * pNewMenu = CMenu::FromHandle(pMainFrame->m_hMenuDefault);
471 pMainFrame->MDISetMenu(pNewMenu, NULL);
473 // The main window has been initialized, so activate and update it.
474 pMainFrame->ActivateFrame(cmdInfo.m_nCmdShow);
475 pMainFrame->UpdateWindow();
477 // Since this function actually opens paths for compare it must be
478 // called after initializing CMainFrame!
479 BOOL bContinue = TRUE;
480 if (ParseArgsAndDoOpen(cmdInfo, pMainFrame) == FALSE && bCommandLineInvoke)
484 ReleaseMutex(hMutex);
486 if (m_bNonInteractive)
491 // If user wants to cancel the compare, close WinMerge
492 if (bContinue == FALSE)
494 pMainFrame->PostMessage(WM_CLOSE, 0, 0);
500 static void OpenContributersFile(int&)
502 theApp.OpenFileToExternalEditor(paths_ConcatPath(env_GetProgPath(), ContributorsPath));
505 // App command to run the dialog
506 void CMergeApp::OnAppAbout()
509 aboutDlg.m_onclick_contributers += Poco::delegate(OpenContributersFile);
511 aboutDlg.m_onclick_contributers.clear();
514 /////////////////////////////////////////////////////////////////////////////
515 // CMergeApp commands
518 * @brief Called when application is about to exit.
519 * This functions is called when application is exiting, so this is
520 * good place to do cleanups.
521 * @return Application's exit value (returned from WinMain()).
523 int CMergeApp::ExitInstance()
527 // Save registry keys if existing WinMerge.reg
528 env_SaveRegistryToFile(paths_ConcatPath(env_GetProgPath(), _T("WinMerge.reg")), RegDir);
531 const String temp = env_GetTempPath();
532 ClearTempfolder(temp);
533 delete m_mainThreadScripts;
534 CWinApp::ExitInstance();
538 static void AddEnglishResourceHook()
541 // After calling AfxSetResourceHandle to point to a language
542 // resource DLL, then the application is no longer on the
543 // resource lookup (defined by AfxFindResourceHandle).
545 // Add a dummy extension DLL record whose resource handle
546 // points to the application resources, just to provide
547 // fallback to English for any resources missing from
548 // the language resource DLL.
550 // (Why didn't Microsoft think of this? Bruno Haible who
551 // made gettext certainly thought of this.)
553 // NB: This does not fix the problem that if a control is
554 // missing from a dialog (because it was added only to the
555 // English version, for example) then the DDX_ function is
556 // going to fail. I see no easy way to intercept all DDX
557 // functions except by macro overriding the call--Perry, 2002-12-07.
559 static AFX_EXTENSION_MODULE FakeEnglishDLL = { NULL, NULL };
560 memset(&FakeEnglishDLL, 0, sizeof(FakeEnglishDLL));
561 FakeEnglishDLL.hModule = AfxGetApp()->m_hInstance;
562 FakeEnglishDLL.hResource = FakeEnglishDLL.hModule;
563 FakeEnglishDLL.bInitialized = TRUE;
564 new CDynLinkLibrary(FakeEnglishDLL); // hook into MFC extension DLL chain
569 int CMergeApp::DoMessageBox( LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt )
571 // This is a convenient point for breakpointing !!!
573 // Create a handle to store the parent window of the message box.
574 CWnd* pParentWnd = CWnd::GetActiveWindow();
576 // Check whether an active window was retrieved successfully.
577 if ( pParentWnd == NULL )
579 // Try to retrieve a handle to the last active popup.
580 CWnd * mainwnd = GetMainWnd();
582 pParentWnd = mainwnd->GetLastActivePopup();
585 // Use our own message box implementation, which adds the
586 // do not show again checkbox, and implements it on subsequent calls
587 // (if caller set the style)
589 if (m_bNonInteractive)
592 // Create the message box dialog.
593 CMessageBoxDialog dlgMessage(pParentWnd, lpszPrompt, _T(""), nType | MB_RIGHT_ALIGN,
596 if (m_pMainWnd->IsIconic())
597 m_pMainWnd->ShowWindow(SW_RESTORE);
599 // Display the message box dialog and return the result.
600 return static_cast<int>(dlgMessage.DoModal());
604 * @brief Set flag so that application will broadcast notification at next
605 * idle time (via WM_TIMER id=IDLE_TIMER)
607 void CMergeApp::SetNeedIdleTimer()
609 m_bNeedIdleTimer = TRUE;
612 BOOL CMergeApp::OnIdle(LONG lCount)
614 if (CWinApp::OnIdle(lCount))
617 // If anyone has requested notification when next idle occurs, send it
618 if (m_bNeedIdleTimer)
620 m_bNeedIdleTimer = FALSE;
621 m_pMainWnd->SendMessageToDescendants(WM_TIMER, IDLE_TIMER, lCount, TRUE, FALSE);
627 * @brief Load any known file filters.
629 * This function loads filter files from paths we know contain them.
630 * @note User's filter location may not be set yet.
632 void CMergeApp::InitializeFileFilters()
634 CString filterPath = GetProfileString(_T("Settings"), _T("UserFilterPath"), _T(""));
636 if (!filterPath.IsEmpty())
638 m_pGlobalFileFilter->SetUserFilterPath((LPCTSTR)filterPath);
640 m_pGlobalFileFilter->LoadAllFileFilters();
643 /** @brief Read command line arguments and open files for comparison.
645 * The name of the function is a legacy code from the time that this function
646 * actually parsed the command line. Today the parsing is done using the
647 * MergeCmdLineInfo class.
648 * @param [in] cmdInfo Commandline parameters info.
649 * @param [in] pMainFrame Pointer to application main frame.
650 * @return TRUE if we opened the compare, FALSE if the compare was canceled.
652 BOOL CMergeApp::ParseArgsAndDoOpen(MergeCmdLineInfo& cmdInfo, CMainFrame* pMainFrame)
654 BOOL bCompared = FALSE;
655 m_bNonInteractive = cmdInfo.m_bNonInteractive;
657 // Set the global file filter.
658 if (!cmdInfo.m_sFileFilter.empty())
660 m_pGlobalFileFilter->SetFilter(cmdInfo.m_sFileFilter.c_str());
664 if (cmdInfo.m_nCodepage)
666 UpdateDefaultCodepage(2,cmdInfo.m_nCodepage);
669 // Unless the user has requested to see WinMerge's usage open files for
671 if (cmdInfo.m_bShowUsage)
673 ShowHelp(CommandLineHelpLocation);
677 // Set the required information we need from the command line:
679 m_bClearCaseTool = cmdInfo.m_bClearCaseTool;
680 m_bExitIfNoDiff = cmdInfo.m_bExitIfNoDiff;
681 m_bEscShutdown = cmdInfo.m_bEscShutdown;
683 m_strSaveAsPath = cmdInfo.m_sOutputpath.c_str();
685 m_strDescriptions[0] = cmdInfo.m_sLeftDesc;
686 if (cmdInfo.m_Files.GetSize() < 3)
688 m_strDescriptions[1] = cmdInfo.m_sRightDesc;
692 m_strDescriptions[1] = cmdInfo.m_sMiddleDesc;
693 m_strDescriptions[2] = cmdInfo.m_sRightDesc;
696 if (cmdInfo.m_Files.GetSize() > 2)
698 cmdInfo.m_dwLeftFlags |= FFILEOPEN_CMDLINE;
699 cmdInfo.m_dwMiddleFlags |= FFILEOPEN_CMDLINE;
700 cmdInfo.m_dwRightFlags |= FFILEOPEN_CMDLINE;
701 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwMiddleFlags, cmdInfo.m_dwRightFlags};
702 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
703 dwFlags, cmdInfo.m_bRecurse, NULL,
704 cmdInfo.m_sPreDiffer.c_str());
706 else if (cmdInfo.m_Files.GetSize() > 1)
708 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
709 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
710 dwFlags, cmdInfo.m_bRecurse, NULL,
711 cmdInfo.m_sPreDiffer.c_str());
713 else if (cmdInfo.m_Files.GetSize() == 1)
715 String sFilepath = cmdInfo.m_Files[0];
716 if (IsProjectFile(sFilepath))
718 bCompared = LoadAndOpenProjectFile(sFilepath);
720 else if (IsConflictFile(sFilepath))
722 bCompared = pMainFrame->DoOpenConflict(sFilepath.c_str());
726 DWORD dwFlags[3] = {cmdInfo.m_dwLeftFlags, cmdInfo.m_dwRightFlags, FFILEOPEN_NONE};
727 bCompared = pMainFrame->DoFileOpen(&cmdInfo.m_Files,
728 dwFlags, cmdInfo.m_bRecurse, NULL,
729 cmdInfo.m_sPreDiffer.c_str());
732 else if (cmdInfo.m_Files.GetSize() == 0) // if there are no input args, we can check the display file dialog flag
734 BOOL showFiles = m_pOptions->GetBool(OPT_SHOW_SELECT_FILES_AT_STARTUP);
736 pMainFrame->DoFileOpen();
742 void CMergeApp::UpdateDefaultCodepage(int cpDefaultMode, int cpCustomCodepage)
746 switch (cpDefaultMode)
749 ucr::setDefaultCodepage(GetACP());
753 wLangId = GetLangId();
754 if (GetLocaleInfo(wLangId, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof(buff)/sizeof(buff[0])))
755 ucr::setDefaultCodepage(_ttol(buff));
757 ucr::setDefaultCodepage(GetACP());
760 ucr::setDefaultCodepage(cpCustomCodepage);
763 // no other valid option
765 ucr::setDefaultCodepage(GetACP());
770 * @brief Send current option settings into codepage module
772 void CMergeApp::UpdateCodepageModule()
774 // Get current codepage settings from the options module
775 // and push them into the codepage module
776 UpdateDefaultCodepage(GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_MODE), GetOptionsMgr()->GetInt(OPT_CP_DEFAULT_CUSTOM));
779 /** @brief Open help from mainframe when user presses F1*/
780 void CMergeApp::OnHelp()
786 * @brief Open given file to external editor specified in options.
787 * @param [in] file Full path to file to open.
789 * Opens file to defined (in Options/system), Notepad by default,
790 * external editor. Path is decorated with quotation marks if needed
791 * (contains spaces). Also '$file' in editor path is replaced by
793 * @param [in] file Full path to file to open.
794 * @param [in] nLineNumber Line number to go to.
796 void CMergeApp::OpenFileToExternalEditor(const String& file, int nLineNumber/* = 1*/)
798 String sCmd = GetOptionsMgr()->GetString(OPT_EXT_EDITOR_CMD);
800 string_replace(sCmd, _T("$linenum"), string_to_str(nLineNumber));
802 size_t nIndex = sCmd.find(_T("$file"));
803 if (nIndex != String::npos)
805 sFile.insert(0, _T("\""));
806 string_replace(sCmd, _T("$file"), sFile);
807 nIndex = sCmd.find(' ', nIndex + sFile.length());
808 if (nIndex != String::npos)
809 sCmd.insert(nIndex, _T("\""));
821 STARTUPINFO stInfo = {0};
822 stInfo.cb = sizeof(STARTUPINFO);
823 PROCESS_INFORMATION processInfo;
825 retVal = CreateProcess(NULL, (LPTSTR)sCmd.c_str(),
826 NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE, NULL, NULL,
827 &stInfo, &processInfo);
831 // Error invoking external editor
832 String msg = string_format_string1(_("Failed to execute external editor: %1"), sCmd);
833 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
837 CloseHandle(processInfo.hThread);
838 CloseHandle(processInfo.hProcess);
843 * @brief Open file, if it exists, else open url
845 void CMergeApp::OpenFileOrUrl(LPCTSTR szFile, LPCTSTR szUrl)
847 if (paths_DoesPathExist(szFile) == IS_EXISTING_FILE)
848 ShellExecute(NULL, _T("open"), _T("notepad.exe"), szFile, NULL, SW_SHOWNORMAL);
850 ShellExecute(NULL, _T("open"), szUrl, NULL, NULL, SW_SHOWNORMAL);
854 * @brief Show Help - this is for opening help from outside mainframe.
855 * @param [in] helpLocation Location inside help, if NULL main help is opened.
857 void CMergeApp::ShowHelp(LPCTSTR helpLocation /*= NULL*/)
859 String sPath = env_GetProgPath();
860 LANGID LangId = GetLangId();
861 if (PRIMARYLANGID(LangId) == LANG_JAPANESE)
862 sPath = paths_ConcatPath(sPath, DocsPath_ja);
864 sPath = paths_ConcatPath(sPath, DocsPath);
865 if (helpLocation == NULL)
867 if (paths_DoesPathExist(sPath) == IS_EXISTING_FILE)
868 ::HtmlHelp(NULL, sPath.c_str(), HH_DISPLAY_TOC, NULL);
870 ShellExecute(NULL, _T("open"), DocsURL, NULL, NULL, SW_SHOWNORMAL);
874 if (paths_DoesPathExist(sPath) == IS_EXISTING_FILE)
876 sPath += helpLocation;
877 ::HtmlHelp(NULL, sPath.c_str(), HH_DISPLAY_TOPIC, NULL);
883 * @brief Creates backup before file is saved or copied over.
884 * This function handles formatting correct path and filename for
885 * backup file. Formatting is done based on several options available
886 * for users in Options/Backups dialog. After path is formatted, file
887 * is simply just copied. Not much error checking, just if copying
888 * succeeded or failed.
889 * @param [in] bFolder Are we creating backup in folder compare?
890 * @param [in] pszPath Full path to file to backup.
891 * @return TRUE if backup succeeds, or isn't just done.
893 BOOL CMergeApp::CreateBackup(BOOL bFolder, const String& pszPath)
895 // If user doesn't want to backups in folder compare, return
896 // success so operations don't abort.
897 if (bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FOLDERCMP)))
899 // Likewise if user doesn't want backups in file compare
900 else if (!bFolder && !(GetOptionsMgr()->GetBool(OPT_BACKUP_FILECMP)))
903 // create backup copy of file if destination file exists
904 if (paths_DoesPathExist(pszPath) == IS_EXISTING_FILE)
911 paths_SplitFilename(paths_GetLongPath(pszPath), &path, &filename, &ext);
913 // Determine backup folder
914 if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
915 PropBackups::FOLDER_ORIGINAL)
917 // Put backups to same folder than original file
920 else if (GetOptionsMgr()->GetInt(OPT_BACKUP_LOCATION) ==
921 PropBackups::FOLDER_GLOBAL)
923 // Put backups to global folder defined in options
924 bakPath = GetOptionsMgr()->GetString(OPT_BACKUP_GLOBALFOLDER);
928 bakPath = paths_GetLongPath(bakPath);
932 _RPTF0(_CRT_ERROR, "Unknown backup location!");
935 BOOL success = FALSE;
936 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_BAK))
938 // Don't add dot if there is no existing extension
941 ext += BACKUP_FILE_EXT;
944 // Append time to filename if wanted so
945 // NOTE just adds timestamp at the moment as I couldn't figure out
946 // nice way to add a real time (invalid chars etc).
947 if (GetOptionsMgr()->GetBool(OPT_BACKUP_ADD_TIME))
952 tm = localtime(&curtime);
954 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);
959 // Append filename and extension (+ optional .bak) to path
960 if ((bakPath.length() + filename.length() + ext.length())
964 bakPath = paths_ConcatPath(bakPath, filename);
970 success = CopyFile(pszPath.c_str(), bakPath.c_str(), FALSE);
974 String msg = string_format_string1(
975 _("Unable to backup original file:\n%1\n\nContinue anyway?"),
977 if (AfxMessageBox(msg.c_str(), MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN) != IDYES)
983 // we got here because we're either not backing up of there was nothing to backup
988 * @brief Sync file to Version Control System
989 * @param pszDest [in] Where to copy (incl. filename)
990 * @param bApplyToAll [in,out] Apply user selection to all items
991 * @param psError [out] Error string that can be shown to user in caller func
992 * @return User selection or -1 if error happened
993 * @sa CMainFrame::HandleReadonlySave()
994 * @sa CDirView::PerformActionList()
996 int CMergeApp::SyncFileToVCS(const String& pszDest, BOOL &bApplyToAll,
1000 String strSavePath(pszDest);
1003 nVerSys = GetOptionsMgr()->GetInt(OPT_VCS_SYSTEM);
1005 int nRetVal = HandleReadonlySave(strSavePath, TRUE, bApplyToAll);
1006 if (nRetVal == IDCANCEL || nRetVal == IDNO)
1009 // If VC project opened from VSS sync and version control used
1010 if ((nVerSys == SourceControl::VCS_VSS4 || nVerSys == SourceControl::VCS_VSS5) && m_pSourceControl->m_bVCProjSync)
1012 if (!m_pSourceControl->m_vssHelper.ReLinkVCProj(strSavePath, sError))
1019 * @brief Checks if path (file/folder) is read-only and asks overwriting it.
1021 * @param strSavePath [in,out] Path where to save (file or folder)
1022 * @param bMultiFile [in] Single file or multiple files/folder
1023 * @param bApplyToAll [in,out] Apply last user selection for all items?
1024 * @return Users selection:
1025 * - IDOK: Item was not readonly, no actions
1026 * - IDYES/IDYESTOALL: Overwrite readonly item
1027 * - IDNO: User selected new filename (single file) or user wants to skip
1028 * - IDCANCEL: Cancel operation
1029 * @sa CMainFrame::SyncFileToVCS()
1030 * @sa CMergeDoc::DoSave()
1032 int CMergeApp::HandleReadonlySave(String& strSavePath, BOOL bMultiFile,
1036 UINT userChoice = 0;
1038 BOOL bFileRO = FALSE;
1039 BOOL bFileExists = FALSE;
1047 TFile file(strSavePath);
1048 bFileExists = file.exists();
1050 bFileRO = !file.canWrite();
1055 nVerSys = GetOptionsMgr()->GetInt(OPT_VCS_SYSTEM);
1057 if (bFileExists && bFileRO)
1059 // Version control system used?
1060 // Checkout file from VCS and modify, don't ask about overwriting
1062 if (nVerSys != SourceControl::VCS_NONE)
1064 bool bRetVal = m_pSourceControl->SaveToVersionControl(strSavePath);
1071 // Don't ask again if its already asked
1076 // Prompt for user choice
1079 // Multiple files or folder
1080 str = string_format_string1(_("%1\nis marked read-only. Would you like to override the read-only item?"), strSavePath);
1081 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1082 MB_ICONWARNING | MB_DEFBUTTON3 | MB_DONT_ASK_AGAIN |
1083 MB_YES_TO_ALL, IDS_SAVEREADONLY_MULTI);
1088 str = string_format_string1(_("%1 is marked read-only. Would you like to override the read-only file ? (No to save as new filename.)"), strSavePath);
1089 userChoice = AfxMessageBox(str.c_str(), MB_YESNOCANCEL |
1090 MB_ICONWARNING | MB_DEFBUTTON2 | MB_DONT_ASK_AGAIN,
1091 IDS_SAVEREADONLY_FMT);
1096 // Overwrite read-only file
1098 bApplyToAll = TRUE; // Don't ask again (no break here)
1100 CFile::GetStatus(strSavePath.c_str(), status);
1101 status.m_mtime = 0; // Avoid unwanted changes
1102 status.m_attribute &= ~CFile::readOnly;
1103 CFile::SetStatus(strSavePath.c_str(), status);
1107 // Save to new filename (single) /skip this item (multiple)
1111 if (SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, strSavePath.c_str(), _("Save As"), _T(""), FALSE))
1133 * @brief Shows VSS error from exception and writes log.
1135 void CMergeApp::ShowVSSError(CException *e, const String& strItem)
1137 TCHAR errStr[1024] = {0};
1138 if (e->GetErrorMessage(errStr, 1024))
1140 String errMsg = theApp.LoadString(IDS_VSS_ERRORFROM);
1141 String logMsg = errMsg;
1146 if (!strItem.empty())
1148 errMsg += _T("\n\n");
1153 LogErrorString(logMsg);
1154 AfxMessageBox(errMsg.c_str(), MB_ICONSTOP);
1158 LogErrorString(_T("VSSError (unable to GetErrorMessage)"));
1159 e->ReportError(MB_ICONSTOP, IDS_VSS_RUN_ERROR);
1164 * @brief Is specified file a project file?
1165 * @param [in] filepath Full path to file to check.
1166 * @return true if file is a projectfile.
1168 bool CMergeApp::IsProjectFile(const String& filepath) const
1171 paths_SplitFilename(filepath, NULL, NULL, &ext);
1172 if (string_compare_nocase(ext, ProjectFile::PROJECTFILE_EXT) == 0)
1178 bool CMergeApp::LoadProjectFile(const String& sProject, ProjectFile &project)
1180 if (sProject.empty())
1185 project.Read(sProject);
1187 catch (Poco::Exception& e)
1189 String sErr = _("Unknown error attempting to open project file");
1190 sErr += ucr::toTString(e.displayText());
1191 String msg = string_format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1192 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1199 bool CMergeApp::SaveProjectFile(const String& sProject, const ProjectFile &project)
1203 project.Save(sProject);
1205 catch (Poco::Exception& e)
1207 String sErr = _("Unknown error attempting to save project file");
1208 sErr += ucr::toTString(e.displayText());
1209 String msg = string_format_string2(_("Cannot open file\n%1\n\n%2"), sProject, sErr);
1210 AfxMessageBox(msg.c_str(), MB_ICONSTOP);
1218 * @brief Read project and perform comparison specified
1219 * @param [in] sProject Full path to project file.
1220 * @return TRUE if loading project file and starting compare succeeded.
1222 bool CMergeApp::LoadAndOpenProjectFile(const String& sProject)
1224 ProjectFile project;
1225 if (!LoadProjectFile(sProject, project))
1229 BOOL bLeftReadOnly = FALSE;
1230 BOOL bMiddleReadOnly = FALSE;
1231 BOOL bRightReadOnly = FALSE;
1232 bool bRecursive = FALSE;
1233 project.GetPaths(files, bRecursive);
1234 bLeftReadOnly = project.GetLeftReadOnly();
1235 bMiddleReadOnly = project.GetMiddleReadOnly();
1236 bRightReadOnly = project.GetRightReadOnly();
1237 if (project.HasFilter())
1239 String filter = project.GetFilter();
1240 filter = string_trim_ws(filter);
1241 m_pGlobalFileFilter->SetFilter(filter);
1243 if (project.HasSubfolders())
1244 bRecursive = project.GetSubfolders() > 0;
1246 DWORD dwFlags[3] = {
1247 files.GetPath(0).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT,
1248 files.GetPath(1).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT,
1249 files.GetPath(2).empty() ? FFILEOPEN_NONE : FFILEOPEN_PROJECT
1252 dwFlags[0] |= FFILEOPEN_READONLY;
1253 if (files.GetSize() == 2)
1256 dwFlags[1] |= FFILEOPEN_READONLY;
1260 if (bMiddleReadOnly)
1261 dwFlags[1] |= FFILEOPEN_READONLY;
1263 dwFlags[2] |= FFILEOPEN_READONLY;
1266 WriteProfileInt(_T("Settings"), _T("Recurse"), bRecursive);
1268 BOOL rtn = GetMainFrame()->DoFileOpen(&files, dwFlags, bRecursive);
1270 AddToRecentProjectsMRU(sProject.c_str());
1275 * @brief Return windows language ID of current WinMerge GUI language
1277 WORD CMergeApp::GetLangId() const
1279 return m_pLangDlg->GetLangId();
1283 * @brief Lang aware version of CStatusBar::SetIndicators()
1285 void CMergeApp::SetIndicators(CStatusBar &sb, const UINT *rgid, int n) const
1287 m_pLangDlg->SetIndicators(sb, rgid, n);
1291 * @brief Translate menu to current WinMerge GUI language
1293 void CMergeApp::TranslateMenu(HMENU h) const
1295 m_pLangDlg->TranslateMenu(h);
1299 * @brief Translate dialog to current WinMerge GUI language
1301 void CMergeApp::TranslateDialog(HWND h) const
1303 CWnd *pWnd = CWnd::FromHandle(h);
1304 pWnd->SetFont(const_cast<CFont *>(&m_fontGUI));
1305 pWnd->SendMessageToDescendants(WM_SETFONT, (WPARAM)m_fontGUI.m_hObject, MAKELPARAM(FALSE, 0), TRUE);
1307 m_pLangDlg->TranslateDialog(h);
1311 * @brief Load string and translate to current WinMerge GUI language
1313 String CMergeApp::LoadString(UINT id) const
1315 return m_pLangDlg->LoadString(id);
1318 bool CMergeApp::TranslateString(const std::string& str, String& translated_str) const
1320 return m_pLangDlg->TranslateString(str, translated_str);
1324 * @brief Load dialog caption and translate to current WinMerge GUI language
1326 std::wstring CMergeApp::LoadDialogCaption(LPCTSTR lpDialogTemplateID) const
1328 return m_pLangDlg->LoadDialogCaption(lpDialogTemplateID);
1332 * @brief Get default editor path.
1333 * @return full path to the editor program executable.
1335 String CMergeApp::GetDefaultEditor() const
1337 return paths_ConcatPath(env_GetWindowsDirectory(), _T("NOTEPAD.EXE"));
1341 * @brief Get default user filter folder path.
1342 * This function returns the default filter path for user filters.
1343 * If wanted so (@p bCreate) path can be created if it does not
1344 * exist yet. But you really want to create the patch only when
1345 * there is no user path defined.
1346 * @param [in] bCreate If TRUE filter path is created if it does
1348 * @return Default folder for user filters.
1350 String CMergeApp::GetDefaultFilterUserPath(BOOL bCreate /*=FALSE*/) const
1352 String pathMyFolders = env_GetMyDocuments();
1353 String pathFilters(pathMyFolders);
1354 pathFilters = paths_ConcatPath(pathFilters, DefaultRelativeFilterPath);
1356 if (bCreate && !paths_CreateIfNeeded(pathFilters))
1358 // Failed to create a folder, check it didn't already
1360 DWORD errCode = GetLastError();
1361 if (errCode != ERROR_ALREADY_EXISTS)
1363 // Failed to create a folder for filters, fallback to
1364 // "My Documents"-folder. It is not worth the trouble to
1365 // bother user about this or user more clever solutions.
1366 pathFilters = pathMyFolders;
1374 * @brief Adds specified file to the recent projects list.
1375 * @param [in] sPathName Path to project file
1377 void CMergeApp::AddToRecentProjectsMRU(LPCTSTR sPathName)
1379 // sPathName will be added to the top of the MRU list.
1380 // If sPathName already exists in the MRU list, it will be moved to the top
1381 if (m_pRecentFileList != NULL) {
1382 m_pRecentFileList->Add(sPathName);
1383 m_pRecentFileList->WriteList();
1387 void CMergeApp::SetupTempPath()
1389 String instTemp = env_GetPerInstanceString(TempFolderPrefix);
1390 if (GetOptionsMgr()->GetBool(OPT_USE_SYSTEM_TEMP_PATH))
1391 env_SetTempPath(paths_ConcatPath(env_GetSystemTempPath(), instTemp));
1393 env_SetTempPath(paths_ConcatPath(GetOptionsMgr()->GetString(OPT_CUSTOM_TEMP_PATH), instTemp));
1397 * @brief Handles menu selection from recent projects list
1398 * @param [in] nID Menu ID of the selected item
1400 BOOL CMergeApp::OnOpenRecentFile(UINT nID)
1402 return LoadAndOpenProjectFile((const TCHAR *)m_pRecentFileList->m_arrNames[nID-ID_FILE_MRU_FILE1]);
1406 * @brief Return if doc is in Merging/Editing mode
1408 bool CMergeApp::GetMergingMode() const
1410 return m_bMergingMode;
1414 * @brief Set doc to Merging/Editing mode
1416 void CMergeApp::SetMergingMode(bool bMergingMode)
1418 m_bMergingMode = bMergingMode;
1419 GetOptionsMgr()->SaveOption(OPT_MERGE_MODE, m_bMergingMode);
1423 * @brief Switch Merging/Editing mode and update
1424 * buffer read-only states accordingly
1426 void CMergeApp::OnMergingMode()
1428 bool bMergingMode = GetMergingMode();
1431 LangMessageBox(IDS_MERGE_MODE, MB_ICONINFORMATION | MB_DONT_DISPLAY_AGAIN);
1432 SetMergingMode(!bMergingMode);
1436 * @brief Update Menuitem for Merging Mode
1438 void CMergeApp::OnUpdateMergingMode(CCmdUI* pCmdUI)
1440 pCmdUI->Enable(true);
1441 pCmdUI->SetCheck(GetMergingMode());
1445 * @brief Update MergingMode UI in statusbar
1447 void CMergeApp::OnUpdateMergingStatus(CCmdUI *pCmdUI)
1449 String text = theApp.LoadString(IDS_MERGEMODE_MERGING);
1450 pCmdUI->SetText(text.c_str());
1451 pCmdUI->Enable(GetMergingMode());