Do not include version.h in CrashReport.h in order to speed up building
[TortoiseGit.git] / src / TortoiseMerge / TortoiseMerge.cpp
blob46e910eed0e83fbf8dc564a4231079bb7f64a38b
1 // TortoiseGitMerge - a Diff/Patch program
3 // Copyright (C) 2013 - TortoiseGit
4 // Copyright (C) 2006-2012 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (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 Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include <dlgs.h>
22 #include "TortoiseMerge.h"
23 #include "MainFrm.h"
24 #include "AboutDlg.h"
25 #include "CmdLineParser.h"
26 #include "version.h"
27 #include "AppUtils.h"
28 #include "PathUtils.h"
29 #include "BrowseFolder.h"
30 #include "DirFileEnum.h"
31 #include "SelectFileFilter.h"
32 #include "FileDlgEventHandler.h"
33 #include "TempFile.h"
34 #include "TaskbarUUID.h"
36 #ifdef _DEBUG
37 #define new DEBUG_NEW
38 #endif
40 #pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
42 BEGIN_MESSAGE_MAP(CTortoiseMergeApp, CWinAppEx)
43 ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
44 END_MESSAGE_MAP()
46 class PatchOpenDlgEventHandler : public CFileDlgEventHandler
48 public:
49 PatchOpenDlgEventHandler() {}
50 ~PatchOpenDlgEventHandler() {}
52 virtual STDMETHODIMP OnButtonClicked(IFileDialogCustomize* pfdc, DWORD dwIDCtl)
54 if (dwIDCtl == 101)
56 CComQIPtr<IFileOpenDialog> pDlg = pfdc;
57 if (pDlg)
59 pDlg->Close(S_OK);
62 return S_OK;
67 CTortoiseMergeApp::CTortoiseMergeApp()
68 : m_nAppLook(0)
70 EnableHtmlHelp();
71 m_bHiColorIcons = TRUE;
74 // The one and only CTortoiseMergeApp object
75 CTortoiseMergeApp theApp;
76 CString sOrigCWD;
77 CCrashReportTGit g_crasher(L"TortoiseGitMerge " _T(APP_X64_STRING), TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD);
79 CString g_sGroupingUUID;
81 // CTortoiseMergeApp initialization
82 BOOL CTortoiseMergeApp::InitInstance()
84 SetDllDirectory(L"");
85 SetTaskIDPerUUID();
86 CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine());
89 DWORD len = GetCurrentDirectory(0, NULL);
90 if (len)
92 std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
93 if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
95 sOrigCWD = originalCurrentDirectory.get();
96 sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
101 //set the resource dll for the required language
102 CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
103 long langId = loc;
104 CString langDll;
105 HINSTANCE hInst = NULL;
108 langDll.Format(_T("%sLanguages\\TortoiseMerge%d.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);
110 hInst = LoadLibrary(langDll);
111 CString sVer = _T(STRPRODUCTVER);
112 CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
113 if (sFileVer.Compare(sVer)!=0)
115 FreeLibrary(hInst);
116 hInst = NULL;
118 if (hInst != NULL)
119 AfxSetResourceHandle(hInst);
120 else
122 DWORD lid = SUBLANGID(langId);
123 lid--;
124 if (lid > 0)
126 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
128 else
129 langId = 0;
131 } while ((hInst == NULL) && (langId != 0));
132 TCHAR buf[6];
133 _tcscpy_s(buf, _T("en"));
134 langId = loc;
135 CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseMerge_en.chm");
136 free((void*)m_pszHelpFilePath);
137 m_pszHelpFilePath=_tcsdup(sHelppath);
138 sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm");
141 GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
142 CString sLang = _T("_");
143 sLang += buf;
144 sHelppath.Replace(_T("_en"), sLang);
145 if (PathFileExists(sHelppath))
147 free((void*)m_pszHelpFilePath);
148 m_pszHelpFilePath=_tcsdup(sHelppath);
149 break;
151 sHelppath.Replace(sLang, _T("_en"));
152 GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
153 sLang += _T("_");
154 sLang += buf;
155 sHelppath.Replace(_T("_en"), sLang);
156 if (PathFileExists(sHelppath))
158 free((void*)m_pszHelpFilePath);
159 m_pszHelpFilePath=_tcsdup(sHelppath);
160 break;
162 sHelppath.Replace(sLang, _T("_en"));
164 DWORD lid = SUBLANGID(langId);
165 lid--;
166 if (lid > 0)
168 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
170 else
171 langId = 0;
172 } while (langId);
173 setlocale(LC_ALL, "");
174 // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
175 // The problems occures when the language of OS differs from the regional settings
176 // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
177 SetThreadLocale(LOCALE_SYSTEM_DEFAULT);
179 // InitCommonControls() is required on Windows XP if an application
180 // manifest specifies use of ComCtl32.dll version 6 or later to enable
181 // visual styles. Otherwise, any window creation will fail.
182 InitCommonControls();
184 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
185 CMFCButton::EnableWindowsTheming();
186 EnableTaskbarInteraction(FALSE);
188 // Initialize all Managers for usage. They are automatically constructed
189 // if not yet present
190 InitContextMenuManager();
191 InitKeyboardManager();
192 InitTooltipManager ();
193 CMFCToolTipInfo params;
194 params.m_bVislManagerTheme = TRUE;
196 GetTooltipManager ()->SetTooltipParams (
197 AFX_TOOLTIP_TYPE_ALL,
198 RUNTIME_CLASS (CMFCToolTipCtrl),
199 &params);
201 CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);
203 g_sGroupingUUID = parser.GetVal(L"groupuuid");
205 if (parser.HasKey(_T("?")) || parser.HasKey(_T("help")))
207 CString sHelpText;
208 sHelpText.LoadString(IDS_COMMANDLINEHELP);
209 MessageBox(NULL, sHelpText, _T("TortoiseGitMerge"), MB_ICONINFORMATION);
210 return FALSE;
213 // Initialize OLE libraries
214 if (!AfxOleInit())
216 AfxMessageBox(IDP_OLE_INIT_FAILED);
217 return FALSE;
219 AfxEnableControlContainer();
220 // Standard initialization
221 // If you are not using these features and wish to reduce the size
222 // of your final executable, you should remove from the following
223 // the specific initialization routines you do not need
224 // Change the registry key under which our settings are stored
225 SetRegistryKey(_T("TortoiseGitMerge"));
227 if (CRegDWORD(_T("Software\\TortoiseGitMerge\\Debug"), FALSE)==TRUE)
228 AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);
230 // To create the main window, this code creates a new frame window
231 // object and then sets it as the application's main window object
232 CMainFrame* pFrame = new CMainFrame;
233 if (pFrame == NULL)
234 return FALSE;
235 m_pMainWnd = pFrame;
237 // create and load the frame with its resources
238 if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL))
239 return FALSE;
241 // Fill in the command line options
242 pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(_T("base")));
243 pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(_T("basename")));
244 pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(_T("theirs")));
245 pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(_T("theirsname")));
246 pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(_T("mine")));
247 pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(_T("minename")));
248 pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(_T("merged")));
249 pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(_T("mergedname")));
250 pFrame->m_Data.m_sPatchPath = parser.HasVal(_T("patchpath")) ? parser.GetVal(_T("patchpath")) : _T("");
251 pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
252 if (parser.HasKey(_T("patchoriginal")))
253 pFrame->m_Data.m_sPatchOriginal = parser.GetVal(_T("patchoriginal"));
254 if (parser.HasKey(_T("patchpatched")))
255 pFrame->m_Data.m_sPatchPatched = parser.GetVal(_T("patchpatched"));
256 pFrame->m_Data.m_sDiffFile = parser.GetVal(_T("diff"));
257 pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
258 if (parser.HasKey(_T("oneway")))
259 pFrame->m_bOneWay = TRUE;
260 if (parser.HasKey(_T("diff")))
261 pFrame->m_bOneWay = FALSE;
262 if (parser.HasKey(_T("reversedpatch")))
263 pFrame->m_bReversedPatch = TRUE;
264 if (parser.HasKey(_T("saverequired")))
265 pFrame->m_bSaveRequired = true;
266 if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
268 pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
271 if ((!parser.HasKey(_T("patchpath")))&&(parser.HasVal(_T("diff"))))
273 // a patchfile was given, but not folder path to apply the patch to
274 // If the patchfile is located inside a working copy, then use the parent directory
275 // of the patchfile as the target directory, otherwise ask the user for a path.
276 if (parser.HasKey(_T("wc")))
277 pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
278 else
280 CBrowseFolder fbrowser;
281 fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
282 if (fbrowser.Show(NULL, pFrame->m_Data.m_sPatchPath)==CBrowseFolder::CANCEL)
283 return FALSE;
287 if ((parser.HasKey(_T("patchpath")))&&(!parser.HasVal(_T("diff"))))
289 // A path was given for applying a patchfile, but
290 // the patchfile itself was not.
291 // So ask the user for that patchfile
293 HRESULT hr;
294 // Create a new common save file dialog
295 CComPtr<IFileOpenDialog> pfd = NULL;
296 hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER);
297 if (SUCCEEDED(hr))
299 // Set the dialog options
300 DWORD dwOptions;
301 if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions)))
303 hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
306 // Set a title
307 if (SUCCEEDED(hr))
309 CString temp;
310 temp.LoadString(IDS_OPENDIFFFILETITLE);
311 pfd->SetTitle(temp);
313 CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
314 hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter);
315 bool bAdvised = false;
316 DWORD dwCookie = 0;
317 CComObjectStackEx<PatchOpenDlgEventHandler> cbk;
318 CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();
321 CComPtr<IFileDialogCustomize> pfdCustomize;
322 hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize));
323 if (SUCCEEDED(hr))
325 // check if there's a unified diff on the clipboard and
326 // add a button to the fileopen dialog if there is.
327 UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
328 if ((cFormat)&&(OpenClipboard(NULL)))
330 HGLOBAL hglb = GetClipboardData(cFormat);
331 if (hglb)
333 pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD)));
334 hr = pfd->Advise(pEvents, &dwCookie);
335 bAdvised = SUCCEEDED(hr);
337 CloseClipboard();
342 // Show the save file dialog
343 if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd)))
345 // Get the selection from the user
346 CComPtr<IShellItem> psiResult = NULL;
347 hr = pfd->GetResult(&psiResult);
348 if (bAdvised)
349 pfd->Unadvise(dwCookie);
350 if (SUCCEEDED(hr))
352 PWSTR pszPath = NULL;
353 hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
354 if (SUCCEEDED(hr))
356 pFrame->m_Data.m_sDiffFile = pszPath;
357 CoTaskMemFree(pszPath);
360 else
362 // no result, which means we closed the dialog in our button handler
363 std::wstring sTempFile;
364 if (TrySavePatchFromClipboard(sTempFile))
365 pFrame->m_Data.m_sDiffFile = sTempFile.c_str();
368 else
370 if (bAdvised)
371 pfd->Unadvise(dwCookie);
372 return FALSE;
375 else
377 OPENFILENAME ofn = {0}; // common dialog box structure
378 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name
379 // Initialize OPENFILENAME
380 ofn.lStructSize = sizeof(OPENFILENAME);
381 ofn.hwndOwner = pFrame->m_hWnd;
382 ofn.lpstrFile = szFile;
383 ofn.nMaxFile = _countof(szFile);
384 CString temp;
385 temp.LoadString(IDS_OPENDIFFFILETITLE);
386 if (temp.IsEmpty())
387 ofn.lpstrTitle = NULL;
388 else
389 ofn.lpstrTitle = temp;
391 ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
392 if( HasClipboardPatch() ) {
393 ofn.Flags |= ( OFN_ENABLETEMPLATE | OFN_ENABLEHOOK );
394 ofn.hInstance = AfxGetResourceHandle();
395 ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM);
396 ofn.lpfnHook = CreatePatchFileOpenHook;
399 CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
400 ofn.lpstrFilter = fileFilter;
401 ofn.nFilterIndex = 1;
403 // Display the Open dialog box.
404 if (GetOpenFileName(&ofn)==FALSE)
406 return FALSE;
408 pFrame->m_Data.m_sDiffFile = ofn.lpstrFile;
412 if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
414 int nArgs;
415 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
416 if( NULL == szArglist )
418 TRACE("CommandLineToArgvW failed\n");
420 else
422 if ( nArgs==3 || nArgs==4 )
424 // Four parameters:
425 // [0]: Program name
426 // [1]: BASE file
427 // [2]: my file
428 // [3]: THEIR file (optional)
429 // This is the same format CAppUtils::StartExtDiff
430 // uses if %base and %mine are not set and most
431 // other diff tools use it too.
432 if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
434 pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
435 pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
436 if ( nArgs == 4 && PathFileExists(szArglist[3]) )
438 pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
444 // Free memory allocated for CommandLineToArgvW arguments.
445 LocalFree(szArglist);
448 pFrame->m_bReadOnly = !!parser.HasKey(_T("readonly"));
449 if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
450 pFrame->m_bReadOnly = true;
451 pFrame->m_bBlame = !!parser.HasKey(_T("blame"));
452 // diffing a blame means no editing!
453 if (pFrame->m_bBlame)
454 pFrame->m_bReadOnly = true;
456 pFrame->SetWindowTitle();
458 if (parser.HasKey(_T("createunifieddiff")))
460 // user requested to create a unified diff file
461 CString origFile = parser.GetVal(_T("origfile"));
462 CString modifiedFile = parser.GetVal(_T("modifiedfile"));
463 if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
465 CString outfile = parser.GetVal(_T("outfile"));
466 if (outfile.IsEmpty())
468 CCommonAppUtils::FileOpenSave(outfile, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, NULL);
470 if (!outfile.IsEmpty())
472 CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, false);
473 return FALSE;
478 #if 0
479 pFrame->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0;
480 pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
481 pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0;
482 #endif
484 // The one and only window has been initialized, so show and update it
485 pFrame->ActivateFrame();
486 pFrame->ShowWindow(SW_SHOW);
487 pFrame->UpdateWindow();
488 pFrame->ShowDiffBar(!pFrame->m_bOneWay);
489 if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
491 pFrame->OnFileOpen();
492 return TRUE;
495 int line = -2;
496 if (parser.HasVal(_T("line")))
498 line = parser.GetLongVal(_T("line"));
499 line--; // we need the index
502 return pFrame->LoadViews(line);
505 // CTortoiseMergeApp message handlers
507 void CTortoiseMergeApp::OnAppAbout()
509 CAboutDlg aboutDlg;
510 aboutDlg.DoModal();
513 UINT_PTR CALLBACK
514 CTortoiseMergeApp::CreatePatchFileOpenHook(HWND hDlg, UINT uiMsg, WPARAM wParam, LPARAM /*lParam*/)
516 if(uiMsg == WM_COMMAND && LOWORD(wParam) == IDC_PATCH_TO_CLIPBOARD)
518 HWND hFileDialog = GetParent(hDlg);
520 // if there's a patchfile in the clipboard, we save it
521 // to a temporary file and tell TortoiseMerge to use that one
522 std::wstring sTempFile;
523 if (TrySavePatchFromClipboard(sTempFile))
525 CommDlg_OpenSave_SetControlText(hFileDialog, edt1, sTempFile.c_str());
526 PostMessage(hFileDialog, WM_COMMAND, MAKEWPARAM(IDOK, BM_CLICK), (LPARAM)(GetDlgItem(hDlg, IDOK)));
529 return 0;
532 int CTortoiseMergeApp::ExitInstance()
534 // Look for temporary files left around by TortoiseMerge and
535 // remove them. But only delete 'old' files
536 CTempFiles::DeleteOldTempFiles(_T("*tsm*.*"));
538 return CWinAppEx::ExitInstance();
541 bool CTortoiseMergeApp::HasClipboardPatch()
543 // check if there's a patchfile in the clipboard
544 const UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
545 if (cFormat == 0)
546 return false;
548 if (OpenClipboard(NULL) == 0)
549 return false;
551 bool containsPatch = false;
552 UINT enumFormat = 0;
555 if (enumFormat == cFormat)
557 containsPatch = true; // yes, there's a patchfile in the clipboard
559 } while((enumFormat = EnumClipboardFormats(enumFormat))!=0);
560 CloseClipboard();
562 return containsPatch;
565 bool CTortoiseMergeApp::TrySavePatchFromClipboard(std::wstring& resultFile)
567 resultFile.clear();
569 UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
570 if (cFormat == 0)
571 return false;
572 if (OpenClipboard(NULL) == 0)
573 return false;
575 HGLOBAL hglb = GetClipboardData(cFormat);
576 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
578 DWORD len = GetTempPath(0, NULL);
579 std::unique_ptr<TCHAR[]> path(new TCHAR[len+1]);
580 std::unique_ptr<TCHAR[]> tempF(new TCHAR[len+100]);
581 GetTempPath (len+1, path.get());
582 GetTempFileName (path.get(), _T("tsm"), 0, tempF.get());
583 std::wstring sTempFile = std::wstring(tempF.get());
585 FILE* outFile = 0;
586 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
587 if (outFile != 0)
589 size_t patchlen = strlen(lpstr);
590 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
591 if (size == patchlen)
592 resultFile = sTempFile;
594 fclose(outFile);
596 GlobalUnlock(hglb);
597 CloseClipboard();
599 return !resultFile.empty();