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.
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
;
74 // The one and only CTortoiseMergeApp object
75 CTortoiseMergeApp theApp
;
77 #if ENABLE_CRASHHANLDER
78 CCrashReportTGit
g_crasher(L
"TortoiseGitMerge " _T(APP_X64_STRING
), TGIT_VERMAJOR
, TGIT_VERMINOR
, TGIT_VERMICRO
, TGIT_VERBUILD
, TGIT_VERDATE
);
81 CString g_sGroupingUUID
;
83 // CTortoiseMergeApp initialization
84 BOOL
CTortoiseMergeApp::InitInstance()
88 CCrashReport::Instance().AddUserInfoToReport(L
"CommandLine", GetCommandLine());
91 DWORD len
= GetCurrentDirectory(0, NULL
);
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);
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)
121 AfxSetResourceHandle(hInst
);
124 DWORD lid
= SUBLANGID(langId
);
128 langId
= MAKELANGID(PRIMARYLANGID(langId
), lid
);
133 } while ((hInst
== NULL
) && (langId
!= 0));
135 _tcscpy_s(buf
, _T("en"));
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("_");
146 sHelppath
.Replace(_T("_en"), sLang
);
147 if (PathFileExists(sHelppath
))
149 free((void*)m_pszHelpFilePath
);
150 m_pszHelpFilePath
=_tcsdup(sHelppath
);
153 sHelppath
.Replace(sLang
, _T("_en"));
154 GetLocaleInfo(MAKELCID(langId
, SORT_DEFAULT
), LOCALE_SISO3166CTRYNAME
, buf
, _countof(buf
));
157 sHelppath
.Replace(_T("_en"), sLang
);
158 if (PathFileExists(sHelppath
))
160 free((void*)m_pszHelpFilePath
);
161 m_pszHelpFilePath
=_tcsdup(sHelppath
);
164 sHelppath
.Replace(sLang
, _T("_en"));
166 DWORD lid
= SUBLANGID(langId
);
170 langId
= MAKELANGID(PRIMARYLANGID(langId
), lid
);
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
),
203 CCmdLineParser parser
= CCmdLineParser(this->m_lpCmdLine
);
205 g_sGroupingUUID
= parser
.GetVal(L
"groupuuid");
207 if (parser
.HasKey(_T("?")) || parser
.HasKey(_T("help")))
210 sHelpText
.LoadString(IDS_COMMANDLINEHELP
);
211 MessageBox(NULL
, sHelpText
, _T("TortoiseGitMerge"), MB_ICONINFORMATION
);
215 // Initialize OLE libraries
218 AfxMessageBox(IDP_OLE_INIT_FAILED
);
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
;
239 // create and load the frame with its resources
240 if (!pFrame
->LoadFrame(IDR_MAINFRAME
, WS_OVERLAPPEDWINDOW
| FWS_ADDTOTITLE
, NULL
, NULL
))
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('\\'));
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
)
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
296 // Create a new common save file dialog
297 CComPtr
<IFileOpenDialog
> pfd
= NULL
;
298 hr
= pfd
.CoCreateInstance(CLSID_FileOpenDialog
, NULL
, CLSCTX_INPROC_SERVER
);
301 // Set the dialog options
303 if (SUCCEEDED(hr
= pfd
->GetOptions(&dwOptions
)))
305 hr
= pfd
->SetOptions(dwOptions
| FOS_FILEMUSTEXIST
| FOS_FORCEFILESYSTEM
| FOS_PATHMUSTEXIST
);
312 temp
.LoadString(IDS_OPENDIFFFILETITLE
);
315 CSelectFileFilter
fileFilter(IDS_PATCHFILEFILTER
);
316 hr
= pfd
->SetFileTypes(fileFilter
.GetCount(), fileFilter
);
317 bool bAdvised
= false;
319 CComObjectStackEx
<PatchOpenDlgEventHandler
> cbk
;
320 CComQIPtr
<IFileDialogEvents
> pEvents
= cbk
.GetUnknown();
323 CComPtr
<IFileDialogCustomize
> pfdCustomize
;
324 hr
= pfd
->QueryInterface(IID_PPV_ARGS(&pfdCustomize
));
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
);
335 pfdCustomize
->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD
)));
336 hr
= pfd
->Advise(pEvents
, &dwCookie
);
337 bAdvised
= SUCCEEDED(hr
);
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
);
351 pfd
->Unadvise(dwCookie
);
354 PWSTR pszPath
= NULL
;
355 hr
= psiResult
->GetDisplayName(SIGDN_FILESYSPATH
, &pszPath
);
358 pFrame
->m_Data
.m_sDiffFile
= pszPath
;
359 CoTaskMemFree(pszPath
);
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();
373 pfd
->Unadvise(dwCookie
);
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
);
387 temp
.LoadString(IDS_OPENDIFFFILETITLE
);
389 ofn
.lpstrTitle
= NULL
;
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
)
410 pFrame
->m_Data
.m_sDiffFile
= ofn
.lpstrFile
;
414 if ( pFrame
->m_Data
.m_baseFile
.GetFilename().IsEmpty() && pFrame
->m_Data
.m_yourFile
.GetFilename().IsEmpty() )
417 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
418 if( NULL
== szArglist
)
420 TRACE("CommandLineToArgvW failed\n");
424 if ( nArgs
==3 || nArgs
==4 )
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);
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;
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();
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()
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
)));
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"));
550 if (OpenClipboard(NULL
) == 0)
553 bool containsPatch
= false;
557 if (enumFormat
== cFormat
)
559 containsPatch
= true; // yes, there's a patchfile in the clipboard
561 } while((enumFormat
= EnumClipboardFormats(enumFormat
))!=0);
564 return containsPatch
;
567 bool CTortoiseMergeApp::TrySavePatchFromClipboard(std::wstring
& resultFile
)
571 UINT cFormat
= RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
574 if (OpenClipboard(NULL
) == 0)
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());
588 _tfopen_s(&outFile
, sTempFile
.c_str(), _T("wb"));
591 size_t patchlen
= strlen(lpstr
);
592 size_t size
= fwrite(lpstr
, sizeof(char), patchlen
, outFile
);
593 if (size
== patchlen
)
594 resultFile
= sTempFile
;
601 return !resultFile
.empty();