Fixed issue #429: When applying patches, tortoise doesn't remember last file location
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob08c75e3a0a5f64162144f5c6ce6d4386e3d7988a
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"
46 #include "SendMailDlg.h"
47 #include "SVNProgressDlg.h"
48 #include "PushDlg.h"
49 #include "CommitDlg.h"
50 #include "MergeDlg.h"
52 CAppUtils::CAppUtils(void)
56 CAppUtils::~CAppUtils(void)
60 int CAppUtils::StashApply(CString ref)
62 CString cmd,out;
63 cmd=_T("git.exe stash apply ");
64 cmd+=ref;
66 if(g_Git.Run(cmd,&out,CP_ACP))
68 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
70 }else
72 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
73 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
75 CChangedDlg dlg;
76 dlg.m_pathList.AddPath(CTGitPath());
77 dlg.DoModal();
79 return 0;
81 return -1;
84 int CAppUtils::StashPop()
86 CString cmd,out;
87 cmd=_T("git.exe stash pop ");
89 if(g_Git.Run(cmd,&out,CP_ACP))
91 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
93 }else
95 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
96 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
98 CChangedDlg dlg;
99 dlg.m_pathList.AddPath(CTGitPath());
100 dlg.DoModal();
102 return 0;
104 return -1;
107 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
109 #if 0
110 GitProperties props(file, GitRev::REV_WC, false);
111 for (int i = 0; i < props.GetCount(); ++i)
113 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
115 mimetype = props.GetItemValue(i).c_str();
116 return true;
119 #endif
120 return false;
123 BOOL CAppUtils::StartExtMerge(
124 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
125 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
128 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
129 CString ext = mergedfile.GetFileExtension();
130 CString com = regCom;
131 bool bInternal = false;
133 CString mimetype;
134 if (ext != "")
136 // is there an extension specific merge tool?
137 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
138 if (CString(mergetool) != "")
140 com = mergetool;
143 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
145 // is there a mime type specific merge tool?
146 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
147 if (CString(mergetool) != "")
149 com = mergetool;
153 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
155 // use TortoiseMerge
156 bInternal = true;
157 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
158 com = tortoiseMergePath;
159 if (com.IsEmpty())
161 com = CPathUtils::GetAppDirectory();
162 com += _T("TortoiseMerge.exe");
164 com = _T("\"") + com + _T("\"");
165 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
166 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
168 // check if the params are set. If not, just add the files to the command line
169 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
171 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
172 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
173 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
174 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
176 if (basefile.IsEmpty())
178 com.Replace(_T("/base:%base"), _T(""));
179 com.Replace(_T("%base"), _T(""));
181 else
182 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
183 if (theirfile.IsEmpty())
185 com.Replace(_T("/theirs:%theirs"), _T(""));
186 com.Replace(_T("%theirs"), _T(""));
188 else
189 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
190 if (yourfile.IsEmpty())
192 com.Replace(_T("/mine:%mine"), _T(""));
193 com.Replace(_T("%mine"), _T(""));
195 else
196 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
197 if (mergedfile.IsEmpty())
199 com.Replace(_T("/merged:%merged"), _T(""));
200 com.Replace(_T("%merged"), _T(""));
202 else
203 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
204 if (basename.IsEmpty())
206 if (basefile.IsEmpty())
208 com.Replace(_T("/basename:%bname"), _T(""));
209 com.Replace(_T("%bname"), _T(""));
211 else
213 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
216 else
217 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
218 if (theirname.IsEmpty())
220 if (theirfile.IsEmpty())
222 com.Replace(_T("/theirsname:%tname"), _T(""));
223 com.Replace(_T("%tname"), _T(""));
225 else
227 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
230 else
231 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
232 if (yourname.IsEmpty())
234 if (yourfile.IsEmpty())
236 com.Replace(_T("/minename:%yname"), _T(""));
237 com.Replace(_T("%yname"), _T(""));
239 else
241 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
244 else
245 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
246 if (mergedname.IsEmpty())
248 if (mergedfile.IsEmpty())
250 com.Replace(_T("/mergedname:%mname"), _T(""));
251 com.Replace(_T("%mname"), _T(""));
253 else
255 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
258 else
259 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
261 if ((bReadOnly)&&(bInternal))
262 com += _T(" /readonly");
264 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
266 return FALSE;
269 return TRUE;
272 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
274 CString viewer;
275 // use TortoiseMerge
276 viewer = CPathUtils::GetAppDirectory();
277 viewer += _T("TortoiseMerge.exe");
279 viewer = _T("\"") + viewer + _T("\"");
280 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
281 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
282 if (bReversed)
283 viewer += _T(" /reversedpatch");
284 if (!sOriginalDescription.IsEmpty())
285 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
286 if (!sPatchedDescription.IsEmpty())
287 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
288 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
290 return FALSE;
292 return TRUE;
295 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
297 // Is there a mime type specific diff tool?
298 CString mimetype;
299 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
301 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
302 if (!difftool.IsEmpty())
303 return difftool;
306 // Is there an extension specific diff tool?
307 CString ext = file2.GetFileExtension().MakeLower();
308 if (!ext.IsEmpty())
310 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
311 if (!difftool.IsEmpty())
312 return difftool;
313 // Maybe we should use TortoiseIDiff?
314 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
315 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
316 (ext == _T(".png")) || (ext == _T(".ico")) ||
317 (ext == _T(".dib")) || (ext == _T(".emf")))
319 return
320 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
321 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
325 // Finally, pick a generic external diff tool
326 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
327 return difftool;
330 bool CAppUtils::StartExtDiff(
331 const CString& file1, const CString& file2,
332 const CString& sName1, const CString& sName2,
333 const DiffFlags& flags)
335 CString viewer;
337 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
338 if (!flags.bBlame || !(DWORD)blamediff)
340 viewer = PickDiffTool(file1, file2);
341 // If registry entry for a diff program is commented out, use TortoiseMerge.
342 bool bCommentedOut = viewer.Left(1) == _T("#");
343 if (flags.bAlternativeTool)
345 // Invert external vs. internal diff tool selection.
346 if (bCommentedOut)
347 viewer.Delete(0); // uncomment
348 else
349 viewer = "";
351 else if (bCommentedOut)
352 viewer = "";
355 bool bInternal = viewer.IsEmpty();
356 if (bInternal)
358 viewer =
359 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
360 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
361 if (flags.bBlame)
362 viewer += _T(" /blame");
364 // check if the params are set. If not, just add the files to the command line
365 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
367 viewer += _T(" \"")+file1+_T("\"");
368 viewer += _T(" \"")+file2+_T("\"");
370 if (viewer.Find(_T("%base")) >= 0)
372 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
374 if (viewer.Find(_T("%mine")) >= 0)
376 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
379 if (sName1.IsEmpty())
380 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
381 else
382 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
384 if (sName2.IsEmpty())
385 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
386 else
387 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
389 if (flags.bReadOnly && bInternal)
390 viewer += _T(" /readonly");
392 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
395 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
397 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
398 CString viewer = diffpropsexe;
399 bool bInternal = false;
400 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
402 //no registry entry (or commented out) for a diff program
403 //use TortoiseMerge
404 bInternal = true;
405 viewer = CPathUtils::GetAppDirectory();
406 viewer += _T("TortoiseMerge.exe");
407 viewer = _T("\"") + viewer + _T("\"");
408 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
410 // check if the params are set. If not, just add the files to the command line
411 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
413 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
414 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
416 if (viewer.Find(_T("%base")) >= 0)
418 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
420 if (viewer.Find(_T("%mine")) >= 0)
422 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
425 if (sName1.IsEmpty())
426 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
427 else
428 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
430 if (sName2.IsEmpty())
431 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
432 else
433 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
435 if ((bReadOnly)&&(bInternal))
436 viewer += _T(" /readonly");
438 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
440 return FALSE;
442 return TRUE;
445 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
447 CString viewer;
448 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
449 viewer = v;
450 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
452 // use TortoiseUDiff
453 viewer = CPathUtils::GetAppDirectory();
454 viewer += _T("TortoiseUDiff.exe");
455 // enquote the path to TortoiseUDiff
456 viewer = _T("\"") + viewer + _T("\"");
457 // add the params
458 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
461 if (viewer.Find(_T("%1"))>=0)
463 if (viewer.Find(_T("\"%1\"")) >= 0)
464 viewer.Replace(_T("%1"), patchfile);
465 else
466 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
468 else
469 viewer += _T(" \"") + patchfile + _T("\"");
470 if (viewer.Find(_T("%title")) >= 0)
472 viewer.Replace(_T("%title"), title);
475 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
477 return FALSE;
479 return TRUE;
482 BOOL CAppUtils::StartTextViewer(CString file)
484 CString viewer;
485 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
486 viewer = txt;
487 viewer = viewer + _T("\\Shell\\Open\\Command\\");
488 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
489 viewer = txtexe;
491 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
492 TCHAR * buf = new TCHAR[len+1];
493 ExpandEnvironmentStrings(viewer, buf, len);
494 viewer = buf;
495 delete [] buf;
496 len = ExpandEnvironmentStrings(file, NULL, 0);
497 buf = new TCHAR[len+1];
498 ExpandEnvironmentStrings(file, buf, len);
499 file = buf;
500 delete [] buf;
501 file = _T("\"")+file+_T("\"");
502 if (viewer.IsEmpty())
504 OPENFILENAME ofn = {0}; // common dialog box structure
505 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
506 // Initialize OPENFILENAME
507 ofn.lStructSize = sizeof(OPENFILENAME);
508 ofn.hwndOwner = NULL;
509 ofn.lpstrFile = szFile;
510 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
511 CString sFilter;
512 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
513 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
514 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
515 // Replace '|' delimiters with '\0's
516 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
517 while (ptr != pszFilters)
519 if (*ptr == '|')
520 *ptr = '\0';
521 ptr--;
523 ofn.lpstrFilter = pszFilters;
524 ofn.nFilterIndex = 1;
525 ofn.lpstrFileTitle = NULL;
526 ofn.nMaxFileTitle = 0;
527 ofn.lpstrInitialDir = NULL;
528 CString temp;
529 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
530 CStringUtils::RemoveAccelerators(temp);
531 ofn.lpstrTitle = temp;
532 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
534 // Display the Open dialog box.
536 if (GetOpenFileName(&ofn)==TRUE)
538 delete [] pszFilters;
539 viewer = CString(ofn.lpstrFile);
541 else
543 delete [] pszFilters;
544 return FALSE;
547 if (viewer.Find(_T("\"%1\"")) >= 0)
549 viewer.Replace(_T("\"%1\""), file);
551 else if (viewer.Find(_T("%1")) >= 0)
553 viewer.Replace(_T("%1"), file);
555 else
557 viewer += _T(" ");
558 viewer += file;
561 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
563 return FALSE;
565 return TRUE;
568 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
570 DWORD length = 0;
571 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
572 if (hFile == INVALID_HANDLE_VALUE)
573 return TRUE;
574 length = ::GetFileSize(hFile, NULL);
575 ::CloseHandle(hFile);
576 if (length < 4)
577 return TRUE;
578 return FALSE;
582 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
584 LOGFONT logFont;
585 HDC hScreenDC = ::GetDC(NULL);
586 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
587 ::ReleaseDC(NULL, hScreenDC);
588 logFont.lfWidth = 0;
589 logFont.lfEscapement = 0;
590 logFont.lfOrientation = 0;
591 logFont.lfWeight = FW_NORMAL;
592 logFont.lfItalic = 0;
593 logFont.lfUnderline = 0;
594 logFont.lfStrikeOut = 0;
595 logFont.lfCharSet = DEFAULT_CHARSET;
596 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
597 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
598 logFont.lfQuality = DRAFT_QUALITY;
599 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
600 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
601 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
604 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
606 STARTUPINFO startup;
607 PROCESS_INFORMATION process;
608 memset(&startup, 0, sizeof(startup));
609 startup.cb = sizeof(startup);
610 memset(&process, 0, sizeof(process));
612 CString cleanCommandLine(sCommandLine);
614 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
616 if(idErrMessageFormat != 0)
618 LPVOID lpMsgBuf;
619 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
620 FORMAT_MESSAGE_FROM_SYSTEM |
621 FORMAT_MESSAGE_IGNORE_INSERTS,
622 NULL,
623 GetLastError(),
624 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
625 (LPTSTR) &lpMsgBuf,
627 NULL
629 CString temp;
630 temp.Format(idErrMessageFormat, lpMsgBuf);
631 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
632 LocalFree( lpMsgBuf );
634 return false;
637 if (bWaitForStartup)
639 WaitForInputIdle(process.hProcess, 10000);
642 CloseHandle(process.hThread);
643 CloseHandle(process.hProcess);
644 return true;
646 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
648 CString key,remote;
649 CString cmd,out;
650 if( pRemote == NULL)
652 remote=_T("origin");
653 }else
655 remote=*pRemote;
657 if(keyfile == NULL)
659 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
660 g_Git.Run(cmd,&key,CP_ACP);
661 int start=0;
662 key = key.Tokenize(_T("\n"),start);
664 else
665 key=*keyfile;
667 if(key.IsEmpty())
668 return false;
670 CString proc=CPathUtils::GetAppDirectory();
671 proc += _T("pageant.exe \"");
672 proc += key;
673 proc += _T("\"");
675 return LaunchApplication(proc, IDS_ERR_PAGEANT, false);
677 bool CAppUtils::LaunchRemoteSetting()
679 CString proc=CPathUtils::GetAppDirectory();
680 proc += _T("TortoiseProc.exe /command:settings");
681 proc += _T(" /path:\"");
682 proc += g_Git.m_CurrentDir;
683 proc += _T("\" /page:gitremote");
684 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
687 * Launch the external blame viewer
689 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
691 CString viewer = CPathUtils::GetAppDirectory();
692 viewer += _T("TortoiseGitBlame.exe");
693 viewer += _T(" \"") + sBlameFile + _T("\"");
694 //viewer += _T(" \"") + sLogFile + _T("\"");
695 //viewer += _T(" \"") + sOriginalFile + _T("\"");
696 if(!Rev.IsEmpty())
697 viewer += CString(_T(" /rev:"))+Rev;
698 viewer += _T(" ")+sParams;
700 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
703 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
705 CString sText;
706 if (pWnd == NULL)
707 return false;
708 bool bStyled = false;
709 pWnd->GetWindowText(sText);
710 // the rich edit control doesn't count the CR char!
711 // to be exact: CRLF is treated as one char.
712 sText.Replace(_T("\r"), _T(""));
714 // style each line separately
715 int offset = 0;
716 int nNewlinePos;
719 nNewlinePos = sText.Find('\n', offset);
720 CString sLine = sText.Mid(offset);
721 if (nNewlinePos>=0)
722 sLine = sLine.Left(nNewlinePos-offset);
723 int start = 0;
724 int end = 0;
725 while (FindStyleChars(sLine, '*', start, end))
727 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
728 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
729 CHARFORMAT2 format;
730 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
731 format.cbSize = sizeof(CHARFORMAT2);
732 format.dwMask = CFM_BOLD;
733 format.dwEffects = CFE_BOLD;
734 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
735 bStyled = true;
736 start = end;
738 start = 0;
739 end = 0;
740 while (FindStyleChars(sLine, '^', start, end))
742 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
743 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
744 CHARFORMAT2 format;
745 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
746 format.cbSize = sizeof(CHARFORMAT2);
747 format.dwMask = CFM_ITALIC;
748 format.dwEffects = CFE_ITALIC;
749 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
750 bStyled = true;
751 start = end;
753 start = 0;
754 end = 0;
755 while (FindStyleChars(sLine, '_', start, end))
757 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
758 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
759 CHARFORMAT2 format;
760 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
761 format.cbSize = sizeof(CHARFORMAT2);
762 format.dwMask = CFM_UNDERLINE;
763 format.dwEffects = CFE_UNDERLINE;
764 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
765 bStyled = true;
766 start = end;
768 offset = nNewlinePos+1;
769 } while(nNewlinePos>=0);
770 return bStyled;
773 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
775 int i=start;
776 bool bFoundMarker = false;
777 // find a starting marker
778 while (sText[i] != 0)
780 if (sText[i] == stylechar)
782 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
783 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
785 start = i+1;
786 i++;
787 bFoundMarker = true;
788 break;
791 i++;
793 if (!bFoundMarker)
794 return false;
795 // find ending marker
796 bFoundMarker = false;
797 while (sText[i] != 0)
799 if (sText[i] == stylechar)
801 if ((IsCharAlphaNumeric(sText[i-1])) &&
802 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
804 end = i;
805 i++;
806 bFoundMarker = true;
807 break;
810 i++;
812 return bFoundMarker;
815 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
817 #if 0
818 CString strUrl;
819 combo.GetWindowText(strUrl);
820 strUrl.Replace('\\', '/');
821 strUrl.Replace(_T("%"), _T("%25"));
822 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
823 if (strUrl.Left(7) == _T("file://"))
825 CString strFile(strUrl);
826 Git::UrlToPath(strFile);
828 Git svn;
829 if (svn.IsRepository(CTGitPath(strFile)))
831 // browse repository - show repository browser
832 Git::preparePath(strUrl);
833 CRepositoryBrowser browser(strUrl, rev, pParent);
834 if (browser.DoModal() == IDOK)
836 combo.SetCurSel(-1);
837 combo.SetWindowText(browser.GetPath());
838 rev = browser.GetRevision();
839 return true;
842 else
844 // browse local directories
845 CBrowseFolder folderBrowser;
846 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
847 // remove the 'file:///' so the shell can recognize the local path
848 Git::UrlToPath(strUrl);
849 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
851 Git::PathToUrl(strUrl);
853 combo.SetCurSel(-1);
854 combo.SetWindowText(strUrl);
855 return true;
859 else if ((strUrl.Left(7) == _T("http://")
860 ||(strUrl.Left(8) == _T("https://"))
861 ||(strUrl.Left(6) == _T("svn://"))
862 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
864 // browse repository - show repository browser
865 CRepositoryBrowser browser(strUrl, rev, pParent);
866 if (browser.DoModal() == IDOK)
868 combo.SetCurSel(-1);
869 combo.SetWindowText(browser.GetPath());
870 rev = browser.GetRevision();
871 return true;
874 else
876 // browse local directories
877 CBrowseFolder folderBrowser;
878 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
879 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
881 Git::PathToUrl(strUrl);
883 combo.SetCurSel(-1);
884 combo.SetWindowText(strUrl);
885 return true;
888 #endif
889 return false;
892 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
894 OPENFILENAME ofn = {0}; // common dialog box structure
895 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
896 ofn.lStructSize = sizeof(OPENFILENAME);
897 ofn.hwndOwner = hwndOwner;
898 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
899 ofn.lpstrFile = szFile;
900 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
901 CString sFilter;
902 TCHAR * pszFilters = NULL;
903 if (filter)
905 sFilter.LoadString(filter);
906 pszFilters = new TCHAR[sFilter.GetLength()+4];
907 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
908 // Replace '|' delimiters with '\0's
909 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
910 while (ptr != pszFilters)
912 if (*ptr == '|')
913 *ptr = '\0';
914 ptr--;
916 ofn.lpstrFilter = pszFilters;
918 ofn.nFilterIndex = 1;
919 ofn.lpstrFileTitle = NULL;
920 ofn.nMaxFileTitle = 0;
921 ofn.lpstrInitialDir = NULL;
922 CString temp;
923 if (title)
925 temp.LoadString(title);
926 CStringUtils::RemoveAccelerators(temp);
928 ofn.lpstrTitle = temp;
929 if (bOpen)
930 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
931 else
932 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
935 // Display the Open dialog box.
936 bool bRet = false;
937 if (bOpen)
939 bRet = !!GetOpenFileName(&ofn);
941 else
943 bRet = !!GetSaveFileName(&ofn);
945 if (bRet)
947 if (pszFilters)
948 delete [] pszFilters;
949 path = CString(ofn.lpstrFile);
950 if (filterindex)
951 *filterindex = ofn.nFilterIndex;
952 return true;
954 if (pszFilters)
955 delete [] pszFilters;
956 return false;
959 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
961 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
962 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
963 // create a bitmap from the icon
964 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
965 if (!hIcon)
966 return false;
968 RECT rect = {0};
969 rect.right = width;
970 rect.bottom = height;
971 HBITMAP bmp = NULL;
973 HWND desktop = ::GetDesktopWindow();
974 if (desktop)
976 HDC screen_dev = ::GetDC(desktop);
977 if (screen_dev)
979 // Create a compatible DC
980 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
981 if (dst_hdc)
983 // Create a new bitmap of icon size
984 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
985 if (bmp)
987 // Select it into the compatible DC
988 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
989 // Fill the background of the compatible DC with the given color
990 ::SetBkColor(dst_hdc, bkColor);
991 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
993 // Draw the icon into the compatible DC
994 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
995 ::SelectObject(dst_hdc, old_dst_bmp);
997 ::DeleteDC(dst_hdc);
1000 ::ReleaseDC(desktop, screen_dev);
1003 // Restore settings
1004 DestroyIcon(hIcon);
1006 if (bmp == NULL)
1007 return false;
1009 LVBKIMAGE lv;
1010 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1011 lv.hbm = bmp;
1012 lv.xOffsetPercent = 100;
1013 lv.yOffsetPercent = 100;
1014 ListView_SetBkImage(hListCtrl, &lv);
1015 return true;
1018 CString CAppUtils::GetProjectNameFromURL(CString url)
1020 CString name;
1021 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1022 (name.CompareNoCase(_T("tags"))==0) ||
1023 (name.CompareNoCase(_T("trunk"))==0))
1025 name = url.Mid(url.ReverseFind('/')+1);
1026 url = url.Left(url.ReverseFind('/'));
1028 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1030 // a name of svn or svnroot indicates that it's not really the project name. In that
1031 // case, we try the first part of the URL
1032 // of course, this won't work in all cases (but it works for Google project hosting)
1033 url.Replace(_T("http://"), _T(""));
1034 url.Replace(_T("https://"), _T(""));
1035 url.Replace(_T("svn://"), _T(""));
1036 url.Replace(_T("svn+ssh://"), _T(""));
1037 url.TrimLeft(_T("/"));
1038 name = url.Left(url.Find('.'));
1040 return name;
1043 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1044 const CTGitPath& url2, const git_revnum_t& rev2,
1045 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1046 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1049 CString tempfile=GetTempFile();
1050 CString cmd;
1051 if(rev1 == GitRev::GetWorkingCopy())
1053 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1054 }else
1056 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1059 if( !url1.IsEmpty() )
1061 cmd+=_T(" \"");
1062 cmd+=url1.GetGitPathString();
1063 cmd+=_T("\" ");
1065 g_Git.RunLogFile(cmd,tempfile);
1066 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1069 #if 0
1070 CString sCmd;
1071 sCmd.Format(_T("%s /command:showcompare /unified"),
1072 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1073 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1074 if (rev1.IsValid())
1075 sCmd += _T(" /revision1:") + rev1.ToString();
1076 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1077 if (rev2.IsValid())
1078 sCmd += _T(" /revision2:") + rev2.ToString();
1079 if (peg.IsValid())
1080 sCmd += _T(" /pegrevision:") + peg.ToString();
1081 if (headpeg.IsValid())
1082 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1084 if (bAlternateDiff)
1085 sCmd += _T(" /alternatediff");
1087 if (bIgnoreAncestry)
1088 sCmd += _T(" /ignoreancestry");
1090 if (hWnd)
1092 sCmd += _T(" /hwnd:");
1093 TCHAR buf[30];
1094 _stprintf_s(buf, 30, _T("%d"), hWnd);
1095 sCmd += buf;
1098 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1099 #endif
1100 return TRUE;
1103 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1104 const CTGitPath& url2, const GitRev& rev2,
1105 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1106 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1108 #if 0
1109 CString sCmd;
1110 sCmd.Format(_T("%s /command:showcompare"),
1111 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1112 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1113 if (rev1.IsValid())
1114 sCmd += _T(" /revision1:") + rev1.ToString();
1115 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1116 if (rev2.IsValid())
1117 sCmd += _T(" /revision2:") + rev2.ToString();
1118 if (peg.IsValid())
1119 sCmd += _T(" /pegrevision:") + peg.ToString();
1120 if (headpeg.IsValid())
1121 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1122 if (bAlternateDiff)
1123 sCmd += _T(" /alternatediff");
1124 if (bIgnoreAncestry)
1125 sCmd += _T(" /ignoreancestry");
1126 if (blame)
1127 sCmd += _T(" /blame");
1129 if (hWnd)
1131 sCmd += _T(" /hwnd:");
1132 TCHAR buf[30];
1133 _stprintf_s(buf, 30, _T("%d"), hWnd);
1134 sCmd += buf;
1137 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1138 #endif
1139 return true;
1142 bool CAppUtils::Export(CString *BashHash)
1144 bool bRet = false;
1146 // ask from where the export has to be done
1147 CExportDlg dlg;
1148 if(BashHash)
1149 dlg.m_Revision=*BashHash;
1151 if (dlg.DoModal() == IDOK)
1153 CString cmd;
1154 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1155 dlg.m_VersionName);
1157 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1158 CProgressDlg pro;
1159 pro.m_GitCmd=cmd;
1160 pro.m_LogFile=dlg.m_strExportDirectory;
1161 pro.DoModal();
1162 return TRUE;
1164 return bRet;
1167 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1169 CCreateBranchTagDlg dlg;
1170 dlg.m_bIsTag=IsTag;
1171 if(CommitHash)
1172 dlg.m_Base = *CommitHash;
1174 if(dlg.DoModal()==IDOK)
1176 CString cmd;
1177 CString force;
1178 CString track;
1179 if(dlg.m_bTrack)
1180 track=_T(" --track ");
1182 if(dlg.m_bForce)
1183 force=_T(" -f ");
1185 if(IsTag)
1187 cmd.Format(_T("git.exe tag %s %s %s %s"),
1188 track,
1189 force,
1190 dlg.m_BranchTagName,
1191 dlg.m_VersionName
1194 CString tempfile=::GetTempFile();
1195 if(!dlg.m_Message.Trim().IsEmpty())
1197 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1198 cmd += _T(" -F ")+tempfile;
1201 }else
1203 cmd.Format(_T("git.exe branch %s %s %s %s"),
1204 track,
1205 force,
1206 dlg.m_BranchTagName,
1207 dlg.m_VersionName
1210 CString out;
1211 if(g_Git.Run(cmd,&out,CP_UTF8))
1213 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1215 if( !IsTag && dlg.m_bSwitch )
1217 // it is a new branch and the user has requested to switch to it
1218 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1219 g_Git.Run(cmd,&out,CP_UTF8);
1220 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1223 return TRUE;
1226 return FALSE;
1229 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1231 CGitSwitchDlg dlg;
1232 if(CommitHash)
1233 dlg.m_Base=*CommitHash;
1234 if(!initialRefName.IsEmpty())
1235 dlg.m_initialRefName = initialRefName;
1237 if (dlg.DoModal() == IDOK)
1239 CString cmd;
1240 CString track;
1241 // CString base;
1242 CString force;
1243 CString branch;
1245 if(dlg.m_bBranch)
1246 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1247 if(dlg.m_bForce)
1248 force=_T("-f");
1249 if(dlg.m_bTrack)
1250 track=_T("--track");
1252 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1253 force,
1254 track,
1255 branch,
1256 dlg.m_VersionName);
1258 CProgressDlg progress;
1259 progress.m_GitCmd=cmd;
1260 if(progress.DoModal()==IDOK)
1261 return TRUE;
1264 return FALSE;
1267 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1269 CString ignorefile;
1270 ignorefile=g_Git.m_CurrentDir+_T("\\");
1272 if(IsMask)
1274 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1276 }else
1278 ignorefile+=_T("\\.gitignore");
1281 CStdioFile file;
1282 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1284 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1285 return FALSE;
1288 CString ignorelist;
1289 CString mask;
1292 //file.ReadString(ignorelist);
1293 file.SeekToEnd();
1294 for(int i=0;i<path.GetCount();i++)
1296 if(IsMask)
1298 mask=_T("*")+path[i].GetFileExtension();
1299 if(ignorelist.Find(mask)<0)
1300 ignorelist+=_T("\n")+mask;
1302 }else
1304 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1307 file.WriteString(ignorelist);
1309 file.Close();
1311 }catch(...)
1313 file.Close();
1314 return FALSE;
1317 return TRUE;
1321 bool CAppUtils::GitReset(CString *CommitHash,int type)
1323 CResetDlg dlg;
1324 dlg.m_ResetType=type;
1325 if (dlg.DoModal() == IDOK)
1327 CString cmd;
1328 CString type;
1329 switch(dlg.m_ResetType)
1331 case 0:
1332 type=_T("--soft");
1333 break;
1334 case 1:
1335 type=_T("--mixed");
1336 break;
1337 case 2:
1338 type=_T("--hard");
1339 break;
1340 default:
1341 type=_T("--mixed");
1342 break;
1344 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1346 CProgressDlg progress;
1347 progress.m_GitCmd=cmd;
1348 if(progress.DoModal()==IDOK)
1349 return TRUE;
1352 return FALSE;
1355 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1357 if(mode == FALSE)
1359 descript=_T("Deleted");
1360 return;
1362 if(base)
1364 descript=_T("Modified");
1365 return;
1367 descript=_T("Created");
1368 return;
1371 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1373 CString file;
1374 file=g_Git.m_CurrentDir+_T("\\")+ type + merge.GetWinPathString();
1376 return file;
1379 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool,bool revertTheirMy)
1381 bool bRet = false;
1383 CTGitPath merge=path;
1384 CTGitPath directory = merge.GetDirectory();
1388 // we have the conflicted file (%merged)
1389 // now look for the other required files
1390 //GitStatus stat;
1391 //stat.GetStatus(merge);
1392 //if (stat.status == NULL)
1393 // return false;
1395 BYTE_VECTOR vector;
1397 CString cmd;
1398 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1400 if(g_Git.Run(cmd,&vector))
1402 return FALSE;
1405 CTGitPathList list;
1406 list.ParserFromLsFile(vector);
1408 if(list.GetCount() == 0)
1409 return FALSE;
1411 TCHAR szTempName[512];
1412 GetTempFileName(_T(""),_T(""),0,szTempName);
1413 CString temp(szTempName);
1414 temp=temp.Mid(1,temp.GetLength()-5);
1416 CTGitPath theirs;
1417 CTGitPath mine;
1418 CTGitPath base;
1421 mine.SetFromGit(GetMergeTempFile(_T("LOCAL."),merge));
1422 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE."),merge));
1423 base.SetFromGit(GetMergeTempFile(_T("BASE."),merge));
1425 CString format;
1427 //format=_T("git.exe cat-file blob \":%d:%s\"");
1428 format = _T("git checkout-index -f --prefix=%s --stage=%d -- \"%s\"");
1429 CFile tempfile;
1430 //create a empty file, incase stage is not three
1431 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1432 tempfile.Close();
1433 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1434 tempfile.Close();
1435 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1436 tempfile.Close();
1438 bool b_base=false, b_local=false, b_remote=false;
1440 for(int i=0;i<list.GetCount();i++)
1442 CString cmd;
1443 CString outfile;
1445 if( list[i].m_Stage == 1)
1447 cmd.Format(format,_T("BASE."), list[i].m_Stage, list[i].GetGitPathString());
1448 b_base = true;
1451 if( list[i].m_Stage == 2 )
1453 cmd.Format(format,_T("LOCAL."), list[i].m_Stage, list[i].GetGitPathString());
1454 b_local = true;
1457 if( list[i].m_Stage == 3 )
1459 cmd.Format(format,_T("REMOTE."), list[i].m_Stage, list[i].GetGitPathString());
1460 b_remote = true;
1463 CString output;
1464 g_Git.Run(cmd,&output,CP_ACP);
1467 if(b_local && b_remote )
1469 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1470 if( revertTheirMy )
1471 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1472 else
1473 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1475 }else
1477 CFile::Remove(mine.GetWinPathString());
1478 CFile::Remove(theirs.GetWinPathString());
1479 CFile::Remove(base.GetWinPathString());
1481 CDeleteConflictDlg dlg;
1482 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1483 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1484 dlg.m_bShowModifiedButton=b_base;
1485 dlg.m_File=merge.GetGitPathString();
1486 if(dlg.DoModal() == IDOK)
1488 CString cmd,out;
1489 if(dlg.m_bIsDelete)
1491 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1492 }else
1493 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1495 if(g_Git.Run(cmd,&out,CP_ACP))
1497 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1498 return FALSE;
1500 return TRUE;
1502 else
1503 return FALSE;
1509 #if 0
1511 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1512 base, theirs, mine, merge);
1513 #endif
1514 #if 0
1515 if (stat.status->text_status == svn_wc_status_conflicted)
1517 // we have a text conflict, use our merge tool to resolve the conflict
1519 CTSVNPath theirs(directory);
1520 CTSVNPath mine(directory);
1521 CTSVNPath base(directory);
1522 bool bConflictData = false;
1524 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1526 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1527 bConflictData = true;
1529 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1531 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1532 bConflictData = true;
1534 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1536 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1537 bConflictData = true;
1539 else
1541 mine = merge;
1543 if (bConflictData)
1544 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1545 base, theirs, mine, merge);
1548 if (stat.status->prop_status == svn_wc_status_conflicted)
1550 // we have a property conflict
1551 CTSVNPath prej(directory);
1552 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1554 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1555 // there's a problem: the prej file contains a _description_ of the conflict, and
1556 // that description string might be translated. That means we have no way of parsing
1557 // the file to find out the conflicting values.
1558 // The only thing we can do: show a dialog with the conflict description, then
1559 // let the user either accept the existing property or open the property edit dialog
1560 // to manually change the properties and values. And a button to mark the conflict as
1561 // resolved.
1562 CEditPropConflictDlg dlg;
1563 dlg.SetPrejFile(prej);
1564 dlg.SetConflictedItem(merge);
1565 bRet = (dlg.DoModal() != IDCANCEL);
1569 if (stat.status->tree_conflict)
1571 // we have a tree conflict
1572 SVNInfo info;
1573 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1574 if (pInfoData)
1576 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1578 CTSVNPath theirs(directory);
1579 CTSVNPath mine(directory);
1580 CTSVNPath base(directory);
1581 bool bConflictData = false;
1583 if (pInfoData->treeconflict_theirfile)
1585 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1586 bConflictData = true;
1588 if (pInfoData->treeconflict_basefile)
1590 base.AppendPathString(pInfoData->treeconflict_basefile);
1591 bConflictData = true;
1593 if (pInfoData->treeconflict_myfile)
1595 mine.AppendPathString(pInfoData->treeconflict_myfile);
1596 bConflictData = true;
1598 else
1600 mine = merge;
1602 if (bConflictData)
1603 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1604 base, theirs, mine, merge);
1606 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1608 CString sConflictAction;
1609 CString sConflictReason;
1610 CString sResolveTheirs;
1611 CString sResolveMine;
1612 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1613 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1615 if (pInfoData->treeconflict_nodekind == svn_node_file)
1617 switch (pInfoData->treeconflict_operation)
1619 case svn_wc_operation_update:
1620 switch (pInfoData->treeconflict_action)
1622 case svn_wc_conflict_action_edit:
1623 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1624 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1625 break;
1626 case svn_wc_conflict_action_add:
1627 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1628 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1629 break;
1630 case svn_wc_conflict_action_delete:
1631 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1632 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1633 break;
1635 break;
1636 case svn_wc_operation_switch:
1637 switch (pInfoData->treeconflict_action)
1639 case svn_wc_conflict_action_edit:
1640 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1641 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1642 break;
1643 case svn_wc_conflict_action_add:
1644 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1645 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1646 break;
1647 case svn_wc_conflict_action_delete:
1648 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1649 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1650 break;
1652 break;
1653 case svn_wc_operation_merge:
1654 switch (pInfoData->treeconflict_action)
1656 case svn_wc_conflict_action_edit:
1657 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1658 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1659 break;
1660 case svn_wc_conflict_action_add:
1661 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1662 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1663 break;
1664 case svn_wc_conflict_action_delete:
1665 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1666 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1667 break;
1669 break;
1672 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1674 switch (pInfoData->treeconflict_operation)
1676 case svn_wc_operation_update:
1677 switch (pInfoData->treeconflict_action)
1679 case svn_wc_conflict_action_edit:
1680 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1681 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1682 break;
1683 case svn_wc_conflict_action_add:
1684 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1685 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1686 break;
1687 case svn_wc_conflict_action_delete:
1688 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1689 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1690 break;
1692 break;
1693 case svn_wc_operation_switch:
1694 switch (pInfoData->treeconflict_action)
1696 case svn_wc_conflict_action_edit:
1697 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1698 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1699 break;
1700 case svn_wc_conflict_action_add:
1701 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1702 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1703 break;
1704 case svn_wc_conflict_action_delete:
1705 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1706 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1707 break;
1709 break;
1710 case svn_wc_operation_merge:
1711 switch (pInfoData->treeconflict_action)
1713 case svn_wc_conflict_action_edit:
1714 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1715 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1716 break;
1717 case svn_wc_conflict_action_add:
1718 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1719 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1720 break;
1721 case svn_wc_conflict_action_delete:
1722 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1723 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1724 break;
1726 break;
1730 UINT uReasonID = 0;
1731 switch (pInfoData->treeconflict_reason)
1733 case svn_wc_conflict_reason_edited:
1734 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1735 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1736 break;
1737 case svn_wc_conflict_reason_obstructed:
1738 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1739 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1740 break;
1741 case svn_wc_conflict_reason_deleted:
1742 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1743 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1744 break;
1745 case svn_wc_conflict_reason_added:
1746 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1747 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1748 break;
1749 case svn_wc_conflict_reason_missing:
1750 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1751 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1752 break;
1753 case svn_wc_conflict_reason_unversioned:
1754 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1755 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1756 break;
1758 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1760 CTreeConflictEditorDlg dlg;
1761 dlg.SetConflictInfoText(sConflictReason);
1762 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1763 dlg.SetPath(treeConflictPath);
1764 INT_PTR dlgRet = dlg.DoModal();
1765 bRet = (dlgRet != IDCANCEL);
1769 #endif
1770 return bRet;
1774 * FUNCTION : FormatDateAndTime
1775 * DESCRIPTION : Generates a displayable string from a CTime object in
1776 * system short or long format or as a relative value
1777 * cTime - the time
1778 * option - DATE_SHORTDATE or DATE_LONGDATE
1779 * bIncluedeTime - whether to show time as well as date
1780 * bRelative - if true then relative time is shown if reasonable
1781 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1782 * rather than locale
1783 * RETURN : CString containing date/time
1785 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1786 bool bRelative /*=false*/)
1788 CString datetime;
1789 if ( bRelative )
1791 datetime = ToRelativeTimeString( cTime );
1793 else
1795 // should we use the locale settings for formatting the date/time?
1796 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1798 // yes
1799 SYSTEMTIME sysTime;
1800 cTime.GetAsSystemTime( sysTime );
1802 TCHAR buf[100];
1804 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1805 sizeof(buf)/sizeof(TCHAR)-1);
1806 datetime = buf;
1807 if ( bIncludeTime )
1809 datetime += _T(" ");
1810 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1811 datetime += buf;
1814 else
1816 // no, so fixed format
1817 if ( bIncludeTime )
1819 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1821 else
1823 datetime = cTime.Format(_T("%Y-%m-%d"));
1827 return datetime;
1831 * Converts a given time to a relative display string (relative to current time)
1832 * Given time must be in local timezone
1834 CString CAppUtils::ToRelativeTimeString(CTime time)
1836 CString answer;
1837 // convert to COleDateTime
1838 SYSTEMTIME sysTime;
1839 time.GetAsSystemTime( sysTime );
1840 COleDateTime oleTime( sysTime );
1841 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1842 return answer;
1846 * Generates a display string showing the relative time between the two given times as COleDateTimes
1848 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1850 CString answer;
1851 COleDateTimeSpan ts = RelativeTo - time;
1852 //years
1853 if(fabs(ts.GetTotalDays()) >= 3*365)
1855 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1857 //Months
1858 if(fabs(ts.GetTotalDays()) >= 60)
1860 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1861 return answer;
1863 //Weeks
1864 if(fabs(ts.GetTotalDays()) >= 14)
1866 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1867 return answer;
1869 //Days
1870 if(fabs(ts.GetTotalDays()) >= 2)
1872 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1873 return answer;
1875 //hours
1876 if(fabs(ts.GetTotalHours()) >= 2)
1878 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1879 return answer;
1881 //minutes
1882 if(fabs(ts.GetTotalMinutes()) >= 2)
1884 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1885 return answer;
1887 //seconds
1888 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1889 return answer;
1892 /**
1893 * Passed a value and two resource string ids
1894 * if count is 1 then FormatString is called with format_1 and the value
1895 * otherwise format_2 is used
1896 * the formatted string is returned
1898 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1900 CString answer;
1901 if ( count == 1 )
1903 answer.FormatMessage( format_1, count );
1905 else
1907 answer.FormatMessage( format_n, count );
1909 return answer;
1912 bool CAppUtils::IsSSHPutty()
1914 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1915 sshclient=sshclient.MakeLower();
1916 if(sshclient.Find(_T("plink.exe"),0)>=0)
1918 return true;
1920 return false;
1923 CString CAppUtils::GetClipboardLink()
1925 if (!OpenClipboard(NULL))
1926 return CString();
1928 CString sClipboardText;
1929 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1930 if (hglb)
1932 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1933 sClipboardText = CString(lpstr);
1934 GlobalUnlock(hglb);
1936 hglb = GetClipboardData(CF_UNICODETEXT);
1937 if (hglb)
1939 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1940 sClipboardText = lpstr;
1941 GlobalUnlock(hglb);
1943 CloseClipboard();
1945 if(!sClipboardText.IsEmpty())
1947 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1948 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1950 if(sClipboardText.Find( _T("http://")) == 0)
1951 return sClipboardText;
1953 if(sClipboardText.Find( _T("https://")) == 0)
1954 return sClipboardText;
1956 if(sClipboardText.Find( _T("git://")) == 0)
1957 return sClipboardText;
1959 if(sClipboardText.Find( _T("ssh://")) == 0)
1960 return sClipboardText;
1962 if(sClipboardText.GetLength()>=2)
1963 if( sClipboardText[1] == _T(':') )
1964 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1965 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1966 return sClipboardText;
1969 return CString(_T(""));
1972 CString CAppUtils::ChooseRepository(CString *path)
1974 CBrowseFolder browseFolder;
1975 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1977 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1978 CString strCloneDirectory;
1979 if(path)
1980 strCloneDirectory=*path;
1981 else
1983 strCloneDirectory = regLastResopitory;
1986 CString title;
1987 title.LoadString(IDS_CHOOSE_REPOSITORY);
1989 browseFolder.SetInfo(title);
1991 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1993 regLastResopitory = strCloneDirectory;
1994 return strCloneDirectory;
1996 }else
1998 return CString();
2003 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2005 CSendMailDlg dlg;
2007 dlg.m_PathList = list;
2009 if(dlg.DoModal()==IDOK)
2011 if(dlg.m_PathList.GetCount() == 0)
2012 return FALSE;
2014 CGitProgressDlg progDlg;
2016 theApp.m_pMainWnd = &progDlg;
2017 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2019 progDlg.SetAutoClose(autoclose);
2021 progDlg.SetPathList(dlg.m_PathList);
2022 //ProjectProperties props;
2023 //props.ReadPropsPathList(dlg.m_pathList);
2024 //progDlg.SetProjectProperties(props);
2025 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2027 DWORD flags =0;
2028 if(dlg.m_bAttachment)
2029 flags |= SENDMAIL_ATTACHMENT;
2030 if(dlg.m_bCombine)
2031 flags |= SENDMAIL_COMBINED;
2033 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2035 progDlg.DoModal();
2037 return true;
2039 return false;
2042 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2044 CTGitPathList list;
2045 CString log=formatpatchoutput;
2046 int start=log.Find(cmd);
2047 if(start >=0)
2048 CString one=log.Tokenize(_T("\n"),start);
2049 else
2050 start = 0;
2052 while(start>=0)
2054 CString one=log.Tokenize(_T("\n"),start);
2055 one=one.Trim();
2056 if(one.IsEmpty())
2057 continue;
2058 one.Replace(_T('/'),_T('\\'));
2059 CTGitPath path;
2060 path.SetFromWin(one);
2061 list.AddPath(path);
2063 return SendPatchMail(list,autoclose);
2067 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2069 CString cmd,output;
2070 int start=0;
2071 cmd=_T("git.exe config i18n.logOutputEncoding");
2072 if(pGit->Run(cmd,&output,CP_ACP))
2074 cmd=_T("git.exe config i18n.commitencoding");
2075 if(pGit->Run(cmd,&output,CP_ACP))
2076 return CP_UTF8;
2078 int start=0;
2079 output=output.Tokenize(_T("\n"),start);
2080 return CUnicodeUtils::GetCPCode(output);
2082 }else
2084 output=output.Tokenize(_T("\n"),start);
2085 return CUnicodeUtils::GetCPCode(output);
2088 int CAppUtils::GetCommitTemplate(CString &temp)
2090 CString cmd,output;
2091 cmd = _T("git.exe config commit.template");
2092 if( g_Git.Run(cmd,&output,CP_ACP) )
2093 return -1;
2095 if( output.GetLength()<1)
2096 return -1;
2098 if( output[0] == _T('/'))
2100 if(output.GetLength()>=3)
2101 if(output[2] == _T('/'))
2103 output.GetBuffer()[0] = output[1];
2104 output.GetBuffer()[1] = _T(':');
2108 int start=0;
2109 output=output.Tokenize(_T("\n"),start);
2111 output.Replace(_T('/'),_T('\\'));
2115 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2116 CString str;
2117 while(file.ReadString(str))
2119 temp+=str+_T("\n");
2122 }catch(...)
2124 return -1;
2126 return 0;
2130 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2132 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2133 CString cmd,output;
2134 int cp=CP_UTF8;
2136 cmd=_T("git.exe config i18n.commitencoding");
2137 if(g_Git.Run(cmd,&output,CP_ACP))
2138 cp=CP_UTF8;
2140 int start=0;
2141 output=output.Tokenize(_T("\n"),start);
2142 cp=CUnicodeUtils::GetCPCode(output);
2144 int len=message.GetLength();
2146 char * buf;
2147 buf = new char[len*4 + 4];
2148 SecureZeroMemory(buf, (len*4 + 4));
2150 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2152 file.Write(buf,lengthIncTerminator-1);
2153 file.Close();
2154 delete buf;
2155 return 0;
2158 bool CAppUtils::Push()
2160 CPushDlg dlg;
2161 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2162 if(dlg.DoModal()==IDOK)
2164 // CString dir=dlg.m_Directory;
2165 // CString url=dlg.m_URL;
2166 CString cmd;
2167 CString force;
2168 CString tags;
2169 CString thin;
2171 if(dlg.m_bAutoLoad)
2173 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2176 if(dlg.m_bPack)
2177 thin=_T("--thin");
2178 if(dlg.m_bTags)
2179 tags=_T("--tags");
2180 if(dlg.m_bForce)
2181 force=_T("--force");
2183 cmd.Format(_T("git.exe push %s %s %s \"%s\" %s"),
2184 thin,tags,force,
2185 dlg.m_URL,
2186 dlg.m_BranchSourceName);
2187 if (!dlg.m_BranchRemoteName.IsEmpty())
2189 cmd += _T(":") + dlg.m_BranchRemoteName;
2192 CProgressDlg progress;
2193 progress.m_GitCmd=cmd;
2194 if(progress.DoModal()==IDOK)
2195 return TRUE;
2198 return FALSE;
2201 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2203 CString strDir(szPath);
2204 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2206 strDir.AppendChar(_T('\\'));
2208 std::vector<CString> vPath;
2209 CString strTemp;
2210 bool bSuccess = false;
2212 for (int i=0;i<strDir.GetLength();++i)
2214 if (strDir.GetAt(i) != _T('\\'))
2216 strTemp.AppendChar(strDir.GetAt(i));
2218 else
2220 vPath.push_back(strTemp);
2221 strTemp.AppendChar(_T('\\'));
2225 std::vector<CString>::const_iterator vIter;
2226 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2228 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2231 return bSuccess;
2234 void CAppUtils::RemoveTrailSlash(CString &path)
2236 if(path.IsEmpty())
2237 return ;
2239 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2241 path=path.Left(path.GetLength()-1);
2242 if(path.IsEmpty())
2243 return;
2247 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2248 CTGitPathList &pathList,
2249 CTGitPathList &selectedList,
2250 BOOL bSelectFilesForCommit)
2252 bool bFailed = true;
2254 while (bFailed)
2256 bFailed = false;
2257 CCommitDlg dlg;
2258 dlg.m_sBugID = bugid;
2260 dlg.m_bWholeProject = bWholeProject;
2262 dlg.m_sLogMessage = sLogMsg;
2263 dlg.m_pathList = pathList;
2264 dlg.m_checkedPathList = selectedList;
2265 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2266 if (dlg.DoModal() == IDOK)
2268 if (dlg.m_pathList.GetCount()==0)
2269 return false;
2270 // if the user hasn't changed the list of selected items
2271 // we don't use that list. Because if we would use the list
2272 // of pre-checked items, the dialog would show different
2273 // checked items on the next startup: it would only try
2274 // to check the parent folder (which might not even show)
2275 // instead, we simply use an empty list and let the
2276 // default checking do its job.
2277 if (!dlg.m_pathList.IsEqual(pathList))
2278 selectedList = dlg.m_pathList;
2279 pathList = dlg.m_updatedPathList;
2280 sLogMsg = dlg.m_sLogMessage;
2281 bSelectFilesForCommit = true;
2283 if( dlg.m_bPushAfterCommit )
2285 switch(dlg.m_PostCmd)
2287 case GIT_POST_CMD_DCOMMIT:
2288 CAppUtils::SVNDCommit();
2289 break;
2290 default:
2291 CAppUtils::Push();
2294 // CGitProgressDlg progDlg;
2295 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2296 // if (parser.HasVal(_T("closeonend")))
2297 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2298 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2299 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2300 // progDlg.SetPathList(dlg.m_pathList);
2301 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2302 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2303 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2304 // progDlg.SetItemCount(dlg.m_itemsCount);
2305 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2306 // progDlg.DoModal();
2307 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2308 // err = (DWORD)progDlg.DidErrorsOccur();
2309 // bFailed = progDlg.DidErrorsOccur();
2310 // bRet = progDlg.DidErrorsOccur();
2311 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2312 // if (DWORD(bFailRepeat)==0)
2313 // bFailed = false; // do not repeat if the user chose not to in the settings.
2316 return true;
2320 BOOL CAppUtils::SVNDCommit()
2322 if(!g_Git.CheckCleanWorkTree())
2324 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2326 CString cmd,out;
2327 cmd=_T("git.exe stash");
2328 if(g_Git.Run(cmd,&out,CP_ACP))
2330 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2331 return false;
2334 }else
2336 return false;
2340 CProgressDlg progress;
2341 progress.m_GitCmd=_T("git.exe svn dcommit");
2342 if(progress.DoModal()==IDOK)
2343 return TRUE;
2347 BOOL CAppUtils::Merge(CString *commit, int mode)
2349 CMergeDlg dlg;
2350 if(commit)
2351 dlg.m_initialRefName = *commit;
2353 if(dlg.DoModal()==IDOK)
2355 CString cmd;
2356 CString noff;
2357 CString squash;
2358 CString nocommit;
2359 CString msg;
2361 if(dlg.m_bNoFF)
2362 noff=_T("--no-ff");
2364 if(dlg.m_bSquash)
2365 squash=_T("--squash");
2367 if(dlg.m_bNoCommit)
2368 nocommit=_T("--no-commit");
2370 if(!dlg.m_strLogMesage.IsEmpty())
2372 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2374 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2375 msg,
2376 noff,
2377 squash,
2378 nocommit,
2379 dlg.m_VersionName);
2381 CProgressDlg Prodlg;
2382 Prodlg.m_GitCmd = cmd;
2384 Prodlg.DoModal();
2386 return !Prodlg.m_GitStatus;
2388 return false;