Fixed issue #933: implement git stash --include-untracked
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob7e30b43699367350a0cab1b1f89ff3442f633e3b
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_bIncludeUntracked && CAppUtils::GetMsysgitVersion() >= 0x01070700)
80 cmd += _T(" --include-untracked");
82 if (!dlg.m_sMessage.IsEmpty())
84 CString message = dlg.m_sMessage;
85 message.Replace(_T("\""), _T("\"\""));
86 cmd += _T(" \"") + message + _T("\"");
89 if (g_Git.Run(cmd, &out, CP_ACP))
91 CMessageBox::Show(NULL, CString(_T("<ct=0x0000FF>Stash Fail!!!</ct>\n")) + out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
93 else
95 CMessageBox::Show(NULL, CString(_T("<ct=0xff0000>Stash Success</ct>\n")) + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
96 return true;
99 return false;
102 int CAppUtils::StashApply(CString ref)
104 CString cmd,out;
105 cmd = _T("git.exe stash apply ");
106 if (ref.Find(_T("refs/")) == 0)
107 ref = ref.Mid(5);
108 if (ref.Find(_T("stash{")) == 0)
109 ref = _T("stash@") + ref.Mid(5);
110 cmd += ref;
112 if(g_Git.Run(cmd,&out,CP_ACP))
114 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
116 else
118 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
119 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
121 CChangedDlg dlg;
122 dlg.m_pathList.AddPath(CTGitPath());
123 dlg.DoModal();
125 return 0;
127 return -1;
130 int CAppUtils::StashPop()
132 CString cmd,out;
133 cmd=_T("git.exe stash pop ");
135 if(g_Git.Run(cmd,&out,CP_ACP))
137 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
140 else
142 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
143 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
145 CChangedDlg dlg;
146 dlg.m_pathList.AddPath(CTGitPath());
147 dlg.DoModal();
149 return 0;
151 return -1;
154 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
156 #if 0
157 GitProperties props(file, GitRev::REV_WC, false);
158 for (int i = 0; i < props.GetCount(); ++i)
160 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
162 mimetype = props.GetItemValue(i).c_str();
163 return true;
166 #endif
167 return false;
170 BOOL CAppUtils::StartExtMerge(
171 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
172 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
175 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
176 CString ext = mergedfile.GetFileExtension();
177 CString com = regCom;
178 bool bInternal = false;
180 CString mimetype;
181 if (ext != "")
183 // is there an extension specific merge tool?
184 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
185 if (CString(mergetool) != "")
187 com = mergetool;
190 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
192 // is there a mime type specific merge tool?
193 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
194 if (CString(mergetool) != "")
196 com = mergetool;
200 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
202 // use TortoiseMerge
203 bInternal = true;
204 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
205 com = tortoiseMergePath;
206 if (com.IsEmpty())
208 com = CPathUtils::GetAppDirectory();
209 com += _T("TortoiseMerge.exe");
211 com = _T("\"") + com + _T("\"");
212 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
213 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
215 // check if the params are set. If not, just add the files to the command line
216 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
218 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
219 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
220 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
221 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
223 if (basefile.IsEmpty())
225 com.Replace(_T("/base:%base"), _T(""));
226 com.Replace(_T("%base"), _T(""));
228 else
229 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
230 if (theirfile.IsEmpty())
232 com.Replace(_T("/theirs:%theirs"), _T(""));
233 com.Replace(_T("%theirs"), _T(""));
235 else
236 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
237 if (yourfile.IsEmpty())
239 com.Replace(_T("/mine:%mine"), _T(""));
240 com.Replace(_T("%mine"), _T(""));
242 else
243 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
244 if (mergedfile.IsEmpty())
246 com.Replace(_T("/merged:%merged"), _T(""));
247 com.Replace(_T("%merged"), _T(""));
249 else
250 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
251 if (basename.IsEmpty())
253 if (basefile.IsEmpty())
255 com.Replace(_T("/basename:%bname"), _T(""));
256 com.Replace(_T("%bname"), _T(""));
258 else
260 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
263 else
264 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
265 if (theirname.IsEmpty())
267 if (theirfile.IsEmpty())
269 com.Replace(_T("/theirsname:%tname"), _T(""));
270 com.Replace(_T("%tname"), _T(""));
272 else
274 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
277 else
278 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
279 if (yourname.IsEmpty())
281 if (yourfile.IsEmpty())
283 com.Replace(_T("/minename:%yname"), _T(""));
284 com.Replace(_T("%yname"), _T(""));
286 else
288 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
291 else
292 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
293 if (mergedname.IsEmpty())
295 if (mergedfile.IsEmpty())
297 com.Replace(_T("/mergedname:%mname"), _T(""));
298 com.Replace(_T("%mname"), _T(""));
300 else
302 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
305 else
306 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
308 if ((bReadOnly)&&(bInternal))
309 com += _T(" /readonly");
311 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
313 return FALSE;
316 return TRUE;
319 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
321 CString viewer;
322 // use TortoiseMerge
323 viewer = CPathUtils::GetAppDirectory();
324 viewer += _T("TortoiseMerge.exe");
326 viewer = _T("\"") + viewer + _T("\"");
327 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
328 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
329 if (bReversed)
330 viewer += _T(" /reversedpatch");
331 if (!sOriginalDescription.IsEmpty())
332 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
333 if (!sPatchedDescription.IsEmpty())
334 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
335 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
337 return FALSE;
339 return TRUE;
342 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
344 // Is there a mime type specific diff tool?
345 CString mimetype;
346 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
348 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
349 if (!difftool.IsEmpty())
350 return difftool;
353 // Is there an extension specific diff tool?
354 CString ext = file2.GetFileExtension().MakeLower();
355 if (!ext.IsEmpty())
357 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
358 if (!difftool.IsEmpty())
359 return difftool;
360 // Maybe we should use TortoiseIDiff?
361 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
362 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
363 (ext == _T(".png")) || (ext == _T(".ico")) ||
364 (ext == _T(".dib")) || (ext == _T(".emf")))
366 return
367 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
368 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
372 // Finally, pick a generic external diff tool
373 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
374 return difftool;
377 bool CAppUtils::StartExtDiff(
378 const CString& file1, const CString& file2,
379 const CString& sName1, const CString& sName2,
380 const DiffFlags& flags)
382 CString viewer;
384 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
385 if (!flags.bBlame || !(DWORD)blamediff)
387 viewer = PickDiffTool(file1, file2);
388 // If registry entry for a diff program is commented out, use TortoiseMerge.
389 bool bCommentedOut = viewer.Left(1) == _T("#");
390 if (flags.bAlternativeTool)
392 // Invert external vs. internal diff tool selection.
393 if (bCommentedOut)
394 viewer.Delete(0); // uncomment
395 else
396 viewer = "";
398 else if (bCommentedOut)
399 viewer = "";
402 bool bInternal = viewer.IsEmpty();
403 if (bInternal)
405 viewer =
406 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
407 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
408 if (flags.bBlame)
409 viewer += _T(" /blame");
411 // check if the params are set. If not, just add the files to the command line
412 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
414 viewer += _T(" \"")+file1+_T("\"");
415 viewer += _T(" \"")+file2+_T("\"");
417 if (viewer.Find(_T("%base")) >= 0)
419 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
421 if (viewer.Find(_T("%mine")) >= 0)
423 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
426 if (sName1.IsEmpty())
427 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
428 else
429 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
431 if (sName2.IsEmpty())
432 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
433 else
434 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
436 if (flags.bReadOnly && bInternal)
437 viewer += _T(" /readonly");
439 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
442 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
444 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
445 CString viewer = diffpropsexe;
446 bool bInternal = false;
447 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
449 //no registry entry (or commented out) for a diff program
450 //use TortoiseMerge
451 bInternal = true;
452 viewer = CPathUtils::GetAppDirectory();
453 viewer += _T("TortoiseMerge.exe");
454 viewer = _T("\"") + viewer + _T("\"");
455 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
457 // check if the params are set. If not, just add the files to the command line
458 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
460 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
461 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
463 if (viewer.Find(_T("%base")) >= 0)
465 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
467 if (viewer.Find(_T("%mine")) >= 0)
469 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
472 if (sName1.IsEmpty())
473 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
474 else
475 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
477 if (sName2.IsEmpty())
478 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
479 else
480 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
482 if ((bReadOnly)&&(bInternal))
483 viewer += _T(" /readonly");
485 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
487 return FALSE;
489 return TRUE;
492 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
494 CString viewer;
495 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
496 viewer = v;
497 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
499 // use TortoiseUDiff
500 viewer = CPathUtils::GetAppDirectory();
501 viewer += _T("TortoiseUDiff.exe");
502 // enquote the path to TortoiseUDiff
503 viewer = _T("\"") + viewer + _T("\"");
504 // add the params
505 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
508 if (viewer.Find(_T("%1"))>=0)
510 if (viewer.Find(_T("\"%1\"")) >= 0)
511 viewer.Replace(_T("%1"), patchfile);
512 else
513 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
515 else
516 viewer += _T(" \"") + patchfile + _T("\"");
517 if (viewer.Find(_T("%title")) >= 0)
519 viewer.Replace(_T("%title"), title);
522 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
524 return FALSE;
526 return TRUE;
529 BOOL CAppUtils::StartTextViewer(CString file)
531 CString viewer;
532 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
533 viewer = txt;
534 viewer = viewer + _T("\\Shell\\Open\\Command\\");
535 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
536 viewer = txtexe;
538 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
539 TCHAR * buf = new TCHAR[len+1];
540 ExpandEnvironmentStrings(viewer, buf, len);
541 viewer = buf;
542 delete [] buf;
543 len = ExpandEnvironmentStrings(file, NULL, 0);
544 buf = new TCHAR[len+1];
545 ExpandEnvironmentStrings(file, buf, len);
546 file = buf;
547 delete [] buf;
548 file = _T("\"")+file+_T("\"");
549 if (viewer.IsEmpty())
551 OPENFILENAME ofn = {0}; // common dialog box structure
552 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
553 // Initialize OPENFILENAME
554 ofn.lStructSize = sizeof(OPENFILENAME);
555 ofn.hwndOwner = NULL;
556 ofn.lpstrFile = szFile;
557 ofn.nMaxFile = _countof(szFile);
558 CString sFilter;
559 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
560 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
561 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
562 // Replace '|' delimiters with '\0's
563 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
564 while (ptr != pszFilters)
566 if (*ptr == '|')
567 *ptr = '\0';
568 ptr--;
570 ofn.lpstrFilter = pszFilters;
571 ofn.nFilterIndex = 1;
572 ofn.lpstrFileTitle = NULL;
573 ofn.nMaxFileTitle = 0;
574 ofn.lpstrInitialDir = NULL;
575 CString temp;
576 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
577 CStringUtils::RemoveAccelerators(temp);
578 ofn.lpstrTitle = temp;
579 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
581 // Display the Open dialog box.
583 if (GetOpenFileName(&ofn)==TRUE)
585 delete [] pszFilters;
586 viewer = CString(ofn.lpstrFile);
588 else
590 delete [] pszFilters;
591 return FALSE;
594 if (viewer.Find(_T("\"%1\"")) >= 0)
596 viewer.Replace(_T("\"%1\""), file);
598 else if (viewer.Find(_T("%1")) >= 0)
600 viewer.Replace(_T("%1"), file);
602 else
604 viewer += _T(" ");
605 viewer += file;
608 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
610 return FALSE;
612 return TRUE;
615 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
617 DWORD length = 0;
618 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
619 if (hFile == INVALID_HANDLE_VALUE)
620 return TRUE;
621 length = ::GetFileSize(hFile, NULL);
622 ::CloseHandle(hFile);
623 if (length < 4)
624 return TRUE;
625 return FALSE;
629 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
631 LOGFONT logFont;
632 HDC hScreenDC = ::GetDC(NULL);
633 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
634 ::ReleaseDC(NULL, hScreenDC);
635 logFont.lfWidth = 0;
636 logFont.lfEscapement = 0;
637 logFont.lfOrientation = 0;
638 logFont.lfWeight = FW_NORMAL;
639 logFont.lfItalic = 0;
640 logFont.lfUnderline = 0;
641 logFont.lfStrikeOut = 0;
642 logFont.lfCharSet = DEFAULT_CHARSET;
643 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
644 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
645 logFont.lfQuality = DRAFT_QUALITY;
646 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
647 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
648 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
651 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
653 STARTUPINFO startup;
654 PROCESS_INFORMATION process;
655 memset(&startup, 0, sizeof(startup));
656 startup.cb = sizeof(startup);
657 memset(&process, 0, sizeof(process));
659 CString cleanCommandLine(sCommandLine);
661 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
663 if(idErrMessageFormat != 0)
665 LPVOID lpMsgBuf;
666 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
667 FORMAT_MESSAGE_FROM_SYSTEM |
668 FORMAT_MESSAGE_IGNORE_INSERTS,
669 NULL,
670 GetLastError(),
671 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
672 (LPTSTR) &lpMsgBuf,
674 NULL
676 CString temp;
677 temp.Format(idErrMessageFormat, lpMsgBuf);
678 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
679 LocalFree( lpMsgBuf );
681 return false;
684 if (bWaitForStartup)
686 WaitForInputIdle(process.hProcess, 10000);
689 CloseHandle(process.hThread);
690 CloseHandle(process.hProcess);
691 return true;
693 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
695 CString key,remote;
696 CString cmd,out;
697 if( pRemote == NULL)
699 remote=_T("origin");
701 else
703 remote=*pRemote;
705 if(keyfile == NULL)
707 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
708 key = g_Git.GetConfigValue(cmd);
709 int start=0;
710 key = key.Tokenize(_T("\n"),start);
712 else
713 key=*keyfile;
715 if(key.IsEmpty())
716 return false;
718 CString proc=CPathUtils::GetAppDirectory();
719 proc += _T("pageant.exe \"");
720 proc += key;
721 proc += _T("\"");
723 CString tempfile = GetTempFile();
724 ::DeleteFile(tempfile);
726 proc += _T(" -c \"");
727 proc += CPathUtils::GetAppDirectory();
728 proc += _T("touch.exe\"");
729 proc += _T(" \"");
730 proc += tempfile;
731 proc += _T("\"");
733 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
734 if(!b)
735 return b;
737 int i=0;
738 while(!::PathFileExists(tempfile))
740 Sleep(100);
741 i++;
742 if(i>10*60*5)
743 break; //timeout 5 minutes
746 if( i== 10*60*5)
748 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
750 ::DeleteFile(tempfile);
751 return true;
753 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
755 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
756 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
757 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
760 CString sCmd;
761 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
763 LaunchApplication(sCmd, NULL, false);
764 return true;
766 bool CAppUtils::LaunchRemoteSetting()
768 CTGitPath path(g_Git.m_CurrentDir);
769 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
770 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
771 //dlg.SetTreeWidth(220);
772 dlg.m_DefaultPage = _T("gitremote");
774 dlg.DoModal();
775 dlg.HandleRestart();
776 return true;
779 * Launch the external blame viewer
781 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
783 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
784 viewer += _T("TortoiseGitBlame.exe");
785 viewer += _T("\" \"") + sBlameFile + _T("\"");
786 //viewer += _T(" \"") + sLogFile + _T("\"");
787 //viewer += _T(" \"") + sOriginalFile + _T("\"");
788 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
789 viewer += CString(_T(" /rev:"))+Rev;
790 viewer += _T(" ")+sParams;
792 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
795 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
797 CString sText;
798 if (pWnd == NULL)
799 return false;
800 bool bStyled = false;
801 pWnd->GetWindowText(sText);
802 // the rich edit control doesn't count the CR char!
803 // to be exact: CRLF is treated as one char.
804 sText.Remove('\r');
806 // style each line separately
807 int offset = 0;
808 int nNewlinePos;
811 nNewlinePos = sText.Find('\n', offset);
812 CString sLine = sText.Mid(offset);
813 if (nNewlinePos>=0)
814 sLine = sLine.Left(nNewlinePos-offset);
815 int start = 0;
816 int end = 0;
817 while (FindStyleChars(sLine, '*', start, end))
819 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
820 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
821 CHARFORMAT2 format;
822 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
823 format.cbSize = sizeof(CHARFORMAT2);
824 format.dwMask = CFM_BOLD;
825 format.dwEffects = CFE_BOLD;
826 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
827 bStyled = true;
828 start = end;
830 start = 0;
831 end = 0;
832 while (FindStyleChars(sLine, '^', start, end))
834 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
835 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
836 CHARFORMAT2 format;
837 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
838 format.cbSize = sizeof(CHARFORMAT2);
839 format.dwMask = CFM_ITALIC;
840 format.dwEffects = CFE_ITALIC;
841 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
842 bStyled = true;
843 start = end;
845 start = 0;
846 end = 0;
847 while (FindStyleChars(sLine, '_', start, end))
849 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
850 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
851 CHARFORMAT2 format;
852 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
853 format.cbSize = sizeof(CHARFORMAT2);
854 format.dwMask = CFM_UNDERLINE;
855 format.dwEffects = CFE_UNDERLINE;
856 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
857 bStyled = true;
858 start = end;
860 offset = nNewlinePos+1;
861 } while(nNewlinePos>=0);
862 return bStyled;
865 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
867 int i=start;
868 bool bFoundMarker = false;
869 // find a starting marker
870 while (sText[i] != 0)
872 if (sText[i] == stylechar)
874 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
875 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
877 start = i+1;
878 i++;
879 bFoundMarker = true;
880 break;
883 i++;
885 if (!bFoundMarker)
886 return false;
887 // find ending marker
888 bFoundMarker = false;
889 while (sText[i] != 0)
891 if (sText[i] == stylechar)
893 if ((IsCharAlphaNumeric(sText[i-1])) &&
894 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
896 end = i;
897 i++;
898 bFoundMarker = true;
899 break;
902 i++;
904 return bFoundMarker;
907 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
909 OPENFILENAME ofn = {0}; // common dialog box structure
910 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
911 ofn.lStructSize = sizeof(OPENFILENAME);
912 ofn.hwndOwner = hwndOwner;
913 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
914 ofn.lpstrFile = szFile;
915 ofn.nMaxFile = _countof(szFile);
916 CString sFilter;
917 TCHAR * pszFilters = NULL;
918 if (filter)
920 sFilter.LoadString(filter);
921 pszFilters = new TCHAR[sFilter.GetLength()+4];
922 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
923 // Replace '|' delimiters with '\0's
924 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
925 while (ptr != pszFilters)
927 if (*ptr == '|')
928 *ptr = '\0';
929 ptr--;
931 ofn.lpstrFilter = pszFilters;
933 ofn.nFilterIndex = 1;
934 ofn.lpstrFileTitle = NULL;
935 ofn.nMaxFileTitle = 0;
936 ofn.lpstrInitialDir = NULL;
937 CString temp;
938 if (title)
940 temp.LoadString(title);
941 CStringUtils::RemoveAccelerators(temp);
943 ofn.lpstrTitle = temp;
944 if (bOpen)
945 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
946 else
947 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
950 // Display the Open dialog box.
951 bool bRet = false;
952 if (bOpen)
954 bRet = !!GetOpenFileName(&ofn);
956 else
958 bRet = !!GetSaveFileName(&ofn);
960 if (bRet)
962 if (pszFilters)
963 delete [] pszFilters;
964 path = CString(ofn.lpstrFile);
965 if (filterindex)
966 *filterindex = ofn.nFilterIndex;
967 return true;
969 if (pszFilters)
970 delete [] pszFilters;
971 return false;
974 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
976 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
977 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
978 // create a bitmap from the icon
979 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
980 if (!hIcon)
981 return false;
983 RECT rect = {0};
984 rect.right = width;
985 rect.bottom = height;
986 HBITMAP bmp = NULL;
988 HWND desktop = ::GetDesktopWindow();
989 if (desktop)
991 HDC screen_dev = ::GetDC(desktop);
992 if (screen_dev)
994 // Create a compatible DC
995 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
996 if (dst_hdc)
998 // Create a new bitmap of icon size
999 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
1000 if (bmp)
1002 // Select it into the compatible DC
1003 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
1004 // Fill the background of the compatible DC with the given color
1005 ::SetBkColor(dst_hdc, bkColor);
1006 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
1008 // Draw the icon into the compatible DC
1009 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
1010 ::SelectObject(dst_hdc, old_dst_bmp);
1012 ::DeleteDC(dst_hdc);
1015 ::ReleaseDC(desktop, screen_dev);
1018 // Restore settings
1019 DestroyIcon(hIcon);
1021 if (bmp == NULL)
1022 return false;
1024 LVBKIMAGE lv;
1025 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1026 lv.hbm = bmp;
1027 lv.xOffsetPercent = 100;
1028 lv.yOffsetPercent = 100;
1029 ListView_SetBkImage(hListCtrl, &lv);
1030 return true;
1033 CString CAppUtils::GetProjectNameFromURL(CString url)
1035 CString name;
1036 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1037 (name.CompareNoCase(_T("tags"))==0) ||
1038 (name.CompareNoCase(_T("trunk"))==0))
1040 name = url.Mid(url.ReverseFind('/')+1);
1041 url = url.Left(url.ReverseFind('/'));
1043 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1045 // a name of svn or svnroot indicates that it's not really the project name. In that
1046 // case, we try the first part of the URL
1047 // of course, this won't work in all cases (but it works for Google project hosting)
1048 url.Replace(_T("http://"), _T(""));
1049 url.Replace(_T("https://"), _T(""));
1050 url.Replace(_T("svn://"), _T(""));
1051 url.Replace(_T("svn+ssh://"), _T(""));
1052 url.TrimLeft(_T("/"));
1053 name = url.Left(url.Find('.'));
1055 return name;
1058 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1059 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1060 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1061 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1064 CString tempfile=GetTempFile();
1065 CString cmd;
1066 if(rev1 == GitRev::GetWorkingCopy())
1068 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1070 else
1072 CString merge;
1073 if(bMerge)
1074 merge = _T("-c");
1076 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1079 if( !url1.IsEmpty() )
1081 cmd += _T(" \"");
1082 cmd += url1.GetGitPathString();
1083 cmd += _T("\" ");
1085 g_Git.RunLogFile(cmd,tempfile);
1086 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1089 #if 0
1090 CString sCmd;
1091 sCmd.Format(_T("%s /command:showcompare /unified"),
1092 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1093 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1094 if (rev1.IsValid())
1095 sCmd += _T(" /revision1:") + rev1.ToString();
1096 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1097 if (rev2.IsValid())
1098 sCmd += _T(" /revision2:") + rev2.ToString();
1099 if (peg.IsValid())
1100 sCmd += _T(" /pegrevision:") + peg.ToString();
1101 if (headpeg.IsValid())
1102 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1104 if (bAlternateDiff)
1105 sCmd += _T(" /alternatediff");
1107 if (bIgnoreAncestry)
1108 sCmd += _T(" /ignoreancestry");
1110 if (hWnd)
1112 sCmd += _T(" /hwnd:");
1113 TCHAR buf[30];
1114 _stprintf_s(buf, 30, _T("%d"), hWnd);
1115 sCmd += buf;
1118 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1119 #endif
1120 return TRUE;
1124 bool CAppUtils::Export(CString *BashHash)
1126 bool bRet = false;
1128 // ask from where the export has to be done
1129 CExportDlg dlg;
1130 if(BashHash)
1131 dlg.m_Revision=*BashHash;
1133 if (dlg.DoModal() == IDOK)
1135 CString cmd;
1136 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1137 g_Git.FixBranchName(dlg.m_VersionName));
1139 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1140 CProgressDlg pro;
1141 pro.m_GitCmd=cmd;
1142 pro.m_LogFile=dlg.m_strExportDirectory;
1143 pro.DoModal();
1144 return TRUE;
1146 return bRet;
1149 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1151 CCreateBranchTagDlg dlg;
1152 dlg.m_bIsTag=IsTag;
1153 dlg.m_bSwitch=switch_new_brach;
1155 if(CommitHash)
1156 dlg.m_Base = *CommitHash;
1158 if(dlg.DoModal()==IDOK)
1160 CString cmd;
1161 CString force;
1162 CString track;
1163 if(dlg.m_bTrack)
1164 track=_T(" --track ");
1166 if(dlg.m_bForce)
1167 force=_T(" -f ");
1169 if(IsTag)
1171 CString sign;
1172 if(dlg.m_bSign)
1173 sign=_T("-s");
1175 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1176 track,
1177 force,
1178 sign,
1179 dlg.m_BranchTagName,
1180 g_Git.FixBranchName(dlg.m_VersionName)
1183 CString tempfile=::GetTempFile();
1184 if(!dlg.m_Message.Trim().IsEmpty())
1186 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1187 cmd += _T(" -F ")+tempfile;
1190 else
1192 cmd.Format(_T("git.exe branch %s %s %s %s"),
1193 track,
1194 force,
1195 dlg.m_BranchTagName,
1196 g_Git.FixBranchName(dlg.m_VersionName)
1199 CString out;
1200 if(g_Git.Run(cmd,&out,CP_UTF8))
1202 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1204 if( !IsTag && dlg.m_bSwitch )
1206 // it is a new branch and the user has requested to switch to it
1207 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1208 g_Git.Run(cmd,&out,CP_UTF8);
1209 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1212 return TRUE;
1214 return FALSE;
1217 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1219 CGitSwitchDlg dlg;
1220 if(CommitHash)
1221 dlg.m_Base=*CommitHash;
1222 if(!initialRefName.IsEmpty())
1223 dlg.m_initialRefName = initialRefName;
1225 if (dlg.DoModal() == IDOK)
1227 CString branch;
1228 if (dlg.m_bBranch)
1229 branch = dlg.m_NewBranch;
1231 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1233 return FALSE;
1236 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1238 CString cmd;
1239 CString track;
1240 CString force;
1241 CString branch;
1243 if(!sNewBranch.IsEmpty()){
1244 if (bBranchOverride)
1246 branch.Format(_T("-B %s"), sNewBranch);
1248 else
1250 branch.Format(_T("-b %s"), sNewBranch);
1252 if (bTrack)
1253 track = _T("--track");
1255 if (bForce)
1256 force = _T("-f");
1258 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1259 force,
1260 track,
1261 branch,
1262 g_Git.FixBranchName(ref));
1264 CProgressDlg progress;
1265 progress.m_bAutoCloseOnSuccess = autoClose;
1266 progress.m_GitCmd = cmd;
1268 CTGitPath gitPath = g_Git.m_CurrentDir;
1269 if (gitPath.HasSubmodules())
1270 progress.m_PostCmdList.Add(_T("Update Submodules"));
1272 int ret = progress.DoModal();
1273 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1275 CString sCmd;
1276 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1278 LaunchApplication(sCmd, NULL, false);
1279 return TRUE;
1281 else if (ret == IDOK)
1282 return TRUE;
1284 return FALSE;
1287 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1289 CString ignorefile;
1290 ignorefile=g_Git.m_CurrentDir+_T("\\");
1292 if(IsMask)
1294 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1297 else
1299 ignorefile += _T("\\.gitignore");
1302 CStdioFile file;
1303 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1305 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1306 return FALSE;
1309 CString ignorelist;
1310 CString mask;
1313 //file.ReadString(ignorelist);
1314 file.SeekToEnd();
1315 for(int i=0;i<path.GetCount();i++)
1317 if(IsMask)
1319 mask=_T("*")+path[i].GetFileExtension();
1320 if(ignorelist.Find(mask)<0)
1321 ignorelist += _T("\n")+mask;
1323 else
1325 ignorelist += _T("\n/")+path[i].GetGitPathString();
1328 file.WriteString(ignorelist);
1330 file.Close();
1332 }catch(...)
1334 file.Close();
1335 return FALSE;
1338 return TRUE;
1342 bool CAppUtils::GitReset(CString *CommitHash,int type)
1344 CResetDlg dlg;
1345 dlg.m_ResetType=type;
1346 dlg.m_ResetToVersion=*CommitHash;
1347 if (dlg.DoModal() == IDOK)
1349 CString cmd;
1350 CString type;
1351 switch(dlg.m_ResetType)
1353 case 0:
1354 type=_T("--soft");
1355 break;
1356 case 1:
1357 type=_T("--mixed");
1358 break;
1359 case 2:
1360 type=_T("--hard");
1361 break;
1362 default:
1363 type=_T("--mixed");
1364 break;
1366 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1368 CProgressDlg progress;
1369 progress.m_GitCmd=cmd;
1371 CTGitPath gitPath = g_Git.m_CurrentDir;
1372 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1373 progress.m_PostCmdList.Add(_T("Update Submodules"));
1375 int ret = progress.DoModal();
1376 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1378 CString sCmd;
1379 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1381 LaunchApplication(sCmd, NULL, false);
1382 return TRUE;
1384 else if (ret == IDOK)
1385 return TRUE;
1388 return FALSE;
1391 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1393 if(mode == FALSE)
1395 descript=_T("Deleted");
1396 return;
1398 if(base)
1400 descript=_T("Modified");
1401 return;
1403 descript=_T("Created");
1404 return;
1407 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1409 CString tempmergefile;
1412 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1413 CFile::Remove(tempmergefile);
1414 }catch(...)
1420 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1421 CFile::Remove(tempmergefile);
1422 }catch(...)
1428 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1429 CFile::Remove(tempmergefile);
1430 }catch(...)
1434 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1436 CString file;
1437 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1439 return file;
1442 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1444 bool bRet = false;
1446 CTGitPath merge=path;
1447 CTGitPath directory = merge.GetDirectory();
1449 // we have the conflicted file (%merged)
1450 // now look for the other required files
1451 //GitStatus stat;
1452 //stat.GetStatus(merge);
1453 //if (stat.status == NULL)
1454 // return false;
1456 BYTE_VECTOR vector;
1458 CString cmd;
1459 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1461 if (g_Git.Run(cmd, &vector))
1463 return FALSE;
1466 CTGitPathList list;
1467 list.ParserFromLsFile(vector);
1469 if(list.GetCount() == 0)
1470 return FALSE;
1472 CTGitPath theirs;
1473 CTGitPath mine;
1474 CTGitPath base;
1476 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1477 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1478 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1480 CString format;
1482 //format=_T("git.exe cat-file blob \":%d:%s\"");
1483 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1484 CFile tempfile;
1485 //create a empty file, incase stage is not three
1486 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1487 tempfile.Close();
1488 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1489 tempfile.Close();
1490 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1491 tempfile.Close();
1493 bool b_base=false, b_local=false, b_remote=false;
1495 for(int i=0;i<list.GetCount();i++)
1497 CString cmd;
1498 CString outfile;
1499 cmd.Empty();
1500 outfile.Empty();
1502 if( list[i].m_Stage == 1)
1504 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1505 b_base = true;
1506 outfile = base.GetWinPathString();
1509 if( list[i].m_Stage == 2 )
1511 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1512 b_local = true;
1513 outfile = mine.GetWinPathString();
1516 if( list[i].m_Stage == 3 )
1518 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1519 b_remote = true;
1520 outfile = theirs.GetWinPathString();
1522 CString output, err;
1523 if(!outfile.IsEmpty())
1524 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1526 CString file;
1527 int start =0 ;
1528 file = output.Tokenize(_T("\t"), start);
1529 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1531 else
1533 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1537 if(b_local && b_remote )
1539 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1540 if( revertTheirMy )
1541 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1542 else
1543 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1546 else
1548 CFile::Remove(mine.GetWinPathString());
1549 CFile::Remove(theirs.GetWinPathString());
1550 CFile::Remove(base.GetWinPathString());
1552 CDeleteConflictDlg dlg;
1553 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1554 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1555 dlg.m_bShowModifiedButton=b_base;
1556 dlg.m_File=merge.GetGitPathString();
1557 if(dlg.DoModal() == IDOK)
1559 CString cmd,out;
1560 if(dlg.m_bIsDelete)
1562 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1564 else
1565 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1567 if(g_Git.Run(cmd,&out,CP_ACP))
1569 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1570 return FALSE;
1572 return TRUE;
1574 else
1575 return FALSE;
1578 #if 0
1579 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1580 base, theirs, mine, merge);
1581 #endif
1582 #if 0
1583 if (stat.status->text_status == svn_wc_status_conflicted)
1585 // we have a text conflict, use our merge tool to resolve the conflict
1587 CTSVNPath theirs(directory);
1588 CTSVNPath mine(directory);
1589 CTSVNPath base(directory);
1590 bool bConflictData = false;
1592 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1594 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1595 bConflictData = true;
1597 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1599 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1600 bConflictData = true;
1602 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1604 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1605 bConflictData = true;
1607 else
1609 mine = merge;
1611 if (bConflictData)
1612 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1613 base, theirs, mine, merge);
1616 if (stat.status->prop_status == svn_wc_status_conflicted)
1618 // we have a property conflict
1619 CTSVNPath prej(directory);
1620 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1622 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1623 // there's a problem: the prej file contains a _description_ of the conflict, and
1624 // that description string might be translated. That means we have no way of parsing
1625 // the file to find out the conflicting values.
1626 // The only thing we can do: show a dialog with the conflict description, then
1627 // let the user either accept the existing property or open the property edit dialog
1628 // to manually change the properties and values. And a button to mark the conflict as
1629 // resolved.
1630 CEditPropConflictDlg dlg;
1631 dlg.SetPrejFile(prej);
1632 dlg.SetConflictedItem(merge);
1633 bRet = (dlg.DoModal() != IDCANCEL);
1637 if (stat.status->tree_conflict)
1639 // we have a tree conflict
1640 SVNInfo info;
1641 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1642 if (pInfoData)
1644 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1646 CTSVNPath theirs(directory);
1647 CTSVNPath mine(directory);
1648 CTSVNPath base(directory);
1649 bool bConflictData = false;
1651 if (pInfoData->treeconflict_theirfile)
1653 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1654 bConflictData = true;
1656 if (pInfoData->treeconflict_basefile)
1658 base.AppendPathString(pInfoData->treeconflict_basefile);
1659 bConflictData = true;
1661 if (pInfoData->treeconflict_myfile)
1663 mine.AppendPathString(pInfoData->treeconflict_myfile);
1664 bConflictData = true;
1666 else
1668 mine = merge;
1670 if (bConflictData)
1671 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1672 base, theirs, mine, merge);
1674 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1676 CString sConflictAction;
1677 CString sConflictReason;
1678 CString sResolveTheirs;
1679 CString sResolveMine;
1680 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1681 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1683 if (pInfoData->treeconflict_nodekind == svn_node_file)
1685 switch (pInfoData->treeconflict_operation)
1687 case svn_wc_operation_update:
1688 switch (pInfoData->treeconflict_action)
1690 case svn_wc_conflict_action_edit:
1691 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1692 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1693 break;
1694 case svn_wc_conflict_action_add:
1695 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1696 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1697 break;
1698 case svn_wc_conflict_action_delete:
1699 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1700 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1701 break;
1703 break;
1704 case svn_wc_operation_switch:
1705 switch (pInfoData->treeconflict_action)
1707 case svn_wc_conflict_action_edit:
1708 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1709 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1710 break;
1711 case svn_wc_conflict_action_add:
1712 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1713 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1714 break;
1715 case svn_wc_conflict_action_delete:
1716 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1717 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1718 break;
1720 break;
1721 case svn_wc_operation_merge:
1722 switch (pInfoData->treeconflict_action)
1724 case svn_wc_conflict_action_edit:
1725 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1726 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1727 break;
1728 case svn_wc_conflict_action_add:
1729 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1730 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1731 break;
1732 case svn_wc_conflict_action_delete:
1733 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1734 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1735 break;
1737 break;
1740 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1742 switch (pInfoData->treeconflict_operation)
1744 case svn_wc_operation_update:
1745 switch (pInfoData->treeconflict_action)
1747 case svn_wc_conflict_action_edit:
1748 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1749 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1750 break;
1751 case svn_wc_conflict_action_add:
1752 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1753 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1754 break;
1755 case svn_wc_conflict_action_delete:
1756 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1757 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1758 break;
1760 break;
1761 case svn_wc_operation_switch:
1762 switch (pInfoData->treeconflict_action)
1764 case svn_wc_conflict_action_edit:
1765 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1766 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1767 break;
1768 case svn_wc_conflict_action_add:
1769 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1770 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1771 break;
1772 case svn_wc_conflict_action_delete:
1773 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1774 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1775 break;
1777 break;
1778 case svn_wc_operation_merge:
1779 switch (pInfoData->treeconflict_action)
1781 case svn_wc_conflict_action_edit:
1782 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1783 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1784 break;
1785 case svn_wc_conflict_action_add:
1786 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1787 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1788 break;
1789 case svn_wc_conflict_action_delete:
1790 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1791 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1792 break;
1794 break;
1798 UINT uReasonID = 0;
1799 switch (pInfoData->treeconflict_reason)
1801 case svn_wc_conflict_reason_edited:
1802 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1803 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1804 break;
1805 case svn_wc_conflict_reason_obstructed:
1806 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1807 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1808 break;
1809 case svn_wc_conflict_reason_deleted:
1810 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1811 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1812 break;
1813 case svn_wc_conflict_reason_added:
1814 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1815 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1816 break;
1817 case svn_wc_conflict_reason_missing:
1818 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1819 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1820 break;
1821 case svn_wc_conflict_reason_unversioned:
1822 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1823 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1824 break;
1826 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1828 CTreeConflictEditorDlg dlg;
1829 dlg.SetConflictInfoText(sConflictReason);
1830 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1831 dlg.SetPath(treeConflictPath);
1832 INT_PTR dlgRet = dlg.DoModal();
1833 bRet = (dlgRet != IDCANCEL);
1837 #endif
1838 return bRet;
1842 * FUNCTION : FormatDateAndTime
1843 * DESCRIPTION : Generates a displayable string from a CTime object in
1844 * system short or long format or as a relative value
1845 * cTime - the time
1846 * option - DATE_SHORTDATE or DATE_LONGDATE
1847 * bIncluedeTime - whether to show time as well as date
1848 * bRelative - if true then relative time is shown if reasonable
1849 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1850 * rather than locale
1851 * RETURN : CString containing date/time
1853 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1854 bool bRelative /*=false*/)
1856 CString datetime;
1857 if ( bRelative )
1859 datetime = ToRelativeTimeString( cTime );
1861 else
1863 // should we use the locale settings for formatting the date/time?
1864 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1866 // yes
1867 SYSTEMTIME sysTime;
1868 cTime.GetAsSystemTime( sysTime );
1870 TCHAR buf[100];
1872 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1873 _countof(buf) - 1);
1874 datetime = buf;
1875 if ( bIncludeTime )
1877 datetime += _T(" ");
1878 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1879 datetime += buf;
1882 else
1884 // no, so fixed format
1885 if ( bIncludeTime )
1887 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1889 else
1891 datetime = cTime.Format(_T("%Y-%m-%d"));
1895 return datetime;
1899 * Converts a given time to a relative display string (relative to current time)
1900 * Given time must be in local timezone
1902 CString CAppUtils::ToRelativeTimeString(CTime time)
1904 CString answer;
1905 // convert to COleDateTime
1906 SYSTEMTIME sysTime;
1907 time.GetAsSystemTime( sysTime );
1908 COleDateTime oleTime( sysTime );
1909 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1910 return answer;
1914 * Generates a display string showing the relative time between the two given times as COleDateTimes
1916 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1918 CString answer;
1919 COleDateTimeSpan ts = RelativeTo - time;
1920 //years
1921 if(fabs(ts.GetTotalDays()) >= 3*365)
1923 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1925 //Months
1926 if(fabs(ts.GetTotalDays()) >= 60)
1928 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1929 return answer;
1931 //Weeks
1932 if(fabs(ts.GetTotalDays()) >= 14)
1934 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1935 return answer;
1937 //Days
1938 if(fabs(ts.GetTotalDays()) >= 2)
1940 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1941 return answer;
1943 //hours
1944 if(fabs(ts.GetTotalHours()) >= 2)
1946 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1947 return answer;
1949 //minutes
1950 if(fabs(ts.GetTotalMinutes()) >= 2)
1952 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1953 return answer;
1955 //seconds
1956 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1957 return answer;
1961 * Passed a value and two resource string ids
1962 * if count is 1 then FormatString is called with format_1 and the value
1963 * otherwise format_2 is used
1964 * the formatted string is returned
1966 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1968 CString answer;
1969 if ( count == 1 )
1971 answer.FormatMessage( format_1, count );
1973 else
1975 answer.FormatMessage( format_n, count );
1977 return answer;
1980 bool CAppUtils::IsSSHPutty()
1982 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1983 sshclient=sshclient.MakeLower();
1984 if(sshclient.Find(_T("plink.exe"),0)>=0)
1986 return true;
1988 return false;
1991 CString CAppUtils::GetClipboardLink()
1993 if (!OpenClipboard(NULL))
1994 return CString();
1996 CString sClipboardText;
1997 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1998 if (hglb)
2000 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2001 sClipboardText = CString(lpstr);
2002 GlobalUnlock(hglb);
2004 hglb = GetClipboardData(CF_UNICODETEXT);
2005 if (hglb)
2007 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2008 sClipboardText = lpstr;
2009 GlobalUnlock(hglb);
2011 CloseClipboard();
2013 if(!sClipboardText.IsEmpty())
2015 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2016 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2018 if(sClipboardText.Find( _T("http://")) == 0)
2019 return sClipboardText;
2021 if(sClipboardText.Find( _T("https://")) == 0)
2022 return sClipboardText;
2024 if(sClipboardText.Find( _T("git://")) == 0)
2025 return sClipboardText;
2027 if(sClipboardText.Find( _T("ssh://")) == 0)
2028 return sClipboardText;
2030 if(sClipboardText.GetLength()>=2)
2031 if( sClipboardText[1] == _T(':') )
2032 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2033 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2034 return sClipboardText;
2037 return CString(_T(""));
2040 CString CAppUtils::ChooseRepository(CString *path)
2042 CBrowseFolder browseFolder;
2043 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2045 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2046 CString strCloneDirectory;
2047 if(path)
2048 strCloneDirectory=*path;
2049 else
2051 strCloneDirectory = regLastResopitory;
2054 CString title;
2055 title.LoadString(IDS_CHOOSE_REPOSITORY);
2057 browseFolder.SetInfo(title);
2059 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2061 regLastResopitory = strCloneDirectory;
2062 return strCloneDirectory;
2064 else
2066 return CString();
2070 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2072 CSendMailDlg dlg;
2074 dlg.m_PathList = list;
2076 if(dlg.DoModal()==IDOK)
2078 if(dlg.m_PathList.GetCount() == 0)
2079 return FALSE;
2081 CGitProgressDlg progDlg;
2083 theApp.m_pMainWnd = &progDlg;
2084 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2086 progDlg.SetAutoClose(autoclose);
2088 progDlg.SetPathList(dlg.m_PathList);
2089 //ProjectProperties props;
2090 //props.ReadPropsPathList(dlg.m_pathList);
2091 //progDlg.SetProjectProperties(props);
2092 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2094 DWORD flags =0;
2095 if(dlg.m_bAttachment)
2096 flags |= SENDMAIL_ATTACHMENT;
2097 if(dlg.m_bCombine)
2098 flags |= SENDMAIL_COMBINED;
2099 if(dlg.m_bUseMAPI)
2100 flags |= SENDMAIL_MAPI;
2102 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2104 progDlg.DoModal();
2106 return true;
2108 return false;
2111 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2113 CTGitPathList list;
2114 CString log=formatpatchoutput;
2115 int start=log.Find(cmd);
2116 if(start >=0)
2117 CString one=log.Tokenize(_T("\n"),start);
2118 else
2119 start = 0;
2121 while(start>=0)
2123 CString one=log.Tokenize(_T("\n"),start);
2124 one=one.Trim();
2125 if(one.IsEmpty() || one == _T("Success"))
2126 continue;
2127 one.Replace(_T('/'),_T('\\'));
2128 CTGitPath path;
2129 path.SetFromWin(one);
2130 list.AddPath(path);
2132 if (list.GetCount() > 0)
2134 return SendPatchMail(list, autoclose);
2136 else
2138 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2139 return true;
2144 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2146 CString cmd,output;
2147 int start=0;
2149 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2150 if(output.IsEmpty())
2152 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2153 if(output.IsEmpty())
2154 return CP_UTF8;
2156 int start=0;
2157 output=output.Tokenize(_T("\n"),start);
2158 return CUnicodeUtils::GetCPCode(output);
2161 else
2163 output=output.Tokenize(_T("\n"),start);
2164 return CUnicodeUtils::GetCPCode(output);
2167 int CAppUtils::GetCommitTemplate(CString &temp)
2169 CString cmd,output;
2171 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2172 if( output.IsEmpty() )
2173 return -1;
2175 if( output.GetLength()<1)
2176 return -1;
2178 if( output[0] == _T('/'))
2180 if(output.GetLength()>=3)
2181 if(output[2] == _T('/'))
2183 output.GetBuffer()[0] = output[1];
2184 output.GetBuffer()[1] = _T(':');
2188 int start=0;
2189 output=output.Tokenize(_T("\n"),start);
2191 output.Replace(_T('/'),_T('\\'));
2195 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2196 CString str;
2197 while(file.ReadString(str))
2199 temp+=str+_T("\n");
2202 }catch(...)
2204 return -1;
2206 return 0;
2208 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2210 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2211 CString cmd,output;
2212 int cp=CP_UTF8;
2214 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2215 if(output.IsEmpty())
2216 cp=CP_UTF8;
2218 int start=0;
2219 output=output.Tokenize(_T("\n"),start);
2220 cp=CUnicodeUtils::GetCPCode(output);
2222 int len=message.GetLength();
2224 char * buf;
2225 buf = new char[len*4 + 4];
2226 SecureZeroMemory(buf, (len*4 + 4));
2228 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2230 file.Write(buf,lengthIncTerminator-1);
2231 file.Close();
2232 delete buf;
2233 return 0;
2236 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2238 CPullFetchDlg dlg;
2239 dlg.m_PreSelectRemote = remoteName;
2240 dlg.m_bAllowRebase = allowRebase;
2241 dlg.m_IsPull=FALSE;
2243 if(dlg.DoModal()==IDOK)
2245 if(dlg.m_bAutoLoad)
2247 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2250 CString url;
2251 url=dlg.m_RemoteURL;
2252 CString cmd;
2253 CString arg;
2255 int ver = CAppUtils::GetMsysgitVersion();
2257 if(ver >= 0x01070203) //above 1.7.0.2
2258 arg = _T("--progress ");
2260 if (dlg.m_bPrune) {
2261 arg += _T("--prune ");
2264 if (dlg.m_bFetchTags) {
2265 arg += _T("--tags ");
2268 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2269 CProgressDlg progress;
2271 progress.m_bAutoCloseOnSuccess = autoClose;
2273 progress.m_PostCmdList.Add(_T("Show Log"));
2275 if(!dlg.m_bRebase)
2277 progress.m_PostCmdList.Add(_T("&Rebase"));
2280 progress.m_GitCmd=cmd;
2281 int userResponse=progress.DoModal();
2283 if (userResponse == IDC_PROGRESS_BUTTON1)
2285 CString cmd;
2286 cmd = CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe");
2287 cmd += _T(" /command:log");
2288 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2289 CAppUtils::LaunchApplication(cmd, IDS_ERR_PROC, false);
2290 return TRUE;
2292 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2294 while(1)
2296 CRebaseDlg dlg;
2297 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2298 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2299 int response = dlg.DoModal();
2300 if(response == IDOK)
2302 return TRUE;
2304 if(response == IDC_REBASE_POST_BUTTON )
2306 CString cmd, out, err;
2307 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2308 g_Git.m_CurrentDir,
2309 g_Git.FixBranchName(dlg.m_Upstream),
2310 g_Git.FixBranchName(dlg.m_Branch));
2311 if (g_Git.Run(cmd, &out, &err, CP_ACP))
2313 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2314 return FALSE;
2317 CAppUtils::SendPatchMail(cmd,out);
2318 return TRUE;
2321 if(response == IDC_REBASE_POST_BUTTON +1 )
2322 continue;
2324 if(response == IDCANCEL)
2325 return FALSE;
2327 return TRUE;
2330 return FALSE;
2333 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2335 CPushDlg dlg;
2336 dlg.m_BranchSourceName = selectLocalBranch;
2337 CString error;
2338 DWORD exitcode = 0xFFFFFFFF;
2339 CTGitPathList list;
2340 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2341 if (CHooks::Instance().PrePush(list,exitcode, error))
2343 if (exitcode)
2345 CString temp;
2346 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2347 //ReportError(temp);
2348 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2349 return false;
2353 if(dlg.DoModal()==IDOK)
2355 CString cmd;
2356 CString arg;
2358 if(dlg.m_bAutoLoad)
2360 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2363 if(dlg.m_bPack)
2364 arg += _T("--thin ");
2365 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2366 arg += _T("--tags ");
2367 if(dlg.m_bForce)
2368 arg += _T("--force ");
2370 int ver = CAppUtils::GetMsysgitVersion();
2372 if(ver >= 0x01070203) //above 1.7.0.2
2373 arg += _T("--progress ");
2375 if (dlg.m_bPushAllBranches)
2377 cmd.Format(_T("git.exe push --all %s \"%s\""),
2378 arg,
2379 dlg.m_URL);
2381 else
2383 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2384 arg,
2385 dlg.m_URL,
2386 dlg.m_BranchSourceName);
2387 if (!dlg.m_BranchRemoteName.IsEmpty())
2389 cmd += _T(":") + dlg.m_BranchRemoteName;
2393 CProgressDlg progress;
2394 progress.m_bAutoCloseOnSuccess=autoClose;
2395 progress.m_GitCmd=cmd;
2396 progress.m_PostCmdList.Add(_T("&Request pull"));
2397 progress.m_PostCmdList.Add(_T("Re&Push"));
2398 int ret = progress.DoModal();
2400 if(!progress.m_GitStatus)
2402 if (CHooks::Instance().PostPush(list,exitcode, error))
2404 if (exitcode)
2406 CString temp;
2407 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2408 //ReportError(temp);
2409 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2410 return false;
2413 if(ret == IDC_PROGRESS_BUTTON1)
2415 RequestPull(dlg.m_BranchRemoteName);
2417 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2419 Push();
2421 return TRUE;
2425 return FALSE;
2428 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2430 CRequestPullDlg dlg;
2431 dlg.m_RepositoryURL = repositoryUrl;
2432 dlg.m_EndRevision = endrevision;
2433 if (dlg.DoModal()==IDOK)
2435 CString cmd;
2436 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2438 CProgressDlg progress;
2439 progress.m_GitCmd=cmd;
2440 progress.DoModal();
2442 return true;
2445 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2447 CString strDir(szPath);
2448 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2450 strDir.AppendChar(_T('\\'));
2452 std::vector<CString> vPath;
2453 CString strTemp;
2454 bool bSuccess = false;
2456 for (int i=0;i<strDir.GetLength();++i)
2458 if (strDir.GetAt(i) != _T('\\'))
2460 strTemp.AppendChar(strDir.GetAt(i));
2462 else
2464 vPath.push_back(strTemp);
2465 strTemp.AppendChar(_T('\\'));
2469 std::vector<CString>::const_iterator vIter;
2470 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2472 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2475 return bSuccess;
2478 void CAppUtils::RemoveTrailSlash(CString &path)
2480 if(path.IsEmpty())
2481 return ;
2483 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2485 path=path.Left(path.GetLength()-1);
2486 if(path.IsEmpty())
2487 return;
2491 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2492 CTGitPathList &pathList,
2493 CTGitPathList &selectedList,
2494 bool bSelectFilesForCommit,
2495 bool autoClose)
2497 bool bFailed = true;
2499 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2501 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"),
2502 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2504 CTGitPath path(g_Git.m_CurrentDir);
2505 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2506 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2507 dlg.SetTreeWidth(220);
2508 dlg.m_DefaultPage = _T("gitconfig");
2510 dlg.DoModal();
2511 dlg.HandleRestart();
2514 else
2515 return false;
2518 while (bFailed)
2520 bFailed = false;
2521 CCommitDlg dlg;
2522 dlg.m_sBugID = bugid;
2524 dlg.m_bWholeProject = bWholeProject;
2526 dlg.m_sLogMessage = sLogMsg;
2527 dlg.m_pathList = pathList;
2528 dlg.m_checkedPathList = selectedList;
2529 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2530 dlg.m_bAutoClose = autoClose;
2531 if (dlg.DoModal() == IDOK)
2533 if (dlg.m_pathList.GetCount()==0)
2534 return false;
2535 // if the user hasn't changed the list of selected items
2536 // we don't use that list. Because if we would use the list
2537 // of pre-checked items, the dialog would show different
2538 // checked items on the next startup: it would only try
2539 // to check the parent folder (which might not even show)
2540 // instead, we simply use an empty list and let the
2541 // default checking do its job.
2542 if (!dlg.m_pathList.IsEqual(pathList))
2543 selectedList = dlg.m_pathList;
2544 pathList = dlg.m_updatedPathList;
2545 sLogMsg = dlg.m_sLogMessage;
2546 bSelectFilesForCommit = true;
2548 if( dlg.m_bPushAfterCommit )
2550 switch(dlg.m_PostCmd)
2552 case GIT_POST_CMD_DCOMMIT:
2553 CAppUtils::SVNDCommit();
2554 break;
2555 default:
2556 CAppUtils::Push();
2559 // CGitProgressDlg progDlg;
2560 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2561 // if (parser.HasVal(_T("closeonend")))
2562 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2563 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2564 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2565 // progDlg.SetPathList(dlg.m_pathList);
2566 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2567 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2568 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2569 // progDlg.SetItemCount(dlg.m_itemsCount);
2570 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2571 // progDlg.DoModal();
2572 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2573 // err = (DWORD)progDlg.DidErrorsOccur();
2574 // bFailed = progDlg.DidErrorsOccur();
2575 // bRet = progDlg.DidErrorsOccur();
2576 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2577 // if (DWORD(bFailRepeat)==0)
2578 // bFailed = false; // do not repeat if the user chose not to in the settings.
2581 return true;
2585 BOOL CAppUtils::SVNDCommit()
2587 CSVNDCommitDlg dcommitdlg;
2588 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2589 if (gitSetting == _T("")) {
2590 if (dcommitdlg.DoModal() != IDOK)
2592 return false;
2594 else
2596 if (dcommitdlg.m_remember)
2598 if (dcommitdlg.m_rmdir)
2600 gitSetting = _T("true");
2602 else
2604 gitSetting = _T("false");
2606 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2608 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2614 BOOL IsStash = false;
2615 if(!g_Git.CheckCleanWorkTree())
2617 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2619 CString cmd,out;
2620 cmd=_T("git.exe stash");
2621 if(g_Git.Run(cmd,&out,CP_ACP))
2623 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2624 return false;
2626 IsStash =true;
2629 else
2631 return false;
2635 CProgressDlg progress;
2636 if (dcommitdlg.m_rmdir)
2638 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2640 else
2642 progress.m_GitCmd=_T("git.exe svn dcommit");
2644 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2646 if( IsStash)
2648 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2650 CString cmd,out;
2651 cmd=_T("git.exe stash pop");
2652 if(g_Git.Run(cmd,&out,CP_ACP))
2654 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2655 return false;
2659 else
2661 return false;
2664 return TRUE;
2666 return FALSE;
2669 BOOL CAppUtils::Merge(CString *commit)
2671 CMergeDlg dlg;
2672 if(commit)
2673 dlg.m_initialRefName = *commit;
2675 if(dlg.DoModal()==IDOK)
2677 CString cmd;
2678 CString noff;
2679 CString squash;
2680 CString nocommit;
2681 CString msg;
2683 if(dlg.m_bNoFF)
2684 noff=_T("--no-ff");
2686 if(dlg.m_bSquash)
2687 squash=_T("--squash");
2689 if(dlg.m_bNoCommit)
2690 nocommit=_T("--no-commit");
2692 if(!dlg.m_strLogMesage.IsEmpty())
2694 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2696 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2697 msg,
2698 noff,
2699 squash,
2700 nocommit,
2701 g_Git.FixBranchName(dlg.m_VersionName));
2703 CProgressDlg Prodlg;
2704 Prodlg.m_GitCmd = cmd;
2706 if (dlg.m_bNoCommit)
2707 Prodlg.m_PostCmdList.Add(_T("Commit"));
2709 int ret = Prodlg.DoModal();
2711 if (ret == IDC_PROGRESS_BUTTON1)
2712 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2714 return !Prodlg.m_GitStatus;
2716 return false;
2719 void CAppUtils::EditNote(GitRev *rev)
2721 CInputDlg dlg;
2722 dlg.m_sHintText=_T("Edit Notes");
2723 dlg.m_sInputText = rev->m_Notes;
2724 dlg.m_sTitle=_T("Edit Notes");
2725 //dlg.m_pProjectProperties = &m_ProjectProperties;
2726 dlg.m_bUseLogWidth = true;
2727 if(dlg.DoModal() == IDOK)
2729 CString cmd,output;
2730 cmd=_T("notes add -f -F \"");
2732 CString tempfile=::GetTempFile();
2733 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2734 cmd += tempfile;
2735 cmd += _T("\" ");
2736 cmd += rev->m_CommitHash.ToString();
2740 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2742 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2745 else
2747 rev->m_Notes = dlg.m_sInputText;
2749 }catch(...)
2751 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2753 CFile::Remove(tempfile);
2758 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2760 CString cmd;
2761 CString progressarg;
2762 CString version;
2764 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2765 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2767 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2769 __int64 time=0;
2770 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2772 if((DWORD)time == regTime)
2774 return regVersion;
2778 if(versionstr)
2779 version = *versionstr;
2780 else
2782 CString err;
2783 cmd = _T("git.exe --version");
2784 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2786 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2787 return false;
2791 int start=0;
2792 int ver;
2794 CString str=version.Tokenize(_T("."),start);
2795 int space = str.ReverseFind(_T(' '));
2796 str=str.Mid(space+1,start);
2797 ver = _ttol(str);
2798 ver <<=24;
2800 version = version.Mid(start);
2801 start = 0;
2802 str = version.Tokenize(_T("."),start);
2804 ver |= (_ttol(str)&0xFF)<<16;
2806 str = version.Tokenize(_T("."),start);
2807 ver |= (_ttol(str)&0xFF)<<8;
2809 str = version.Tokenize(_T("."),start);
2810 ver |= (_ttol(str)&0xFF);
2812 regTime = time&0xFFFFFFFF;
2813 regVersion = ver;
2815 return ver;
2818 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2820 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2822 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2824 if (hShell) {
2825 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2826 if (pfnSHGPSFW) {
2827 IPropertyStore *pps;
2828 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2829 if (SUCCEEDED(hr)) {
2830 PROPVARIANT var;
2831 var.vt = VT_BOOL;
2832 var.boolVal = VARIANT_TRUE;
2833 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2834 pps->Release();
2837 FreeLibrary(hShell);
2841 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2843 ASSERT(dialogname.GetLength() < 70);
2844 ASSERT(urlorpath.GetLength() < MAX_PATH);
2845 WCHAR pathbuf[MAX_PATH] = {0};
2847 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2849 wcscat_s(pathbuf, L" - ");
2850 wcscat_s(pathbuf, dialogname);
2851 wcscat_s(pathbuf, L" - ");
2852 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2853 SetWindowText(hWnd, pathbuf);