Fixed issue #801: Be able to enter a custom stash message
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobfbad4ca0376429261b31b9a179d3c5f0edc5e406
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - TortoiseGit
4 // Copyright (C) 2003-2011 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "StdAfx.h"
21 #include "resource.h"
22 #include "TortoiseProc.h"
23 #include "PathUtils.h"
24 #include "AppUtils.h"
25 //#include "GitProperties.h"
26 #include "StringUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "TGitPath.h"
30 #include "Git.h"
31 //#include "RepositoryBrowser.h"
32 //#include "BrowseFolder.h"
33 #include "UnicodeUtils.h"
34 #include "ExportDlg.h"
35 #include "ProgressDlg.h"
36 #include "GitAdminDir.h"
37 #include "ProgressDlg.h"
38 #include "BrowseFolder.h"
39 #include "DirFileEnum.h"
40 #include "MessageBox.h"
41 #include "GitStatus.h"
42 #include "CreateBranchTagDlg.h"
43 #include "GitSwitchDlg.h"
44 #include "ResetDlg.h"
45 #include "DeleteConflictDlg.h"
46 #include "ChangedDlg.h"
47 #include "SendMailDlg.h"
48 #include "GITProgressDlg.h"
49 #include "PushDlg.h"
50 #include "CommitDlg.h"
51 #include "MergeDlg.h"
52 #include "hooks.h"
53 #include "..\Settings\Settings.h"
54 #include "InputDlg.h"
55 #include "SVNDCommitDlg.h"
56 #include "requestpulldlg.h"
57 #include "PullFetchDlg.h"
58 #include "RebaseDlg.h"
59 #include "PropKey.h"
60 #include "StashSave.h"
62 CAppUtils::CAppUtils(void)
66 CAppUtils::~CAppUtils(void)
70 bool CAppUtils::StashSave()
72 CStashSaveDlg dlg;
74 if (dlg.DoModal() == IDOK)
76 CString cmd, out;
77 cmd = _T("git.exe stash save");
79 if (!dlg.m_sMessage.IsEmpty())
81 CString message = dlg.m_sMessage;
82 message.Replace(_T("\""), _T("\"\""));
83 cmd += _T(" \"") + message + _T("\"");
86 if (g_Git.Run(cmd, &out, CP_ACP))
88 CMessageBox::Show(NULL, CString(_T("<ct=0x0000FF>Stash Fail!!!</ct>\n")) + out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
90 else
92 CMessageBox::Show(NULL, CString(_T("<ct=0xff0000>Stash Success</ct>\n")) + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
93 return true;
96 return false;
99 int CAppUtils::StashApply(CString ref)
101 CString cmd,out;
102 cmd = _T("git.exe stash apply ");
103 if (ref.Find(_T("refs/")) == 0)
104 ref = ref.Mid(5);
105 if (ref.Find(_T("stash{")) == 0)
106 ref = _T("stash@") + ref.Mid(5);
107 cmd += ref;
109 if(g_Git.Run(cmd,&out,CP_ACP))
111 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
113 else
115 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
116 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
118 CChangedDlg dlg;
119 dlg.m_pathList.AddPath(CTGitPath());
120 dlg.DoModal();
122 return 0;
124 return -1;
127 int CAppUtils::StashPop()
129 CString cmd,out;
130 cmd=_T("git.exe stash pop ");
132 if(g_Git.Run(cmd,&out,CP_ACP))
134 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
137 else
139 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
140 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
142 CChangedDlg dlg;
143 dlg.m_pathList.AddPath(CTGitPath());
144 dlg.DoModal();
146 return 0;
148 return -1;
151 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
153 #if 0
154 GitProperties props(file, GitRev::REV_WC, false);
155 for (int i = 0; i < props.GetCount(); ++i)
157 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
159 mimetype = props.GetItemValue(i).c_str();
160 return true;
163 #endif
164 return false;
167 BOOL CAppUtils::StartExtMerge(
168 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
169 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
172 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
173 CString ext = mergedfile.GetFileExtension();
174 CString com = regCom;
175 bool bInternal = false;
177 CString mimetype;
178 if (ext != "")
180 // is there an extension specific merge tool?
181 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
182 if (CString(mergetool) != "")
184 com = mergetool;
187 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
189 // is there a mime type specific merge tool?
190 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
191 if (CString(mergetool) != "")
193 com = mergetool;
197 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
199 // use TortoiseMerge
200 bInternal = true;
201 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
202 com = tortoiseMergePath;
203 if (com.IsEmpty())
205 com = CPathUtils::GetAppDirectory();
206 com += _T("TortoiseMerge.exe");
208 com = _T("\"") + com + _T("\"");
209 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
210 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
212 // check if the params are set. If not, just add the files to the command line
213 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
215 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
216 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
217 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
218 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
220 if (basefile.IsEmpty())
222 com.Replace(_T("/base:%base"), _T(""));
223 com.Replace(_T("%base"), _T(""));
225 else
226 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
227 if (theirfile.IsEmpty())
229 com.Replace(_T("/theirs:%theirs"), _T(""));
230 com.Replace(_T("%theirs"), _T(""));
232 else
233 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
234 if (yourfile.IsEmpty())
236 com.Replace(_T("/mine:%mine"), _T(""));
237 com.Replace(_T("%mine"), _T(""));
239 else
240 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
241 if (mergedfile.IsEmpty())
243 com.Replace(_T("/merged:%merged"), _T(""));
244 com.Replace(_T("%merged"), _T(""));
246 else
247 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
248 if (basename.IsEmpty())
250 if (basefile.IsEmpty())
252 com.Replace(_T("/basename:%bname"), _T(""));
253 com.Replace(_T("%bname"), _T(""));
255 else
257 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
260 else
261 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
262 if (theirname.IsEmpty())
264 if (theirfile.IsEmpty())
266 com.Replace(_T("/theirsname:%tname"), _T(""));
267 com.Replace(_T("%tname"), _T(""));
269 else
271 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
274 else
275 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
276 if (yourname.IsEmpty())
278 if (yourfile.IsEmpty())
280 com.Replace(_T("/minename:%yname"), _T(""));
281 com.Replace(_T("%yname"), _T(""));
283 else
285 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
288 else
289 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
290 if (mergedname.IsEmpty())
292 if (mergedfile.IsEmpty())
294 com.Replace(_T("/mergedname:%mname"), _T(""));
295 com.Replace(_T("%mname"), _T(""));
297 else
299 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
302 else
303 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
305 if ((bReadOnly)&&(bInternal))
306 com += _T(" /readonly");
308 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
310 return FALSE;
313 return TRUE;
316 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
318 CString viewer;
319 // use TortoiseMerge
320 viewer = CPathUtils::GetAppDirectory();
321 viewer += _T("TortoiseMerge.exe");
323 viewer = _T("\"") + viewer + _T("\"");
324 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
325 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
326 if (bReversed)
327 viewer += _T(" /reversedpatch");
328 if (!sOriginalDescription.IsEmpty())
329 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
330 if (!sPatchedDescription.IsEmpty())
331 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
332 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
334 return FALSE;
336 return TRUE;
339 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
341 // Is there a mime type specific diff tool?
342 CString mimetype;
343 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
345 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
346 if (!difftool.IsEmpty())
347 return difftool;
350 // Is there an extension specific diff tool?
351 CString ext = file2.GetFileExtension().MakeLower();
352 if (!ext.IsEmpty())
354 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
355 if (!difftool.IsEmpty())
356 return difftool;
357 // Maybe we should use TortoiseIDiff?
358 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
359 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
360 (ext == _T(".png")) || (ext == _T(".ico")) ||
361 (ext == _T(".dib")) || (ext == _T(".emf")))
363 return
364 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
365 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
369 // Finally, pick a generic external diff tool
370 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
371 return difftool;
374 bool CAppUtils::StartExtDiff(
375 const CString& file1, const CString& file2,
376 const CString& sName1, const CString& sName2,
377 const DiffFlags& flags)
379 CString viewer;
381 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
382 if (!flags.bBlame || !(DWORD)blamediff)
384 viewer = PickDiffTool(file1, file2);
385 // If registry entry for a diff program is commented out, use TortoiseMerge.
386 bool bCommentedOut = viewer.Left(1) == _T("#");
387 if (flags.bAlternativeTool)
389 // Invert external vs. internal diff tool selection.
390 if (bCommentedOut)
391 viewer.Delete(0); // uncomment
392 else
393 viewer = "";
395 else if (bCommentedOut)
396 viewer = "";
399 bool bInternal = viewer.IsEmpty();
400 if (bInternal)
402 viewer =
403 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
404 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
405 if (flags.bBlame)
406 viewer += _T(" /blame");
408 // check if the params are set. If not, just add the files to the command line
409 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
411 viewer += _T(" \"")+file1+_T("\"");
412 viewer += _T(" \"")+file2+_T("\"");
414 if (viewer.Find(_T("%base")) >= 0)
416 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
418 if (viewer.Find(_T("%mine")) >= 0)
420 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
423 if (sName1.IsEmpty())
424 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
425 else
426 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
428 if (sName2.IsEmpty())
429 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
430 else
431 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
433 if (flags.bReadOnly && bInternal)
434 viewer += _T(" /readonly");
436 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
439 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
441 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
442 CString viewer = diffpropsexe;
443 bool bInternal = false;
444 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
446 //no registry entry (or commented out) for a diff program
447 //use TortoiseMerge
448 bInternal = true;
449 viewer = CPathUtils::GetAppDirectory();
450 viewer += _T("TortoiseMerge.exe");
451 viewer = _T("\"") + viewer + _T("\"");
452 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
454 // check if the params are set. If not, just add the files to the command line
455 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
457 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
458 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
460 if (viewer.Find(_T("%base")) >= 0)
462 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
464 if (viewer.Find(_T("%mine")) >= 0)
466 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
469 if (sName1.IsEmpty())
470 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
471 else
472 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
474 if (sName2.IsEmpty())
475 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
476 else
477 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
479 if ((bReadOnly)&&(bInternal))
480 viewer += _T(" /readonly");
482 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
484 return FALSE;
486 return TRUE;
489 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
491 CString viewer;
492 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
493 viewer = v;
494 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
496 // use TortoiseUDiff
497 viewer = CPathUtils::GetAppDirectory();
498 viewer += _T("TortoiseUDiff.exe");
499 // enquote the path to TortoiseUDiff
500 viewer = _T("\"") + viewer + _T("\"");
501 // add the params
502 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
505 if (viewer.Find(_T("%1"))>=0)
507 if (viewer.Find(_T("\"%1\"")) >= 0)
508 viewer.Replace(_T("%1"), patchfile);
509 else
510 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
512 else
513 viewer += _T(" \"") + patchfile + _T("\"");
514 if (viewer.Find(_T("%title")) >= 0)
516 viewer.Replace(_T("%title"), title);
519 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
521 return FALSE;
523 return TRUE;
526 BOOL CAppUtils::StartTextViewer(CString file)
528 CString viewer;
529 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
530 viewer = txt;
531 viewer = viewer + _T("\\Shell\\Open\\Command\\");
532 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
533 viewer = txtexe;
535 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
536 TCHAR * buf = new TCHAR[len+1];
537 ExpandEnvironmentStrings(viewer, buf, len);
538 viewer = buf;
539 delete [] buf;
540 len = ExpandEnvironmentStrings(file, NULL, 0);
541 buf = new TCHAR[len+1];
542 ExpandEnvironmentStrings(file, buf, len);
543 file = buf;
544 delete [] buf;
545 file = _T("\"")+file+_T("\"");
546 if (viewer.IsEmpty())
548 OPENFILENAME ofn = {0}; // common dialog box structure
549 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
550 // Initialize OPENFILENAME
551 ofn.lStructSize = sizeof(OPENFILENAME);
552 ofn.hwndOwner = NULL;
553 ofn.lpstrFile = szFile;
554 ofn.nMaxFile = _countof(szFile);
555 CString sFilter;
556 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
557 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
558 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
559 // Replace '|' delimiters with '\0's
560 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
561 while (ptr != pszFilters)
563 if (*ptr == '|')
564 *ptr = '\0';
565 ptr--;
567 ofn.lpstrFilter = pszFilters;
568 ofn.nFilterIndex = 1;
569 ofn.lpstrFileTitle = NULL;
570 ofn.nMaxFileTitle = 0;
571 ofn.lpstrInitialDir = NULL;
572 CString temp;
573 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
574 CStringUtils::RemoveAccelerators(temp);
575 ofn.lpstrTitle = temp;
576 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
578 // Display the Open dialog box.
580 if (GetOpenFileName(&ofn)==TRUE)
582 delete [] pszFilters;
583 viewer = CString(ofn.lpstrFile);
585 else
587 delete [] pszFilters;
588 return FALSE;
591 if (viewer.Find(_T("\"%1\"")) >= 0)
593 viewer.Replace(_T("\"%1\""), file);
595 else if (viewer.Find(_T("%1")) >= 0)
597 viewer.Replace(_T("%1"), file);
599 else
601 viewer += _T(" ");
602 viewer += file;
605 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
607 return FALSE;
609 return TRUE;
612 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
614 DWORD length = 0;
615 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
616 if (hFile == INVALID_HANDLE_VALUE)
617 return TRUE;
618 length = ::GetFileSize(hFile, NULL);
619 ::CloseHandle(hFile);
620 if (length < 4)
621 return TRUE;
622 return FALSE;
626 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
628 LOGFONT logFont;
629 HDC hScreenDC = ::GetDC(NULL);
630 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
631 ::ReleaseDC(NULL, hScreenDC);
632 logFont.lfWidth = 0;
633 logFont.lfEscapement = 0;
634 logFont.lfOrientation = 0;
635 logFont.lfWeight = FW_NORMAL;
636 logFont.lfItalic = 0;
637 logFont.lfUnderline = 0;
638 logFont.lfStrikeOut = 0;
639 logFont.lfCharSet = DEFAULT_CHARSET;
640 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
641 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
642 logFont.lfQuality = DRAFT_QUALITY;
643 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
644 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
645 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
648 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
650 STARTUPINFO startup;
651 PROCESS_INFORMATION process;
652 memset(&startup, 0, sizeof(startup));
653 startup.cb = sizeof(startup);
654 memset(&process, 0, sizeof(process));
656 CString cleanCommandLine(sCommandLine);
658 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
660 if(idErrMessageFormat != 0)
662 LPVOID lpMsgBuf;
663 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
664 FORMAT_MESSAGE_FROM_SYSTEM |
665 FORMAT_MESSAGE_IGNORE_INSERTS,
666 NULL,
667 GetLastError(),
668 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
669 (LPTSTR) &lpMsgBuf,
671 NULL
673 CString temp;
674 temp.Format(idErrMessageFormat, lpMsgBuf);
675 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
676 LocalFree( lpMsgBuf );
678 return false;
681 if (bWaitForStartup)
683 WaitForInputIdle(process.hProcess, 10000);
686 CloseHandle(process.hThread);
687 CloseHandle(process.hProcess);
688 return true;
690 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
692 CString key,remote;
693 CString cmd,out;
694 if( pRemote == NULL)
696 remote=_T("origin");
698 else
700 remote=*pRemote;
702 if(keyfile == NULL)
704 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
705 key = g_Git.GetConfigValue(cmd);
706 int start=0;
707 key = key.Tokenize(_T("\n"),start);
709 else
710 key=*keyfile;
712 if(key.IsEmpty())
713 return false;
715 CString proc=CPathUtils::GetAppDirectory();
716 proc += _T("pageant.exe \"");
717 proc += key;
718 proc += _T("\"");
720 CString tempfile = GetTempFile();
721 ::DeleteFile(tempfile);
723 proc += _T(" -c \"");
724 proc += CPathUtils::GetAppDirectory();
725 proc += _T("touch.exe\"");
726 proc += _T(" \"");
727 proc += tempfile;
728 proc += _T("\"");
730 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
731 if(!b)
732 return b;
734 int i=0;
735 while(!::PathFileExists(tempfile))
737 Sleep(100);
738 i++;
739 if(i>10*60*5)
740 break; //timeout 5 minutes
743 if( i== 10*60*5)
745 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
747 ::DeleteFile(tempfile);
748 return true;
750 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
752 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
753 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
754 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
757 CString sCmd;
758 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
760 LaunchApplication(sCmd, NULL, false);
761 return true;
763 bool CAppUtils::LaunchRemoteSetting()
765 CTGitPath path(g_Git.m_CurrentDir);
766 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
767 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
768 //dlg.SetTreeWidth(220);
769 dlg.m_DefaultPage = _T("gitremote");
771 dlg.DoModal();
772 dlg.HandleRestart();
773 return true;
776 * Launch the external blame viewer
778 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
780 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
781 viewer += _T("TortoiseGitBlame.exe");
782 viewer += _T("\" \"") + sBlameFile + _T("\"");
783 //viewer += _T(" \"") + sLogFile + _T("\"");
784 //viewer += _T(" \"") + sOriginalFile + _T("\"");
785 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
786 viewer += CString(_T(" /rev:"))+Rev;
787 viewer += _T(" ")+sParams;
789 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
792 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
794 CString sText;
795 if (pWnd == NULL)
796 return false;
797 bool bStyled = false;
798 pWnd->GetWindowText(sText);
799 // the rich edit control doesn't count the CR char!
800 // to be exact: CRLF is treated as one char.
801 sText.Remove('\r');
803 // style each line separately
804 int offset = 0;
805 int nNewlinePos;
808 nNewlinePos = sText.Find('\n', offset);
809 CString sLine = sText.Mid(offset);
810 if (nNewlinePos>=0)
811 sLine = sLine.Left(nNewlinePos-offset);
812 int start = 0;
813 int end = 0;
814 while (FindStyleChars(sLine, '*', start, end))
816 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
817 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
818 CHARFORMAT2 format;
819 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
820 format.cbSize = sizeof(CHARFORMAT2);
821 format.dwMask = CFM_BOLD;
822 format.dwEffects = CFE_BOLD;
823 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
824 bStyled = true;
825 start = end;
827 start = 0;
828 end = 0;
829 while (FindStyleChars(sLine, '^', start, end))
831 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
832 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
833 CHARFORMAT2 format;
834 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
835 format.cbSize = sizeof(CHARFORMAT2);
836 format.dwMask = CFM_ITALIC;
837 format.dwEffects = CFE_ITALIC;
838 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
839 bStyled = true;
840 start = end;
842 start = 0;
843 end = 0;
844 while (FindStyleChars(sLine, '_', start, end))
846 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
847 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
848 CHARFORMAT2 format;
849 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
850 format.cbSize = sizeof(CHARFORMAT2);
851 format.dwMask = CFM_UNDERLINE;
852 format.dwEffects = CFE_UNDERLINE;
853 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
854 bStyled = true;
855 start = end;
857 offset = nNewlinePos+1;
858 } while(nNewlinePos>=0);
859 return bStyled;
862 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
864 int i=start;
865 bool bFoundMarker = false;
866 // find a starting marker
867 while (sText[i] != 0)
869 if (sText[i] == stylechar)
871 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
872 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
874 start = i+1;
875 i++;
876 bFoundMarker = true;
877 break;
880 i++;
882 if (!bFoundMarker)
883 return false;
884 // find ending marker
885 bFoundMarker = false;
886 while (sText[i] != 0)
888 if (sText[i] == stylechar)
890 if ((IsCharAlphaNumeric(sText[i-1])) &&
891 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
893 end = i;
894 i++;
895 bFoundMarker = true;
896 break;
899 i++;
901 return bFoundMarker;
904 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
906 OPENFILENAME ofn = {0}; // common dialog box structure
907 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
908 ofn.lStructSize = sizeof(OPENFILENAME);
909 ofn.hwndOwner = hwndOwner;
910 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
911 ofn.lpstrFile = szFile;
912 ofn.nMaxFile = _countof(szFile);
913 CString sFilter;
914 TCHAR * pszFilters = NULL;
915 if (filter)
917 sFilter.LoadString(filter);
918 pszFilters = new TCHAR[sFilter.GetLength()+4];
919 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
920 // Replace '|' delimiters with '\0's
921 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
922 while (ptr != pszFilters)
924 if (*ptr == '|')
925 *ptr = '\0';
926 ptr--;
928 ofn.lpstrFilter = pszFilters;
930 ofn.nFilterIndex = 1;
931 ofn.lpstrFileTitle = NULL;
932 ofn.nMaxFileTitle = 0;
933 ofn.lpstrInitialDir = NULL;
934 CString temp;
935 if (title)
937 temp.LoadString(title);
938 CStringUtils::RemoveAccelerators(temp);
940 ofn.lpstrTitle = temp;
941 if (bOpen)
942 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
943 else
944 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
947 // Display the Open dialog box.
948 bool bRet = false;
949 if (bOpen)
951 bRet = !!GetOpenFileName(&ofn);
953 else
955 bRet = !!GetSaveFileName(&ofn);
957 if (bRet)
959 if (pszFilters)
960 delete [] pszFilters;
961 path = CString(ofn.lpstrFile);
962 if (filterindex)
963 *filterindex = ofn.nFilterIndex;
964 return true;
966 if (pszFilters)
967 delete [] pszFilters;
968 return false;
971 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
973 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
974 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
975 // create a bitmap from the icon
976 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
977 if (!hIcon)
978 return false;
980 RECT rect = {0};
981 rect.right = width;
982 rect.bottom = height;
983 HBITMAP bmp = NULL;
985 HWND desktop = ::GetDesktopWindow();
986 if (desktop)
988 HDC screen_dev = ::GetDC(desktop);
989 if (screen_dev)
991 // Create a compatible DC
992 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
993 if (dst_hdc)
995 // Create a new bitmap of icon size
996 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
997 if (bmp)
999 // Select it into the compatible DC
1000 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
1001 // Fill the background of the compatible DC with the given color
1002 ::SetBkColor(dst_hdc, bkColor);
1003 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
1005 // Draw the icon into the compatible DC
1006 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
1007 ::SelectObject(dst_hdc, old_dst_bmp);
1009 ::DeleteDC(dst_hdc);
1012 ::ReleaseDC(desktop, screen_dev);
1015 // Restore settings
1016 DestroyIcon(hIcon);
1018 if (bmp == NULL)
1019 return false;
1021 LVBKIMAGE lv;
1022 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1023 lv.hbm = bmp;
1024 lv.xOffsetPercent = 100;
1025 lv.yOffsetPercent = 100;
1026 ListView_SetBkImage(hListCtrl, &lv);
1027 return true;
1030 CString CAppUtils::GetProjectNameFromURL(CString url)
1032 CString name;
1033 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1034 (name.CompareNoCase(_T("tags"))==0) ||
1035 (name.CompareNoCase(_T("trunk"))==0))
1037 name = url.Mid(url.ReverseFind('/')+1);
1038 url = url.Left(url.ReverseFind('/'));
1040 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1042 // a name of svn or svnroot indicates that it's not really the project name. In that
1043 // case, we try the first part of the URL
1044 // of course, this won't work in all cases (but it works for Google project hosting)
1045 url.Replace(_T("http://"), _T(""));
1046 url.Replace(_T("https://"), _T(""));
1047 url.Replace(_T("svn://"), _T(""));
1048 url.Replace(_T("svn+ssh://"), _T(""));
1049 url.TrimLeft(_T("/"));
1050 name = url.Left(url.Find('.'));
1052 return name;
1055 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1056 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1057 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1058 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1061 CString tempfile=GetTempFile();
1062 CString cmd;
1063 if(rev1 == GitRev::GetWorkingCopy())
1065 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1067 else
1069 CString merge;
1070 if(bMerge)
1071 merge = _T("-c");
1073 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1076 if( !url1.IsEmpty() )
1078 cmd += _T(" \"");
1079 cmd += url1.GetGitPathString();
1080 cmd += _T("\" ");
1082 g_Git.RunLogFile(cmd,tempfile);
1083 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1086 #if 0
1087 CString sCmd;
1088 sCmd.Format(_T("%s /command:showcompare /unified"),
1089 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1090 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1091 if (rev1.IsValid())
1092 sCmd += _T(" /revision1:") + rev1.ToString();
1093 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1094 if (rev2.IsValid())
1095 sCmd += _T(" /revision2:") + rev2.ToString();
1096 if (peg.IsValid())
1097 sCmd += _T(" /pegrevision:") + peg.ToString();
1098 if (headpeg.IsValid())
1099 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1101 if (bAlternateDiff)
1102 sCmd += _T(" /alternatediff");
1104 if (bIgnoreAncestry)
1105 sCmd += _T(" /ignoreancestry");
1107 if (hWnd)
1109 sCmd += _T(" /hwnd:");
1110 TCHAR buf[30];
1111 _stprintf_s(buf, 30, _T("%d"), hWnd);
1112 sCmd += buf;
1115 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1116 #endif
1117 return TRUE;
1121 bool CAppUtils::Export(CString *BashHash)
1123 bool bRet = false;
1125 // ask from where the export has to be done
1126 CExportDlg dlg;
1127 if(BashHash)
1128 dlg.m_Revision=*BashHash;
1130 if (dlg.DoModal() == IDOK)
1132 CString cmd;
1133 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1134 g_Git.FixBranchName(dlg.m_VersionName));
1136 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1137 CProgressDlg pro;
1138 pro.m_GitCmd=cmd;
1139 pro.m_LogFile=dlg.m_strExportDirectory;
1140 pro.DoModal();
1141 return TRUE;
1143 return bRet;
1146 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1148 CCreateBranchTagDlg dlg;
1149 dlg.m_bIsTag=IsTag;
1150 dlg.m_bSwitch=switch_new_brach;
1152 if(CommitHash)
1153 dlg.m_Base = *CommitHash;
1155 if(dlg.DoModal()==IDOK)
1157 CString cmd;
1158 CString force;
1159 CString track;
1160 if(dlg.m_bTrack)
1161 track=_T(" --track ");
1163 if(dlg.m_bForce)
1164 force=_T(" -f ");
1166 if(IsTag)
1168 CString sign;
1169 if(dlg.m_bSign)
1170 sign=_T("-s");
1172 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1173 track,
1174 force,
1175 sign,
1176 dlg.m_BranchTagName,
1177 g_Git.FixBranchName(dlg.m_VersionName)
1180 CString tempfile=::GetTempFile();
1181 if(!dlg.m_Message.Trim().IsEmpty())
1183 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1184 cmd += _T(" -F ")+tempfile;
1187 else
1189 cmd.Format(_T("git.exe branch %s %s %s %s"),
1190 track,
1191 force,
1192 dlg.m_BranchTagName,
1193 g_Git.FixBranchName(dlg.m_VersionName)
1196 CString out;
1197 if(g_Git.Run(cmd,&out,CP_UTF8))
1199 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1201 if( !IsTag && dlg.m_bSwitch )
1203 // it is a new branch and the user has requested to switch to it
1204 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1205 g_Git.Run(cmd,&out,CP_UTF8);
1206 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1209 return TRUE;
1211 return FALSE;
1214 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1216 CGitSwitchDlg dlg;
1217 if(CommitHash)
1218 dlg.m_Base=*CommitHash;
1219 if(!initialRefName.IsEmpty())
1220 dlg.m_initialRefName = initialRefName;
1222 if (dlg.DoModal() == IDOK)
1224 CString branch;
1225 if (dlg.m_bBranch)
1226 branch = dlg.m_NewBranch;
1228 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1230 return FALSE;
1233 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1235 CString cmd;
1236 CString track;
1237 CString force;
1238 CString branch;
1240 if(!sNewBranch.IsEmpty()){
1241 if (bBranchOverride)
1243 branch.Format(_T("-B %s"), sNewBranch);
1245 else
1247 branch.Format(_T("-b %s"), sNewBranch);
1249 if (bTrack)
1250 track = _T("--track");
1252 if (bForce)
1253 force = _T("-f");
1255 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1256 force,
1257 track,
1258 branch,
1259 g_Git.FixBranchName(ref));
1261 CProgressDlg progress;
1262 progress.m_bAutoCloseOnSuccess = autoClose;
1263 progress.m_GitCmd = cmd;
1265 CTGitPath gitPath = g_Git.m_CurrentDir;
1266 if (gitPath.HasSubmodules())
1267 progress.m_PostCmdList.Add(_T("Update Submodules"));
1269 int ret = progress.DoModal();
1270 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1272 CString sCmd;
1273 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1275 LaunchApplication(sCmd, NULL, false);
1276 return TRUE;
1278 else if (ret == IDOK)
1279 return TRUE;
1281 return FALSE;
1284 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1286 CString ignorefile;
1287 ignorefile=g_Git.m_CurrentDir+_T("\\");
1289 if(IsMask)
1291 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1294 else
1296 ignorefile += _T("\\.gitignore");
1299 CStdioFile file;
1300 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1302 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1303 return FALSE;
1306 CString ignorelist;
1307 CString mask;
1310 //file.ReadString(ignorelist);
1311 file.SeekToEnd();
1312 for(int i=0;i<path.GetCount();i++)
1314 if(IsMask)
1316 mask=_T("*")+path[i].GetFileExtension();
1317 if(ignorelist.Find(mask)<0)
1318 ignorelist += _T("\n")+mask;
1320 else
1322 ignorelist += _T("\n/")+path[i].GetGitPathString();
1325 file.WriteString(ignorelist);
1327 file.Close();
1329 }catch(...)
1331 file.Close();
1332 return FALSE;
1335 return TRUE;
1339 bool CAppUtils::GitReset(CString *CommitHash,int type)
1341 CResetDlg dlg;
1342 dlg.m_ResetType=type;
1343 dlg.m_ResetToVersion=*CommitHash;
1344 if (dlg.DoModal() == IDOK)
1346 CString cmd;
1347 CString type;
1348 switch(dlg.m_ResetType)
1350 case 0:
1351 type=_T("--soft");
1352 break;
1353 case 1:
1354 type=_T("--mixed");
1355 break;
1356 case 2:
1357 type=_T("--hard");
1358 break;
1359 default:
1360 type=_T("--mixed");
1361 break;
1363 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1365 CProgressDlg progress;
1366 progress.m_GitCmd=cmd;
1368 CTGitPath gitPath = g_Git.m_CurrentDir;
1369 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1370 progress.m_PostCmdList.Add(_T("Update Submodules"));
1372 int ret = progress.DoModal();
1373 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1375 CString sCmd;
1376 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1378 LaunchApplication(sCmd, NULL, false);
1379 return TRUE;
1381 else if (ret == IDOK)
1382 return TRUE;
1385 return FALSE;
1388 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1390 if(mode == FALSE)
1392 descript=_T("Deleted");
1393 return;
1395 if(base)
1397 descript=_T("Modified");
1398 return;
1400 descript=_T("Created");
1401 return;
1404 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1406 CString tempmergefile;
1409 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1410 CFile::Remove(tempmergefile);
1411 }catch(...)
1417 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1418 CFile::Remove(tempmergefile);
1419 }catch(...)
1425 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1426 CFile::Remove(tempmergefile);
1427 }catch(...)
1431 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1433 CString file;
1434 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1436 return file;
1439 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1441 bool bRet = false;
1443 CTGitPath merge=path;
1444 CTGitPath directory = merge.GetDirectory();
1446 // we have the conflicted file (%merged)
1447 // now look for the other required files
1448 //GitStatus stat;
1449 //stat.GetStatus(merge);
1450 //if (stat.status == NULL)
1451 // return false;
1453 BYTE_VECTOR vector;
1455 CString cmd;
1456 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1458 if (g_Git.Run(cmd, &vector))
1460 return FALSE;
1463 CTGitPathList list;
1464 list.ParserFromLsFile(vector);
1466 if(list.GetCount() == 0)
1467 return FALSE;
1469 CTGitPath theirs;
1470 CTGitPath mine;
1471 CTGitPath base;
1473 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1474 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1475 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1477 CString format;
1479 //format=_T("git.exe cat-file blob \":%d:%s\"");
1480 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1481 CFile tempfile;
1482 //create a empty file, incase stage is not three
1483 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1484 tempfile.Close();
1485 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1486 tempfile.Close();
1487 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1488 tempfile.Close();
1490 bool b_base=false, b_local=false, b_remote=false;
1492 for(int i=0;i<list.GetCount();i++)
1494 CString cmd;
1495 CString outfile;
1496 cmd.Empty();
1497 outfile.Empty();
1499 if( list[i].m_Stage == 1)
1501 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1502 b_base = true;
1503 outfile = base.GetWinPathString();
1506 if( list[i].m_Stage == 2 )
1508 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1509 b_local = true;
1510 outfile = mine.GetWinPathString();
1513 if( list[i].m_Stage == 3 )
1515 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1516 b_remote = true;
1517 outfile = theirs.GetWinPathString();
1519 CString output, err;
1520 if(!outfile.IsEmpty())
1521 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1523 CString file;
1524 int start =0 ;
1525 file = output.Tokenize(_T("\t"), start);
1526 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1528 else
1530 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1534 if(b_local && b_remote )
1536 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1537 if( revertTheirMy )
1538 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1539 else
1540 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1543 else
1545 CFile::Remove(mine.GetWinPathString());
1546 CFile::Remove(theirs.GetWinPathString());
1547 CFile::Remove(base.GetWinPathString());
1549 CDeleteConflictDlg dlg;
1550 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1551 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1552 dlg.m_bShowModifiedButton=b_base;
1553 dlg.m_File=merge.GetGitPathString();
1554 if(dlg.DoModal() == IDOK)
1556 CString cmd,out;
1557 if(dlg.m_bIsDelete)
1559 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1561 else
1562 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1564 if(g_Git.Run(cmd,&out,CP_ACP))
1566 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1567 return FALSE;
1569 return TRUE;
1571 else
1572 return FALSE;
1575 #if 0
1576 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1577 base, theirs, mine, merge);
1578 #endif
1579 #if 0
1580 if (stat.status->text_status == svn_wc_status_conflicted)
1582 // we have a text conflict, use our merge tool to resolve the conflict
1584 CTSVNPath theirs(directory);
1585 CTSVNPath mine(directory);
1586 CTSVNPath base(directory);
1587 bool bConflictData = false;
1589 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1591 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1592 bConflictData = true;
1594 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1596 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1597 bConflictData = true;
1599 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1601 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1602 bConflictData = true;
1604 else
1606 mine = merge;
1608 if (bConflictData)
1609 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1610 base, theirs, mine, merge);
1613 if (stat.status->prop_status == svn_wc_status_conflicted)
1615 // we have a property conflict
1616 CTSVNPath prej(directory);
1617 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1619 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1620 // there's a problem: the prej file contains a _description_ of the conflict, and
1621 // that description string might be translated. That means we have no way of parsing
1622 // the file to find out the conflicting values.
1623 // The only thing we can do: show a dialog with the conflict description, then
1624 // let the user either accept the existing property or open the property edit dialog
1625 // to manually change the properties and values. And a button to mark the conflict as
1626 // resolved.
1627 CEditPropConflictDlg dlg;
1628 dlg.SetPrejFile(prej);
1629 dlg.SetConflictedItem(merge);
1630 bRet = (dlg.DoModal() != IDCANCEL);
1634 if (stat.status->tree_conflict)
1636 // we have a tree conflict
1637 SVNInfo info;
1638 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1639 if (pInfoData)
1641 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1643 CTSVNPath theirs(directory);
1644 CTSVNPath mine(directory);
1645 CTSVNPath base(directory);
1646 bool bConflictData = false;
1648 if (pInfoData->treeconflict_theirfile)
1650 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1651 bConflictData = true;
1653 if (pInfoData->treeconflict_basefile)
1655 base.AppendPathString(pInfoData->treeconflict_basefile);
1656 bConflictData = true;
1658 if (pInfoData->treeconflict_myfile)
1660 mine.AppendPathString(pInfoData->treeconflict_myfile);
1661 bConflictData = true;
1663 else
1665 mine = merge;
1667 if (bConflictData)
1668 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1669 base, theirs, mine, merge);
1671 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1673 CString sConflictAction;
1674 CString sConflictReason;
1675 CString sResolveTheirs;
1676 CString sResolveMine;
1677 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1678 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1680 if (pInfoData->treeconflict_nodekind == svn_node_file)
1682 switch (pInfoData->treeconflict_operation)
1684 case svn_wc_operation_update:
1685 switch (pInfoData->treeconflict_action)
1687 case svn_wc_conflict_action_edit:
1688 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1689 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1690 break;
1691 case svn_wc_conflict_action_add:
1692 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1693 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1694 break;
1695 case svn_wc_conflict_action_delete:
1696 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1697 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1698 break;
1700 break;
1701 case svn_wc_operation_switch:
1702 switch (pInfoData->treeconflict_action)
1704 case svn_wc_conflict_action_edit:
1705 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1706 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1707 break;
1708 case svn_wc_conflict_action_add:
1709 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1710 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1711 break;
1712 case svn_wc_conflict_action_delete:
1713 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1714 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1715 break;
1717 break;
1718 case svn_wc_operation_merge:
1719 switch (pInfoData->treeconflict_action)
1721 case svn_wc_conflict_action_edit:
1722 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1723 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1724 break;
1725 case svn_wc_conflict_action_add:
1726 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1727 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1728 break;
1729 case svn_wc_conflict_action_delete:
1730 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1731 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1732 break;
1734 break;
1737 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1739 switch (pInfoData->treeconflict_operation)
1741 case svn_wc_operation_update:
1742 switch (pInfoData->treeconflict_action)
1744 case svn_wc_conflict_action_edit:
1745 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1746 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1747 break;
1748 case svn_wc_conflict_action_add:
1749 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1750 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1751 break;
1752 case svn_wc_conflict_action_delete:
1753 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1754 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1755 break;
1757 break;
1758 case svn_wc_operation_switch:
1759 switch (pInfoData->treeconflict_action)
1761 case svn_wc_conflict_action_edit:
1762 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1763 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1764 break;
1765 case svn_wc_conflict_action_add:
1766 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1767 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1768 break;
1769 case svn_wc_conflict_action_delete:
1770 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1771 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1772 break;
1774 break;
1775 case svn_wc_operation_merge:
1776 switch (pInfoData->treeconflict_action)
1778 case svn_wc_conflict_action_edit:
1779 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1780 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1781 break;
1782 case svn_wc_conflict_action_add:
1783 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1784 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1785 break;
1786 case svn_wc_conflict_action_delete:
1787 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1788 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1789 break;
1791 break;
1795 UINT uReasonID = 0;
1796 switch (pInfoData->treeconflict_reason)
1798 case svn_wc_conflict_reason_edited:
1799 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1800 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1801 break;
1802 case svn_wc_conflict_reason_obstructed:
1803 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1804 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1805 break;
1806 case svn_wc_conflict_reason_deleted:
1807 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1808 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1809 break;
1810 case svn_wc_conflict_reason_added:
1811 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1812 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1813 break;
1814 case svn_wc_conflict_reason_missing:
1815 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1816 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1817 break;
1818 case svn_wc_conflict_reason_unversioned:
1819 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1820 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1821 break;
1823 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1825 CTreeConflictEditorDlg dlg;
1826 dlg.SetConflictInfoText(sConflictReason);
1827 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1828 dlg.SetPath(treeConflictPath);
1829 INT_PTR dlgRet = dlg.DoModal();
1830 bRet = (dlgRet != IDCANCEL);
1834 #endif
1835 return bRet;
1839 * FUNCTION : FormatDateAndTime
1840 * DESCRIPTION : Generates a displayable string from a CTime object in
1841 * system short or long format or as a relative value
1842 * cTime - the time
1843 * option - DATE_SHORTDATE or DATE_LONGDATE
1844 * bIncluedeTime - whether to show time as well as date
1845 * bRelative - if true then relative time is shown if reasonable
1846 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1847 * rather than locale
1848 * RETURN : CString containing date/time
1850 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1851 bool bRelative /*=false*/)
1853 CString datetime;
1854 if ( bRelative )
1856 datetime = ToRelativeTimeString( cTime );
1858 else
1860 // should we use the locale settings for formatting the date/time?
1861 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1863 // yes
1864 SYSTEMTIME sysTime;
1865 cTime.GetAsSystemTime( sysTime );
1867 TCHAR buf[100];
1869 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1870 _countof(buf) - 1);
1871 datetime = buf;
1872 if ( bIncludeTime )
1874 datetime += _T(" ");
1875 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1876 datetime += buf;
1879 else
1881 // no, so fixed format
1882 if ( bIncludeTime )
1884 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1886 else
1888 datetime = cTime.Format(_T("%Y-%m-%d"));
1892 return datetime;
1896 * Converts a given time to a relative display string (relative to current time)
1897 * Given time must be in local timezone
1899 CString CAppUtils::ToRelativeTimeString(CTime time)
1901 CString answer;
1902 // convert to COleDateTime
1903 SYSTEMTIME sysTime;
1904 time.GetAsSystemTime( sysTime );
1905 COleDateTime oleTime( sysTime );
1906 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1907 return answer;
1911 * Generates a display string showing the relative time between the two given times as COleDateTimes
1913 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1915 CString answer;
1916 COleDateTimeSpan ts = RelativeTo - time;
1917 //years
1918 if(fabs(ts.GetTotalDays()) >= 3*365)
1920 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1922 //Months
1923 if(fabs(ts.GetTotalDays()) >= 60)
1925 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1926 return answer;
1928 //Weeks
1929 if(fabs(ts.GetTotalDays()) >= 14)
1931 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1932 return answer;
1934 //Days
1935 if(fabs(ts.GetTotalDays()) >= 2)
1937 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1938 return answer;
1940 //hours
1941 if(fabs(ts.GetTotalHours()) >= 2)
1943 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1944 return answer;
1946 //minutes
1947 if(fabs(ts.GetTotalMinutes()) >= 2)
1949 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1950 return answer;
1952 //seconds
1953 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1954 return answer;
1958 * Passed a value and two resource string ids
1959 * if count is 1 then FormatString is called with format_1 and the value
1960 * otherwise format_2 is used
1961 * the formatted string is returned
1963 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1965 CString answer;
1966 if ( count == 1 )
1968 answer.FormatMessage( format_1, count );
1970 else
1972 answer.FormatMessage( format_n, count );
1974 return answer;
1977 bool CAppUtils::IsSSHPutty()
1979 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1980 sshclient=sshclient.MakeLower();
1981 if(sshclient.Find(_T("plink.exe"),0)>=0)
1983 return true;
1985 return false;
1988 CString CAppUtils::GetClipboardLink()
1990 if (!OpenClipboard(NULL))
1991 return CString();
1993 CString sClipboardText;
1994 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1995 if (hglb)
1997 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1998 sClipboardText = CString(lpstr);
1999 GlobalUnlock(hglb);
2001 hglb = GetClipboardData(CF_UNICODETEXT);
2002 if (hglb)
2004 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2005 sClipboardText = lpstr;
2006 GlobalUnlock(hglb);
2008 CloseClipboard();
2010 if(!sClipboardText.IsEmpty())
2012 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2013 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2015 if(sClipboardText.Find( _T("http://")) == 0)
2016 return sClipboardText;
2018 if(sClipboardText.Find( _T("https://")) == 0)
2019 return sClipboardText;
2021 if(sClipboardText.Find( _T("git://")) == 0)
2022 return sClipboardText;
2024 if(sClipboardText.Find( _T("ssh://")) == 0)
2025 return sClipboardText;
2027 if(sClipboardText.GetLength()>=2)
2028 if( sClipboardText[1] == _T(':') )
2029 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2030 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2031 return sClipboardText;
2034 return CString(_T(""));
2037 CString CAppUtils::ChooseRepository(CString *path)
2039 CBrowseFolder browseFolder;
2040 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2042 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2043 CString strCloneDirectory;
2044 if(path)
2045 strCloneDirectory=*path;
2046 else
2048 strCloneDirectory = regLastResopitory;
2051 CString title;
2052 title.LoadString(IDS_CHOOSE_REPOSITORY);
2054 browseFolder.SetInfo(title);
2056 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2058 regLastResopitory = strCloneDirectory;
2059 return strCloneDirectory;
2061 else
2063 return CString();
2067 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2069 CSendMailDlg dlg;
2071 dlg.m_PathList = list;
2073 if(dlg.DoModal()==IDOK)
2075 if(dlg.m_PathList.GetCount() == 0)
2076 return FALSE;
2078 CGitProgressDlg progDlg;
2080 theApp.m_pMainWnd = &progDlg;
2081 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2083 progDlg.SetAutoClose(autoclose);
2085 progDlg.SetPathList(dlg.m_PathList);
2086 //ProjectProperties props;
2087 //props.ReadPropsPathList(dlg.m_pathList);
2088 //progDlg.SetProjectProperties(props);
2089 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2091 DWORD flags =0;
2092 if(dlg.m_bAttachment)
2093 flags |= SENDMAIL_ATTACHMENT;
2094 if(dlg.m_bCombine)
2095 flags |= SENDMAIL_COMBINED;
2096 if(dlg.m_bUseMAPI)
2097 flags |= SENDMAIL_MAPI;
2099 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2101 progDlg.DoModal();
2103 return true;
2105 return false;
2108 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2110 CTGitPathList list;
2111 CString log=formatpatchoutput;
2112 int start=log.Find(cmd);
2113 if(start >=0)
2114 CString one=log.Tokenize(_T("\n"),start);
2115 else
2116 start = 0;
2118 while(start>=0)
2120 CString one=log.Tokenize(_T("\n"),start);
2121 one=one.Trim();
2122 if(one.IsEmpty() || one == _T("Success"))
2123 continue;
2124 one.Replace(_T('/'),_T('\\'));
2125 CTGitPath path;
2126 path.SetFromWin(one);
2127 list.AddPath(path);
2129 if (list.GetCount() > 0)
2131 return SendPatchMail(list, autoclose);
2133 else
2135 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2136 return true;
2141 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2143 CString cmd,output;
2144 int start=0;
2146 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2147 if(output.IsEmpty())
2149 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2150 if(output.IsEmpty())
2151 return CP_UTF8;
2153 int start=0;
2154 output=output.Tokenize(_T("\n"),start);
2155 return CUnicodeUtils::GetCPCode(output);
2158 else
2160 output=output.Tokenize(_T("\n"),start);
2161 return CUnicodeUtils::GetCPCode(output);
2164 int CAppUtils::GetCommitTemplate(CString &temp)
2166 CString cmd,output;
2168 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2169 if( output.IsEmpty() )
2170 return -1;
2172 if( output.GetLength()<1)
2173 return -1;
2175 if( output[0] == _T('/'))
2177 if(output.GetLength()>=3)
2178 if(output[2] == _T('/'))
2180 output.GetBuffer()[0] = output[1];
2181 output.GetBuffer()[1] = _T(':');
2185 int start=0;
2186 output=output.Tokenize(_T("\n"),start);
2188 output.Replace(_T('/'),_T('\\'));
2192 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2193 CString str;
2194 while(file.ReadString(str))
2196 temp+=str+_T("\n");
2199 }catch(...)
2201 return -1;
2203 return 0;
2205 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2207 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2208 CString cmd,output;
2209 int cp=CP_UTF8;
2211 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2212 if(output.IsEmpty())
2213 cp=CP_UTF8;
2215 int start=0;
2216 output=output.Tokenize(_T("\n"),start);
2217 cp=CUnicodeUtils::GetCPCode(output);
2219 int len=message.GetLength();
2221 char * buf;
2222 buf = new char[len*4 + 4];
2223 SecureZeroMemory(buf, (len*4 + 4));
2225 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2227 file.Write(buf,lengthIncTerminator-1);
2228 file.Close();
2229 delete buf;
2230 return 0;
2233 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2235 CPullFetchDlg dlg;
2236 dlg.m_PreSelectRemote = remoteName;
2237 dlg.m_bAllowRebase = allowRebase;
2238 dlg.m_IsPull=FALSE;
2240 if(dlg.DoModal()==IDOK)
2242 if(dlg.m_bAutoLoad)
2244 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2247 CString url;
2248 url=dlg.m_RemoteURL;
2249 CString cmd;
2250 CString arg;
2252 int ver = CAppUtils::GetMsysgitVersion();
2254 if(ver >= 0x01070203) //above 1.7.0.2
2255 arg = _T("--progress ");
2257 if (dlg.m_bPrune) {
2258 arg += _T("--prune ");
2261 if (dlg.m_bFetchTags) {
2262 arg += _T("--tags ");
2265 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2266 CProgressDlg progress;
2268 progress.m_bAutoCloseOnSuccess = autoClose;
2270 progress.m_PostCmdList.Add(_T("Show Log"));
2272 if(!dlg.m_bRebase)
2274 progress.m_PostCmdList.Add(_T("&Rebase"));
2277 progress.m_GitCmd=cmd;
2278 int userResponse=progress.DoModal();
2280 if (userResponse == IDC_PROGRESS_BUTTON1)
2282 CString cmd;
2283 cmd = CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe");
2284 cmd += _T(" /command:log");
2285 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2286 CAppUtils::LaunchApplication(cmd, IDS_ERR_PROC, false);
2287 return TRUE;
2289 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2291 while(1)
2293 CRebaseDlg dlg;
2294 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2295 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2296 int response = dlg.DoModal();
2297 if(response == IDOK)
2299 return TRUE;
2301 if(response == IDC_REBASE_POST_BUTTON )
2303 CString cmd, out, err;
2304 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2305 g_Git.m_CurrentDir,
2306 g_Git.FixBranchName(dlg.m_Upstream),
2307 g_Git.FixBranchName(dlg.m_Branch));
2308 if (g_Git.Run(cmd, &out, &err, CP_ACP))
2310 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2311 return FALSE;
2314 CAppUtils::SendPatchMail(cmd,out);
2315 return TRUE;
2318 if(response == IDC_REBASE_POST_BUTTON +1 )
2319 continue;
2321 if(response == IDCANCEL)
2322 return FALSE;
2324 return TRUE;
2327 return FALSE;
2330 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2332 CPushDlg dlg;
2333 dlg.m_BranchSourceName = selectLocalBranch;
2334 CString error;
2335 DWORD exitcode = 0xFFFFFFFF;
2336 CTGitPathList list;
2337 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2338 if (CHooks::Instance().PrePush(list,exitcode, error))
2340 if (exitcode)
2342 CString temp;
2343 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2344 //ReportError(temp);
2345 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2346 return false;
2350 if(dlg.DoModal()==IDOK)
2352 CString cmd;
2353 CString arg;
2355 if(dlg.m_bAutoLoad)
2357 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2360 if(dlg.m_bPack)
2361 arg += _T("--thin ");
2362 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2363 arg += _T("--tags ");
2364 if(dlg.m_bForce)
2365 arg += _T("--force ");
2367 int ver = CAppUtils::GetMsysgitVersion();
2369 if(ver >= 0x01070203) //above 1.7.0.2
2370 arg += _T("--progress ");
2372 if (dlg.m_bPushAllBranches)
2374 cmd.Format(_T("git.exe push --all %s \"%s\""),
2375 arg,
2376 dlg.m_URL);
2378 else
2380 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2381 arg,
2382 dlg.m_URL,
2383 dlg.m_BranchSourceName);
2384 if (!dlg.m_BranchRemoteName.IsEmpty())
2386 cmd += _T(":") + dlg.m_BranchRemoteName;
2390 CProgressDlg progress;
2391 progress.m_bAutoCloseOnSuccess=autoClose;
2392 progress.m_GitCmd=cmd;
2393 progress.m_PostCmdList.Add(_T("&Request pull"));
2394 progress.m_PostCmdList.Add(_T("Re&Push"));
2395 int ret = progress.DoModal();
2397 if(!progress.m_GitStatus)
2399 if (CHooks::Instance().PostPush(list,exitcode, error))
2401 if (exitcode)
2403 CString temp;
2404 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2405 //ReportError(temp);
2406 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2407 return false;
2410 if(ret == IDC_PROGRESS_BUTTON1)
2412 RequestPull(dlg.m_BranchRemoteName);
2414 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2416 Push();
2418 return TRUE;
2422 return FALSE;
2425 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2427 CRequestPullDlg dlg;
2428 dlg.m_RepositoryURL = repositoryUrl;
2429 dlg.m_EndRevision = endrevision;
2430 if (dlg.DoModal()==IDOK)
2432 CString cmd;
2433 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2435 CProgressDlg progress;
2436 progress.m_GitCmd=cmd;
2437 progress.DoModal();
2439 return true;
2442 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2444 CString strDir(szPath);
2445 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2447 strDir.AppendChar(_T('\\'));
2449 std::vector<CString> vPath;
2450 CString strTemp;
2451 bool bSuccess = false;
2453 for (int i=0;i<strDir.GetLength();++i)
2455 if (strDir.GetAt(i) != _T('\\'))
2457 strTemp.AppendChar(strDir.GetAt(i));
2459 else
2461 vPath.push_back(strTemp);
2462 strTemp.AppendChar(_T('\\'));
2466 std::vector<CString>::const_iterator vIter;
2467 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2469 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2472 return bSuccess;
2475 void CAppUtils::RemoveTrailSlash(CString &path)
2477 if(path.IsEmpty())
2478 return ;
2480 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2482 path=path.Left(path.GetLength()-1);
2483 if(path.IsEmpty())
2484 return;
2488 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2489 CTGitPathList &pathList,
2490 CTGitPathList &selectedList,
2491 bool bSelectFilesForCommit,
2492 bool autoClose)
2494 bool bFailed = true;
2496 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2498 if(CMessageBox::Show(NULL,_T("User name and email must be set before commit.\r\n Do you want to set these now?\r\n"),
2499 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2501 CTGitPath path(g_Git.m_CurrentDir);
2502 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2503 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2504 dlg.SetTreeWidth(220);
2505 dlg.m_DefaultPage = _T("gitconfig");
2507 dlg.DoModal();
2508 dlg.HandleRestart();
2511 else
2512 return false;
2515 while (bFailed)
2517 bFailed = false;
2518 CCommitDlg dlg;
2519 dlg.m_sBugID = bugid;
2521 dlg.m_bWholeProject = bWholeProject;
2523 dlg.m_sLogMessage = sLogMsg;
2524 dlg.m_pathList = pathList;
2525 dlg.m_checkedPathList = selectedList;
2526 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2527 dlg.m_bAutoClose = autoClose;
2528 if (dlg.DoModal() == IDOK)
2530 if (dlg.m_pathList.GetCount()==0)
2531 return false;
2532 // if the user hasn't changed the list of selected items
2533 // we don't use that list. Because if we would use the list
2534 // of pre-checked items, the dialog would show different
2535 // checked items on the next startup: it would only try
2536 // to check the parent folder (which might not even show)
2537 // instead, we simply use an empty list and let the
2538 // default checking do its job.
2539 if (!dlg.m_pathList.IsEqual(pathList))
2540 selectedList = dlg.m_pathList;
2541 pathList = dlg.m_updatedPathList;
2542 sLogMsg = dlg.m_sLogMessage;
2543 bSelectFilesForCommit = true;
2545 if( dlg.m_bPushAfterCommit )
2547 switch(dlg.m_PostCmd)
2549 case GIT_POST_CMD_DCOMMIT:
2550 CAppUtils::SVNDCommit();
2551 break;
2552 default:
2553 CAppUtils::Push();
2556 // CGitProgressDlg progDlg;
2557 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2558 // if (parser.HasVal(_T("closeonend")))
2559 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2560 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2561 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2562 // progDlg.SetPathList(dlg.m_pathList);
2563 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2564 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2565 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2566 // progDlg.SetItemCount(dlg.m_itemsCount);
2567 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2568 // progDlg.DoModal();
2569 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2570 // err = (DWORD)progDlg.DidErrorsOccur();
2571 // bFailed = progDlg.DidErrorsOccur();
2572 // bRet = progDlg.DidErrorsOccur();
2573 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2574 // if (DWORD(bFailRepeat)==0)
2575 // bFailed = false; // do not repeat if the user chose not to in the settings.
2578 return true;
2582 BOOL CAppUtils::SVNDCommit()
2584 CSVNDCommitDlg dcommitdlg;
2585 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2586 if (gitSetting == _T("")) {
2587 if (dcommitdlg.DoModal() != IDOK)
2589 return false;
2591 else
2593 if (dcommitdlg.m_remember)
2595 if (dcommitdlg.m_rmdir)
2597 gitSetting = _T("true");
2599 else
2601 gitSetting = _T("false");
2603 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2605 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2611 BOOL IsStash = false;
2612 if(!g_Git.CheckCleanWorkTree())
2614 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2616 CString cmd,out;
2617 cmd=_T("git.exe stash");
2618 if(g_Git.Run(cmd,&out,CP_ACP))
2620 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2621 return false;
2623 IsStash =true;
2626 else
2628 return false;
2632 CProgressDlg progress;
2633 if (dcommitdlg.m_rmdir)
2635 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2637 else
2639 progress.m_GitCmd=_T("git.exe svn dcommit");
2641 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2643 if( IsStash)
2645 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2647 CString cmd,out;
2648 cmd=_T("git.exe stash pop");
2649 if(g_Git.Run(cmd,&out,CP_ACP))
2651 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2652 return false;
2656 else
2658 return false;
2661 return TRUE;
2663 return FALSE;
2666 BOOL CAppUtils::Merge(CString *commit)
2668 CMergeDlg dlg;
2669 if(commit)
2670 dlg.m_initialRefName = *commit;
2672 if(dlg.DoModal()==IDOK)
2674 CString cmd;
2675 CString noff;
2676 CString squash;
2677 CString nocommit;
2678 CString msg;
2680 if(dlg.m_bNoFF)
2681 noff=_T("--no-ff");
2683 if(dlg.m_bSquash)
2684 squash=_T("--squash");
2686 if(dlg.m_bNoCommit)
2687 nocommit=_T("--no-commit");
2689 if(!dlg.m_strLogMesage.IsEmpty())
2691 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2693 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2694 msg,
2695 noff,
2696 squash,
2697 nocommit,
2698 g_Git.FixBranchName(dlg.m_VersionName));
2700 CProgressDlg Prodlg;
2701 Prodlg.m_GitCmd = cmd;
2703 if (dlg.m_bNoCommit)
2704 Prodlg.m_PostCmdList.Add(_T("Commit"));
2706 int ret = Prodlg.DoModal();
2708 if (ret == IDC_PROGRESS_BUTTON1)
2709 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2711 return !Prodlg.m_GitStatus;
2713 return false;
2716 void CAppUtils::EditNote(GitRev *rev)
2718 CInputDlg dlg;
2719 dlg.m_sHintText=_T("Edit Notes");
2720 dlg.m_sInputText = rev->m_Notes;
2721 dlg.m_sTitle=_T("Edit Notes");
2722 //dlg.m_pProjectProperties = &m_ProjectProperties;
2723 dlg.m_bUseLogWidth = true;
2724 if(dlg.DoModal() == IDOK)
2726 CString cmd,output;
2727 cmd=_T("notes add -f -F \"");
2729 CString tempfile=::GetTempFile();
2730 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2731 cmd += tempfile;
2732 cmd += _T("\" ");
2733 cmd += rev->m_CommitHash.ToString();
2737 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2739 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2742 else
2744 rev->m_Notes = dlg.m_sInputText;
2746 }catch(...)
2748 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2750 CFile::Remove(tempfile);
2755 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2757 CString cmd;
2758 CString progressarg;
2759 CString version;
2761 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2762 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2764 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2766 __int64 time=0;
2767 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2769 if((DWORD)time == regTime)
2771 return regVersion;
2775 if(versionstr)
2776 version = *versionstr;
2777 else
2779 CString err;
2780 cmd = _T("git.exe --version");
2781 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2783 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2784 return false;
2788 int start=0;
2789 int ver;
2791 CString str=version.Tokenize(_T("."),start);
2792 int space = str.ReverseFind(_T(' '));
2793 str=str.Mid(space+1,start);
2794 ver = _ttol(str);
2795 ver <<=24;
2797 version = version.Mid(start);
2798 start = 0;
2799 str = version.Tokenize(_T("."),start);
2801 ver |= (_ttol(str)&0xFF)<<16;
2803 str = version.Tokenize(_T("."),start);
2804 ver |= (_ttol(str)&0xFF)<<8;
2806 str = version.Tokenize(_T("."),start);
2807 ver |= (_ttol(str)&0xFF);
2809 regTime = time&0xFFFFFFFF;
2810 regVersion = ver;
2812 return ver;
2815 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2817 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2819 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2821 if (hShell) {
2822 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2823 if (pfnSHGPSFW) {
2824 IPropertyStore *pps;
2825 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2826 if (SUCCEEDED(hr)) {
2827 PROPVARIANT var;
2828 var.vt = VT_BOOL;
2829 var.boolVal = VARIANT_TRUE;
2830 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2831 pps->Release();
2834 FreeLibrary(hShell);
2838 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2840 ASSERT(dialogname.GetLength() < 70);
2841 ASSERT(urlorpath.GetLength() < MAX_PATH);
2842 WCHAR pathbuf[MAX_PATH] = {0};
2844 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2846 wcscat_s(pathbuf, L" - ");
2847 wcscat_s(pathbuf, dialogname);
2848 wcscat_s(pathbuf, L" - ");
2849 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2850 SetWindowText(hWnd, pathbuf);