Correct Handle case when patch file is not in repository path.
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob0f676e7926ff24f47f25552ef6a99f6958736146
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2008 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "StdAfx.h"
20 #include "resource.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 //#include "GitProperties.h"
25 #include "StringUtils.h"
26 #include "MessageBox.h"
27 #include "Registry.h"
28 #include "TGitPath.h"
29 #include "Git.h"
30 //#include "RepositoryBrowser.h"
31 //#include "BrowseFolder.h"
32 #include "UnicodeUtils.h"
33 #include "ExportDlg.h"
34 #include "ProgressDlg.h"
35 #include "GitAdminDir.h"
36 #include "ProgressDlg.h"
37 #include "BrowseFolder.h"
38 #include "DirFileEnum.h"
39 #include "MessageBox.h"
40 #include "GitStatus.h"
41 #include "CreateBranchTagDlg.h"
42 #include "GitSwitchDlg.h"
43 #include "ResetDlg.h"
44 #include "DeleteConflictDlg.h"
45 #include "ChangedDlg.h"
47 CAppUtils::CAppUtils(void)
51 CAppUtils::~CAppUtils(void)
55 int CAppUtils::StashApply(CString ref)
57 CString cmd,out;
58 cmd=_T("git.exe stash apply ");
59 cmd+=ref;
61 if(g_Git.Run(cmd,&out,CP_ACP))
63 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
65 }else
67 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
68 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
70 CChangedDlg dlg;
71 dlg.m_pathList.AddPath(CTGitPath());
72 dlg.DoModal();
74 return 0;
76 return -1;
78 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
80 #if 0
81 GitProperties props(file, GitRev::REV_WC, false);
82 for (int i = 0; i < props.GetCount(); ++i)
84 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
86 mimetype = props.GetItemValue(i).c_str();
87 return true;
90 #endif
91 return false;
94 BOOL CAppUtils::StartExtMerge(
95 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
96 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
99 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
100 CString ext = mergedfile.GetFileExtension();
101 CString com = regCom;
102 bool bInternal = false;
104 CString mimetype;
105 if (ext != "")
107 // is there an extension specific merge tool?
108 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
109 if (CString(mergetool) != "")
111 com = mergetool;
114 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
116 // is there a mime type specific merge tool?
117 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
118 if (CString(mergetool) != "")
120 com = mergetool;
124 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
126 // use TortoiseMerge
127 bInternal = true;
128 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
129 com = tortoiseMergePath;
130 if (com.IsEmpty())
132 com = CPathUtils::GetAppDirectory();
133 com += _T("TortoiseMerge.exe");
135 com = _T("\"") + com + _T("\"");
136 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
137 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
139 // check if the params are set. If not, just add the files to the command line
140 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
142 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
143 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
144 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
145 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
147 if (basefile.IsEmpty())
149 com.Replace(_T("/base:%base"), _T(""));
150 com.Replace(_T("%base"), _T(""));
152 else
153 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
154 if (theirfile.IsEmpty())
156 com.Replace(_T("/theirs:%theirs"), _T(""));
157 com.Replace(_T("%theirs"), _T(""));
159 else
160 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
161 if (yourfile.IsEmpty())
163 com.Replace(_T("/mine:%mine"), _T(""));
164 com.Replace(_T("%mine"), _T(""));
166 else
167 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
168 if (mergedfile.IsEmpty())
170 com.Replace(_T("/merged:%merged"), _T(""));
171 com.Replace(_T("%merged"), _T(""));
173 else
174 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
175 if (basename.IsEmpty())
177 if (basefile.IsEmpty())
179 com.Replace(_T("/basename:%bname"), _T(""));
180 com.Replace(_T("%bname"), _T(""));
182 else
184 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
187 else
188 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
189 if (theirname.IsEmpty())
191 if (theirfile.IsEmpty())
193 com.Replace(_T("/theirsname:%tname"), _T(""));
194 com.Replace(_T("%tname"), _T(""));
196 else
198 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
201 else
202 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
203 if (yourname.IsEmpty())
205 if (yourfile.IsEmpty())
207 com.Replace(_T("/minename:%yname"), _T(""));
208 com.Replace(_T("%yname"), _T(""));
210 else
212 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
215 else
216 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
217 if (mergedname.IsEmpty())
219 if (mergedfile.IsEmpty())
221 com.Replace(_T("/mergedname:%mname"), _T(""));
222 com.Replace(_T("%mname"), _T(""));
224 else
226 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
229 else
230 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
232 if ((bReadOnly)&&(bInternal))
233 com += _T(" /readonly");
235 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
237 return FALSE;
240 return TRUE;
243 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
245 CString viewer;
246 // use TortoiseMerge
247 viewer = CPathUtils::GetAppDirectory();
248 viewer += _T("TortoiseMerge.exe");
250 viewer = _T("\"") + viewer + _T("\"");
251 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
252 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
253 if (bReversed)
254 viewer += _T(" /reversedpatch");
255 if (!sOriginalDescription.IsEmpty())
256 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
257 if (!sPatchedDescription.IsEmpty())
258 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
259 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
261 return FALSE;
263 return TRUE;
266 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
268 // Is there a mime type specific diff tool?
269 CString mimetype;
270 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
272 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
273 if (!difftool.IsEmpty())
274 return difftool;
277 // Is there an extension specific diff tool?
278 CString ext = file2.GetFileExtension().MakeLower();
279 if (!ext.IsEmpty())
281 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
282 if (!difftool.IsEmpty())
283 return difftool;
284 // Maybe we should use TortoiseIDiff?
285 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
286 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
287 (ext == _T(".png")) || (ext == _T(".ico")) ||
288 (ext == _T(".dib")) || (ext == _T(".emf")))
290 return
291 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
292 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
296 // Finally, pick a generic external diff tool
297 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
298 return difftool;
301 bool CAppUtils::StartExtDiff(
302 const CString& file1, const CString& file2,
303 const CString& sName1, const CString& sName2,
304 const DiffFlags& flags)
306 CString viewer;
308 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
309 if (!flags.bBlame || !(DWORD)blamediff)
311 viewer = PickDiffTool(file1, file2);
312 // If registry entry for a diff program is commented out, use TortoiseMerge.
313 bool bCommentedOut = viewer.Left(1) == _T("#");
314 if (flags.bAlternativeTool)
316 // Invert external vs. internal diff tool selection.
317 if (bCommentedOut)
318 viewer.Delete(0); // uncomment
319 else
320 viewer = "";
322 else if (bCommentedOut)
323 viewer = "";
326 bool bInternal = viewer.IsEmpty();
327 if (bInternal)
329 viewer =
330 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
331 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
332 if (flags.bBlame)
333 viewer += _T(" /blame");
335 // check if the params are set. If not, just add the files to the command line
336 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
338 viewer += _T(" \"")+file1+_T("\"");
339 viewer += _T(" \"")+file2+_T("\"");
341 if (viewer.Find(_T("%base")) >= 0)
343 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
345 if (viewer.Find(_T("%mine")) >= 0)
347 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
350 if (sName1.IsEmpty())
351 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
352 else
353 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
355 if (sName2.IsEmpty())
356 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
357 else
358 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
360 if (flags.bReadOnly && bInternal)
361 viewer += _T(" /readonly");
363 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
366 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
368 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
369 CString viewer = diffpropsexe;
370 bool bInternal = false;
371 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
373 //no registry entry (or commented out) for a diff program
374 //use TortoiseMerge
375 bInternal = true;
376 viewer = CPathUtils::GetAppDirectory();
377 viewer += _T("TortoiseMerge.exe");
378 viewer = _T("\"") + viewer + _T("\"");
379 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
381 // check if the params are set. If not, just add the files to the command line
382 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
384 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
385 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
387 if (viewer.Find(_T("%base")) >= 0)
389 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
391 if (viewer.Find(_T("%mine")) >= 0)
393 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
396 if (sName1.IsEmpty())
397 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
398 else
399 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
401 if (sName2.IsEmpty())
402 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
403 else
404 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
406 if ((bReadOnly)&&(bInternal))
407 viewer += _T(" /readonly");
409 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
411 return FALSE;
413 return TRUE;
416 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
418 CString viewer;
419 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
420 viewer = v;
421 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
423 // use TortoiseUDiff
424 viewer = CPathUtils::GetAppDirectory();
425 viewer += _T("TortoiseUDiff.exe");
426 // enquote the path to TortoiseUDiff
427 viewer = _T("\"") + viewer + _T("\"");
428 // add the params
429 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
432 if (viewer.Find(_T("%1"))>=0)
434 if (viewer.Find(_T("\"%1\"")) >= 0)
435 viewer.Replace(_T("%1"), patchfile);
436 else
437 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
439 else
440 viewer += _T(" \"") + patchfile + _T("\"");
441 if (viewer.Find(_T("%title")) >= 0)
443 viewer.Replace(_T("%title"), title);
446 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
448 return FALSE;
450 return TRUE;
453 BOOL CAppUtils::StartTextViewer(CString file)
455 CString viewer;
456 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
457 viewer = txt;
458 viewer = viewer + _T("\\Shell\\Open\\Command\\");
459 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
460 viewer = txtexe;
462 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
463 TCHAR * buf = new TCHAR[len+1];
464 ExpandEnvironmentStrings(viewer, buf, len);
465 viewer = buf;
466 delete [] buf;
467 len = ExpandEnvironmentStrings(file, NULL, 0);
468 buf = new TCHAR[len+1];
469 ExpandEnvironmentStrings(file, buf, len);
470 file = buf;
471 delete [] buf;
472 file = _T("\"")+file+_T("\"");
473 if (viewer.IsEmpty())
475 OPENFILENAME ofn = {0}; // common dialog box structure
476 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
477 // Initialize OPENFILENAME
478 ofn.lStructSize = sizeof(OPENFILENAME);
479 ofn.hwndOwner = NULL;
480 ofn.lpstrFile = szFile;
481 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
482 CString sFilter;
483 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
484 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
485 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
486 // Replace '|' delimiters with '\0's
487 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
488 while (ptr != pszFilters)
490 if (*ptr == '|')
491 *ptr = '\0';
492 ptr--;
494 ofn.lpstrFilter = pszFilters;
495 ofn.nFilterIndex = 1;
496 ofn.lpstrFileTitle = NULL;
497 ofn.nMaxFileTitle = 0;
498 ofn.lpstrInitialDir = NULL;
499 CString temp;
500 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
501 CStringUtils::RemoveAccelerators(temp);
502 ofn.lpstrTitle = temp;
503 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
505 // Display the Open dialog box.
507 if (GetOpenFileName(&ofn)==TRUE)
509 delete [] pszFilters;
510 viewer = CString(ofn.lpstrFile);
512 else
514 delete [] pszFilters;
515 return FALSE;
518 if (viewer.Find(_T("\"%1\"")) >= 0)
520 viewer.Replace(_T("\"%1\""), file);
522 else if (viewer.Find(_T("%1")) >= 0)
524 viewer.Replace(_T("%1"), file);
526 else
528 viewer += _T(" ");
529 viewer += file;
532 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
534 return FALSE;
536 return TRUE;
539 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
541 DWORD length = 0;
542 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
543 if (hFile == INVALID_HANDLE_VALUE)
544 return TRUE;
545 length = ::GetFileSize(hFile, NULL);
546 ::CloseHandle(hFile);
547 if (length < 4)
548 return TRUE;
549 return FALSE;
553 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
555 LOGFONT logFont;
556 HDC hScreenDC = ::GetDC(NULL);
557 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
558 ::ReleaseDC(NULL, hScreenDC);
559 logFont.lfWidth = 0;
560 logFont.lfEscapement = 0;
561 logFont.lfOrientation = 0;
562 logFont.lfWeight = FW_NORMAL;
563 logFont.lfItalic = 0;
564 logFont.lfUnderline = 0;
565 logFont.lfStrikeOut = 0;
566 logFont.lfCharSet = DEFAULT_CHARSET;
567 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
568 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
569 logFont.lfQuality = DRAFT_QUALITY;
570 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
571 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
572 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
575 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
577 STARTUPINFO startup;
578 PROCESS_INFORMATION process;
579 memset(&startup, 0, sizeof(startup));
580 startup.cb = sizeof(startup);
581 memset(&process, 0, sizeof(process));
583 CString cleanCommandLine(sCommandLine);
585 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, sOrigCWD, &startup, &process)==0)
587 if(idErrMessageFormat != 0)
589 LPVOID lpMsgBuf;
590 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
591 FORMAT_MESSAGE_FROM_SYSTEM |
592 FORMAT_MESSAGE_IGNORE_INSERTS,
593 NULL,
594 GetLastError(),
595 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
596 (LPTSTR) &lpMsgBuf,
598 NULL
600 CString temp;
601 temp.Format(idErrMessageFormat, lpMsgBuf);
602 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
603 LocalFree( lpMsgBuf );
605 return false;
608 if (bWaitForStartup)
610 WaitForInputIdle(process.hProcess, 10000);
613 CloseHandle(process.hThread);
614 CloseHandle(process.hProcess);
615 return true;
617 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
619 CString key,remote;
620 CString cmd,out;
621 if( pRemote == NULL)
623 remote=_T("origin");
624 }else
626 remote=*pRemote;
628 if(keyfile == NULL)
630 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
631 g_Git.Run(cmd,&key,CP_ACP);
632 int start=0;
633 key = key.Tokenize(_T("\n"),start);
635 else
636 key=*keyfile;
638 if(key.IsEmpty())
639 return false;
641 CString proc=CPathUtils::GetAppDirectory();
642 proc += _T("pageant.exe \"");
643 proc += key;
644 proc += _T("\"");
646 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
648 bool CAppUtils::LaunchRemoteSetting()
650 CString proc=CPathUtils::GetAppDirectory();
651 proc += _T("TortoiseProc.exe /command:settings");
652 proc += _T(" /path:\"");
653 proc += g_Git.m_CurrentDir;
654 proc += _T("\" /page:remote");
655 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
658 * Launch the external blame viewer
660 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
662 CString viewer = CPathUtils::GetAppDirectory();
663 viewer += _T("TortoiseGitBlame.exe");
664 viewer += _T(" \"") + sBlameFile + _T("\"");
665 //viewer += _T(" \"") + sLogFile + _T("\"");
666 //viewer += _T(" \"") + sOriginalFile + _T("\"");
667 if(!Rev.IsEmpty())
668 viewer += CString(_T(" /rev:"))+Rev;
669 viewer += _T(" ")+sParams;
671 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
674 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
676 CString sText;
677 if (pWnd == NULL)
678 return false;
679 bool bStyled = false;
680 pWnd->GetWindowText(sText);
681 // the rich edit control doesn't count the CR char!
682 // to be exact: CRLF is treated as one char.
683 sText.Replace(_T("\r"), _T(""));
685 // style each line separately
686 int offset = 0;
687 int nNewlinePos;
690 nNewlinePos = sText.Find('\n', offset);
691 CString sLine = sText.Mid(offset);
692 if (nNewlinePos>=0)
693 sLine = sLine.Left(nNewlinePos-offset);
694 int start = 0;
695 int end = 0;
696 while (FindStyleChars(sLine, '*', start, end))
698 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
699 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
700 CHARFORMAT2 format;
701 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
702 format.cbSize = sizeof(CHARFORMAT2);
703 format.dwMask = CFM_BOLD;
704 format.dwEffects = CFE_BOLD;
705 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
706 bStyled = true;
707 start = end;
709 start = 0;
710 end = 0;
711 while (FindStyleChars(sLine, '^', start, end))
713 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
714 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
715 CHARFORMAT2 format;
716 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
717 format.cbSize = sizeof(CHARFORMAT2);
718 format.dwMask = CFM_ITALIC;
719 format.dwEffects = CFE_ITALIC;
720 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
721 bStyled = true;
722 start = end;
724 start = 0;
725 end = 0;
726 while (FindStyleChars(sLine, '_', start, end))
728 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
729 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
730 CHARFORMAT2 format;
731 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
732 format.cbSize = sizeof(CHARFORMAT2);
733 format.dwMask = CFM_UNDERLINE;
734 format.dwEffects = CFE_UNDERLINE;
735 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
736 bStyled = true;
737 start = end;
739 offset = nNewlinePos+1;
740 } while(nNewlinePos>=0);
741 return bStyled;
744 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
746 int i=start;
747 bool bFoundMarker = false;
748 // find a starting marker
749 while (sText[i] != 0)
751 if (sText[i] == stylechar)
753 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
754 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
756 start = i+1;
757 i++;
758 bFoundMarker = true;
759 break;
762 i++;
764 if (!bFoundMarker)
765 return false;
766 // find ending marker
767 bFoundMarker = false;
768 while (sText[i] != 0)
770 if (sText[i] == stylechar)
772 if ((IsCharAlphaNumeric(sText[i-1])) &&
773 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
775 end = i;
776 i++;
777 bFoundMarker = true;
778 break;
781 i++;
783 return bFoundMarker;
786 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
788 #if 0
789 CString strUrl;
790 combo.GetWindowText(strUrl);
791 strUrl.Replace('\\', '/');
792 strUrl.Replace(_T("%"), _T("%25"));
793 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
794 if (strUrl.Left(7) == _T("file://"))
796 CString strFile(strUrl);
797 Git::UrlToPath(strFile);
799 Git svn;
800 if (svn.IsRepository(CTGitPath(strFile)))
802 // browse repository - show repository browser
803 Git::preparePath(strUrl);
804 CRepositoryBrowser browser(strUrl, rev, pParent);
805 if (browser.DoModal() == IDOK)
807 combo.SetCurSel(-1);
808 combo.SetWindowText(browser.GetPath());
809 rev = browser.GetRevision();
810 return true;
813 else
815 // browse local directories
816 CBrowseFolder folderBrowser;
817 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
818 // remove the 'file:///' so the shell can recognize the local path
819 Git::UrlToPath(strUrl);
820 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
822 Git::PathToUrl(strUrl);
824 combo.SetCurSel(-1);
825 combo.SetWindowText(strUrl);
826 return true;
830 else if ((strUrl.Left(7) == _T("http://")
831 ||(strUrl.Left(8) == _T("https://"))
832 ||(strUrl.Left(6) == _T("svn://"))
833 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
835 // browse repository - show repository browser
836 CRepositoryBrowser browser(strUrl, rev, pParent);
837 if (browser.DoModal() == IDOK)
839 combo.SetCurSel(-1);
840 combo.SetWindowText(browser.GetPath());
841 rev = browser.GetRevision();
842 return true;
845 else
847 // browse local directories
848 CBrowseFolder folderBrowser;
849 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
850 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
852 Git::PathToUrl(strUrl);
854 combo.SetCurSel(-1);
855 combo.SetWindowText(strUrl);
856 return true;
859 #endif
860 return false;
863 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
865 OPENFILENAME ofn = {0}; // common dialog box structure
866 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
867 ofn.lStructSize = sizeof(OPENFILENAME);
868 ofn.hwndOwner = hwndOwner;
869 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
870 ofn.lpstrFile = szFile;
871 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
872 CString sFilter;
873 TCHAR * pszFilters = NULL;
874 if (filter)
876 sFilter.LoadString(filter);
877 pszFilters = new TCHAR[sFilter.GetLength()+4];
878 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
879 // Replace '|' delimiters with '\0's
880 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
881 while (ptr != pszFilters)
883 if (*ptr == '|')
884 *ptr = '\0';
885 ptr--;
887 ofn.lpstrFilter = pszFilters;
889 ofn.nFilterIndex = 1;
890 ofn.lpstrFileTitle = NULL;
891 ofn.nMaxFileTitle = 0;
892 ofn.lpstrInitialDir = NULL;
893 CString temp;
894 if (title)
896 temp.LoadString(title);
897 CStringUtils::RemoveAccelerators(temp);
899 ofn.lpstrTitle = temp;
900 if (bOpen)
901 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
902 else
903 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
906 // Display the Open dialog box.
907 bool bRet = false;
908 if (bOpen)
910 bRet = !!GetOpenFileName(&ofn);
912 else
914 bRet = !!GetSaveFileName(&ofn);
916 if (bRet)
918 if (pszFilters)
919 delete [] pszFilters;
920 path = CString(ofn.lpstrFile);
921 if (filterindex)
922 *filterindex = ofn.nFilterIndex;
923 return true;
925 if (pszFilters)
926 delete [] pszFilters;
927 return false;
930 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
932 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
933 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
934 // create a bitmap from the icon
935 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
936 if (!hIcon)
937 return false;
939 RECT rect = {0};
940 rect.right = width;
941 rect.bottom = height;
942 HBITMAP bmp = NULL;
944 HWND desktop = ::GetDesktopWindow();
945 if (desktop)
947 HDC screen_dev = ::GetDC(desktop);
948 if (screen_dev)
950 // Create a compatible DC
951 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
952 if (dst_hdc)
954 // Create a new bitmap of icon size
955 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
956 if (bmp)
958 // Select it into the compatible DC
959 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
960 // Fill the background of the compatible DC with the given color
961 ::SetBkColor(dst_hdc, bkColor);
962 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
964 // Draw the icon into the compatible DC
965 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
966 ::SelectObject(dst_hdc, old_dst_bmp);
968 ::DeleteDC(dst_hdc);
971 ::ReleaseDC(desktop, screen_dev);
974 // Restore settings
975 DestroyIcon(hIcon);
977 if (bmp == NULL)
978 return false;
980 LVBKIMAGE lv;
981 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
982 lv.hbm = bmp;
983 lv.xOffsetPercent = 100;
984 lv.yOffsetPercent = 100;
985 ListView_SetBkImage(hListCtrl, &lv);
986 return true;
989 CString CAppUtils::GetProjectNameFromURL(CString url)
991 CString name;
992 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
993 (name.CompareNoCase(_T("tags"))==0) ||
994 (name.CompareNoCase(_T("trunk"))==0))
996 name = url.Mid(url.ReverseFind('/')+1);
997 url = url.Left(url.ReverseFind('/'));
999 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1001 // a name of svn or svnroot indicates that it's not really the project name. In that
1002 // case, we try the first part of the URL
1003 // of course, this won't work in all cases (but it works for Google project hosting)
1004 url.Replace(_T("http://"), _T(""));
1005 url.Replace(_T("https://"), _T(""));
1006 url.Replace(_T("svn://"), _T(""));
1007 url.Replace(_T("svn+ssh://"), _T(""));
1008 url.TrimLeft(_T("/"));
1009 name = url.Left(url.Find('.'));
1011 return name;
1014 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1015 const CTGitPath& url2, const git_revnum_t& rev2,
1016 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1017 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1020 CString tempfile=GetTempFile();
1021 CString cmd;
1022 if(rev1 == GitRev::GetWorkingCopy())
1024 cmd.Format(_T("git.exe diff --stat -p %s"),rev2);
1025 }else
1027 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1029 g_Git.RunLogFile(cmd,tempfile);
1030 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1033 #if 0
1034 CString sCmd;
1035 sCmd.Format(_T("%s /command:showcompare /unified"),
1036 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1037 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1038 if (rev1.IsValid())
1039 sCmd += _T(" /revision1:") + rev1.ToString();
1040 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1041 if (rev2.IsValid())
1042 sCmd += _T(" /revision2:") + rev2.ToString();
1043 if (peg.IsValid())
1044 sCmd += _T(" /pegrevision:") + peg.ToString();
1045 if (headpeg.IsValid())
1046 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1048 if (bAlternateDiff)
1049 sCmd += _T(" /alternatediff");
1051 if (bIgnoreAncestry)
1052 sCmd += _T(" /ignoreancestry");
1054 if (hWnd)
1056 sCmd += _T(" /hwnd:");
1057 TCHAR buf[30];
1058 _stprintf_s(buf, 30, _T("%d"), hWnd);
1059 sCmd += buf;
1062 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1063 #endif
1064 return TRUE;
1067 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1068 const CTGitPath& url2, const GitRev& rev2,
1069 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1070 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1072 #if 0
1073 CString sCmd;
1074 sCmd.Format(_T("%s /command:showcompare"),
1075 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1076 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1077 if (rev1.IsValid())
1078 sCmd += _T(" /revision1:") + rev1.ToString();
1079 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1080 if (rev2.IsValid())
1081 sCmd += _T(" /revision2:") + rev2.ToString();
1082 if (peg.IsValid())
1083 sCmd += _T(" /pegrevision:") + peg.ToString();
1084 if (headpeg.IsValid())
1085 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1086 if (bAlternateDiff)
1087 sCmd += _T(" /alternatediff");
1088 if (bIgnoreAncestry)
1089 sCmd += _T(" /ignoreancestry");
1090 if (blame)
1091 sCmd += _T(" /blame");
1093 if (hWnd)
1095 sCmd += _T(" /hwnd:");
1096 TCHAR buf[30];
1097 _stprintf_s(buf, 30, _T("%d"), hWnd);
1098 sCmd += buf;
1101 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1102 #endif
1103 return true;
1106 bool CAppUtils::Export(CString *BashHash)
1108 bool bRet = false;
1110 // ask from where the export has to be done
1111 CExportDlg dlg;
1112 if(BashHash)
1113 dlg.m_Revision=*BashHash;
1115 if (dlg.DoModal() == IDOK)
1117 CString cmd;
1118 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1119 dlg.m_VersionName);
1121 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1122 CProgressDlg pro;
1123 pro.m_GitCmd=cmd;
1124 pro.m_LogFile=dlg.m_strExportDirectory;
1125 pro.DoModal();
1126 return TRUE;
1128 return bRet;
1131 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1133 CCreateBranchTagDlg dlg;
1134 dlg.m_bIsTag=IsTag;
1135 if(CommitHash)
1136 dlg.m_Base = *CommitHash;
1138 if(dlg.DoModal()==IDOK)
1140 CString cmd;
1141 CString force;
1142 CString track;
1143 if(dlg.m_bTrack)
1144 track=_T(" --track ");
1146 if(dlg.m_bForce)
1147 force=_T(" -f ");
1149 if(IsTag)
1151 cmd.Format(_T("git.exe tag %s %s %s %s"),
1152 track,
1153 force,
1154 dlg.m_BranchTagName,
1155 dlg.m_VersionName
1159 }else
1161 cmd.Format(_T("git.exe branch %s %s %s %s"),
1162 track,
1163 force,
1164 dlg.m_BranchTagName,
1165 dlg.m_VersionName
1168 CString out;
1169 if(g_Git.Run(cmd,&out,CP_UTF8))
1171 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1173 if( !IsTag && dlg.m_bSwitch )
1175 // it is a new branch and the user has requested to switch to it
1176 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1177 g_Git.Run(cmd,&out,CP_UTF8);
1178 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1181 return TRUE;
1184 return FALSE;
1187 bool CAppUtils::Switch(CString *CommitHash)
1189 CGitSwitchDlg dlg;
1190 if(CommitHash)
1191 dlg.m_Base=*CommitHash;
1193 if (dlg.DoModal() == IDOK)
1195 CString cmd;
1196 CString track;
1197 CString base;
1198 CString force;
1199 CString branch;
1201 if(dlg.m_bBranch)
1202 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1203 if(dlg.m_bForce)
1204 force=_T("-f");
1205 if(dlg.m_bTrack)
1206 track=_T("--track");
1208 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1209 force,
1210 track,
1211 branch,
1212 dlg.m_VersionName);
1214 CProgressDlg progress;
1215 progress.m_GitCmd=cmd;
1216 if(progress.DoModal()==IDOK)
1217 return TRUE;
1220 return FALSE;
1223 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1225 CString ignorefile;
1226 ignorefile=g_Git.m_CurrentDir+_T("\\");
1228 if(IsMask)
1230 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1232 }else
1234 ignorefile+=_T("\\.gitignore");
1237 CStdioFile file;
1238 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1240 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1241 return FALSE;
1244 CString ignorelist;
1245 CString mask;
1248 //file.ReadString(ignorelist);
1249 file.SeekToEnd();
1250 for(int i=0;i<path.GetCount();i++)
1252 if(IsMask)
1254 mask=_T("*")+path[i].GetFileExtension();
1255 if(ignorelist.Find(mask)<0)
1256 ignorelist+=_T("\n")+mask;
1258 }else
1260 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1263 file.WriteString(ignorelist);
1265 file.Close();
1267 }catch(...)
1269 file.Close();
1270 return FALSE;
1273 return TRUE;
1277 bool CAppUtils::GitReset(CString *CommitHash,int type)
1279 CResetDlg dlg;
1280 dlg.m_ResetType=type;
1281 if (dlg.DoModal() == IDOK)
1283 CString cmd;
1284 CString type;
1285 switch(dlg.m_ResetType)
1287 case 0:
1288 type=_T("--soft");
1289 break;
1290 case 1:
1291 type=_T("--mixed");
1292 break;
1293 case 2:
1294 type=_T("--hard");
1295 break;
1296 default:
1297 type=_T("--mixed");
1298 break;
1300 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1302 CProgressDlg progress;
1303 progress.m_GitCmd=cmd;
1304 if(progress.DoModal()==IDOK)
1305 return TRUE;
1308 return FALSE;
1311 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1313 if(mode == FALSE)
1315 descript=_T("Deleted");
1316 return;
1318 if(base)
1320 descript=_T("Modified");
1321 return;
1323 descript=_T("Created");
1324 return;
1327 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1329 CString file;
1330 file=g_Git.m_CurrentDir+_T("\\")+merge.GetDirectory().GetWinPathString()+_T("\\")+merge.GetFilename()+_T(".")+type+merge.GetFileExtension();
1332 return file;
1335 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool)
1337 bool bRet = false;
1339 CTGitPath merge=path;
1340 CTGitPath directory = merge.GetDirectory();
1344 // we have the conflicted file (%merged)
1345 // now look for the other required files
1346 //GitStatus stat;
1347 //stat.GetStatus(merge);
1348 //if (stat.status == NULL)
1349 // return false;
1351 BYTE_VECTOR vector;
1353 CString cmd;
1354 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1356 if(g_Git.Run(cmd,&vector))
1358 return FALSE;
1361 CTGitPathList list;
1362 list.ParserFromLsFile(vector);
1364 if(list.GetCount() == 0)
1365 return FALSE;
1367 TCHAR szTempName[512];
1368 GetTempFileName(_T(""),_T(""),0,szTempName);
1369 CString temp(szTempName);
1370 temp=temp.Mid(1,temp.GetLength()-5);
1372 CTGitPath theirs;
1373 CTGitPath mine;
1374 CTGitPath base;
1377 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1378 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1379 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1381 CString format;
1383 format=_T("git.exe cat-file blob \":%d:%s\"");
1384 CFile tempfile;
1385 //create a empty file, incase stage is not three
1386 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1387 tempfile.Close();
1388 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1389 tempfile.Close();
1390 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1391 tempfile.Close();
1393 bool b_base=false, b_local=false, b_remote=false;
1395 for(int i=0;i<list.GetCount();i++)
1397 CString cmd;
1398 CString outfile;
1399 cmd.Format(format,list[i].m_Stage,list[i].GetGitPathString());
1401 if( list[i].m_Stage == 1)
1403 b_base = true;
1404 outfile=base.GetWinPathString();
1406 if( list[i].m_Stage == 2 )
1408 b_local = true;
1409 outfile=mine.GetWinPathString();
1411 if( list[i].m_Stage == 3 )
1413 b_remote = true;
1414 outfile=theirs.GetWinPathString();
1416 g_Git.RunLogFile(cmd,outfile);
1419 if(b_local && b_remote )
1421 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1422 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1424 }else
1426 CFile::Remove(mine.GetWinPathString());
1427 CFile::Remove(theirs.GetWinPathString());
1428 CFile::Remove(base.GetWinPathString());
1430 CDeleteConflictDlg dlg;
1431 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1432 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1433 dlg.m_bShowModifiedButton=b_base;
1434 dlg.m_File=merge.GetGitPathString();
1435 if(dlg.DoModal() == IDOK)
1437 CString cmd,out;
1438 if(dlg.m_bIsDelete)
1440 cmd.Format(_T("git.exe rm \"%s\""),merge.GetGitPathString());
1441 }else
1442 cmd.Format(_T("git.exe add \"%s\""),merge.GetGitPathString());
1444 if(g_Git.Run(cmd,&out,CP_ACP))
1446 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1447 return FALSE;
1449 return TRUE;
1451 else
1452 return FALSE;
1458 #if 0
1460 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1461 base, theirs, mine, merge);
1462 #endif
1463 #if 0
1464 if (stat.status->text_status == svn_wc_status_conflicted)
1466 // we have a text conflict, use our merge tool to resolve the conflict
1468 CTSVNPath theirs(directory);
1469 CTSVNPath mine(directory);
1470 CTSVNPath base(directory);
1471 bool bConflictData = false;
1473 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1475 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1476 bConflictData = true;
1478 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1480 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1481 bConflictData = true;
1483 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1485 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1486 bConflictData = true;
1488 else
1490 mine = merge;
1492 if (bConflictData)
1493 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1494 base, theirs, mine, merge);
1497 if (stat.status->prop_status == svn_wc_status_conflicted)
1499 // we have a property conflict
1500 CTSVNPath prej(directory);
1501 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1503 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1504 // there's a problem: the prej file contains a _description_ of the conflict, and
1505 // that description string might be translated. That means we have no way of parsing
1506 // the file to find out the conflicting values.
1507 // The only thing we can do: show a dialog with the conflict description, then
1508 // let the user either accept the existing property or open the property edit dialog
1509 // to manually change the properties and values. And a button to mark the conflict as
1510 // resolved.
1511 CEditPropConflictDlg dlg;
1512 dlg.SetPrejFile(prej);
1513 dlg.SetConflictedItem(merge);
1514 bRet = (dlg.DoModal() != IDCANCEL);
1518 if (stat.status->tree_conflict)
1520 // we have a tree conflict
1521 SVNInfo info;
1522 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1523 if (pInfoData)
1525 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1527 CTSVNPath theirs(directory);
1528 CTSVNPath mine(directory);
1529 CTSVNPath base(directory);
1530 bool bConflictData = false;
1532 if (pInfoData->treeconflict_theirfile)
1534 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1535 bConflictData = true;
1537 if (pInfoData->treeconflict_basefile)
1539 base.AppendPathString(pInfoData->treeconflict_basefile);
1540 bConflictData = true;
1542 if (pInfoData->treeconflict_myfile)
1544 mine.AppendPathString(pInfoData->treeconflict_myfile);
1545 bConflictData = true;
1547 else
1549 mine = merge;
1551 if (bConflictData)
1552 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1553 base, theirs, mine, merge);
1555 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1557 CString sConflictAction;
1558 CString sConflictReason;
1559 CString sResolveTheirs;
1560 CString sResolveMine;
1561 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1562 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1564 if (pInfoData->treeconflict_nodekind == svn_node_file)
1566 switch (pInfoData->treeconflict_operation)
1568 case svn_wc_operation_update:
1569 switch (pInfoData->treeconflict_action)
1571 case svn_wc_conflict_action_edit:
1572 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1573 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1574 break;
1575 case svn_wc_conflict_action_add:
1576 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1577 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1578 break;
1579 case svn_wc_conflict_action_delete:
1580 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1581 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1582 break;
1584 break;
1585 case svn_wc_operation_switch:
1586 switch (pInfoData->treeconflict_action)
1588 case svn_wc_conflict_action_edit:
1589 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1590 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1591 break;
1592 case svn_wc_conflict_action_add:
1593 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1594 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1595 break;
1596 case svn_wc_conflict_action_delete:
1597 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1598 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1599 break;
1601 break;
1602 case svn_wc_operation_merge:
1603 switch (pInfoData->treeconflict_action)
1605 case svn_wc_conflict_action_edit:
1606 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1607 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1608 break;
1609 case svn_wc_conflict_action_add:
1610 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1611 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1612 break;
1613 case svn_wc_conflict_action_delete:
1614 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1615 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1616 break;
1618 break;
1621 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1623 switch (pInfoData->treeconflict_operation)
1625 case svn_wc_operation_update:
1626 switch (pInfoData->treeconflict_action)
1628 case svn_wc_conflict_action_edit:
1629 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1630 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1631 break;
1632 case svn_wc_conflict_action_add:
1633 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1634 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1635 break;
1636 case svn_wc_conflict_action_delete:
1637 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1638 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1639 break;
1641 break;
1642 case svn_wc_operation_switch:
1643 switch (pInfoData->treeconflict_action)
1645 case svn_wc_conflict_action_edit:
1646 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1647 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1648 break;
1649 case svn_wc_conflict_action_add:
1650 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1651 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1652 break;
1653 case svn_wc_conflict_action_delete:
1654 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1655 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1656 break;
1658 break;
1659 case svn_wc_operation_merge:
1660 switch (pInfoData->treeconflict_action)
1662 case svn_wc_conflict_action_edit:
1663 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1664 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1665 break;
1666 case svn_wc_conflict_action_add:
1667 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1668 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1669 break;
1670 case svn_wc_conflict_action_delete:
1671 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1672 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1673 break;
1675 break;
1679 UINT uReasonID = 0;
1680 switch (pInfoData->treeconflict_reason)
1682 case svn_wc_conflict_reason_edited:
1683 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1684 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1685 break;
1686 case svn_wc_conflict_reason_obstructed:
1687 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1688 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1689 break;
1690 case svn_wc_conflict_reason_deleted:
1691 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1692 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1693 break;
1694 case svn_wc_conflict_reason_added:
1695 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1696 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1697 break;
1698 case svn_wc_conflict_reason_missing:
1699 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1700 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1701 break;
1702 case svn_wc_conflict_reason_unversioned:
1703 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1704 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1705 break;
1707 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1709 CTreeConflictEditorDlg dlg;
1710 dlg.SetConflictInfoText(sConflictReason);
1711 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1712 dlg.SetPath(treeConflictPath);
1713 INT_PTR dlgRet = dlg.DoModal();
1714 bRet = (dlgRet != IDCANCEL);
1718 #endif
1719 return bRet;
1723 * FUNCTION : FormatDateAndTime
1724 * DESCRIPTION : Generates a displayable string from a CTime object in
1725 * system short or long format or as a relative value
1726 * cTime - the time
1727 * option - DATE_SHORTDATE or DATE_LONGDATE
1728 * bIncluedeTime - whether to show time as well as date
1729 * bRelative - if true then relative time is shown if reasonable
1730 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1731 * rather than locale
1732 * RETURN : CString containing date/time
1734 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1735 bool bRelative /*=false*/)
1737 CString datetime;
1738 if ( bRelative )
1740 datetime = ToRelativeTimeString( cTime );
1742 else
1744 // should we use the locale settings for formatting the date/time?
1745 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1747 // yes
1748 SYSTEMTIME sysTime;
1749 cTime.GetAsSystemTime( sysTime );
1751 TCHAR buf[100];
1753 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1754 sizeof(buf)/sizeof(TCHAR)-1);
1755 datetime = buf;
1756 if ( bIncludeTime )
1758 datetime += _T(" ");
1759 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1760 datetime += buf;
1763 else
1765 // no, so fixed format
1766 if ( bIncludeTime )
1768 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1770 else
1772 datetime = cTime.Format(_T("%Y-%m-%d"));
1776 return datetime;
1780 * Converts a given time to a relative display string (relative to current time)
1781 * Given time must be in local timezone
1783 CString CAppUtils::ToRelativeTimeString(CTime time)
1785 CString answer;
1786 // convert to COleDateTime
1787 SYSTEMTIME sysTime;
1788 time.GetAsSystemTime( sysTime );
1789 COleDateTime oleTime( sysTime );
1790 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1791 return answer;
1795 * Generates a display string showing the relative time between the two given times as COleDateTimes
1797 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1799 CString answer;
1800 COleDateTimeSpan ts = RelativeTo - time;
1801 //years
1802 if(fabs(ts.GetTotalDays()) >= 3*365)
1804 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1806 //Months
1807 if(fabs(ts.GetTotalDays()) >= 60)
1809 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1810 return answer;
1812 //Weeks
1813 if(fabs(ts.GetTotalDays()) >= 14)
1815 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1816 return answer;
1818 //Days
1819 if(fabs(ts.GetTotalDays()) >= 2)
1821 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1822 return answer;
1824 //hours
1825 if(fabs(ts.GetTotalHours()) >= 2)
1827 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1828 return answer;
1830 //minutes
1831 if(fabs(ts.GetTotalMinutes()) >= 2)
1833 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1834 return answer;
1836 //seconds
1837 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1838 return answer;
1841 /**
1842 * Passed a value and two resource string ids
1843 * if count is 1 then FormatString is called with format_1 and the value
1844 * otherwise format_2 is used
1845 * the formatted string is returned
1847 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1849 CString answer;
1850 if ( count == 1 )
1852 answer.FormatMessage( format_1, count );
1854 else
1856 answer.FormatMessage( format_n, count );
1858 return answer;
1861 bool CAppUtils::IsSSHPutty()
1863 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1864 sshclient=sshclient.MakeLower();
1865 if(sshclient.Find(_T("plink.exe"),0)>=0)
1867 return true;
1869 return false;
1872 CString CAppUtils::GetClipboardLink()
1874 if (!OpenClipboard(NULL))
1875 return CString();
1877 CString sClipboardText;
1878 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1879 if (hglb)
1881 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1882 sClipboardText = CString(lpstr);
1883 GlobalUnlock(hglb);
1885 hglb = GetClipboardData(CF_UNICODETEXT);
1886 if (hglb)
1888 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1889 sClipboardText = lpstr;
1890 GlobalUnlock(hglb);
1892 CloseClipboard();
1894 if(!sClipboardText.IsEmpty())
1896 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1897 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1899 if(sClipboardText.Find( _T("http://")) == 0)
1900 return sClipboardText;
1902 if(sClipboardText.Find( _T("https://")) == 0)
1903 return sClipboardText;
1905 if(sClipboardText.Find( _T("git://")) == 0)
1906 return sClipboardText;
1908 if(sClipboardText.Find( _T("ssh://")) == 0)
1909 return sClipboardText;
1911 if(sClipboardText.GetLength()>=2)
1912 if( sClipboardText[1] == _T(':') )
1913 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1914 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1915 return sClipboardText;
1918 return CString(_T(""));
1921 CString CAppUtils::ChooseRepository(CString *path)
1923 CBrowseFolder browseFolder;
1924 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1925 CString strCloneDirectory;
1926 if(path)
1927 strCloneDirectory=*path;
1929 CString title;
1930 title.LoadString(IDS_CHOOSE_REPOSITORY);
1932 browseFolder.SetInfo(title);
1934 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1936 return strCloneDirectory;
1938 }else
1940 return CString();