1 // TortoiseGitMerge - a Diff/Patch program
3 // Copyright (C) 2013-2015 - TortoiseGit
4 // Copyright (C) 2006-2014 - 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.
22 #include "TortoiseMerge.h"
25 #include "CmdLineParser.h"
28 #include "PathUtils.h"
29 #include "BrowseFolder.h"
30 #include "DirFileEnum.h"
31 #include "SelectFileFilter.h"
32 #include "FileDlgEventHandler.h"
34 #include "TaskbarUUID.h"
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
)
46 class PatchOpenDlgEventHandler
: public CFileDlgEventHandler
49 PatchOpenDlgEventHandler() {}
50 ~PatchOpenDlgEventHandler() {}
52 virtual STDMETHODIMP
OnButtonClicked(IFileDialogCustomize
* pfdc
, DWORD dwIDCtl
)
56 CComQIPtr
<IFileOpenDialog
> pDlg
= pfdc
;
67 CTortoiseMergeApp::CTortoiseMergeApp()
71 m_bHiColorIcons
= TRUE
;
75 CTortoiseMergeApp::~CTortoiseMergeApp()
77 git_libgit2_shutdown();
80 // The one and only CTortoiseMergeApp object
81 CTortoiseMergeApp theApp
;
83 #if ENABLE_CRASHHANLDER
84 CCrashReportTGit
g_crasher(L
"TortoiseGitMerge " _T(APP_X64_STRING
), TGIT_VERMAJOR
, TGIT_VERMINOR
, TGIT_VERMICRO
, TGIT_VERBUILD
, TGIT_VERDATE
);
87 CString g_sGroupingUUID
;
88 CString g_sGroupingIcon
;
89 bool g_bGroupingRemoveIcon
= false;
91 // CTortoiseMergeApp initialization
92 BOOL
CTortoiseMergeApp::InitInstance()
96 CCrashReport::Instance().AddUserInfoToReport(L
"CommandLine", GetCommandLine());
99 DWORD len
= GetCurrentDirectory(0, NULL
);
102 std::unique_ptr
<TCHAR
[]> originalCurrentDirectory(new TCHAR
[len
]);
103 if (GetCurrentDirectory(len
, originalCurrentDirectory
.get()))
105 sOrigCWD
= originalCurrentDirectory
.get();
106 sOrigCWD
= CPathUtils::GetLongPathname(sOrigCWD
);
111 //set the resource dll for the required language
112 CRegDWORD loc
= CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
115 HINSTANCE hInst
= NULL
;
118 langDll
.Format(_T("%sLanguages\\TortoiseMerge%ld.dll"), (LPCTSTR
)CPathUtils::GetAppParentDirectory(), langId
);
120 hInst
= LoadLibrary(langDll
);
121 CString sVer
= _T(STRPRODUCTVER
);
122 CString sFileVer
= CPathUtils::GetVersionFromFile(langDll
);
123 if (sFileVer
.Compare(sVer
)!=0)
129 AfxSetResourceHandle(hInst
);
132 DWORD lid
= SUBLANGID(langId
);
136 langId
= MAKELANGID(PRIMARYLANGID(langId
), lid
);
141 } while ((hInst
== NULL
) && (langId
!= 0));
142 TCHAR buf
[6] = { 0 };
143 _tcscpy_s(buf
, _T("en"));
145 CString sHelppath
= CPathUtils::GetAppDirectory() + _T("TortoiseMerge_en.chm");
146 free((void*)m_pszHelpFilePath
);
147 m_pszHelpFilePath
=_tcsdup(sHelppath
);
148 sHelppath
= CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm");
151 GetLocaleInfo(MAKELCID(langId
, SORT_DEFAULT
), LOCALE_SISO639LANGNAME
, buf
, _countof(buf
));
152 CString sLang
= _T("_");
154 sHelppath
.Replace(_T("_en"), sLang
);
155 if (PathFileExists(sHelppath
))
157 free((void*)m_pszHelpFilePath
);
158 m_pszHelpFilePath
=_tcsdup(sHelppath
);
161 sHelppath
.Replace(sLang
, _T("_en"));
162 GetLocaleInfo(MAKELCID(langId
, SORT_DEFAULT
), LOCALE_SISO3166CTRYNAME
, buf
, _countof(buf
));
165 sHelppath
.Replace(_T("_en"), sLang
);
166 if (PathFileExists(sHelppath
))
168 free((void*)m_pszHelpFilePath
);
169 m_pszHelpFilePath
=_tcsdup(sHelppath
);
172 sHelppath
.Replace(sLang
, _T("_en"));
174 DWORD lid
= SUBLANGID(langId
);
178 langId
= MAKELANGID(PRIMARYLANGID(langId
), lid
);
183 setlocale(LC_ALL
, "");
184 // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
185 // The problems occures when the language of OS differs from the regional settings
186 // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
187 SetThreadLocale(LOCALE_SYSTEM_DEFAULT
);
189 // InitCommonControls() is required on Windows XP if an application
190 // manifest specifies use of ComCtl32.dll version 6 or later to enable
191 // visual styles. Otherwise, any window creation will fail.
192 InitCommonControls();
194 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows
));
195 CMFCButton::EnableWindowsTheming();
196 EnableTaskbarInteraction(FALSE
);
198 // Initialize all Managers for usage. They are automatically constructed
199 // if not yet present
200 InitContextMenuManager();
201 InitKeyboardManager();
202 InitTooltipManager ();
203 CMFCToolTipInfo params
;
204 params
.m_bVislManagerTheme
= TRUE
;
206 GetTooltipManager ()->SetTooltipParams (
207 AFX_TOOLTIP_TYPE_ALL
,
208 RUNTIME_CLASS (CMFCToolTipCtrl
),
211 CCmdLineParser parser
= CCmdLineParser(this->m_lpCmdLine
);
213 g_sGroupingUUID
= parser
.GetVal(L
"groupuuid");
215 if (parser
.HasKey(_T("?")) || parser
.HasKey(_T("help")))
218 sHelpText
.LoadString(IDS_COMMANDLINEHELP
);
219 MessageBox(NULL
, sHelpText
, _T("TortoiseGitMerge"), MB_ICONINFORMATION
);
223 // Initialize OLE libraries
226 AfxMessageBox(IDP_OLE_INIT_FAILED
);
229 AfxEnableControlContainer();
230 // Standard initialization
231 // If you are not using these features and wish to reduce the size
232 // of your final executable, you should remove from the following
233 // the specific initialization routines you do not need
234 // Change the registry key under which our settings are stored
235 SetRegistryKey(_T("TortoiseGitMerge"));
237 if (CRegDWORD(_T("Software\\TortoiseGitMerge\\Debug"), FALSE
)==TRUE
)
238 AfxMessageBox(AfxGetApp()->m_lpCmdLine
, MB_OK
| MB_ICONINFORMATION
);
240 // To create the main window, this code creates a new frame window
241 // object and then sets it as the application's main window object
242 CMainFrame
* pFrame
= new CMainFrame
;
247 // create and load the frame with its resources
248 if (!pFrame
->LoadFrame(IDR_MAINFRAME
, WS_OVERLAPPEDWINDOW
| FWS_ADDTOTITLE
, NULL
, NULL
))
251 // Fill in the command line options
252 pFrame
->m_Data
.m_baseFile
.SetFileName(parser
.GetVal(_T("base")));
253 pFrame
->m_Data
.m_baseFile
.SetDescriptiveName(parser
.GetVal(_T("basename")));
254 pFrame
->m_Data
.m_baseFile
.SetReflectedName(parser
.GetVal(_T("basereflectedname")));
255 pFrame
->m_Data
.m_theirFile
.SetFileName(parser
.GetVal(_T("theirs")));
256 pFrame
->m_Data
.m_theirFile
.SetDescriptiveName(parser
.GetVal(_T("theirsname")));
257 pFrame
->m_Data
.m_theirFile
.SetReflectedName(parser
.GetVal(_T("theirsreflectedname")));
258 pFrame
->m_Data
.m_yourFile
.SetFileName(parser
.GetVal(_T("mine")));
259 pFrame
->m_Data
.m_yourFile
.SetDescriptiveName(parser
.GetVal(_T("minename")));
260 pFrame
->m_Data
.m_yourFile
.SetReflectedName(parser
.GetVal(_T("minereflectedname")));
261 pFrame
->m_Data
.m_mergedFile
.SetFileName(parser
.GetVal(_T("merged")));
262 pFrame
->m_Data
.m_mergedFile
.SetDescriptiveName(parser
.GetVal(_T("mergedname")));
263 pFrame
->m_Data
.m_mergedFile
.SetReflectedName(parser
.GetVal(_T("mergedreflectedname")));
264 pFrame
->m_Data
.m_sPatchPath
= parser
.HasVal(_T("patchpath")) ? parser
.GetVal(_T("patchpath")) : _T("");
265 pFrame
->m_Data
.m_sPatchPath
.Replace('/', '\\');
266 if (parser
.HasKey(_T("patchoriginal")))
267 pFrame
->m_Data
.m_sPatchOriginal
= parser
.GetVal(_T("patchoriginal"));
268 if (parser
.HasKey(_T("patchpatched")))
269 pFrame
->m_Data
.m_sPatchPatched
= parser
.GetVal(_T("patchpatched"));
270 pFrame
->m_Data
.m_sDiffFile
= parser
.GetVal(_T("diff"));
271 pFrame
->m_Data
.m_sDiffFile
.Replace('/', '\\');
272 if (parser
.HasKey(_T("oneway")))
273 pFrame
->m_bOneWay
= TRUE
;
274 if (parser
.HasKey(_T("diff")))
275 pFrame
->m_bOneWay
= FALSE
;
276 if (parser
.HasKey(_T("reversedpatch")))
277 pFrame
->m_bReversedPatch
= TRUE
;
278 if (parser
.HasKey(_T("saverequired")))
279 pFrame
->m_bSaveRequired
= true;
280 if (parser
.HasKey(_T("saverequiredonconflicts")))
281 pFrame
->m_bSaveRequiredOnConflicts
= true;
282 if (parser
.HasKey(_T("deletebasetheirsmineonclose")))
283 pFrame
->m_bDeleteBaseTheirsMineOnClose
= true;
284 if (pFrame
->m_Data
.IsBaseFileInUse() && !pFrame
->m_Data
.IsYourFileInUse() && pFrame
->m_Data
.IsTheirFileInUse())
286 pFrame
->m_Data
.m_yourFile
.TransferDetailsFrom(pFrame
->m_Data
.m_theirFile
);
289 if ((!parser
.HasKey(_T("patchpath")))&&(parser
.HasVal(_T("diff"))))
291 // a patchfile was given, but not folder path to apply the patch to
292 // If the patchfile is located inside a working copy, then use the parent directory
293 // of the patchfile as the target directory, otherwise ask the user for a path.
294 if (parser
.HasKey(_T("wc")))
295 pFrame
->m_Data
.m_sPatchPath
= pFrame
->m_Data
.m_sDiffFile
.Left(pFrame
->m_Data
.m_sDiffFile
.ReverseFind('\\'));
298 CBrowseFolder fbrowser
;
299 fbrowser
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
300 if (fbrowser
.Show(NULL
, pFrame
->m_Data
.m_sPatchPath
)==CBrowseFolder::CANCEL
)
305 if ((parser
.HasKey(_T("patchpath")))&&(!parser
.HasVal(_T("diff"))))
307 // A path was given for applying a patchfile, but
308 // the patchfile itself was not.
309 // So ask the user for that patchfile
312 // Create a new common save file dialog
313 CComPtr
<IFileOpenDialog
> pfd
= NULL
;
314 hr
= pfd
.CoCreateInstance(CLSID_FileOpenDialog
, NULL
, CLSCTX_INPROC_SERVER
);
317 // Set the dialog options
319 if (SUCCEEDED(hr
= pfd
->GetOptions(&dwOptions
)))
321 hr
= pfd
->SetOptions(dwOptions
| FOS_FILEMUSTEXIST
| FOS_FORCEFILESYSTEM
| FOS_PATHMUSTEXIST
);
328 temp
.LoadString(IDS_OPENDIFFFILETITLE
);
331 CSelectFileFilter
fileFilter(IDS_PATCHFILEFILTER
);
332 hr
= pfd
->SetFileTypes(fileFilter
.GetCount(), fileFilter
);
333 bool bAdvised
= false;
335 CComObjectStackEx
<PatchOpenDlgEventHandler
> cbk
;
336 CComQIPtr
<IFileDialogEvents
> pEvents
= cbk
.GetUnknown();
339 CComPtr
<IFileDialogCustomize
> pfdCustomize
;
340 hr
= pfd
->QueryInterface(IID_PPV_ARGS(&pfdCustomize
));
343 // check if there's a unified diff on the clipboard and
344 // add a button to the fileopen dialog if there is.
345 UINT cFormat
= RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
346 if ((cFormat
)&&(OpenClipboard(NULL
)))
348 HGLOBAL hglb
= GetClipboardData(cFormat
);
351 pfdCustomize
->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD
)));
352 hr
= pfd
->Advise(pEvents
, &dwCookie
);
353 bAdvised
= SUCCEEDED(hr
);
360 // Show the save file dialog
361 if (SUCCEEDED(hr
) && SUCCEEDED(hr
= pfd
->Show(pFrame
->m_hWnd
)))
363 // Get the selection from the user
364 CComPtr
<IShellItem
> psiResult
= NULL
;
365 hr
= pfd
->GetResult(&psiResult
);
367 pfd
->Unadvise(dwCookie
);
370 PWSTR pszPath
= NULL
;
371 hr
= psiResult
->GetDisplayName(SIGDN_FILESYSPATH
, &pszPath
);
374 pFrame
->m_Data
.m_sDiffFile
= pszPath
;
375 CoTaskMemFree(pszPath
);
380 // no result, which means we closed the dialog in our button handler
381 std::wstring sTempFile
;
382 if (TrySavePatchFromClipboard(sTempFile
))
383 pFrame
->m_Data
.m_sDiffFile
= sTempFile
.c_str();
389 pfd
->Unadvise(dwCookie
);
395 OPENFILENAME ofn
= {0}; // common dialog box structure
396 TCHAR szFile
[MAX_PATH
] = {0}; // buffer for file name
397 // Initialize OPENFILENAME
398 ofn
.lStructSize
= sizeof(OPENFILENAME
);
399 ofn
.hwndOwner
= pFrame
->m_hWnd
;
400 ofn
.lpstrFile
= szFile
;
401 ofn
.nMaxFile
= _countof(szFile
);
403 temp
.LoadString(IDS_OPENDIFFFILETITLE
);
405 ofn
.lpstrTitle
= NULL
;
407 ofn
.lpstrTitle
= temp
;
409 ofn
.Flags
= OFN_FILEMUSTEXIST
| OFN_PATHMUSTEXIST
| OFN_HIDEREADONLY
| OFN_EXPLORER
;
410 if( HasClipboardPatch() ) {
411 ofn
.Flags
|= ( OFN_ENABLETEMPLATE
| OFN_ENABLEHOOK
);
412 ofn
.hInstance
= AfxGetResourceHandle();
413 ofn
.lpTemplateName
= MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM
);
414 ofn
.lpfnHook
= CreatePatchFileOpenHook
;
417 CSelectFileFilter
fileFilter(IDS_PATCHFILEFILTER
);
418 ofn
.lpstrFilter
= fileFilter
;
419 ofn
.nFilterIndex
= 1;
421 // Display the Open dialog box.
422 if (GetOpenFileName(&ofn
)==FALSE
)
426 pFrame
->m_Data
.m_sDiffFile
= ofn
.lpstrFile
;
430 if ( pFrame
->m_Data
.m_baseFile
.GetFilename().IsEmpty() && pFrame
->m_Data
.m_yourFile
.GetFilename().IsEmpty() )
433 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
434 if( NULL
== szArglist
)
436 TRACE("CommandLineToArgvW failed\n");
440 if ( nArgs
==3 || nArgs
==4 )
446 // [3]: THEIR file (optional)
447 // This is the same format CAppUtils::StartExtDiff
448 // uses if %base and %mine are not set and most
449 // other diff tools use it too.
450 if ( PathFileExists(szArglist
[1]) && PathFileExists(szArglist
[2]) )
452 pFrame
->m_Data
.m_baseFile
.SetFileName(szArglist
[1]);
453 pFrame
->m_Data
.m_yourFile
.SetFileName(szArglist
[2]);
454 if ( nArgs
== 4 && PathFileExists(szArglist
[3]) )
456 pFrame
->m_Data
.m_theirFile
.SetFileName(szArglist
[3]);
462 // only one path specified: use it to fill the "open" dialog
463 if (PathFileExists(szArglist
[1]))
465 pFrame
->m_Data
.m_yourFile
.SetFileName(szArglist
[1]);
466 pFrame
->m_Data
.m_yourFile
.StoreFileAttributes();
471 // Free memory allocated for CommandLineToArgvW arguments.
472 LocalFree(szArglist
);
475 pFrame
->m_bReadOnly
= !!parser
.HasKey(_T("readonly"));
476 if (GetFileAttributes(pFrame
->m_Data
.m_yourFile
.GetFilename()) & FILE_ATTRIBUTE_READONLY
)
477 pFrame
->m_bReadOnly
= true;
478 pFrame
->m_bBlame
= !!parser
.HasKey(_T("blame"));
479 // diffing a blame means no editing!
480 if (pFrame
->m_bBlame
)
481 pFrame
->m_bReadOnly
= true;
483 pFrame
->SetWindowTitle();
485 if (parser
.HasKey(_T("createunifieddiff")))
487 // user requested to create a unified diff file
488 CString origFile
= parser
.GetVal(_T("origfile"));
489 CString modifiedFile
= parser
.GetVal(_T("modifiedfile"));
490 if (!origFile
.IsEmpty() && !modifiedFile
.IsEmpty())
492 CString outfile
= parser
.GetVal(_T("outfile"));
493 if (outfile
.IsEmpty())
495 CCommonAppUtils::FileOpenSave(outfile
, NULL
, IDS_SAVEASTITLE
, IDS_COMMONFILEFILTER
, false, NULL
);
497 if (!outfile
.IsEmpty())
499 CRegStdDWORD
regContextLines(L
"Software\\TortoiseGitMerge\\ContextLines", (DWORD
)-1);
500 CAppUtils::CreateUnifiedDiff(origFile
, modifiedFile
, outfile
, regContextLines
, false);
506 pFrame
->resolveMsgWnd
= parser
.HasVal(L
"resolvemsghwnd") ? (HWND
)parser
.GetLongLongVal(L
"resolvemsghwnd") : 0;
507 pFrame
->resolveMsgWParam
= parser
.HasVal(L
"resolvemsgwparam") ? (WPARAM
)parser
.GetLongLongVal(L
"resolvemsgwparam") : 0;
508 pFrame
->resolveMsgLParam
= parser
.HasVal(L
"resolvemsglparam") ? (LPARAM
)parser
.GetLongLongVal(L
"resolvemsglparam") : 0;
510 // The one and only window has been initialized, so show and update it
511 pFrame
->ActivateFrame();
512 pFrame
->ShowWindow(SW_SHOW
);
513 pFrame
->UpdateWindow();
514 pFrame
->ShowDiffBar(!pFrame
->m_bOneWay
);
515 if (!pFrame
->m_Data
.IsBaseFileInUse() && pFrame
->m_Data
.m_sPatchPath
.IsEmpty() && pFrame
->m_Data
.m_sDiffFile
.IsEmpty())
517 pFrame
->OnFileOpen(pFrame
->m_Data
.m_yourFile
.InUse());
522 if (parser
.HasVal(_T("line")))
524 line
= parser
.GetLongVal(_T("line"));
525 line
--; // we need the index
528 return pFrame
->LoadViews(line
);
531 // CTortoiseMergeApp message handlers
533 void CTortoiseMergeApp::OnAppAbout()
540 CTortoiseMergeApp::CreatePatchFileOpenHook(HWND hDlg
, UINT uiMsg
, WPARAM wParam
, LPARAM
/*lParam*/)
542 if(uiMsg
== WM_COMMAND
&& LOWORD(wParam
) == IDC_PATCH_TO_CLIPBOARD
)
544 HWND hFileDialog
= GetParent(hDlg
);
546 // if there's a patchfile in the clipboard, we save it
547 // to a temporary file and tell TortoiseMerge to use that one
548 std::wstring sTempFile
;
549 if (TrySavePatchFromClipboard(sTempFile
))
551 CommDlg_OpenSave_SetControlText(hFileDialog
, edt1
, sTempFile
.c_str());
552 PostMessage(hFileDialog
, WM_COMMAND
, MAKEWPARAM(IDOK
, BM_CLICK
), (LPARAM
)(GetDlgItem(hDlg
, IDOK
)));
558 int CTortoiseMergeApp::ExitInstance()
560 // Look for temporary files left around by TortoiseMerge and
561 // remove them. But only delete 'old' files
562 CTempFiles::DeleteOldTempFiles(_T("*tsm*.*"));
564 return CWinAppEx::ExitInstance();
567 bool CTortoiseMergeApp::HasClipboardPatch()
569 // check if there's a patchfile in the clipboard
570 const UINT cFormat
= RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
574 if (OpenClipboard(NULL
) == 0)
577 bool containsPatch
= false;
581 if (enumFormat
== cFormat
)
583 containsPatch
= true; // yes, there's a patchfile in the clipboard
585 } while((enumFormat
= EnumClipboardFormats(enumFormat
))!=0);
588 return containsPatch
;
591 bool CTortoiseMergeApp::TrySavePatchFromClipboard(std::wstring
& resultFile
)
595 UINT cFormat
= RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
598 if (OpenClipboard(NULL
) == 0)
601 HGLOBAL hglb
= GetClipboardData(cFormat
);
602 LPCSTR lpstr
= (LPCSTR
)GlobalLock(hglb
);
604 DWORD len
= GetTempPath(0, NULL
);
605 std::unique_ptr
<TCHAR
[]> path(new TCHAR
[len
+1]);
606 std::unique_ptr
<TCHAR
[]> tempF(new TCHAR
[len
+100]);
607 GetTempPath (len
+1, path
.get());
608 GetTempFileName (path
.get(), _T("tsm"), 0, tempF
.get());
609 std::wstring sTempFile
= std::wstring(tempF
.get());
612 _tfopen_s(&outFile
, sTempFile
.c_str(), _T("wb"));
615 size_t patchlen
= strlen(lpstr
);
616 size_t size
= fwrite(lpstr
, sizeof(char), patchlen
, outFile
);
617 if (size
== patchlen
)
618 resultFile
= sTempFile
;
625 return !resultFile
.empty();