dropped unused TSVN settings
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobb949772989abdd9bf459aa69d810bfab98fde809
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, bool showChanges /* true */)
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 int ret = g_Git.Run(cmd, &out, CP_ACP);
113 if (ret && !(ret == 1 && out.Find(_T("CONFLICT"))))
115 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
117 else if (showChanges)
119 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
120 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
122 CChangedDlg dlg;
123 dlg.m_pathList.AddPath(CTGitPath());
124 dlg.DoModal();
126 return 0;
128 else
130 CMessageBox::Show(NULL, _T("<ct=0xff0000>Stash Apply Success</ct>") ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
131 return 0;
133 return -1;
136 int CAppUtils::StashPop(bool showChanges /* true */)
138 CString cmd,out;
139 cmd=_T("git.exe stash pop ");
141 int ret = g_Git.Run(cmd, &out, CP_ACP);
142 if (ret && !(ret == 1 && out.Find(_T("CONFLICT"))))
144 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
147 else if (showChanges)
149 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
150 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
152 CChangedDlg dlg;
153 dlg.m_pathList.AddPath(CTGitPath());
154 dlg.DoModal();
156 return 0;
158 else
160 CMessageBox::Show(NULL, _T("<ct=0xff0000>Stash POP Success</ct>") ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
161 return 0;
163 return -1;
166 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
168 #if 0
169 GitProperties props(file, GitRev::REV_WC, false);
170 for (int i = 0; i < props.GetCount(); ++i)
172 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
174 mimetype = props.GetItemValue(i).c_str();
175 return true;
178 #endif
179 return false;
182 BOOL CAppUtils::StartExtMerge(
183 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
184 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
187 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
188 CString ext = mergedfile.GetFileExtension();
189 CString com = regCom;
190 bool bInternal = false;
192 CString mimetype;
193 if (ext != "")
195 // is there an extension specific merge tool?
196 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
197 if (CString(mergetool) != "")
199 com = mergetool;
202 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
204 // is there a mime type specific merge tool?
205 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
206 if (CString(mergetool) != "")
208 com = mergetool;
212 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
214 // use TortoiseMerge
215 bInternal = true;
216 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
217 com = tortoiseMergePath;
218 if (com.IsEmpty())
220 com = CPathUtils::GetAppDirectory();
221 com += _T("TortoiseMerge.exe");
223 com = _T("\"") + com + _T("\"");
224 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
225 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
227 // check if the params are set. If not, just add the files to the command line
228 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
230 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
231 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
232 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
233 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
235 if (basefile.IsEmpty())
237 com.Replace(_T("/base:%base"), _T(""));
238 com.Replace(_T("%base"), _T(""));
240 else
241 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
242 if (theirfile.IsEmpty())
244 com.Replace(_T("/theirs:%theirs"), _T(""));
245 com.Replace(_T("%theirs"), _T(""));
247 else
248 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
249 if (yourfile.IsEmpty())
251 com.Replace(_T("/mine:%mine"), _T(""));
252 com.Replace(_T("%mine"), _T(""));
254 else
255 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
256 if (mergedfile.IsEmpty())
258 com.Replace(_T("/merged:%merged"), _T(""));
259 com.Replace(_T("%merged"), _T(""));
261 else
262 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
263 if (basename.IsEmpty())
265 if (basefile.IsEmpty())
267 com.Replace(_T("/basename:%bname"), _T(""));
268 com.Replace(_T("%bname"), _T(""));
270 else
272 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
275 else
276 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
277 if (theirname.IsEmpty())
279 if (theirfile.IsEmpty())
281 com.Replace(_T("/theirsname:%tname"), _T(""));
282 com.Replace(_T("%tname"), _T(""));
284 else
286 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
289 else
290 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
291 if (yourname.IsEmpty())
293 if (yourfile.IsEmpty())
295 com.Replace(_T("/minename:%yname"), _T(""));
296 com.Replace(_T("%yname"), _T(""));
298 else
300 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
303 else
304 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
305 if (mergedname.IsEmpty())
307 if (mergedfile.IsEmpty())
309 com.Replace(_T("/mergedname:%mname"), _T(""));
310 com.Replace(_T("%mname"), _T(""));
312 else
314 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
317 else
318 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
320 if ((bReadOnly)&&(bInternal))
321 com += _T(" /readonly");
323 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
325 return FALSE;
328 return TRUE;
331 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
333 CString viewer;
334 // use TortoiseMerge
335 viewer = CPathUtils::GetAppDirectory();
336 viewer += _T("TortoiseMerge.exe");
338 viewer = _T("\"") + viewer + _T("\"");
339 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
340 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
341 if (bReversed)
342 viewer += _T(" /reversedpatch");
343 if (!sOriginalDescription.IsEmpty())
344 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
345 if (!sPatchedDescription.IsEmpty())
346 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
347 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
349 return FALSE;
351 return TRUE;
354 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
356 // Is there a mime type specific diff tool?
357 CString mimetype;
358 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
360 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
361 if (!difftool.IsEmpty())
362 return difftool;
365 // Is there an extension specific diff tool?
366 CString ext = file2.GetFileExtension().MakeLower();
367 if (!ext.IsEmpty())
369 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
370 if (!difftool.IsEmpty())
371 return difftool;
372 // Maybe we should use TortoiseIDiff?
373 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
374 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
375 (ext == _T(".png")) || (ext == _T(".ico")) ||
376 (ext == _T(".dib")) || (ext == _T(".emf")))
378 return
379 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
380 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
384 // Finally, pick a generic external diff tool
385 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
386 return difftool;
389 bool CAppUtils::StartExtDiff(
390 const CString& file1, const CString& file2,
391 const CString& sName1, const CString& sName2,
392 const DiffFlags& flags)
394 CString viewer;
396 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
397 if (!flags.bBlame || !(DWORD)blamediff)
399 viewer = PickDiffTool(file1, file2);
400 // If registry entry for a diff program is commented out, use TortoiseMerge.
401 bool bCommentedOut = viewer.Left(1) == _T("#");
402 if (flags.bAlternativeTool)
404 // Invert external vs. internal diff tool selection.
405 if (bCommentedOut)
406 viewer.Delete(0); // uncomment
407 else
408 viewer = "";
410 else if (bCommentedOut)
411 viewer = "";
414 bool bInternal = viewer.IsEmpty();
415 if (bInternal)
417 viewer =
418 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
419 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
420 if (flags.bBlame)
421 viewer += _T(" /blame");
423 // check if the params are set. If not, just add the files to the command line
424 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
426 viewer += _T(" \"")+file1+_T("\"");
427 viewer += _T(" \"")+file2+_T("\"");
429 if (viewer.Find(_T("%base")) >= 0)
431 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
433 if (viewer.Find(_T("%mine")) >= 0)
435 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
438 if (sName1.IsEmpty())
439 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
440 else
441 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
443 if (sName2.IsEmpty())
444 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
445 else
446 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
448 if (flags.bReadOnly && bInternal)
449 viewer += _T(" /readonly");
451 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
454 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
456 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
457 CString viewer = diffpropsexe;
458 bool bInternal = false;
459 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
461 //no registry entry (or commented out) for a diff program
462 //use TortoiseMerge
463 bInternal = true;
464 viewer = CPathUtils::GetAppDirectory();
465 viewer += _T("TortoiseMerge.exe");
466 viewer = _T("\"") + viewer + _T("\"");
467 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
469 // check if the params are set. If not, just add the files to the command line
470 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
472 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
473 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
475 if (viewer.Find(_T("%base")) >= 0)
477 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
479 if (viewer.Find(_T("%mine")) >= 0)
481 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
484 if (sName1.IsEmpty())
485 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
486 else
487 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
489 if (sName2.IsEmpty())
490 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
491 else
492 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
494 if ((bReadOnly)&&(bInternal))
495 viewer += _T(" /readonly");
497 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
499 return FALSE;
501 return TRUE;
504 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
506 CString viewer;
507 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
508 viewer = v;
509 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
511 // use TortoiseUDiff
512 viewer = CPathUtils::GetAppDirectory();
513 viewer += _T("TortoiseUDiff.exe");
514 // enquote the path to TortoiseUDiff
515 viewer = _T("\"") + viewer + _T("\"");
516 // add the params
517 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
520 if (viewer.Find(_T("%1"))>=0)
522 if (viewer.Find(_T("\"%1\"")) >= 0)
523 viewer.Replace(_T("%1"), patchfile);
524 else
525 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
527 else
528 viewer += _T(" \"") + patchfile + _T("\"");
529 if (viewer.Find(_T("%title")) >= 0)
531 viewer.Replace(_T("%title"), title);
534 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
536 return FALSE;
538 return TRUE;
541 BOOL CAppUtils::StartTextViewer(CString file)
543 CString viewer;
544 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
545 viewer = txt;
546 viewer = viewer + _T("\\Shell\\Open\\Command\\");
547 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
548 viewer = txtexe;
550 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
551 TCHAR * buf = new TCHAR[len+1];
552 ExpandEnvironmentStrings(viewer, buf, len);
553 viewer = buf;
554 delete [] buf;
555 len = ExpandEnvironmentStrings(file, NULL, 0);
556 buf = new TCHAR[len+1];
557 ExpandEnvironmentStrings(file, buf, len);
558 file = buf;
559 delete [] buf;
560 file = _T("\"")+file+_T("\"");
561 if (viewer.IsEmpty())
563 OPENFILENAME ofn = {0}; // common dialog box structure
564 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
565 // Initialize OPENFILENAME
566 ofn.lStructSize = sizeof(OPENFILENAME);
567 ofn.hwndOwner = NULL;
568 ofn.lpstrFile = szFile;
569 ofn.nMaxFile = _countof(szFile);
570 CString sFilter;
571 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
572 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
573 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
574 // Replace '|' delimiters with '\0's
575 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
576 while (ptr != pszFilters)
578 if (*ptr == '|')
579 *ptr = '\0';
580 ptr--;
582 ofn.lpstrFilter = pszFilters;
583 ofn.nFilterIndex = 1;
584 ofn.lpstrFileTitle = NULL;
585 ofn.nMaxFileTitle = 0;
586 ofn.lpstrInitialDir = NULL;
587 CString temp;
588 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
589 CStringUtils::RemoveAccelerators(temp);
590 ofn.lpstrTitle = temp;
591 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
593 // Display the Open dialog box.
595 if (GetOpenFileName(&ofn)==TRUE)
597 delete [] pszFilters;
598 viewer = CString(ofn.lpstrFile);
600 else
602 delete [] pszFilters;
603 return FALSE;
606 if (viewer.Find(_T("\"%1\"")) >= 0)
608 viewer.Replace(_T("\"%1\""), file);
610 else if (viewer.Find(_T("%1")) >= 0)
612 viewer.Replace(_T("%1"), file);
614 else
616 viewer += _T(" ");
617 viewer += file;
620 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
622 return FALSE;
624 return TRUE;
627 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
629 DWORD length = 0;
630 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
631 if (hFile == INVALID_HANDLE_VALUE)
632 return TRUE;
633 length = ::GetFileSize(hFile, NULL);
634 ::CloseHandle(hFile);
635 if (length < 4)
636 return TRUE;
637 return FALSE;
641 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
643 LOGFONT logFont;
644 HDC hScreenDC = ::GetDC(NULL);
645 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
646 ::ReleaseDC(NULL, hScreenDC);
647 logFont.lfWidth = 0;
648 logFont.lfEscapement = 0;
649 logFont.lfOrientation = 0;
650 logFont.lfWeight = FW_NORMAL;
651 logFont.lfItalic = 0;
652 logFont.lfUnderline = 0;
653 logFont.lfStrikeOut = 0;
654 logFont.lfCharSet = DEFAULT_CHARSET;
655 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
656 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
657 logFont.lfQuality = DRAFT_QUALITY;
658 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
659 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
660 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
663 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
665 STARTUPINFO startup;
666 PROCESS_INFORMATION process;
667 memset(&startup, 0, sizeof(startup));
668 startup.cb = sizeof(startup);
669 memset(&process, 0, sizeof(process));
671 CString cleanCommandLine(sCommandLine);
673 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
675 if(idErrMessageFormat != 0)
677 LPVOID lpMsgBuf;
678 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
679 FORMAT_MESSAGE_FROM_SYSTEM |
680 FORMAT_MESSAGE_IGNORE_INSERTS,
681 NULL,
682 GetLastError(),
683 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
684 (LPTSTR) &lpMsgBuf,
686 NULL
688 CString temp;
689 temp.Format(idErrMessageFormat, lpMsgBuf);
690 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
691 LocalFree( lpMsgBuf );
693 return false;
696 if (bWaitForStartup)
698 WaitForInputIdle(process.hProcess, 10000);
701 CloseHandle(process.hThread);
702 CloseHandle(process.hProcess);
703 return true;
705 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
707 CString key,remote;
708 CString cmd,out;
709 if( pRemote == NULL)
711 remote=_T("origin");
713 else
715 remote=*pRemote;
717 if(keyfile == NULL)
719 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
720 key = g_Git.GetConfigValue(cmd);
721 int start=0;
722 key = key.Tokenize(_T("\n"),start);
724 else
725 key=*keyfile;
727 if(key.IsEmpty())
728 return false;
730 CString proc=CPathUtils::GetAppDirectory();
731 proc += _T("pageant.exe \"");
732 proc += key;
733 proc += _T("\"");
735 CString tempfile = GetTempFile();
736 ::DeleteFile(tempfile);
738 proc += _T(" -c \"");
739 proc += CPathUtils::GetAppDirectory();
740 proc += _T("touch.exe\"");
741 proc += _T(" \"");
742 proc += tempfile;
743 proc += _T("\"");
745 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
746 if(!b)
747 return b;
749 int i=0;
750 while(!::PathFileExists(tempfile))
752 Sleep(100);
753 i++;
754 if(i>10*60*5)
755 break; //timeout 5 minutes
758 if( i== 10*60*5)
760 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
762 ::DeleteFile(tempfile);
763 return true;
765 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
767 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
768 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
769 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
772 CString sCmd;
773 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
775 LaunchApplication(sCmd, NULL, false);
776 return true;
778 bool CAppUtils::LaunchRemoteSetting()
780 CTGitPath path(g_Git.m_CurrentDir);
781 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
782 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
783 //dlg.SetTreeWidth(220);
784 dlg.m_DefaultPage = _T("gitremote");
786 dlg.DoModal();
787 dlg.HandleRestart();
788 return true;
791 * Launch the external blame viewer
793 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
795 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
796 viewer += _T("TortoiseGitBlame.exe");
797 viewer += _T("\" \"") + sBlameFile + _T("\"");
798 //viewer += _T(" \"") + sLogFile + _T("\"");
799 //viewer += _T(" \"") + sOriginalFile + _T("\"");
800 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
801 viewer += CString(_T(" /rev:"))+Rev;
802 viewer += _T(" ")+sParams;
804 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
807 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
809 CString sText;
810 if (pWnd == NULL)
811 return false;
812 bool bStyled = false;
813 pWnd->GetWindowText(sText);
814 // the rich edit control doesn't count the CR char!
815 // to be exact: CRLF is treated as one char.
816 sText.Remove('\r');
818 // style each line separately
819 int offset = 0;
820 int nNewlinePos;
823 nNewlinePos = sText.Find('\n', offset);
824 CString sLine = sText.Mid(offset);
825 if (nNewlinePos>=0)
826 sLine = sLine.Left(nNewlinePos-offset);
827 int start = 0;
828 int 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_BOLD;
837 format.dwEffects = CFE_BOLD;
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_ITALIC;
852 format.dwEffects = CFE_ITALIC;
853 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
854 bStyled = true;
855 start = end;
857 start = 0;
858 end = 0;
859 while (FindStyleChars(sLine, '_', start, end))
861 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
862 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
863 CHARFORMAT2 format;
864 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
865 format.cbSize = sizeof(CHARFORMAT2);
866 format.dwMask = CFM_UNDERLINE;
867 format.dwEffects = CFE_UNDERLINE;
868 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
869 bStyled = true;
870 start = end;
872 offset = nNewlinePos+1;
873 } while(nNewlinePos>=0);
874 return bStyled;
877 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
879 int i=start;
880 bool bFoundMarker = false;
881 // find a starting marker
882 while (sText[i] != 0)
884 if (sText[i] == stylechar)
886 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
887 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
889 start = i+1;
890 i++;
891 bFoundMarker = true;
892 break;
895 i++;
897 if (!bFoundMarker)
898 return false;
899 // find ending marker
900 bFoundMarker = false;
901 while (sText[i] != 0)
903 if (sText[i] == stylechar)
905 if ((IsCharAlphaNumeric(sText[i-1])) &&
906 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
908 end = i;
909 i++;
910 bFoundMarker = true;
911 break;
914 i++;
916 return bFoundMarker;
919 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
921 OPENFILENAME ofn = {0}; // common dialog box structure
922 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
923 ofn.lStructSize = sizeof(OPENFILENAME);
924 ofn.hwndOwner = hwndOwner;
925 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
926 ofn.lpstrFile = szFile;
927 ofn.nMaxFile = _countof(szFile);
928 CString sFilter;
929 TCHAR * pszFilters = NULL;
930 if (filter)
932 sFilter.LoadString(filter);
933 pszFilters = new TCHAR[sFilter.GetLength()+4];
934 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
935 // Replace '|' delimiters with '\0's
936 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
937 while (ptr != pszFilters)
939 if (*ptr == '|')
940 *ptr = '\0';
941 ptr--;
943 ofn.lpstrFilter = pszFilters;
945 ofn.nFilterIndex = 1;
946 ofn.lpstrFileTitle = NULL;
947 ofn.nMaxFileTitle = 0;
948 ofn.lpstrInitialDir = NULL;
949 CString temp;
950 if (title)
952 temp.LoadString(title);
953 CStringUtils::RemoveAccelerators(temp);
955 ofn.lpstrTitle = temp;
956 if (bOpen)
957 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
958 else
959 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
962 // Display the Open dialog box.
963 bool bRet = false;
964 if (bOpen)
966 bRet = !!GetOpenFileName(&ofn);
968 else
970 bRet = !!GetSaveFileName(&ofn);
972 if (bRet)
974 if (pszFilters)
975 delete [] pszFilters;
976 path = CString(ofn.lpstrFile);
977 if (filterindex)
978 *filterindex = ofn.nFilterIndex;
979 return true;
981 if (pszFilters)
982 delete [] pszFilters;
983 return false;
986 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
988 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
989 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
990 // create a bitmap from the icon
991 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
992 if (!hIcon)
993 return false;
995 RECT rect = {0};
996 rect.right = width;
997 rect.bottom = height;
998 HBITMAP bmp = NULL;
1000 HWND desktop = ::GetDesktopWindow();
1001 if (desktop)
1003 HDC screen_dev = ::GetDC(desktop);
1004 if (screen_dev)
1006 // Create a compatible DC
1007 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
1008 if (dst_hdc)
1010 // Create a new bitmap of icon size
1011 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
1012 if (bmp)
1014 // Select it into the compatible DC
1015 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
1016 // Fill the background of the compatible DC with the given color
1017 ::SetBkColor(dst_hdc, bkColor);
1018 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
1020 // Draw the icon into the compatible DC
1021 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
1022 ::SelectObject(dst_hdc, old_dst_bmp);
1024 ::DeleteDC(dst_hdc);
1027 ::ReleaseDC(desktop, screen_dev);
1030 // Restore settings
1031 DestroyIcon(hIcon);
1033 if (bmp == NULL)
1034 return false;
1036 LVBKIMAGE lv;
1037 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1038 lv.hbm = bmp;
1039 lv.xOffsetPercent = 100;
1040 lv.yOffsetPercent = 100;
1041 ListView_SetBkImage(hListCtrl, &lv);
1042 return true;
1045 CString CAppUtils::GetProjectNameFromURL(CString url)
1047 CString name;
1048 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1049 (name.CompareNoCase(_T("tags"))==0) ||
1050 (name.CompareNoCase(_T("trunk"))==0))
1052 name = url.Mid(url.ReverseFind('/')+1);
1053 url = url.Left(url.ReverseFind('/'));
1055 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1057 // a name of svn or svnroot indicates that it's not really the project name. In that
1058 // case, we try the first part of the URL
1059 // of course, this won't work in all cases (but it works for Google project hosting)
1060 url.Replace(_T("http://"), _T(""));
1061 url.Replace(_T("https://"), _T(""));
1062 url.Replace(_T("svn://"), _T(""));
1063 url.Replace(_T("svn+ssh://"), _T(""));
1064 url.TrimLeft(_T("/"));
1065 name = url.Left(url.Find('.'));
1067 return name;
1070 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1071 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1072 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1073 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1076 CString tempfile=GetTempFile();
1077 CString cmd;
1078 if(rev1 == GitRev::GetWorkingCopy())
1080 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1082 else
1084 CString merge;
1085 if(bMerge)
1086 merge = _T("-c");
1088 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1091 if( !url1.IsEmpty() )
1093 cmd += _T(" \"");
1094 cmd += url1.GetGitPathString();
1095 cmd += _T("\" ");
1097 g_Git.RunLogFile(cmd,tempfile);
1098 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1101 #if 0
1102 CString sCmd;
1103 sCmd.Format(_T("%s /command:showcompare /unified"),
1104 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1105 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1106 if (rev1.IsValid())
1107 sCmd += _T(" /revision1:") + rev1.ToString();
1108 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1109 if (rev2.IsValid())
1110 sCmd += _T(" /revision2:") + rev2.ToString();
1111 if (peg.IsValid())
1112 sCmd += _T(" /pegrevision:") + peg.ToString();
1113 if (headpeg.IsValid())
1114 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1116 if (bAlternateDiff)
1117 sCmd += _T(" /alternatediff");
1119 if (bIgnoreAncestry)
1120 sCmd += _T(" /ignoreancestry");
1122 if (hWnd)
1124 sCmd += _T(" /hwnd:");
1125 TCHAR buf[30];
1126 _stprintf_s(buf, 30, _T("%d"), hWnd);
1127 sCmd += buf;
1130 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1131 #endif
1132 return TRUE;
1136 bool CAppUtils::Export(CString *BashHash)
1138 bool bRet = false;
1140 // ask from where the export has to be done
1141 CExportDlg dlg;
1142 if(BashHash)
1143 dlg.m_Revision=*BashHash;
1145 if (dlg.DoModal() == IDOK)
1147 CString cmd;
1148 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1149 g_Git.FixBranchName(dlg.m_VersionName));
1151 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1152 CProgressDlg pro;
1153 pro.m_GitCmd=cmd;
1154 pro.m_LogFile=dlg.m_strExportDirectory;
1155 pro.DoModal();
1156 return TRUE;
1158 return bRet;
1161 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1163 CCreateBranchTagDlg dlg;
1164 dlg.m_bIsTag=IsTag;
1165 dlg.m_bSwitch=switch_new_brach;
1167 if(CommitHash)
1168 dlg.m_Base = *CommitHash;
1170 if(dlg.DoModal()==IDOK)
1172 CString cmd;
1173 CString force;
1174 CString track;
1175 if(dlg.m_bTrack)
1176 track=_T(" --track ");
1178 if(dlg.m_bForce)
1179 force=_T(" -f ");
1181 if(IsTag)
1183 CString sign;
1184 if(dlg.m_bSign)
1185 sign=_T("-s");
1187 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1188 track,
1189 force,
1190 sign,
1191 dlg.m_BranchTagName,
1192 g_Git.FixBranchName(dlg.m_VersionName)
1195 CString tempfile=::GetTempFile();
1196 if(!dlg.m_Message.Trim().IsEmpty())
1198 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1199 cmd += _T(" -F ")+tempfile;
1202 else
1204 cmd.Format(_T("git.exe branch %s %s %s %s"),
1205 track,
1206 force,
1207 dlg.m_BranchTagName,
1208 g_Git.FixBranchName(dlg.m_VersionName)
1211 CString out;
1212 if(g_Git.Run(cmd,&out,CP_UTF8))
1214 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1216 if( !IsTag && dlg.m_bSwitch )
1218 // it is a new branch and the user has requested to switch to it
1219 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1220 g_Git.Run(cmd,&out,CP_UTF8);
1221 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1224 return TRUE;
1226 return FALSE;
1229 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1231 CGitSwitchDlg dlg;
1232 if(CommitHash)
1233 dlg.m_Base=*CommitHash;
1234 if(!initialRefName.IsEmpty())
1235 dlg.m_initialRefName = initialRefName;
1237 if (dlg.DoModal() == IDOK)
1239 CString branch;
1240 if (dlg.m_bBranch)
1241 branch = dlg.m_NewBranch;
1243 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1245 return FALSE;
1248 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1250 CString cmd;
1251 CString track;
1252 CString force;
1253 CString branch;
1255 if(!sNewBranch.IsEmpty()){
1256 if (bBranchOverride)
1258 branch.Format(_T("-B %s"), sNewBranch);
1260 else
1262 branch.Format(_T("-b %s"), sNewBranch);
1264 if (bTrack)
1265 track = _T("--track");
1267 if (bForce)
1268 force = _T("-f");
1270 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1271 force,
1272 track,
1273 branch,
1274 g_Git.FixBranchName(ref));
1276 CProgressDlg progress;
1277 progress.m_bAutoCloseOnSuccess = autoClose;
1278 progress.m_GitCmd = cmd;
1280 CTGitPath gitPath = g_Git.m_CurrentDir;
1281 if (gitPath.HasSubmodules())
1282 progress.m_PostCmdList.Add(_T("Update Submodules"));
1284 int ret = progress.DoModal();
1285 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1287 CString sCmd;
1288 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1290 LaunchApplication(sCmd, NULL, false);
1291 return TRUE;
1293 else if (ret == IDOK)
1294 return TRUE;
1296 return FALSE;
1299 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1301 CString ignorefile;
1302 ignorefile=g_Git.m_CurrentDir+_T("\\");
1304 if(IsMask)
1306 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1309 else
1311 ignorefile += _T("\\.gitignore");
1314 CStdioFile file;
1315 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1317 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1318 return FALSE;
1321 CString ignorelist;
1322 CString mask;
1325 //file.ReadString(ignorelist);
1326 file.SeekToEnd();
1327 for(int i=0;i<path.GetCount();i++)
1329 if(IsMask)
1331 mask=_T("*")+path[i].GetFileExtension();
1332 if(ignorelist.Find(mask)<0)
1333 ignorelist += _T("\n")+mask;
1335 else
1337 ignorelist += _T("\n/")+path[i].GetGitPathString();
1340 file.WriteString(ignorelist);
1342 file.Close();
1344 }catch(...)
1346 file.Close();
1347 return FALSE;
1350 return TRUE;
1354 bool CAppUtils::GitReset(CString *CommitHash,int type)
1356 CResetDlg dlg;
1357 dlg.m_ResetType=type;
1358 dlg.m_ResetToVersion=*CommitHash;
1359 if (dlg.DoModal() == IDOK)
1361 CString cmd;
1362 CString type;
1363 switch(dlg.m_ResetType)
1365 case 0:
1366 type=_T("--soft");
1367 break;
1368 case 1:
1369 type=_T("--mixed");
1370 break;
1371 case 2:
1372 type=_T("--hard");
1373 break;
1374 default:
1375 type=_T("--mixed");
1376 break;
1378 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1380 CProgressDlg progress;
1381 progress.m_GitCmd=cmd;
1383 CTGitPath gitPath = g_Git.m_CurrentDir;
1384 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1385 progress.m_PostCmdList.Add(_T("Update Submodules"));
1387 int ret = progress.DoModal();
1388 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1390 CString sCmd;
1391 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1393 LaunchApplication(sCmd, NULL, false);
1394 return TRUE;
1396 else if (ret == IDOK)
1397 return TRUE;
1400 return FALSE;
1403 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1405 if(mode == FALSE)
1407 descript=_T("Deleted");
1408 return;
1410 if(base)
1412 descript=_T("Modified");
1413 return;
1415 descript=_T("Created");
1416 return;
1419 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1421 CString tempmergefile;
1424 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1425 CFile::Remove(tempmergefile);
1426 }catch(...)
1432 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1433 CFile::Remove(tempmergefile);
1434 }catch(...)
1440 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1441 CFile::Remove(tempmergefile);
1442 }catch(...)
1446 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1448 CString file;
1449 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1451 return file;
1454 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1456 bool bRet = false;
1458 CTGitPath merge=path;
1459 CTGitPath directory = merge.GetDirectory();
1461 // we have the conflicted file (%merged)
1462 // now look for the other required files
1463 //GitStatus stat;
1464 //stat.GetStatus(merge);
1465 //if (stat.status == NULL)
1466 // return false;
1468 BYTE_VECTOR vector;
1470 CString cmd;
1471 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1473 if (g_Git.Run(cmd, &vector))
1475 return FALSE;
1478 CTGitPathList list;
1479 list.ParserFromLsFile(vector);
1481 if(list.GetCount() == 0)
1482 return FALSE;
1484 CTGitPath theirs;
1485 CTGitPath mine;
1486 CTGitPath base;
1488 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1489 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1490 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1492 CString format;
1494 //format=_T("git.exe cat-file blob \":%d:%s\"");
1495 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1496 CFile tempfile;
1497 //create a empty file, incase stage is not three
1498 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1499 tempfile.Close();
1500 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1501 tempfile.Close();
1502 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1503 tempfile.Close();
1505 bool b_base=false, b_local=false, b_remote=false;
1507 for(int i=0;i<list.GetCount();i++)
1509 CString cmd;
1510 CString outfile;
1511 cmd.Empty();
1512 outfile.Empty();
1514 if( list[i].m_Stage == 1)
1516 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1517 b_base = true;
1518 outfile = base.GetWinPathString();
1521 if( list[i].m_Stage == 2 )
1523 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1524 b_local = true;
1525 outfile = mine.GetWinPathString();
1528 if( list[i].m_Stage == 3 )
1530 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1531 b_remote = true;
1532 outfile = theirs.GetWinPathString();
1534 CString output, err;
1535 if(!outfile.IsEmpty())
1536 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1538 CString file;
1539 int start =0 ;
1540 file = output.Tokenize(_T("\t"), start);
1541 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1543 else
1545 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1549 if(b_local && b_remote )
1551 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1552 if( revertTheirMy )
1553 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1554 else
1555 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1558 else
1560 CFile::Remove(mine.GetWinPathString());
1561 CFile::Remove(theirs.GetWinPathString());
1562 CFile::Remove(base.GetWinPathString());
1564 CDeleteConflictDlg dlg;
1565 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1566 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1567 dlg.m_bShowModifiedButton=b_base;
1568 dlg.m_File=merge.GetGitPathString();
1569 if(dlg.DoModal() == IDOK)
1571 CString cmd,out;
1572 if(dlg.m_bIsDelete)
1574 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1576 else
1577 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1579 if(g_Git.Run(cmd,&out,CP_ACP))
1581 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1582 return FALSE;
1584 return TRUE;
1586 else
1587 return FALSE;
1590 #if 0
1591 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1592 base, theirs, mine, merge);
1593 #endif
1594 #if 0
1595 if (stat.status->text_status == svn_wc_status_conflicted)
1597 // we have a text conflict, use our merge tool to resolve the conflict
1599 CTSVNPath theirs(directory);
1600 CTSVNPath mine(directory);
1601 CTSVNPath base(directory);
1602 bool bConflictData = false;
1604 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1606 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1607 bConflictData = true;
1609 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1611 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1612 bConflictData = true;
1614 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1616 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1617 bConflictData = true;
1619 else
1621 mine = merge;
1623 if (bConflictData)
1624 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1625 base, theirs, mine, merge);
1628 if (stat.status->prop_status == svn_wc_status_conflicted)
1630 // we have a property conflict
1631 CTSVNPath prej(directory);
1632 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1634 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1635 // there's a problem: the prej file contains a _description_ of the conflict, and
1636 // that description string might be translated. That means we have no way of parsing
1637 // the file to find out the conflicting values.
1638 // The only thing we can do: show a dialog with the conflict description, then
1639 // let the user either accept the existing property or open the property edit dialog
1640 // to manually change the properties and values. And a button to mark the conflict as
1641 // resolved.
1642 CEditPropConflictDlg dlg;
1643 dlg.SetPrejFile(prej);
1644 dlg.SetConflictedItem(merge);
1645 bRet = (dlg.DoModal() != IDCANCEL);
1649 if (stat.status->tree_conflict)
1651 // we have a tree conflict
1652 SVNInfo info;
1653 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1654 if (pInfoData)
1656 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1658 CTSVNPath theirs(directory);
1659 CTSVNPath mine(directory);
1660 CTSVNPath base(directory);
1661 bool bConflictData = false;
1663 if (pInfoData->treeconflict_theirfile)
1665 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1666 bConflictData = true;
1668 if (pInfoData->treeconflict_basefile)
1670 base.AppendPathString(pInfoData->treeconflict_basefile);
1671 bConflictData = true;
1673 if (pInfoData->treeconflict_myfile)
1675 mine.AppendPathString(pInfoData->treeconflict_myfile);
1676 bConflictData = true;
1678 else
1680 mine = merge;
1682 if (bConflictData)
1683 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1684 base, theirs, mine, merge);
1686 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1688 CString sConflictAction;
1689 CString sConflictReason;
1690 CString sResolveTheirs;
1691 CString sResolveMine;
1692 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1693 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1695 if (pInfoData->treeconflict_nodekind == svn_node_file)
1697 switch (pInfoData->treeconflict_operation)
1699 case svn_wc_operation_update:
1700 switch (pInfoData->treeconflict_action)
1702 case svn_wc_conflict_action_edit:
1703 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1704 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1705 break;
1706 case svn_wc_conflict_action_add:
1707 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1708 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1709 break;
1710 case svn_wc_conflict_action_delete:
1711 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1712 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1713 break;
1715 break;
1716 case svn_wc_operation_switch:
1717 switch (pInfoData->treeconflict_action)
1719 case svn_wc_conflict_action_edit:
1720 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1721 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1722 break;
1723 case svn_wc_conflict_action_add:
1724 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1725 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1726 break;
1727 case svn_wc_conflict_action_delete:
1728 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1729 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1730 break;
1732 break;
1733 case svn_wc_operation_merge:
1734 switch (pInfoData->treeconflict_action)
1736 case svn_wc_conflict_action_edit:
1737 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1738 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1739 break;
1740 case svn_wc_conflict_action_add:
1741 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1742 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1743 break;
1744 case svn_wc_conflict_action_delete:
1745 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1746 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1747 break;
1749 break;
1752 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1754 switch (pInfoData->treeconflict_operation)
1756 case svn_wc_operation_update:
1757 switch (pInfoData->treeconflict_action)
1759 case svn_wc_conflict_action_edit:
1760 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1761 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1762 break;
1763 case svn_wc_conflict_action_add:
1764 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1765 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1766 break;
1767 case svn_wc_conflict_action_delete:
1768 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1769 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1770 break;
1772 break;
1773 case svn_wc_operation_switch:
1774 switch (pInfoData->treeconflict_action)
1776 case svn_wc_conflict_action_edit:
1777 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1778 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1779 break;
1780 case svn_wc_conflict_action_add:
1781 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1782 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1783 break;
1784 case svn_wc_conflict_action_delete:
1785 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1786 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1787 break;
1789 break;
1790 case svn_wc_operation_merge:
1791 switch (pInfoData->treeconflict_action)
1793 case svn_wc_conflict_action_edit:
1794 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1795 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1796 break;
1797 case svn_wc_conflict_action_add:
1798 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1799 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1800 break;
1801 case svn_wc_conflict_action_delete:
1802 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1803 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1804 break;
1806 break;
1810 UINT uReasonID = 0;
1811 switch (pInfoData->treeconflict_reason)
1813 case svn_wc_conflict_reason_edited:
1814 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
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_obstructed:
1818 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1819 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1820 break;
1821 case svn_wc_conflict_reason_deleted:
1822 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1823 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1824 break;
1825 case svn_wc_conflict_reason_added:
1826 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1827 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1828 break;
1829 case svn_wc_conflict_reason_missing:
1830 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1831 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1832 break;
1833 case svn_wc_conflict_reason_unversioned:
1834 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1835 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1836 break;
1838 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1840 CTreeConflictEditorDlg dlg;
1841 dlg.SetConflictInfoText(sConflictReason);
1842 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1843 dlg.SetPath(treeConflictPath);
1844 INT_PTR dlgRet = dlg.DoModal();
1845 bRet = (dlgRet != IDCANCEL);
1849 #endif
1850 return bRet;
1854 * FUNCTION : FormatDateAndTime
1855 * DESCRIPTION : Generates a displayable string from a CTime object in
1856 * system short or long format or as a relative value
1857 * cTime - the time
1858 * option - DATE_SHORTDATE or DATE_LONGDATE
1859 * bIncluedeTime - whether to show time as well as date
1860 * bRelative - if true then relative time is shown if reasonable
1861 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1862 * rather than locale
1863 * RETURN : CString containing date/time
1865 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1866 bool bRelative /*=false*/)
1868 CString datetime;
1869 if ( bRelative )
1871 datetime = ToRelativeTimeString( cTime );
1873 else
1875 // should we use the locale settings for formatting the date/time?
1876 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1878 // yes
1879 SYSTEMTIME sysTime;
1880 cTime.GetAsSystemTime( sysTime );
1882 TCHAR buf[100];
1884 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1885 _countof(buf) - 1);
1886 datetime = buf;
1887 if ( bIncludeTime )
1889 datetime += _T(" ");
1890 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1891 datetime += buf;
1894 else
1896 // no, so fixed format
1897 if ( bIncludeTime )
1899 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1901 else
1903 datetime = cTime.Format(_T("%Y-%m-%d"));
1907 return datetime;
1911 * Converts a given time to a relative display string (relative to current time)
1912 * Given time must be in local timezone
1914 CString CAppUtils::ToRelativeTimeString(CTime time)
1916 CString answer;
1917 // convert to COleDateTime
1918 SYSTEMTIME sysTime;
1919 time.GetAsSystemTime( sysTime );
1920 COleDateTime oleTime( sysTime );
1921 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1922 return answer;
1926 * Generates a display string showing the relative time between the two given times as COleDateTimes
1928 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1930 CString answer;
1931 COleDateTimeSpan ts = RelativeTo - time;
1932 //years
1933 if(fabs(ts.GetTotalDays()) >= 3*365)
1935 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1937 //Months
1938 if(fabs(ts.GetTotalDays()) >= 60)
1940 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1941 return answer;
1943 //Weeks
1944 if(fabs(ts.GetTotalDays()) >= 14)
1946 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1947 return answer;
1949 //Days
1950 if(fabs(ts.GetTotalDays()) >= 2)
1952 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1953 return answer;
1955 //hours
1956 if(fabs(ts.GetTotalHours()) >= 2)
1958 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1959 return answer;
1961 //minutes
1962 if(fabs(ts.GetTotalMinutes()) >= 2)
1964 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1965 return answer;
1967 //seconds
1968 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1969 return answer;
1973 * Passed a value and two resource string ids
1974 * if count is 1 then FormatString is called with format_1 and the value
1975 * otherwise format_2 is used
1976 * the formatted string is returned
1978 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1980 CString answer;
1981 if ( count == 1 )
1983 answer.FormatMessage( format_1, count );
1985 else
1987 answer.FormatMessage( format_n, count );
1989 return answer;
1992 bool CAppUtils::IsSSHPutty()
1994 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1995 sshclient=sshclient.MakeLower();
1996 if(sshclient.Find(_T("plink.exe"),0)>=0)
1998 return true;
2000 return false;
2003 CString CAppUtils::GetClipboardLink()
2005 if (!OpenClipboard(NULL))
2006 return CString();
2008 CString sClipboardText;
2009 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2010 if (hglb)
2012 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2013 sClipboardText = CString(lpstr);
2014 GlobalUnlock(hglb);
2016 hglb = GetClipboardData(CF_UNICODETEXT);
2017 if (hglb)
2019 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2020 sClipboardText = lpstr;
2021 GlobalUnlock(hglb);
2023 CloseClipboard();
2025 if(!sClipboardText.IsEmpty())
2027 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2028 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2030 if(sClipboardText.Find( _T("http://")) == 0)
2031 return sClipboardText;
2033 if(sClipboardText.Find( _T("https://")) == 0)
2034 return sClipboardText;
2036 if(sClipboardText.Find( _T("git://")) == 0)
2037 return sClipboardText;
2039 if(sClipboardText.Find( _T("ssh://")) == 0)
2040 return sClipboardText;
2042 if(sClipboardText.GetLength()>=2)
2043 if( sClipboardText[1] == _T(':') )
2044 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2045 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2046 return sClipboardText;
2049 return CString(_T(""));
2052 CString CAppUtils::ChooseRepository(CString *path)
2054 CBrowseFolder browseFolder;
2055 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2057 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2058 CString strCloneDirectory;
2059 if(path)
2060 strCloneDirectory=*path;
2061 else
2063 strCloneDirectory = regLastResopitory;
2066 CString title;
2067 title.LoadString(IDS_CHOOSE_REPOSITORY);
2069 browseFolder.SetInfo(title);
2071 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2073 regLastResopitory = strCloneDirectory;
2074 return strCloneDirectory;
2076 else
2078 return CString();
2082 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2084 CSendMailDlg dlg;
2086 dlg.m_PathList = list;
2088 if(dlg.DoModal()==IDOK)
2090 if(dlg.m_PathList.GetCount() == 0)
2091 return FALSE;
2093 CGitProgressDlg progDlg;
2095 theApp.m_pMainWnd = &progDlg;
2096 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2098 progDlg.SetAutoClose(autoclose);
2100 progDlg.SetPathList(dlg.m_PathList);
2101 //ProjectProperties props;
2102 //props.ReadPropsPathList(dlg.m_pathList);
2103 //progDlg.SetProjectProperties(props);
2104 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2106 DWORD flags =0;
2107 if(dlg.m_bAttachment)
2108 flags |= SENDMAIL_ATTACHMENT;
2109 if(dlg.m_bCombine)
2110 flags |= SENDMAIL_COMBINED;
2111 if(dlg.m_bUseMAPI)
2112 flags |= SENDMAIL_MAPI;
2114 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2116 progDlg.DoModal();
2118 return true;
2120 return false;
2123 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2125 CTGitPathList list;
2126 CString log=formatpatchoutput;
2127 int start=log.Find(cmd);
2128 if(start >=0)
2129 CString one=log.Tokenize(_T("\n"),start);
2130 else
2131 start = 0;
2133 while(start>=0)
2135 CString one=log.Tokenize(_T("\n"),start);
2136 one=one.Trim();
2137 if(one.IsEmpty() || one == _T("Success"))
2138 continue;
2139 one.Replace(_T('/'),_T('\\'));
2140 CTGitPath path;
2141 path.SetFromWin(one);
2142 list.AddPath(path);
2144 if (list.GetCount() > 0)
2146 return SendPatchMail(list, autoclose);
2148 else
2150 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2151 return true;
2156 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2158 CString cmd,output;
2159 int start=0;
2161 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2162 if(output.IsEmpty())
2164 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2165 if(output.IsEmpty())
2166 return CP_UTF8;
2168 int start=0;
2169 output=output.Tokenize(_T("\n"),start);
2170 return CUnicodeUtils::GetCPCode(output);
2173 else
2175 output=output.Tokenize(_T("\n"),start);
2176 return CUnicodeUtils::GetCPCode(output);
2179 int CAppUtils::GetCommitTemplate(CString &temp)
2181 CString cmd,output;
2183 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2184 if( output.IsEmpty() )
2185 return -1;
2187 if( output.GetLength()<1)
2188 return -1;
2190 if( output[0] == _T('/'))
2192 if(output.GetLength()>=3)
2193 if(output[2] == _T('/'))
2195 output.GetBuffer()[0] = output[1];
2196 output.GetBuffer()[1] = _T(':');
2200 int start=0;
2201 output=output.Tokenize(_T("\n"),start);
2203 output.Replace(_T('/'),_T('\\'));
2207 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2208 CString str;
2209 while(file.ReadString(str))
2211 temp+=str+_T("\n");
2214 }catch(...)
2216 return -1;
2218 return 0;
2220 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2222 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2223 CString cmd,output;
2224 int cp=CP_UTF8;
2226 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2227 if(output.IsEmpty())
2228 cp=CP_UTF8;
2230 int start=0;
2231 output=output.Tokenize(_T("\n"),start);
2232 cp=CUnicodeUtils::GetCPCode(output);
2234 int len=message.GetLength();
2236 char * buf;
2237 buf = new char[len*4 + 4];
2238 SecureZeroMemory(buf, (len*4 + 4));
2240 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2242 file.Write(buf,lengthIncTerminator-1);
2243 file.Close();
2244 delete buf;
2245 return 0;
2248 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2250 CPullFetchDlg dlg;
2251 dlg.m_PreSelectRemote = remoteName;
2252 dlg.m_bAllowRebase = allowRebase;
2253 dlg.m_IsPull=FALSE;
2255 if(dlg.DoModal()==IDOK)
2257 if(dlg.m_bAutoLoad)
2259 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2262 CString url;
2263 url=dlg.m_RemoteURL;
2264 CString cmd;
2265 CString arg;
2267 int ver = CAppUtils::GetMsysgitVersion();
2269 if(ver >= 0x01070203) //above 1.7.0.2
2270 arg = _T("--progress ");
2272 if (dlg.m_bPrune) {
2273 arg += _T("--prune ");
2276 if (dlg.m_bFetchTags) {
2277 arg += _T("--tags ");
2280 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2281 CProgressDlg progress;
2283 progress.m_bAutoCloseOnSuccess = autoClose;
2285 progress.m_PostCmdList.Add(_T("Show Log"));
2287 if(!dlg.m_bRebase)
2289 progress.m_PostCmdList.Add(_T("&Rebase"));
2292 progress.m_GitCmd=cmd;
2293 int userResponse=progress.DoModal();
2295 if (userResponse == IDC_PROGRESS_BUTTON1)
2297 CString cmd;
2298 cmd = CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe");
2299 cmd += _T(" /command:log");
2300 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2301 CAppUtils::LaunchApplication(cmd, IDS_ERR_PROC, false);
2302 return TRUE;
2304 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2306 while(1)
2308 CRebaseDlg dlg;
2309 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2310 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2311 int response = dlg.DoModal();
2312 if(response == IDOK)
2314 return TRUE;
2316 if(response == IDC_REBASE_POST_BUTTON )
2318 CString cmd, out, err;
2319 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2320 g_Git.m_CurrentDir,
2321 g_Git.FixBranchName(dlg.m_Upstream),
2322 g_Git.FixBranchName(dlg.m_Branch));
2323 if (g_Git.Run(cmd, &out, &err, CP_ACP))
2325 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2326 return FALSE;
2329 CAppUtils::SendPatchMail(cmd,out);
2330 return TRUE;
2333 if(response == IDC_REBASE_POST_BUTTON +1 )
2334 continue;
2336 if(response == IDCANCEL)
2337 return FALSE;
2339 return TRUE;
2342 return FALSE;
2345 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2347 CPushDlg dlg;
2348 dlg.m_BranchSourceName = selectLocalBranch;
2349 CString error;
2350 DWORD exitcode = 0xFFFFFFFF;
2351 CTGitPathList list;
2352 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2353 if (CHooks::Instance().PrePush(list,exitcode, error))
2355 if (exitcode)
2357 CString temp;
2358 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2359 //ReportError(temp);
2360 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2361 return false;
2365 if(dlg.DoModal()==IDOK)
2367 CString cmd;
2368 CString arg;
2370 if(dlg.m_bAutoLoad)
2372 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2375 if(dlg.m_bPack)
2376 arg += _T("--thin ");
2377 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2378 arg += _T("--tags ");
2379 if(dlg.m_bForce)
2380 arg += _T("--force ");
2382 int ver = CAppUtils::GetMsysgitVersion();
2384 if(ver >= 0x01070203) //above 1.7.0.2
2385 arg += _T("--progress ");
2387 if (dlg.m_bPushAllBranches)
2389 cmd.Format(_T("git.exe push --all %s \"%s\""),
2390 arg,
2391 dlg.m_URL);
2393 else
2395 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2396 arg,
2397 dlg.m_URL,
2398 dlg.m_BranchSourceName);
2399 if (!dlg.m_BranchRemoteName.IsEmpty())
2401 cmd += _T(":") + dlg.m_BranchRemoteName;
2405 CProgressDlg progress;
2406 progress.m_bAutoCloseOnSuccess=autoClose;
2407 progress.m_GitCmd=cmd;
2408 progress.m_PostCmdList.Add(_T("&Request pull"));
2409 progress.m_PostCmdList.Add(_T("Re&Push"));
2410 int ret = progress.DoModal();
2412 if(!progress.m_GitStatus)
2414 if (CHooks::Instance().PostPush(list,exitcode, error))
2416 if (exitcode)
2418 CString temp;
2419 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2420 //ReportError(temp);
2421 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2422 return false;
2425 if(ret == IDC_PROGRESS_BUTTON1)
2427 RequestPull(dlg.m_BranchRemoteName);
2429 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2431 Push();
2433 return TRUE;
2437 return FALSE;
2440 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2442 CRequestPullDlg dlg;
2443 dlg.m_RepositoryURL = repositoryUrl;
2444 dlg.m_EndRevision = endrevision;
2445 if (dlg.DoModal()==IDOK)
2447 CString cmd;
2448 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2450 CProgressDlg progress;
2451 progress.m_GitCmd=cmd;
2452 progress.DoModal();
2454 return true;
2457 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2459 CString strDir(szPath);
2460 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2462 strDir.AppendChar(_T('\\'));
2464 std::vector<CString> vPath;
2465 CString strTemp;
2466 bool bSuccess = false;
2468 for (int i=0;i<strDir.GetLength();++i)
2470 if (strDir.GetAt(i) != _T('\\'))
2472 strTemp.AppendChar(strDir.GetAt(i));
2474 else
2476 vPath.push_back(strTemp);
2477 strTemp.AppendChar(_T('\\'));
2481 std::vector<CString>::const_iterator vIter;
2482 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2484 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2487 return bSuccess;
2490 void CAppUtils::RemoveTrailSlash(CString &path)
2492 if(path.IsEmpty())
2493 return ;
2495 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2497 path=path.Left(path.GetLength()-1);
2498 if(path.IsEmpty())
2499 return;
2503 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2504 CTGitPathList &pathList,
2505 CTGitPathList &selectedList,
2506 bool bSelectFilesForCommit,
2507 bool autoClose)
2509 bool bFailed = true;
2511 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2513 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"),
2514 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2516 CTGitPath path(g_Git.m_CurrentDir);
2517 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2518 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2519 dlg.SetTreeWidth(220);
2520 dlg.m_DefaultPage = _T("gitconfig");
2522 dlg.DoModal();
2523 dlg.HandleRestart();
2526 else
2527 return false;
2530 while (bFailed)
2532 bFailed = false;
2533 CCommitDlg dlg;
2534 dlg.m_sBugID = bugid;
2536 dlg.m_bWholeProject = bWholeProject;
2538 dlg.m_sLogMessage = sLogMsg;
2539 dlg.m_pathList = pathList;
2540 dlg.m_checkedPathList = selectedList;
2541 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2542 dlg.m_bAutoClose = autoClose;
2543 if (dlg.DoModal() == IDOK)
2545 if (dlg.m_pathList.GetCount()==0)
2546 return false;
2547 // if the user hasn't changed the list of selected items
2548 // we don't use that list. Because if we would use the list
2549 // of pre-checked items, the dialog would show different
2550 // checked items on the next startup: it would only try
2551 // to check the parent folder (which might not even show)
2552 // instead, we simply use an empty list and let the
2553 // default checking do its job.
2554 if (!dlg.m_pathList.IsEqual(pathList))
2555 selectedList = dlg.m_pathList;
2556 pathList = dlg.m_updatedPathList;
2557 sLogMsg = dlg.m_sLogMessage;
2558 bSelectFilesForCommit = true;
2560 if( dlg.m_bPushAfterCommit )
2562 switch(dlg.m_PostCmd)
2564 case GIT_POST_CMD_DCOMMIT:
2565 CAppUtils::SVNDCommit();
2566 break;
2567 default:
2568 CAppUtils::Push();
2571 // CGitProgressDlg progDlg;
2572 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2573 // if (parser.HasVal(_T("closeonend")))
2574 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2575 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2576 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2577 // progDlg.SetPathList(dlg.m_pathList);
2578 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2579 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2580 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2581 // progDlg.SetItemCount(dlg.m_itemsCount);
2582 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2583 // progDlg.DoModal();
2584 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2585 // err = (DWORD)progDlg.DidErrorsOccur();
2586 // bFailed = progDlg.DidErrorsOccur();
2587 // bRet = progDlg.DidErrorsOccur();
2588 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2589 // if (DWORD(bFailRepeat)==0)
2590 // bFailed = false; // do not repeat if the user chose not to in the settings.
2593 return true;
2597 BOOL CAppUtils::SVNDCommit()
2599 CSVNDCommitDlg dcommitdlg;
2600 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2601 if (gitSetting == _T("")) {
2602 if (dcommitdlg.DoModal() != IDOK)
2604 return false;
2606 else
2608 if (dcommitdlg.m_remember)
2610 if (dcommitdlg.m_rmdir)
2612 gitSetting = _T("true");
2614 else
2616 gitSetting = _T("false");
2618 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2620 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2626 BOOL IsStash = false;
2627 if(!g_Git.CheckCleanWorkTree())
2629 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2631 CString cmd,out;
2632 cmd=_T("git.exe stash");
2633 if(g_Git.Run(cmd,&out,CP_ACP))
2635 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2636 return false;
2638 IsStash =true;
2641 else
2643 return false;
2647 CProgressDlg progress;
2648 if (dcommitdlg.m_rmdir)
2650 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2652 else
2654 progress.m_GitCmd=_T("git.exe svn dcommit");
2656 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2658 if( IsStash)
2660 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2662 CString cmd,out;
2663 cmd=_T("git.exe stash pop");
2664 if(g_Git.Run(cmd,&out,CP_ACP))
2666 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2667 return false;
2671 else
2673 return false;
2676 return TRUE;
2678 return FALSE;
2681 BOOL CAppUtils::Merge(CString *commit)
2683 CMergeDlg dlg;
2684 if(commit)
2685 dlg.m_initialRefName = *commit;
2687 if(dlg.DoModal()==IDOK)
2689 CString cmd;
2690 CString noff;
2691 CString squash;
2692 CString nocommit;
2693 CString msg;
2695 if(dlg.m_bNoFF)
2696 noff=_T("--no-ff");
2698 if(dlg.m_bSquash)
2699 squash=_T("--squash");
2701 if(dlg.m_bNoCommit)
2702 nocommit=_T("--no-commit");
2704 if(!dlg.m_strLogMesage.IsEmpty())
2706 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2708 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2709 msg,
2710 noff,
2711 squash,
2712 nocommit,
2713 g_Git.FixBranchName(dlg.m_VersionName));
2715 CProgressDlg Prodlg;
2716 Prodlg.m_GitCmd = cmd;
2718 if (dlg.m_bNoCommit)
2719 Prodlg.m_PostCmdList.Add(_T("Commit"));
2721 int ret = Prodlg.DoModal();
2723 if (ret == IDC_PROGRESS_BUTTON1)
2724 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2726 return !Prodlg.m_GitStatus;
2728 return false;
2731 void CAppUtils::EditNote(GitRev *rev)
2733 CInputDlg dlg;
2734 dlg.m_sHintText=_T("Edit Notes");
2735 dlg.m_sInputText = rev->m_Notes;
2736 dlg.m_sTitle=_T("Edit Notes");
2737 //dlg.m_pProjectProperties = &m_ProjectProperties;
2738 dlg.m_bUseLogWidth = true;
2739 if(dlg.DoModal() == IDOK)
2741 CString cmd,output;
2742 cmd=_T("notes add -f -F \"");
2744 CString tempfile=::GetTempFile();
2745 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2746 cmd += tempfile;
2747 cmd += _T("\" ");
2748 cmd += rev->m_CommitHash.ToString();
2752 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2754 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2757 else
2759 rev->m_Notes = dlg.m_sInputText;
2761 }catch(...)
2763 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2765 CFile::Remove(tempfile);
2770 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2772 CString cmd;
2773 CString progressarg;
2774 CString version;
2776 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2777 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2779 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2781 __int64 time=0;
2782 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2784 if((DWORD)time == regTime)
2786 return regVersion;
2790 if(versionstr)
2791 version = *versionstr;
2792 else
2794 CString err;
2795 cmd = _T("git.exe --version");
2796 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2798 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2799 return false;
2803 int start=0;
2804 int ver;
2806 CString str=version.Tokenize(_T("."),start);
2807 int space = str.ReverseFind(_T(' '));
2808 str=str.Mid(space+1,start);
2809 ver = _ttol(str);
2810 ver <<=24;
2812 version = version.Mid(start);
2813 start = 0;
2814 str = version.Tokenize(_T("."),start);
2816 ver |= (_ttol(str)&0xFF)<<16;
2818 str = version.Tokenize(_T("."),start);
2819 ver |= (_ttol(str)&0xFF)<<8;
2821 str = version.Tokenize(_T("."),start);
2822 ver |= (_ttol(str)&0xFF);
2824 regTime = time&0xFFFFFFFF;
2825 regVersion = ver;
2827 return ver;
2830 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2832 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2834 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2836 if (hShell) {
2837 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2838 if (pfnSHGPSFW) {
2839 IPropertyStore *pps;
2840 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2841 if (SUCCEEDED(hr)) {
2842 PROPVARIANT var;
2843 var.vt = VT_BOOL;
2844 var.boolVal = VARIANT_TRUE;
2845 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2846 pps->Release();
2849 FreeLibrary(hShell);
2853 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2855 ASSERT(dialogname.GetLength() < 70);
2856 ASSERT(urlorpath.GetLength() < MAX_PATH);
2857 WCHAR pathbuf[MAX_PATH] = {0};
2859 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2861 wcscat_s(pathbuf, L" - ");
2862 wcscat_s(pathbuf, dialogname);
2863 wcscat_s(pathbuf, L" - ");
2864 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2865 SetWindowText(hWnd, pathbuf);