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