Use project properties for reading bugtraq settings
[TortoiseGit.git] / src / TortoiseMerge / TortoiseMerge.cpp
blob551eb5e24913d5189e2d00e7a7954c2f2a51c34d
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 #if ENABLE_CRASHHANLDER
78 CCrashReportTGit g_crasher(L"TortoiseGitMerge " _T(APP_X64_STRING), TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD, TGIT_VERDATE);
79 #endif
81 CString g_sGroupingUUID;
83 // CTortoiseMergeApp initialization
84 BOOL CTortoiseMergeApp::InitInstance()
86 SetDllDirectory(L"");
87 SetTaskIDPerUUID();
88 CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine());
91 DWORD len = GetCurrentDirectory(0, NULL);
92 if (len)
94 std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
95 if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
97 sOrigCWD = originalCurrentDirectory.get();
98 sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
103 //set the resource dll for the required language
104 CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
105 long langId = loc;
106 CString langDll;
107 HINSTANCE hInst = NULL;
110 langDll.Format(_T("%sLanguages\\TortoiseMerge%d.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);
112 hInst = LoadLibrary(langDll);
113 CString sVer = _T(STRPRODUCTVER);
114 CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
115 if (sFileVer.Compare(sVer)!=0)
117 FreeLibrary(hInst);
118 hInst = NULL;
120 if (hInst != NULL)
121 AfxSetResourceHandle(hInst);
122 else
124 DWORD lid = SUBLANGID(langId);
125 lid--;
126 if (lid > 0)
128 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
130 else
131 langId = 0;
133 } while ((hInst == NULL) && (langId != 0));
134 TCHAR buf[6];
135 _tcscpy_s(buf, _T("en"));
136 langId = loc;
137 CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseMerge_en.chm");
138 free((void*)m_pszHelpFilePath);
139 m_pszHelpFilePath=_tcsdup(sHelppath);
140 sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm");
143 GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
144 CString sLang = _T("_");
145 sLang += buf;
146 sHelppath.Replace(_T("_en"), sLang);
147 if (PathFileExists(sHelppath))
149 free((void*)m_pszHelpFilePath);
150 m_pszHelpFilePath=_tcsdup(sHelppath);
151 break;
153 sHelppath.Replace(sLang, _T("_en"));
154 GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
155 sLang += _T("_");
156 sLang += buf;
157 sHelppath.Replace(_T("_en"), sLang);
158 if (PathFileExists(sHelppath))
160 free((void*)m_pszHelpFilePath);
161 m_pszHelpFilePath=_tcsdup(sHelppath);
162 break;
164 sHelppath.Replace(sLang, _T("_en"));
166 DWORD lid = SUBLANGID(langId);
167 lid--;
168 if (lid > 0)
170 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
172 else
173 langId = 0;
174 } while (langId);
175 setlocale(LC_ALL, "");
176 // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
177 // The problems occures when the language of OS differs from the regional settings
178 // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
179 SetThreadLocale(LOCALE_SYSTEM_DEFAULT);
181 // InitCommonControls() is required on Windows XP if an application
182 // manifest specifies use of ComCtl32.dll version 6 or later to enable
183 // visual styles. Otherwise, any window creation will fail.
184 InitCommonControls();
186 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
187 CMFCButton::EnableWindowsTheming();
188 EnableTaskbarInteraction(FALSE);
190 // Initialize all Managers for usage. They are automatically constructed
191 // if not yet present
192 InitContextMenuManager();
193 InitKeyboardManager();
194 InitTooltipManager ();
195 CMFCToolTipInfo params;
196 params.m_bVislManagerTheme = TRUE;
198 GetTooltipManager ()->SetTooltipParams (
199 AFX_TOOLTIP_TYPE_ALL,
200 RUNTIME_CLASS (CMFCToolTipCtrl),
201 &params);
203 CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);
205 g_sGroupingUUID = parser.GetVal(L"groupuuid");
207 if (parser.HasKey(_T("?")) || parser.HasKey(_T("help")))
209 CString sHelpText;
210 sHelpText.LoadString(IDS_COMMANDLINEHELP);
211 MessageBox(NULL, sHelpText, _T("TortoiseGitMerge"), MB_ICONINFORMATION);
212 return FALSE;
215 // Initialize OLE libraries
216 if (!AfxOleInit())
218 AfxMessageBox(IDP_OLE_INIT_FAILED);
219 return FALSE;
221 AfxEnableControlContainer();
222 // Standard initialization
223 // If you are not using these features and wish to reduce the size
224 // of your final executable, you should remove from the following
225 // the specific initialization routines you do not need
226 // Change the registry key under which our settings are stored
227 SetRegistryKey(_T("TortoiseGitMerge"));
229 if (CRegDWORD(_T("Software\\TortoiseGitMerge\\Debug"), FALSE)==TRUE)
230 AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);
232 // To create the main window, this code creates a new frame window
233 // object and then sets it as the application's main window object
234 CMainFrame* pFrame = new CMainFrame;
235 if (pFrame == NULL)
236 return FALSE;
237 m_pMainWnd = pFrame;
239 // create and load the frame with its resources
240 if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL))
241 return FALSE;
243 // Fill in the command line options
244 pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(_T("base")));
245 pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(_T("basename")));
246 pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(_T("theirs")));
247 pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(_T("theirsname")));
248 pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(_T("mine")));
249 pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(_T("minename")));
250 pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(_T("merged")));
251 pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(_T("mergedname")));
252 pFrame->m_Data.m_sPatchPath = parser.HasVal(_T("patchpath")) ? parser.GetVal(_T("patchpath")) : _T("");
253 pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
254 if (parser.HasKey(_T("patchoriginal")))
255 pFrame->m_Data.m_sPatchOriginal = parser.GetVal(_T("patchoriginal"));
256 if (parser.HasKey(_T("patchpatched")))
257 pFrame->m_Data.m_sPatchPatched = parser.GetVal(_T("patchpatched"));
258 pFrame->m_Data.m_sDiffFile = parser.GetVal(_T("diff"));
259 pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
260 if (parser.HasKey(_T("oneway")))
261 pFrame->m_bOneWay = TRUE;
262 if (parser.HasKey(_T("diff")))
263 pFrame->m_bOneWay = FALSE;
264 if (parser.HasKey(_T("reversedpatch")))
265 pFrame->m_bReversedPatch = TRUE;
266 if (parser.HasKey(_T("saverequired")))
267 pFrame->m_bSaveRequired = true;
268 if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
270 pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
273 if ((!parser.HasKey(_T("patchpath")))&&(parser.HasVal(_T("diff"))))
275 // a patchfile was given, but not folder path to apply the patch to
276 // If the patchfile is located inside a working copy, then use the parent directory
277 // of the patchfile as the target directory, otherwise ask the user for a path.
278 if (parser.HasKey(_T("wc")))
279 pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
280 else
282 CBrowseFolder fbrowser;
283 fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
284 if (fbrowser.Show(NULL, pFrame->m_Data.m_sPatchPath)==CBrowseFolder::CANCEL)
285 return FALSE;
289 if ((parser.HasKey(_T("patchpath")))&&(!parser.HasVal(_T("diff"))))
291 // A path was given for applying a patchfile, but
292 // the patchfile itself was not.
293 // So ask the user for that patchfile
295 HRESULT hr;
296 // Create a new common save file dialog
297 CComPtr<IFileOpenDialog> pfd = NULL;
298 hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER);
299 if (SUCCEEDED(hr))
301 // Set the dialog options
302 DWORD dwOptions;
303 if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions)))
305 hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
308 // Set a title
309 if (SUCCEEDED(hr))
311 CString temp;
312 temp.LoadString(IDS_OPENDIFFFILETITLE);
313 pfd->SetTitle(temp);
315 CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
316 hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter);
317 bool bAdvised = false;
318 DWORD dwCookie = 0;
319 CComObjectStackEx<PatchOpenDlgEventHandler> cbk;
320 CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();
323 CComPtr<IFileDialogCustomize> pfdCustomize;
324 hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize));
325 if (SUCCEEDED(hr))
327 // check if there's a unified diff on the clipboard and
328 // add a button to the fileopen dialog if there is.
329 UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
330 if ((cFormat)&&(OpenClipboard(NULL)))
332 HGLOBAL hglb = GetClipboardData(cFormat);
333 if (hglb)
335 pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD)));
336 hr = pfd->Advise(pEvents, &dwCookie);
337 bAdvised = SUCCEEDED(hr);
339 CloseClipboard();
344 // Show the save file dialog
345 if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd)))
347 // Get the selection from the user
348 CComPtr<IShellItem> psiResult = NULL;
349 hr = pfd->GetResult(&psiResult);
350 if (bAdvised)
351 pfd->Unadvise(dwCookie);
352 if (SUCCEEDED(hr))
354 PWSTR pszPath = NULL;
355 hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
356 if (SUCCEEDED(hr))
358 pFrame->m_Data.m_sDiffFile = pszPath;
359 CoTaskMemFree(pszPath);
362 else
364 // no result, which means we closed the dialog in our button handler
365 std::wstring sTempFile;
366 if (TrySavePatchFromClipboard(sTempFile))
367 pFrame->m_Data.m_sDiffFile = sTempFile.c_str();
370 else
372 if (bAdvised)
373 pfd->Unadvise(dwCookie);
374 return FALSE;
377 else
379 OPENFILENAME ofn = {0}; // common dialog box structure
380 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name
381 // Initialize OPENFILENAME
382 ofn.lStructSize = sizeof(OPENFILENAME);
383 ofn.hwndOwner = pFrame->m_hWnd;
384 ofn.lpstrFile = szFile;
385 ofn.nMaxFile = _countof(szFile);
386 CString temp;
387 temp.LoadString(IDS_OPENDIFFFILETITLE);
388 if (temp.IsEmpty())
389 ofn.lpstrTitle = NULL;
390 else
391 ofn.lpstrTitle = temp;
393 ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
394 if( HasClipboardPatch() ) {
395 ofn.Flags |= ( OFN_ENABLETEMPLATE | OFN_ENABLEHOOK );
396 ofn.hInstance = AfxGetResourceHandle();
397 ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM);
398 ofn.lpfnHook = CreatePatchFileOpenHook;
401 CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
402 ofn.lpstrFilter = fileFilter;
403 ofn.nFilterIndex = 1;
405 // Display the Open dialog box.
406 if (GetOpenFileName(&ofn)==FALSE)
408 return FALSE;
410 pFrame->m_Data.m_sDiffFile = ofn.lpstrFile;
414 if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
416 int nArgs;
417 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
418 if( NULL == szArglist )
420 TRACE("CommandLineToArgvW failed\n");
422 else
424 if ( nArgs==3 || nArgs==4 )
426 // Four parameters:
427 // [0]: Program name
428 // [1]: BASE file
429 // [2]: my file
430 // [3]: THEIR file (optional)
431 // This is the same format CAppUtils::StartExtDiff
432 // uses if %base and %mine are not set and most
433 // other diff tools use it too.
434 if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
436 pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
437 pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
438 if ( nArgs == 4 && PathFileExists(szArglist[3]) )
440 pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
446 // Free memory allocated for CommandLineToArgvW arguments.
447 LocalFree(szArglist);
450 pFrame->m_bReadOnly = !!parser.HasKey(_T("readonly"));
451 if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
452 pFrame->m_bReadOnly = true;
453 pFrame->m_bBlame = !!parser.HasKey(_T("blame"));
454 // diffing a blame means no editing!
455 if (pFrame->m_bBlame)
456 pFrame->m_bReadOnly = true;
458 pFrame->SetWindowTitle();
460 if (parser.HasKey(_T("createunifieddiff")))
462 // user requested to create a unified diff file
463 CString origFile = parser.GetVal(_T("origfile"));
464 CString modifiedFile = parser.GetVal(_T("modifiedfile"));
465 if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
467 CString outfile = parser.GetVal(_T("outfile"));
468 if (outfile.IsEmpty())
470 CCommonAppUtils::FileOpenSave(outfile, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, NULL);
472 if (!outfile.IsEmpty())
474 CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, false);
475 return FALSE;
480 #if 0
481 pFrame->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0;
482 pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
483 pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0;
484 #endif
486 // The one and only window has been initialized, so show and update it
487 pFrame->ActivateFrame();
488 pFrame->ShowWindow(SW_SHOW);
489 pFrame->UpdateWindow();
490 pFrame->ShowDiffBar(!pFrame->m_bOneWay);
491 if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
493 pFrame->OnFileOpen();
494 return TRUE;
497 int line = -2;
498 if (parser.HasVal(_T("line")))
500 line = parser.GetLongVal(_T("line"));
501 line--; // we need the index
504 return pFrame->LoadViews(line);
507 // CTortoiseMergeApp message handlers
509 void CTortoiseMergeApp::OnAppAbout()
511 CAboutDlg aboutDlg;
512 aboutDlg.DoModal();
515 UINT_PTR CALLBACK
516 CTortoiseMergeApp::CreatePatchFileOpenHook(HWND hDlg, UINT uiMsg, WPARAM wParam, LPARAM /*lParam*/)
518 if(uiMsg == WM_COMMAND && LOWORD(wParam) == IDC_PATCH_TO_CLIPBOARD)
520 HWND hFileDialog = GetParent(hDlg);
522 // if there's a patchfile in the clipboard, we save it
523 // to a temporary file and tell TortoiseMerge to use that one
524 std::wstring sTempFile;
525 if (TrySavePatchFromClipboard(sTempFile))
527 CommDlg_OpenSave_SetControlText(hFileDialog, edt1, sTempFile.c_str());
528 PostMessage(hFileDialog, WM_COMMAND, MAKEWPARAM(IDOK, BM_CLICK), (LPARAM)(GetDlgItem(hDlg, IDOK)));
531 return 0;
534 int CTortoiseMergeApp::ExitInstance()
536 // Look for temporary files left around by TortoiseMerge and
537 // remove them. But only delete 'old' files
538 CTempFiles::DeleteOldTempFiles(_T("*tsm*.*"));
540 return CWinAppEx::ExitInstance();
543 bool CTortoiseMergeApp::HasClipboardPatch()
545 // check if there's a patchfile in the clipboard
546 const UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
547 if (cFormat == 0)
548 return false;
550 if (OpenClipboard(NULL) == 0)
551 return false;
553 bool containsPatch = false;
554 UINT enumFormat = 0;
557 if (enumFormat == cFormat)
559 containsPatch = true; // yes, there's a patchfile in the clipboard
561 } while((enumFormat = EnumClipboardFormats(enumFormat))!=0);
562 CloseClipboard();
564 return containsPatch;
567 bool CTortoiseMergeApp::TrySavePatchFromClipboard(std::wstring& resultFile)
569 resultFile.clear();
571 UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
572 if (cFormat == 0)
573 return false;
574 if (OpenClipboard(NULL) == 0)
575 return false;
577 HGLOBAL hglb = GetClipboardData(cFormat);
578 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
580 DWORD len = GetTempPath(0, NULL);
581 std::unique_ptr<TCHAR[]> path(new TCHAR[len+1]);
582 std::unique_ptr<TCHAR[]> tempF(new TCHAR[len+100]);
583 GetTempPath (len+1, path.get());
584 GetTempFileName (path.get(), _T("tsm"), 0, tempF.get());
585 std::wstring sTempFile = std::wstring(tempF.get());
587 FILE* outFile = 0;
588 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
589 if (outFile != 0)
591 size_t patchlen = strlen(lpstr);
592 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
593 if (size == patchlen)
594 resultFile = sTempFile;
596 fclose(outFile);
598 GlobalUnlock(hglb);
599 CloseClipboard();
601 return !resultFile.empty();