Support git Notes.
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobb850aa8eb03542ab2fa1f17b7d05402e86df5af5
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2008 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "StdAfx.h"
20 #include "resource.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 //#include "GitProperties.h"
25 #include "StringUtils.h"
26 #include "MessageBox.h"
27 #include "Registry.h"
28 #include "TGitPath.h"
29 #include "Git.h"
30 //#include "RepositoryBrowser.h"
31 //#include "BrowseFolder.h"
32 #include "UnicodeUtils.h"
33 #include "ExportDlg.h"
34 #include "ProgressDlg.h"
35 #include "GitAdminDir.h"
36 #include "ProgressDlg.h"
37 #include "BrowseFolder.h"
38 #include "DirFileEnum.h"
39 #include "MessageBox.h"
40 #include "GitStatus.h"
41 #include "CreateBranchTagDlg.h"
42 #include "GitSwitchDlg.h"
43 #include "ResetDlg.h"
44 #include "DeleteConflictDlg.h"
45 #include "ChangedDlg.h"
46 #include "SendMailDlg.h"
47 #include "SVNProgressDlg.h"
48 #include "PushDlg.h"
49 #include "CommitDlg.h"
50 #include "MergeDlg.h"
51 #include "hooks.h"
52 #include "..\Settings\Settings.h"
53 #include "InputDlg.h"
55 CAppUtils::CAppUtils(void)
59 CAppUtils::~CAppUtils(void)
63 int CAppUtils::StashApply(CString ref)
65 CString cmd,out;
66 cmd=_T("git.exe stash apply ");
67 cmd+=ref;
69 if(g_Git.Run(cmd,&out,CP_ACP))
71 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
73 }else
75 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
76 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
78 CChangedDlg dlg;
79 dlg.m_pathList.AddPath(CTGitPath());
80 dlg.DoModal();
82 return 0;
84 return -1;
87 int CAppUtils::StashPop()
89 CString cmd,out;
90 cmd=_T("git.exe stash pop ");
92 if(g_Git.Run(cmd,&out,CP_ACP))
94 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
96 }else
98 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
99 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
101 CChangedDlg dlg;
102 dlg.m_pathList.AddPath(CTGitPath());
103 dlg.DoModal();
105 return 0;
107 return -1;
110 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
112 #if 0
113 GitProperties props(file, GitRev::REV_WC, false);
114 for (int i = 0; i < props.GetCount(); ++i)
116 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
118 mimetype = props.GetItemValue(i).c_str();
119 return true;
122 #endif
123 return false;
126 BOOL CAppUtils::StartExtMerge(
127 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
128 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
131 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
132 CString ext = mergedfile.GetFileExtension();
133 CString com = regCom;
134 bool bInternal = false;
136 CString mimetype;
137 if (ext != "")
139 // is there an extension specific merge tool?
140 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
141 if (CString(mergetool) != "")
143 com = mergetool;
146 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
148 // is there a mime type specific merge tool?
149 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
150 if (CString(mergetool) != "")
152 com = mergetool;
156 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
158 // use TortoiseMerge
159 bInternal = true;
160 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
161 com = tortoiseMergePath;
162 if (com.IsEmpty())
164 com = CPathUtils::GetAppDirectory();
165 com += _T("TortoiseMerge.exe");
167 com = _T("\"") + com + _T("\"");
168 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
169 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
171 // check if the params are set. If not, just add the files to the command line
172 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
174 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
175 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
176 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
177 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
179 if (basefile.IsEmpty())
181 com.Replace(_T("/base:%base"), _T(""));
182 com.Replace(_T("%base"), _T(""));
184 else
185 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
186 if (theirfile.IsEmpty())
188 com.Replace(_T("/theirs:%theirs"), _T(""));
189 com.Replace(_T("%theirs"), _T(""));
191 else
192 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
193 if (yourfile.IsEmpty())
195 com.Replace(_T("/mine:%mine"), _T(""));
196 com.Replace(_T("%mine"), _T(""));
198 else
199 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
200 if (mergedfile.IsEmpty())
202 com.Replace(_T("/merged:%merged"), _T(""));
203 com.Replace(_T("%merged"), _T(""));
205 else
206 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
207 if (basename.IsEmpty())
209 if (basefile.IsEmpty())
211 com.Replace(_T("/basename:%bname"), _T(""));
212 com.Replace(_T("%bname"), _T(""));
214 else
216 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
219 else
220 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
221 if (theirname.IsEmpty())
223 if (theirfile.IsEmpty())
225 com.Replace(_T("/theirsname:%tname"), _T(""));
226 com.Replace(_T("%tname"), _T(""));
228 else
230 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
233 else
234 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
235 if (yourname.IsEmpty())
237 if (yourfile.IsEmpty())
239 com.Replace(_T("/minename:%yname"), _T(""));
240 com.Replace(_T("%yname"), _T(""));
242 else
244 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
247 else
248 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
249 if (mergedname.IsEmpty())
251 if (mergedfile.IsEmpty())
253 com.Replace(_T("/mergedname:%mname"), _T(""));
254 com.Replace(_T("%mname"), _T(""));
256 else
258 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
261 else
262 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
264 if ((bReadOnly)&&(bInternal))
265 com += _T(" /readonly");
267 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
269 return FALSE;
272 return TRUE;
275 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
277 CString viewer;
278 // use TortoiseMerge
279 viewer = CPathUtils::GetAppDirectory();
280 viewer += _T("TortoiseMerge.exe");
282 viewer = _T("\"") + viewer + _T("\"");
283 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
284 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
285 if (bReversed)
286 viewer += _T(" /reversedpatch");
287 if (!sOriginalDescription.IsEmpty())
288 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
289 if (!sPatchedDescription.IsEmpty())
290 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
291 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
293 return FALSE;
295 return TRUE;
298 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
300 // Is there a mime type specific diff tool?
301 CString mimetype;
302 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
304 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
305 if (!difftool.IsEmpty())
306 return difftool;
309 // Is there an extension specific diff tool?
310 CString ext = file2.GetFileExtension().MakeLower();
311 if (!ext.IsEmpty())
313 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
314 if (!difftool.IsEmpty())
315 return difftool;
316 // Maybe we should use TortoiseIDiff?
317 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
318 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
319 (ext == _T(".png")) || (ext == _T(".ico")) ||
320 (ext == _T(".dib")) || (ext == _T(".emf")))
322 return
323 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
324 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
328 // Finally, pick a generic external diff tool
329 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
330 return difftool;
333 bool CAppUtils::StartExtDiff(
334 const CString& file1, const CString& file2,
335 const CString& sName1, const CString& sName2,
336 const DiffFlags& flags)
338 CString viewer;
340 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
341 if (!flags.bBlame || !(DWORD)blamediff)
343 viewer = PickDiffTool(file1, file2);
344 // If registry entry for a diff program is commented out, use TortoiseMerge.
345 bool bCommentedOut = viewer.Left(1) == _T("#");
346 if (flags.bAlternativeTool)
348 // Invert external vs. internal diff tool selection.
349 if (bCommentedOut)
350 viewer.Delete(0); // uncomment
351 else
352 viewer = "";
354 else if (bCommentedOut)
355 viewer = "";
358 bool bInternal = viewer.IsEmpty();
359 if (bInternal)
361 viewer =
362 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
363 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
364 if (flags.bBlame)
365 viewer += _T(" /blame");
367 // check if the params are set. If not, just add the files to the command line
368 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
370 viewer += _T(" \"")+file1+_T("\"");
371 viewer += _T(" \"")+file2+_T("\"");
373 if (viewer.Find(_T("%base")) >= 0)
375 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
377 if (viewer.Find(_T("%mine")) >= 0)
379 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
382 if (sName1.IsEmpty())
383 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
384 else
385 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
387 if (sName2.IsEmpty())
388 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
389 else
390 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
392 if (flags.bReadOnly && bInternal)
393 viewer += _T(" /readonly");
395 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
398 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
400 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
401 CString viewer = diffpropsexe;
402 bool bInternal = false;
403 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
405 //no registry entry (or commented out) for a diff program
406 //use TortoiseMerge
407 bInternal = true;
408 viewer = CPathUtils::GetAppDirectory();
409 viewer += _T("TortoiseMerge.exe");
410 viewer = _T("\"") + viewer + _T("\"");
411 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
413 // check if the params are set. If not, just add the files to the command line
414 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
416 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
417 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
419 if (viewer.Find(_T("%base")) >= 0)
421 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
423 if (viewer.Find(_T("%mine")) >= 0)
425 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
428 if (sName1.IsEmpty())
429 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
430 else
431 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
433 if (sName2.IsEmpty())
434 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
435 else
436 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
438 if ((bReadOnly)&&(bInternal))
439 viewer += _T(" /readonly");
441 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
443 return FALSE;
445 return TRUE;
448 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
450 CString viewer;
451 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
452 viewer = v;
453 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
455 // use TortoiseUDiff
456 viewer = CPathUtils::GetAppDirectory();
457 viewer += _T("TortoiseUDiff.exe");
458 // enquote the path to TortoiseUDiff
459 viewer = _T("\"") + viewer + _T("\"");
460 // add the params
461 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
464 if (viewer.Find(_T("%1"))>=0)
466 if (viewer.Find(_T("\"%1\"")) >= 0)
467 viewer.Replace(_T("%1"), patchfile);
468 else
469 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
471 else
472 viewer += _T(" \"") + patchfile + _T("\"");
473 if (viewer.Find(_T("%title")) >= 0)
475 viewer.Replace(_T("%title"), title);
478 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
480 return FALSE;
482 return TRUE;
485 BOOL CAppUtils::StartTextViewer(CString file)
487 CString viewer;
488 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
489 viewer = txt;
490 viewer = viewer + _T("\\Shell\\Open\\Command\\");
491 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
492 viewer = txtexe;
494 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
495 TCHAR * buf = new TCHAR[len+1];
496 ExpandEnvironmentStrings(viewer, buf, len);
497 viewer = buf;
498 delete [] buf;
499 len = ExpandEnvironmentStrings(file, NULL, 0);
500 buf = new TCHAR[len+1];
501 ExpandEnvironmentStrings(file, buf, len);
502 file = buf;
503 delete [] buf;
504 file = _T("\"")+file+_T("\"");
505 if (viewer.IsEmpty())
507 OPENFILENAME ofn = {0}; // common dialog box structure
508 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
509 // Initialize OPENFILENAME
510 ofn.lStructSize = sizeof(OPENFILENAME);
511 ofn.hwndOwner = NULL;
512 ofn.lpstrFile = szFile;
513 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
514 CString sFilter;
515 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
516 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
517 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
518 // Replace '|' delimiters with '\0's
519 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
520 while (ptr != pszFilters)
522 if (*ptr == '|')
523 *ptr = '\0';
524 ptr--;
526 ofn.lpstrFilter = pszFilters;
527 ofn.nFilterIndex = 1;
528 ofn.lpstrFileTitle = NULL;
529 ofn.nMaxFileTitle = 0;
530 ofn.lpstrInitialDir = NULL;
531 CString temp;
532 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
533 CStringUtils::RemoveAccelerators(temp);
534 ofn.lpstrTitle = temp;
535 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
537 // Display the Open dialog box.
539 if (GetOpenFileName(&ofn)==TRUE)
541 delete [] pszFilters;
542 viewer = CString(ofn.lpstrFile);
544 else
546 delete [] pszFilters;
547 return FALSE;
550 if (viewer.Find(_T("\"%1\"")) >= 0)
552 viewer.Replace(_T("\"%1\""), file);
554 else if (viewer.Find(_T("%1")) >= 0)
556 viewer.Replace(_T("%1"), file);
558 else
560 viewer += _T(" ");
561 viewer += file;
564 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
566 return FALSE;
568 return TRUE;
571 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
573 DWORD length = 0;
574 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
575 if (hFile == INVALID_HANDLE_VALUE)
576 return TRUE;
577 length = ::GetFileSize(hFile, NULL);
578 ::CloseHandle(hFile);
579 if (length < 4)
580 return TRUE;
581 return FALSE;
585 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
587 LOGFONT logFont;
588 HDC hScreenDC = ::GetDC(NULL);
589 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
590 ::ReleaseDC(NULL, hScreenDC);
591 logFont.lfWidth = 0;
592 logFont.lfEscapement = 0;
593 logFont.lfOrientation = 0;
594 logFont.lfWeight = FW_NORMAL;
595 logFont.lfItalic = 0;
596 logFont.lfUnderline = 0;
597 logFont.lfStrikeOut = 0;
598 logFont.lfCharSet = DEFAULT_CHARSET;
599 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
600 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
601 logFont.lfQuality = DRAFT_QUALITY;
602 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
603 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
604 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
607 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
609 STARTUPINFO startup;
610 PROCESS_INFORMATION process;
611 memset(&startup, 0, sizeof(startup));
612 startup.cb = sizeof(startup);
613 memset(&process, 0, sizeof(process));
615 CString cleanCommandLine(sCommandLine);
617 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
619 if(idErrMessageFormat != 0)
621 LPVOID lpMsgBuf;
622 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
623 FORMAT_MESSAGE_FROM_SYSTEM |
624 FORMAT_MESSAGE_IGNORE_INSERTS,
625 NULL,
626 GetLastError(),
627 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
628 (LPTSTR) &lpMsgBuf,
630 NULL
632 CString temp;
633 temp.Format(idErrMessageFormat, lpMsgBuf);
634 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
635 LocalFree( lpMsgBuf );
637 return false;
640 if (bWaitForStartup)
642 WaitForInputIdle(process.hProcess, 10000);
645 CloseHandle(process.hThread);
646 CloseHandle(process.hProcess);
647 return true;
649 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
651 CString key,remote;
652 CString cmd,out;
653 if( pRemote == NULL)
655 remote=_T("origin");
656 }else
658 remote=*pRemote;
660 if(keyfile == NULL)
662 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
663 g_Git.Run(cmd,&key,CP_ACP);
664 int start=0;
665 key = key.Tokenize(_T("\n"),start);
667 else
668 key=*keyfile;
670 if(key.IsEmpty())
671 return false;
673 CString proc=CPathUtils::GetAppDirectory();
674 proc += _T("pageant.exe \"");
675 proc += key;
676 proc += _T("\"");
678 return LaunchApplication(proc, IDS_ERR_PAGEANT, false);
680 bool CAppUtils::LaunchRemoteSetting()
682 CString proc=CPathUtils::GetAppDirectory();
683 proc += _T("TortoiseProc.exe /command:settings");
684 proc += _T(" /path:\"");
685 proc += g_Git.m_CurrentDir;
686 proc += _T("\" /page:gitremote");
687 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
690 * Launch the external blame viewer
692 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
694 CString viewer = CPathUtils::GetAppDirectory();
695 viewer += _T("TortoiseGitBlame.exe");
696 viewer += _T(" \"") + sBlameFile + _T("\"");
697 //viewer += _T(" \"") + sLogFile + _T("\"");
698 //viewer += _T(" \"") + sOriginalFile + _T("\"");
699 if(!Rev.IsEmpty())
700 viewer += CString(_T(" /rev:"))+Rev;
701 viewer += _T(" ")+sParams;
703 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
706 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
708 CString sText;
709 if (pWnd == NULL)
710 return false;
711 bool bStyled = false;
712 pWnd->GetWindowText(sText);
713 // the rich edit control doesn't count the CR char!
714 // to be exact: CRLF is treated as one char.
715 sText.Replace(_T("\r"), _T(""));
717 // style each line separately
718 int offset = 0;
719 int nNewlinePos;
722 nNewlinePos = sText.Find('\n', offset);
723 CString sLine = sText.Mid(offset);
724 if (nNewlinePos>=0)
725 sLine = sLine.Left(nNewlinePos-offset);
726 int start = 0;
727 int end = 0;
728 while (FindStyleChars(sLine, '*', start, end))
730 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
731 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
732 CHARFORMAT2 format;
733 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
734 format.cbSize = sizeof(CHARFORMAT2);
735 format.dwMask = CFM_BOLD;
736 format.dwEffects = CFE_BOLD;
737 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
738 bStyled = true;
739 start = end;
741 start = 0;
742 end = 0;
743 while (FindStyleChars(sLine, '^', start, end))
745 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
746 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
747 CHARFORMAT2 format;
748 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
749 format.cbSize = sizeof(CHARFORMAT2);
750 format.dwMask = CFM_ITALIC;
751 format.dwEffects = CFE_ITALIC;
752 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
753 bStyled = true;
754 start = end;
756 start = 0;
757 end = 0;
758 while (FindStyleChars(sLine, '_', start, end))
760 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
761 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
762 CHARFORMAT2 format;
763 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
764 format.cbSize = sizeof(CHARFORMAT2);
765 format.dwMask = CFM_UNDERLINE;
766 format.dwEffects = CFE_UNDERLINE;
767 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
768 bStyled = true;
769 start = end;
771 offset = nNewlinePos+1;
772 } while(nNewlinePos>=0);
773 return bStyled;
776 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
778 int i=start;
779 bool bFoundMarker = false;
780 // find a starting marker
781 while (sText[i] != 0)
783 if (sText[i] == stylechar)
785 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
786 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
788 start = i+1;
789 i++;
790 bFoundMarker = true;
791 break;
794 i++;
796 if (!bFoundMarker)
797 return false;
798 // find ending marker
799 bFoundMarker = false;
800 while (sText[i] != 0)
802 if (sText[i] == stylechar)
804 if ((IsCharAlphaNumeric(sText[i-1])) &&
805 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
807 end = i;
808 i++;
809 bFoundMarker = true;
810 break;
813 i++;
815 return bFoundMarker;
818 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
820 #if 0
821 CString strUrl;
822 combo.GetWindowText(strUrl);
823 strUrl.Replace('\\', '/');
824 strUrl.Replace(_T("%"), _T("%25"));
825 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
826 if (strUrl.Left(7) == _T("file://"))
828 CString strFile(strUrl);
829 Git::UrlToPath(strFile);
831 Git svn;
832 if (svn.IsRepository(CTGitPath(strFile)))
834 // browse repository - show repository browser
835 Git::preparePath(strUrl);
836 CRepositoryBrowser browser(strUrl, rev, pParent);
837 if (browser.DoModal() == IDOK)
839 combo.SetCurSel(-1);
840 combo.SetWindowText(browser.GetPath());
841 rev = browser.GetRevision();
842 return true;
845 else
847 // browse local directories
848 CBrowseFolder folderBrowser;
849 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
850 // remove the 'file:///' so the shell can recognize the local path
851 Git::UrlToPath(strUrl);
852 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
854 Git::PathToUrl(strUrl);
856 combo.SetCurSel(-1);
857 combo.SetWindowText(strUrl);
858 return true;
862 else if ((strUrl.Left(7) == _T("http://")
863 ||(strUrl.Left(8) == _T("https://"))
864 ||(strUrl.Left(6) == _T("svn://"))
865 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
867 // browse repository - show repository browser
868 CRepositoryBrowser browser(strUrl, rev, pParent);
869 if (browser.DoModal() == IDOK)
871 combo.SetCurSel(-1);
872 combo.SetWindowText(browser.GetPath());
873 rev = browser.GetRevision();
874 return true;
877 else
879 // browse local directories
880 CBrowseFolder folderBrowser;
881 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
882 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
884 Git::PathToUrl(strUrl);
886 combo.SetCurSel(-1);
887 combo.SetWindowText(strUrl);
888 return true;
891 #endif
892 return false;
895 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
897 OPENFILENAME ofn = {0}; // common dialog box structure
898 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
899 ofn.lStructSize = sizeof(OPENFILENAME);
900 ofn.hwndOwner = hwndOwner;
901 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
902 ofn.lpstrFile = szFile;
903 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
904 CString sFilter;
905 TCHAR * pszFilters = NULL;
906 if (filter)
908 sFilter.LoadString(filter);
909 pszFilters = new TCHAR[sFilter.GetLength()+4];
910 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
911 // Replace '|' delimiters with '\0's
912 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
913 while (ptr != pszFilters)
915 if (*ptr == '|')
916 *ptr = '\0';
917 ptr--;
919 ofn.lpstrFilter = pszFilters;
921 ofn.nFilterIndex = 1;
922 ofn.lpstrFileTitle = NULL;
923 ofn.nMaxFileTitle = 0;
924 ofn.lpstrInitialDir = NULL;
925 CString temp;
926 if (title)
928 temp.LoadString(title);
929 CStringUtils::RemoveAccelerators(temp);
931 ofn.lpstrTitle = temp;
932 if (bOpen)
933 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
934 else
935 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
938 // Display the Open dialog box.
939 bool bRet = false;
940 if (bOpen)
942 bRet = !!GetOpenFileName(&ofn);
944 else
946 bRet = !!GetSaveFileName(&ofn);
948 if (bRet)
950 if (pszFilters)
951 delete [] pszFilters;
952 path = CString(ofn.lpstrFile);
953 if (filterindex)
954 *filterindex = ofn.nFilterIndex;
955 return true;
957 if (pszFilters)
958 delete [] pszFilters;
959 return false;
962 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
964 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
965 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
966 // create a bitmap from the icon
967 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
968 if (!hIcon)
969 return false;
971 RECT rect = {0};
972 rect.right = width;
973 rect.bottom = height;
974 HBITMAP bmp = NULL;
976 HWND desktop = ::GetDesktopWindow();
977 if (desktop)
979 HDC screen_dev = ::GetDC(desktop);
980 if (screen_dev)
982 // Create a compatible DC
983 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
984 if (dst_hdc)
986 // Create a new bitmap of icon size
987 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
988 if (bmp)
990 // Select it into the compatible DC
991 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
992 // Fill the background of the compatible DC with the given color
993 ::SetBkColor(dst_hdc, bkColor);
994 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
996 // Draw the icon into the compatible DC
997 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
998 ::SelectObject(dst_hdc, old_dst_bmp);
1000 ::DeleteDC(dst_hdc);
1003 ::ReleaseDC(desktop, screen_dev);
1006 // Restore settings
1007 DestroyIcon(hIcon);
1009 if (bmp == NULL)
1010 return false;
1012 LVBKIMAGE lv;
1013 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1014 lv.hbm = bmp;
1015 lv.xOffsetPercent = 100;
1016 lv.yOffsetPercent = 100;
1017 ListView_SetBkImage(hListCtrl, &lv);
1018 return true;
1021 CString CAppUtils::GetProjectNameFromURL(CString url)
1023 CString name;
1024 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1025 (name.CompareNoCase(_T("tags"))==0) ||
1026 (name.CompareNoCase(_T("trunk"))==0))
1028 name = url.Mid(url.ReverseFind('/')+1);
1029 url = url.Left(url.ReverseFind('/'));
1031 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1033 // a name of svn or svnroot indicates that it's not really the project name. In that
1034 // case, we try the first part of the URL
1035 // of course, this won't work in all cases (but it works for Google project hosting)
1036 url.Replace(_T("http://"), _T(""));
1037 url.Replace(_T("https://"), _T(""));
1038 url.Replace(_T("svn://"), _T(""));
1039 url.Replace(_T("svn+ssh://"), _T(""));
1040 url.TrimLeft(_T("/"));
1041 name = url.Left(url.Find('.'));
1043 return name;
1046 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1047 const CTGitPath& url2, const git_revnum_t& rev2,
1048 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1049 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1052 CString tempfile=GetTempFile();
1053 CString cmd;
1054 if(rev1 == GitRev::GetWorkingCopy())
1056 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1057 }else
1059 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1062 if( !url1.IsEmpty() )
1064 cmd+=_T(" \"");
1065 cmd+=url1.GetGitPathString();
1066 cmd+=_T("\" ");
1068 g_Git.RunLogFile(cmd,tempfile);
1069 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1072 #if 0
1073 CString sCmd;
1074 sCmd.Format(_T("%s /command:showcompare /unified"),
1075 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1076 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1077 if (rev1.IsValid())
1078 sCmd += _T(" /revision1:") + rev1.ToString();
1079 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1080 if (rev2.IsValid())
1081 sCmd += _T(" /revision2:") + rev2.ToString();
1082 if (peg.IsValid())
1083 sCmd += _T(" /pegrevision:") + peg.ToString();
1084 if (headpeg.IsValid())
1085 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1087 if (bAlternateDiff)
1088 sCmd += _T(" /alternatediff");
1090 if (bIgnoreAncestry)
1091 sCmd += _T(" /ignoreancestry");
1093 if (hWnd)
1095 sCmd += _T(" /hwnd:");
1096 TCHAR buf[30];
1097 _stprintf_s(buf, 30, _T("%d"), hWnd);
1098 sCmd += buf;
1101 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1102 #endif
1103 return TRUE;
1106 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1107 const CTGitPath& url2, const GitRev& rev2,
1108 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1109 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1111 #if 0
1112 CString sCmd;
1113 sCmd.Format(_T("%s /command:showcompare"),
1114 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1115 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1116 if (rev1.IsValid())
1117 sCmd += _T(" /revision1:") + rev1.ToString();
1118 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1119 if (rev2.IsValid())
1120 sCmd += _T(" /revision2:") + rev2.ToString();
1121 if (peg.IsValid())
1122 sCmd += _T(" /pegrevision:") + peg.ToString();
1123 if (headpeg.IsValid())
1124 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1125 if (bAlternateDiff)
1126 sCmd += _T(" /alternatediff");
1127 if (bIgnoreAncestry)
1128 sCmd += _T(" /ignoreancestry");
1129 if (blame)
1130 sCmd += _T(" /blame");
1132 if (hWnd)
1134 sCmd += _T(" /hwnd:");
1135 TCHAR buf[30];
1136 _stprintf_s(buf, 30, _T("%d"), hWnd);
1137 sCmd += buf;
1140 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1141 #endif
1142 return true;
1145 bool CAppUtils::Export(CString *BashHash)
1147 bool bRet = false;
1149 // ask from where the export has to be done
1150 CExportDlg dlg;
1151 if(BashHash)
1152 dlg.m_Revision=*BashHash;
1154 if (dlg.DoModal() == IDOK)
1156 CString cmd;
1157 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1158 dlg.m_VersionName);
1160 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1161 CProgressDlg pro;
1162 pro.m_GitCmd=cmd;
1163 pro.m_LogFile=dlg.m_strExportDirectory;
1164 pro.DoModal();
1165 return TRUE;
1167 return bRet;
1170 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1172 CCreateBranchTagDlg dlg;
1173 dlg.m_bIsTag=IsTag;
1174 if(CommitHash)
1175 dlg.m_Base = *CommitHash;
1177 if(dlg.DoModal()==IDOK)
1179 CString cmd;
1180 CString force;
1181 CString track;
1182 if(dlg.m_bTrack)
1183 track=_T(" --track ");
1185 if(dlg.m_bForce)
1186 force=_T(" -f ");
1188 if(IsTag)
1190 cmd.Format(_T("git.exe tag %s %s %s %s"),
1191 track,
1192 force,
1193 dlg.m_BranchTagName,
1194 dlg.m_VersionName
1197 CString tempfile=::GetTempFile();
1198 if(!dlg.m_Message.Trim().IsEmpty())
1200 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1201 cmd += _T(" -F ")+tempfile;
1204 }else
1206 cmd.Format(_T("git.exe branch %s %s %s %s"),
1207 track,
1208 force,
1209 dlg.m_BranchTagName,
1210 dlg.m_VersionName
1213 CString out;
1214 if(g_Git.Run(cmd,&out,CP_UTF8))
1216 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1218 if( !IsTag && dlg.m_bSwitch )
1220 // it is a new branch and the user has requested to switch to it
1221 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1222 g_Git.Run(cmd,&out,CP_UTF8);
1223 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1226 return TRUE;
1229 return FALSE;
1232 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1234 CGitSwitchDlg dlg;
1235 if(CommitHash)
1236 dlg.m_Base=*CommitHash;
1237 if(!initialRefName.IsEmpty())
1238 dlg.m_initialRefName = initialRefName;
1240 if (dlg.DoModal() == IDOK)
1242 CString cmd;
1243 CString track;
1244 // CString base;
1245 CString force;
1246 CString branch;
1248 if(dlg.m_bBranch)
1249 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1250 if(dlg.m_bForce)
1251 force=_T("-f");
1252 if(dlg.m_bTrack)
1253 track=_T("--track");
1255 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1256 force,
1257 track,
1258 branch,
1259 dlg.m_VersionName);
1261 CProgressDlg progress;
1262 progress.m_GitCmd=cmd;
1263 if(progress.DoModal()==IDOK)
1264 return TRUE;
1267 return FALSE;
1270 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1272 CString ignorefile;
1273 ignorefile=g_Git.m_CurrentDir+_T("\\");
1275 if(IsMask)
1277 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1279 }else
1281 ignorefile+=_T("\\.gitignore");
1284 CStdioFile file;
1285 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1287 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1288 return FALSE;
1291 CString ignorelist;
1292 CString mask;
1295 //file.ReadString(ignorelist);
1296 file.SeekToEnd();
1297 for(int i=0;i<path.GetCount();i++)
1299 if(IsMask)
1301 mask=_T("*")+path[i].GetFileExtension();
1302 if(ignorelist.Find(mask)<0)
1303 ignorelist+=_T("\n")+mask;
1305 }else
1307 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1310 file.WriteString(ignorelist);
1312 file.Close();
1314 }catch(...)
1316 file.Close();
1317 return FALSE;
1320 return TRUE;
1324 bool CAppUtils::GitReset(CString *CommitHash,int type)
1326 CResetDlg dlg;
1327 dlg.m_ResetType=type;
1328 if (dlg.DoModal() == IDOK)
1330 CString cmd;
1331 CString type;
1332 switch(dlg.m_ResetType)
1334 case 0:
1335 type=_T("--soft");
1336 break;
1337 case 1:
1338 type=_T("--mixed");
1339 break;
1340 case 2:
1341 type=_T("--hard");
1342 break;
1343 default:
1344 type=_T("--mixed");
1345 break;
1347 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1349 CProgressDlg progress;
1350 progress.m_GitCmd=cmd;
1351 if(progress.DoModal()==IDOK)
1352 return TRUE;
1355 return FALSE;
1358 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1360 if(mode == FALSE)
1362 descript=_T("Deleted");
1363 return;
1365 if(base)
1367 descript=_T("Modified");
1368 return;
1370 descript=_T("Created");
1371 return;
1374 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1376 CString tempmergefile;
1379 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1380 CFile::Remove(tempmergefile);
1381 }catch(...)
1387 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1388 CFile::Remove(tempmergefile);
1389 }catch(...)
1395 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1396 CFile::Remove(tempmergefile);
1397 }catch(...)
1401 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1403 CString file;
1404 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1406 return file;
1409 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool,bool revertTheirMy)
1411 bool bRet = false;
1413 CTGitPath merge=path;
1414 CTGitPath directory = merge.GetDirectory();
1418 // we have the conflicted file (%merged)
1419 // now look for the other required files
1420 //GitStatus stat;
1421 //stat.GetStatus(merge);
1422 //if (stat.status == NULL)
1423 // return false;
1425 BYTE_VECTOR vector;
1427 CString cmd;
1428 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1430 if(g_Git.Run(cmd,&vector))
1432 return FALSE;
1435 CTGitPathList list;
1436 list.ParserFromLsFile(vector);
1438 if(list.GetCount() == 0)
1439 return FALSE;
1441 TCHAR szTempName[512];
1442 GetTempFileName(_T(""),_T(""),0,szTempName);
1443 CString temp(szTempName);
1444 temp=temp.Mid(1,temp.GetLength()-5);
1446 CTGitPath theirs;
1447 CTGitPath mine;
1448 CTGitPath base;
1451 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1452 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1453 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1455 CString format;
1457 //format=_T("git.exe cat-file blob \":%d:%s\"");
1458 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1459 CFile tempfile;
1460 //create a empty file, incase stage is not three
1461 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1462 tempfile.Close();
1463 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1464 tempfile.Close();
1465 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1466 tempfile.Close();
1468 bool b_base=false, b_local=false, b_remote=false;
1470 for(int i=0;i<list.GetCount();i++)
1472 CString cmd;
1473 CString outfile;
1474 cmd.Empty();
1475 outfile.Empty();
1477 if( list[i].m_Stage == 1)
1479 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1480 b_base = true;
1481 outfile = base.GetWinPathString();
1484 if( list[i].m_Stage == 2 )
1486 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1487 b_local = true;
1488 outfile = mine.GetWinPathString();
1491 if( list[i].m_Stage == 3 )
1493 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1494 b_remote = true;
1495 outfile = theirs.GetWinPathString();
1497 CString output;
1498 if(!outfile.IsEmpty())
1499 if(!g_Git.Run(cmd,&output,CP_ACP))
1501 CString file;
1502 int start =0 ;
1503 file = output.Tokenize(_T("\t"), start);
1504 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1506 else
1508 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1512 if(b_local && b_remote )
1514 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1515 if( revertTheirMy )
1516 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1517 else
1518 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1520 }else
1522 CFile::Remove(mine.GetWinPathString());
1523 CFile::Remove(theirs.GetWinPathString());
1524 CFile::Remove(base.GetWinPathString());
1526 CDeleteConflictDlg dlg;
1527 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1528 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1529 dlg.m_bShowModifiedButton=b_base;
1530 dlg.m_File=merge.GetGitPathString();
1531 if(dlg.DoModal() == IDOK)
1533 CString cmd,out;
1534 if(dlg.m_bIsDelete)
1536 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1537 }else
1538 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1540 if(g_Git.Run(cmd,&out,CP_ACP))
1542 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1543 return FALSE;
1545 return TRUE;
1547 else
1548 return FALSE;
1554 #if 0
1556 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1557 base, theirs, mine, merge);
1558 #endif
1559 #if 0
1560 if (stat.status->text_status == svn_wc_status_conflicted)
1562 // we have a text conflict, use our merge tool to resolve the conflict
1564 CTSVNPath theirs(directory);
1565 CTSVNPath mine(directory);
1566 CTSVNPath base(directory);
1567 bool bConflictData = false;
1569 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1571 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1572 bConflictData = true;
1574 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1576 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1577 bConflictData = true;
1579 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1581 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1582 bConflictData = true;
1584 else
1586 mine = merge;
1588 if (bConflictData)
1589 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1590 base, theirs, mine, merge);
1593 if (stat.status->prop_status == svn_wc_status_conflicted)
1595 // we have a property conflict
1596 CTSVNPath prej(directory);
1597 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1599 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1600 // there's a problem: the prej file contains a _description_ of the conflict, and
1601 // that description string might be translated. That means we have no way of parsing
1602 // the file to find out the conflicting values.
1603 // The only thing we can do: show a dialog with the conflict description, then
1604 // let the user either accept the existing property or open the property edit dialog
1605 // to manually change the properties and values. And a button to mark the conflict as
1606 // resolved.
1607 CEditPropConflictDlg dlg;
1608 dlg.SetPrejFile(prej);
1609 dlg.SetConflictedItem(merge);
1610 bRet = (dlg.DoModal() != IDCANCEL);
1614 if (stat.status->tree_conflict)
1616 // we have a tree conflict
1617 SVNInfo info;
1618 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1619 if (pInfoData)
1621 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1623 CTSVNPath theirs(directory);
1624 CTSVNPath mine(directory);
1625 CTSVNPath base(directory);
1626 bool bConflictData = false;
1628 if (pInfoData->treeconflict_theirfile)
1630 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1631 bConflictData = true;
1633 if (pInfoData->treeconflict_basefile)
1635 base.AppendPathString(pInfoData->treeconflict_basefile);
1636 bConflictData = true;
1638 if (pInfoData->treeconflict_myfile)
1640 mine.AppendPathString(pInfoData->treeconflict_myfile);
1641 bConflictData = true;
1643 else
1645 mine = merge;
1647 if (bConflictData)
1648 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1649 base, theirs, mine, merge);
1651 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1653 CString sConflictAction;
1654 CString sConflictReason;
1655 CString sResolveTheirs;
1656 CString sResolveMine;
1657 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1658 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1660 if (pInfoData->treeconflict_nodekind == svn_node_file)
1662 switch (pInfoData->treeconflict_operation)
1664 case svn_wc_operation_update:
1665 switch (pInfoData->treeconflict_action)
1667 case svn_wc_conflict_action_edit:
1668 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1669 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1670 break;
1671 case svn_wc_conflict_action_add:
1672 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1673 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1674 break;
1675 case svn_wc_conflict_action_delete:
1676 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1677 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1678 break;
1680 break;
1681 case svn_wc_operation_switch:
1682 switch (pInfoData->treeconflict_action)
1684 case svn_wc_conflict_action_edit:
1685 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1686 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1687 break;
1688 case svn_wc_conflict_action_add:
1689 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1690 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1691 break;
1692 case svn_wc_conflict_action_delete:
1693 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1694 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1695 break;
1697 break;
1698 case svn_wc_operation_merge:
1699 switch (pInfoData->treeconflict_action)
1701 case svn_wc_conflict_action_edit:
1702 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1703 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1704 break;
1705 case svn_wc_conflict_action_add:
1706 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1707 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1708 break;
1709 case svn_wc_conflict_action_delete:
1710 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1711 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1712 break;
1714 break;
1717 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1719 switch (pInfoData->treeconflict_operation)
1721 case svn_wc_operation_update:
1722 switch (pInfoData->treeconflict_action)
1724 case svn_wc_conflict_action_edit:
1725 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1726 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1727 break;
1728 case svn_wc_conflict_action_add:
1729 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1730 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1731 break;
1732 case svn_wc_conflict_action_delete:
1733 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1734 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1735 break;
1737 break;
1738 case svn_wc_operation_switch:
1739 switch (pInfoData->treeconflict_action)
1741 case svn_wc_conflict_action_edit:
1742 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1743 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1744 break;
1745 case svn_wc_conflict_action_add:
1746 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1747 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1748 break;
1749 case svn_wc_conflict_action_delete:
1750 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1751 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1752 break;
1754 break;
1755 case svn_wc_operation_merge:
1756 switch (pInfoData->treeconflict_action)
1758 case svn_wc_conflict_action_edit:
1759 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1760 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1761 break;
1762 case svn_wc_conflict_action_add:
1763 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1764 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1765 break;
1766 case svn_wc_conflict_action_delete:
1767 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1768 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1769 break;
1771 break;
1775 UINT uReasonID = 0;
1776 switch (pInfoData->treeconflict_reason)
1778 case svn_wc_conflict_reason_edited:
1779 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1780 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1781 break;
1782 case svn_wc_conflict_reason_obstructed:
1783 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1784 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1785 break;
1786 case svn_wc_conflict_reason_deleted:
1787 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1788 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1789 break;
1790 case svn_wc_conflict_reason_added:
1791 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1792 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1793 break;
1794 case svn_wc_conflict_reason_missing:
1795 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1796 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1797 break;
1798 case svn_wc_conflict_reason_unversioned:
1799 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1800 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1801 break;
1803 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1805 CTreeConflictEditorDlg dlg;
1806 dlg.SetConflictInfoText(sConflictReason);
1807 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1808 dlg.SetPath(treeConflictPath);
1809 INT_PTR dlgRet = dlg.DoModal();
1810 bRet = (dlgRet != IDCANCEL);
1814 #endif
1815 return bRet;
1819 * FUNCTION : FormatDateAndTime
1820 * DESCRIPTION : Generates a displayable string from a CTime object in
1821 * system short or long format or as a relative value
1822 * cTime - the time
1823 * option - DATE_SHORTDATE or DATE_LONGDATE
1824 * bIncluedeTime - whether to show time as well as date
1825 * bRelative - if true then relative time is shown if reasonable
1826 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1827 * rather than locale
1828 * RETURN : CString containing date/time
1830 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1831 bool bRelative /*=false*/)
1833 CString datetime;
1834 if ( bRelative )
1836 datetime = ToRelativeTimeString( cTime );
1838 else
1840 // should we use the locale settings for formatting the date/time?
1841 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1843 // yes
1844 SYSTEMTIME sysTime;
1845 cTime.GetAsSystemTime( sysTime );
1847 TCHAR buf[100];
1849 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1850 sizeof(buf)/sizeof(TCHAR)-1);
1851 datetime = buf;
1852 if ( bIncludeTime )
1854 datetime += _T(" ");
1855 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1856 datetime += buf;
1859 else
1861 // no, so fixed format
1862 if ( bIncludeTime )
1864 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1866 else
1868 datetime = cTime.Format(_T("%Y-%m-%d"));
1872 return datetime;
1876 * Converts a given time to a relative display string (relative to current time)
1877 * Given time must be in local timezone
1879 CString CAppUtils::ToRelativeTimeString(CTime time)
1881 CString answer;
1882 // convert to COleDateTime
1883 SYSTEMTIME sysTime;
1884 time.GetAsSystemTime( sysTime );
1885 COleDateTime oleTime( sysTime );
1886 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1887 return answer;
1891 * Generates a display string showing the relative time between the two given times as COleDateTimes
1893 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1895 CString answer;
1896 COleDateTimeSpan ts = RelativeTo - time;
1897 //years
1898 if(fabs(ts.GetTotalDays()) >= 3*365)
1900 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1902 //Months
1903 if(fabs(ts.GetTotalDays()) >= 60)
1905 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1906 return answer;
1908 //Weeks
1909 if(fabs(ts.GetTotalDays()) >= 14)
1911 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1912 return answer;
1914 //Days
1915 if(fabs(ts.GetTotalDays()) >= 2)
1917 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1918 return answer;
1920 //hours
1921 if(fabs(ts.GetTotalHours()) >= 2)
1923 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1924 return answer;
1926 //minutes
1927 if(fabs(ts.GetTotalMinutes()) >= 2)
1929 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1930 return answer;
1932 //seconds
1933 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1934 return answer;
1937 /**
1938 * Passed a value and two resource string ids
1939 * if count is 1 then FormatString is called with format_1 and the value
1940 * otherwise format_2 is used
1941 * the formatted string is returned
1943 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1945 CString answer;
1946 if ( count == 1 )
1948 answer.FormatMessage( format_1, count );
1950 else
1952 answer.FormatMessage( format_n, count );
1954 return answer;
1957 bool CAppUtils::IsSSHPutty()
1959 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1960 sshclient=sshclient.MakeLower();
1961 if(sshclient.Find(_T("plink.exe"),0)>=0)
1963 return true;
1965 return false;
1968 CString CAppUtils::GetClipboardLink()
1970 if (!OpenClipboard(NULL))
1971 return CString();
1973 CString sClipboardText;
1974 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1975 if (hglb)
1977 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1978 sClipboardText = CString(lpstr);
1979 GlobalUnlock(hglb);
1981 hglb = GetClipboardData(CF_UNICODETEXT);
1982 if (hglb)
1984 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1985 sClipboardText = lpstr;
1986 GlobalUnlock(hglb);
1988 CloseClipboard();
1990 if(!sClipboardText.IsEmpty())
1992 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1993 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1995 if(sClipboardText.Find( _T("http://")) == 0)
1996 return sClipboardText;
1998 if(sClipboardText.Find( _T("https://")) == 0)
1999 return sClipboardText;
2001 if(sClipboardText.Find( _T("git://")) == 0)
2002 return sClipboardText;
2004 if(sClipboardText.Find( _T("ssh://")) == 0)
2005 return sClipboardText;
2007 if(sClipboardText.GetLength()>=2)
2008 if( sClipboardText[1] == _T(':') )
2009 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2010 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2011 return sClipboardText;
2014 return CString(_T(""));
2017 CString CAppUtils::ChooseRepository(CString *path)
2019 CBrowseFolder browseFolder;
2020 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2022 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2023 CString strCloneDirectory;
2024 if(path)
2025 strCloneDirectory=*path;
2026 else
2028 strCloneDirectory = regLastResopitory;
2031 CString title;
2032 title.LoadString(IDS_CHOOSE_REPOSITORY);
2034 browseFolder.SetInfo(title);
2036 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2038 regLastResopitory = strCloneDirectory;
2039 return strCloneDirectory;
2041 }else
2043 return CString();
2048 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2050 CSendMailDlg dlg;
2052 dlg.m_PathList = list;
2054 if(dlg.DoModal()==IDOK)
2056 if(dlg.m_PathList.GetCount() == 0)
2057 return FALSE;
2059 CGitProgressDlg progDlg;
2061 theApp.m_pMainWnd = &progDlg;
2062 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2064 progDlg.SetAutoClose(autoclose);
2066 progDlg.SetPathList(dlg.m_PathList);
2067 //ProjectProperties props;
2068 //props.ReadPropsPathList(dlg.m_pathList);
2069 //progDlg.SetProjectProperties(props);
2070 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2072 DWORD flags =0;
2073 if(dlg.m_bAttachment)
2074 flags |= SENDMAIL_ATTACHMENT;
2075 if(dlg.m_bCombine)
2076 flags |= SENDMAIL_COMBINED;
2078 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2080 progDlg.DoModal();
2082 return true;
2084 return false;
2087 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2089 CTGitPathList list;
2090 CString log=formatpatchoutput;
2091 int start=log.Find(cmd);
2092 if(start >=0)
2093 CString one=log.Tokenize(_T("\n"),start);
2094 else
2095 start = 0;
2097 while(start>=0)
2099 CString one=log.Tokenize(_T("\n"),start);
2100 one=one.Trim();
2101 if(one.IsEmpty())
2102 continue;
2103 one.Replace(_T('/'),_T('\\'));
2104 CTGitPath path;
2105 path.SetFromWin(one);
2106 list.AddPath(path);
2108 return SendPatchMail(list,autoclose);
2112 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2114 CString cmd,output;
2115 int start=0;
2116 cmd=_T("git.exe config i18n.logOutputEncoding");
2117 if(pGit->Run(cmd,&output,CP_ACP))
2119 cmd=_T("git.exe config i18n.commitencoding");
2120 if(pGit->Run(cmd,&output,CP_ACP))
2121 return CP_UTF8;
2123 int start=0;
2124 output=output.Tokenize(_T("\n"),start);
2125 return CUnicodeUtils::GetCPCode(output);
2127 }else
2129 output=output.Tokenize(_T("\n"),start);
2130 return CUnicodeUtils::GetCPCode(output);
2133 int CAppUtils::GetCommitTemplate(CString &temp)
2135 CString cmd,output;
2136 cmd = _T("git.exe config commit.template");
2137 if( g_Git.Run(cmd,&output,CP_ACP) )
2138 return -1;
2140 if( output.GetLength()<1)
2141 return -1;
2143 if( output[0] == _T('/'))
2145 if(output.GetLength()>=3)
2146 if(output[2] == _T('/'))
2148 output.GetBuffer()[0] = output[1];
2149 output.GetBuffer()[1] = _T(':');
2153 int start=0;
2154 output=output.Tokenize(_T("\n"),start);
2156 output.Replace(_T('/'),_T('\\'));
2160 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2161 CString str;
2162 while(file.ReadString(str))
2164 temp+=str+_T("\n");
2167 }catch(...)
2169 return -1;
2171 return 0;
2175 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2177 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2178 CString cmd,output;
2179 int cp=CP_UTF8;
2181 cmd=_T("git.exe config i18n.commitencoding");
2182 if(g_Git.Run(cmd,&output,CP_ACP))
2183 cp=CP_UTF8;
2185 int start=0;
2186 output=output.Tokenize(_T("\n"),start);
2187 cp=CUnicodeUtils::GetCPCode(output);
2189 int len=message.GetLength();
2191 char * buf;
2192 buf = new char[len*4 + 4];
2193 SecureZeroMemory(buf, (len*4 + 4));
2195 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2197 file.Write(buf,lengthIncTerminator-1);
2198 file.Close();
2199 delete buf;
2200 return 0;
2203 bool CAppUtils::Push()
2205 CPushDlg dlg;
2206 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2207 CString error;
2208 DWORD exitcode = -1;
2209 CTGitPathList list;
2210 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2211 if (CHooks::Instance().PrePush(list,exitcode, error))
2213 if (exitcode)
2215 CString temp;
2216 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2217 //ReportError(temp);
2218 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2219 return false;
2223 if(dlg.DoModal()==IDOK)
2225 // CString dir=dlg.m_Directory;
2226 // CString url=dlg.m_URL;
2227 CString cmd;
2228 CString force;
2229 CString tags;
2230 CString thin;
2232 if(dlg.m_bAutoLoad)
2234 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2237 if(dlg.m_bPack)
2238 thin=_T("--thin");
2239 if(dlg.m_bTags)
2240 tags=_T("--tags");
2241 if(dlg.m_bForce)
2242 force=_T("--force");
2244 cmd.Format(_T("git.exe push %s %s %s \"%s\" %s"),
2245 thin,tags,force,
2246 dlg.m_URL,
2247 dlg.m_BranchSourceName);
2248 if (!dlg.m_BranchRemoteName.IsEmpty())
2250 cmd += _T(":") + dlg.m_BranchRemoteName;
2253 CProgressDlg progress;
2254 progress.m_GitCmd=cmd;
2255 progress.DoModal();
2257 if(!progress.m_GitStatus)
2259 if (CHooks::Instance().PostPush(list,exitcode, error))
2261 if (exitcode)
2263 CString temp;
2264 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2265 //ReportError(temp);
2266 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2267 return false;
2271 return TRUE;
2275 return FALSE;
2278 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2280 CString strDir(szPath);
2281 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2283 strDir.AppendChar(_T('\\'));
2285 std::vector<CString> vPath;
2286 CString strTemp;
2287 bool bSuccess = false;
2289 for (int i=0;i<strDir.GetLength();++i)
2291 if (strDir.GetAt(i) != _T('\\'))
2293 strTemp.AppendChar(strDir.GetAt(i));
2295 else
2297 vPath.push_back(strTemp);
2298 strTemp.AppendChar(_T('\\'));
2302 std::vector<CString>::const_iterator vIter;
2303 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2305 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2308 return bSuccess;
2311 void CAppUtils::RemoveTrailSlash(CString &path)
2313 if(path.IsEmpty())
2314 return ;
2316 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2318 path=path.Left(path.GetLength()-1);
2319 if(path.IsEmpty())
2320 return;
2324 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2325 CTGitPathList &pathList,
2326 CTGitPathList &selectedList,
2327 BOOL bSelectFilesForCommit)
2329 bool bFailed = true;
2331 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2333 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"),
2334 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2336 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&CTGitPath(g_Git.m_CurrentDir));
2337 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2338 dlg.SetTreeWidth(220);
2339 dlg.m_DefaultPage = _T("gitconfig");
2341 dlg.DoModal();
2342 dlg.HandleRestart();
2344 }else
2345 return false;
2348 while (bFailed)
2350 bFailed = false;
2351 CCommitDlg dlg;
2352 dlg.m_sBugID = bugid;
2354 dlg.m_bWholeProject = bWholeProject;
2356 dlg.m_sLogMessage = sLogMsg;
2357 dlg.m_pathList = pathList;
2358 dlg.m_checkedPathList = selectedList;
2359 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2360 if (dlg.DoModal() == IDOK)
2362 if (dlg.m_pathList.GetCount()==0)
2363 return false;
2364 // if the user hasn't changed the list of selected items
2365 // we don't use that list. Because if we would use the list
2366 // of pre-checked items, the dialog would show different
2367 // checked items on the next startup: it would only try
2368 // to check the parent folder (which might not even show)
2369 // instead, we simply use an empty list and let the
2370 // default checking do its job.
2371 if (!dlg.m_pathList.IsEqual(pathList))
2372 selectedList = dlg.m_pathList;
2373 pathList = dlg.m_updatedPathList;
2374 sLogMsg = dlg.m_sLogMessage;
2375 bSelectFilesForCommit = true;
2377 if( dlg.m_bPushAfterCommit )
2379 switch(dlg.m_PostCmd)
2381 case GIT_POST_CMD_DCOMMIT:
2382 CAppUtils::SVNDCommit();
2383 break;
2384 default:
2385 CAppUtils::Push();
2388 // CGitProgressDlg progDlg;
2389 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2390 // if (parser.HasVal(_T("closeonend")))
2391 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2392 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2393 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2394 // progDlg.SetPathList(dlg.m_pathList);
2395 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2396 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2397 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2398 // progDlg.SetItemCount(dlg.m_itemsCount);
2399 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2400 // progDlg.DoModal();
2401 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2402 // err = (DWORD)progDlg.DidErrorsOccur();
2403 // bFailed = progDlg.DidErrorsOccur();
2404 // bRet = progDlg.DidErrorsOccur();
2405 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2406 // if (DWORD(bFailRepeat)==0)
2407 // bFailed = false; // do not repeat if the user chose not to in the settings.
2410 return true;
2414 BOOL CAppUtils::SVNDCommit()
2416 BOOL IsStash = false;
2417 if(!g_Git.CheckCleanWorkTree())
2419 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2421 CString cmd,out;
2422 cmd=_T("git.exe stash");
2423 if(g_Git.Run(cmd,&out,CP_ACP))
2425 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2426 return false;
2428 IsStash =true;
2430 }else
2432 return false;
2436 CProgressDlg progress;
2437 progress.m_GitCmd=_T("git.exe svn dcommit");
2438 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2440 if( IsStash)
2442 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2444 CString cmd,out;
2445 cmd=_T("git.exe stash pop");
2446 if(g_Git.Run(cmd,&out,CP_ACP))
2448 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2449 return false;
2452 }else
2454 return false;
2457 return TRUE;
2459 return FALSE;
2462 BOOL CAppUtils::Merge(CString *commit, int mode)
2464 CMergeDlg dlg;
2465 if(commit)
2466 dlg.m_initialRefName = *commit;
2468 if(dlg.DoModal()==IDOK)
2470 CString cmd;
2471 CString noff;
2472 CString squash;
2473 CString nocommit;
2474 CString msg;
2476 if(dlg.m_bNoFF)
2477 noff=_T("--no-ff");
2479 if(dlg.m_bSquash)
2480 squash=_T("--squash");
2482 if(dlg.m_bNoCommit)
2483 nocommit=_T("--no-commit");
2485 if(!dlg.m_strLogMesage.IsEmpty())
2487 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2489 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2490 msg,
2491 noff,
2492 squash,
2493 nocommit,
2494 dlg.m_VersionName);
2496 CProgressDlg Prodlg;
2497 Prodlg.m_GitCmd = cmd;
2499 Prodlg.DoModal();
2501 return !Prodlg.m_GitStatus;
2503 return false;
2506 void CAppUtils::EditNote(GitRev *rev)
2508 CInputDlg dlg;
2509 dlg.m_sHintText=_T("Edit Notes");
2510 dlg.m_sInputText = rev->m_Notes;
2511 dlg.m_sTitle=_T("Edit Notes");
2512 //dlg.m_pProjectProperties = &m_ProjectProperties;
2513 dlg.m_bUseLogWidth = true;
2514 if(dlg.DoModal() == IDOK)
2516 CString cmd,output;
2517 cmd=_T("notes add -f -F \"");
2519 CString tempfile=::GetTempFile();
2520 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2521 cmd+=tempfile;
2522 cmd+=_T("\" ");
2523 cmd+=rev->m_CommitHash.ToString();
2527 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2529 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2532 else
2534 rev->m_Notes = dlg.m_sInputText;
2536 }catch(...)
2538 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2540 CFile::Remove(tempfile);