Fixed Issue 55: "resolved" function doesn't delete temporary files.
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob86f0339e876a3365ee0c911564feeb2ad51ebec9
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"
46 CAppUtils::CAppUtils(void)
50 CAppUtils::~CAppUtils(void)
54 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
56 #if 0
57 GitProperties props(file, GitRev::REV_WC, false);
58 for (int i = 0; i < props.GetCount(); ++i)
60 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
62 mimetype = props.GetItemValue(i).c_str();
63 return true;
66 #endif
67 return false;
70 BOOL CAppUtils::StartExtMerge(
71 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
72 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
75 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
76 CString ext = mergedfile.GetFileExtension();
77 CString com = regCom;
78 bool bInternal = false;
80 CString mimetype;
81 if (ext != "")
83 // is there an extension specific merge tool?
84 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
85 if (CString(mergetool) != "")
87 com = mergetool;
90 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
92 // is there a mime type specific merge tool?
93 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
94 if (CString(mergetool) != "")
96 com = mergetool;
100 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
102 // use TortoiseMerge
103 bInternal = true;
104 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
105 com = tortoiseMergePath;
106 if (com.IsEmpty())
108 com = CPathUtils::GetAppDirectory();
109 com += _T("TortoiseMerge.exe");
111 com = _T("\"") + com + _T("\"");
112 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
113 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
115 // check if the params are set. If not, just add the files to the command line
116 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
118 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
119 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
120 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
121 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
123 if (basefile.IsEmpty())
125 com.Replace(_T("/base:%base"), _T(""));
126 com.Replace(_T("%base"), _T(""));
128 else
129 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
130 if (theirfile.IsEmpty())
132 com.Replace(_T("/theirs:%theirs"), _T(""));
133 com.Replace(_T("%theirs"), _T(""));
135 else
136 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
137 if (yourfile.IsEmpty())
139 com.Replace(_T("/mine:%mine"), _T(""));
140 com.Replace(_T("%mine"), _T(""));
142 else
143 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
144 if (mergedfile.IsEmpty())
146 com.Replace(_T("/merged:%merged"), _T(""));
147 com.Replace(_T("%merged"), _T(""));
149 else
150 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
151 if (basename.IsEmpty())
153 if (basefile.IsEmpty())
155 com.Replace(_T("/basename:%bname"), _T(""));
156 com.Replace(_T("%bname"), _T(""));
158 else
160 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
163 else
164 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
165 if (theirname.IsEmpty())
167 if (theirfile.IsEmpty())
169 com.Replace(_T("/theirsname:%tname"), _T(""));
170 com.Replace(_T("%tname"), _T(""));
172 else
174 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
177 else
178 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
179 if (yourname.IsEmpty())
181 if (yourfile.IsEmpty())
183 com.Replace(_T("/minename:%yname"), _T(""));
184 com.Replace(_T("%yname"), _T(""));
186 else
188 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
191 else
192 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
193 if (mergedname.IsEmpty())
195 if (mergedfile.IsEmpty())
197 com.Replace(_T("/mergedname:%mname"), _T(""));
198 com.Replace(_T("%mname"), _T(""));
200 else
202 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
205 else
206 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
208 if ((bReadOnly)&&(bInternal))
209 com += _T(" /readonly");
211 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
213 return FALSE;
216 return TRUE;
219 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
221 CString viewer;
222 // use TortoiseMerge
223 viewer = CPathUtils::GetAppDirectory();
224 viewer += _T("TortoiseMerge.exe");
226 viewer = _T("\"") + viewer + _T("\"");
227 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
228 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
229 if (bReversed)
230 viewer += _T(" /reversedpatch");
231 if (!sOriginalDescription.IsEmpty())
232 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
233 if (!sPatchedDescription.IsEmpty())
234 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
235 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
237 return FALSE;
239 return TRUE;
242 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
244 // Is there a mime type specific diff tool?
245 CString mimetype;
246 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
248 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
249 if (!difftool.IsEmpty())
250 return difftool;
253 // Is there an extension specific diff tool?
254 CString ext = file2.GetFileExtension().MakeLower();
255 if (!ext.IsEmpty())
257 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
258 if (!difftool.IsEmpty())
259 return difftool;
260 // Maybe we should use TortoiseIDiff?
261 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
262 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
263 (ext == _T(".png")) || (ext == _T(".ico")) ||
264 (ext == _T(".dib")) || (ext == _T(".emf")))
266 return
267 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
268 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
272 // Finally, pick a generic external diff tool
273 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
274 return difftool;
277 bool CAppUtils::StartExtDiff(
278 const CString& file1, const CString& file2,
279 const CString& sName1, const CString& sName2,
280 const DiffFlags& flags)
282 CString viewer;
284 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
285 if (!flags.bBlame || !(DWORD)blamediff)
287 viewer = PickDiffTool(file1, file2);
288 // If registry entry for a diff program is commented out, use TortoiseMerge.
289 bool bCommentedOut = viewer.Left(1) == _T("#");
290 if (flags.bAlternativeTool)
292 // Invert external vs. internal diff tool selection.
293 if (bCommentedOut)
294 viewer.Delete(0); // uncomment
295 else
296 viewer = "";
298 else if (bCommentedOut)
299 viewer = "";
302 bool bInternal = viewer.IsEmpty();
303 if (bInternal)
305 viewer =
306 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
307 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
308 if (flags.bBlame)
309 viewer += _T(" /blame");
311 // check if the params are set. If not, just add the files to the command line
312 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
314 viewer += _T(" \"")+file1+_T("\"");
315 viewer += _T(" \"")+file2+_T("\"");
317 if (viewer.Find(_T("%base")) >= 0)
319 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
321 if (viewer.Find(_T("%mine")) >= 0)
323 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
326 if (sName1.IsEmpty())
327 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
328 else
329 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
331 if (sName2.IsEmpty())
332 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
333 else
334 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
336 if (flags.bReadOnly && bInternal)
337 viewer += _T(" /readonly");
339 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
342 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
344 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
345 CString viewer = diffpropsexe;
346 bool bInternal = false;
347 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
349 //no registry entry (or commented out) for a diff program
350 //use TortoiseMerge
351 bInternal = true;
352 viewer = CPathUtils::GetAppDirectory();
353 viewer += _T("TortoiseMerge.exe");
354 viewer = _T("\"") + viewer + _T("\"");
355 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
357 // check if the params are set. If not, just add the files to the command line
358 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
360 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
361 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
363 if (viewer.Find(_T("%base")) >= 0)
365 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
367 if (viewer.Find(_T("%mine")) >= 0)
369 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
372 if (sName1.IsEmpty())
373 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
374 else
375 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
377 if (sName2.IsEmpty())
378 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
379 else
380 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
382 if ((bReadOnly)&&(bInternal))
383 viewer += _T(" /readonly");
385 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
387 return FALSE;
389 return TRUE;
392 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
394 CString viewer;
395 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
396 viewer = v;
397 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
399 // use TortoiseUDiff
400 viewer = CPathUtils::GetAppDirectory();
401 viewer += _T("TortoiseUDiff.exe");
402 // enquote the path to TortoiseUDiff
403 viewer = _T("\"") + viewer + _T("\"");
404 // add the params
405 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
408 if (viewer.Find(_T("%1"))>=0)
410 if (viewer.Find(_T("\"%1\"")) >= 0)
411 viewer.Replace(_T("%1"), patchfile);
412 else
413 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
415 else
416 viewer += _T(" \"") + patchfile + _T("\"");
417 if (viewer.Find(_T("%title")) >= 0)
419 viewer.Replace(_T("%title"), title);
422 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
424 return FALSE;
426 return TRUE;
429 BOOL CAppUtils::StartTextViewer(CString file)
431 CString viewer;
432 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
433 viewer = txt;
434 viewer = viewer + _T("\\Shell\\Open\\Command\\");
435 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
436 viewer = txtexe;
438 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
439 TCHAR * buf = new TCHAR[len+1];
440 ExpandEnvironmentStrings(viewer, buf, len);
441 viewer = buf;
442 delete [] buf;
443 len = ExpandEnvironmentStrings(file, NULL, 0);
444 buf = new TCHAR[len+1];
445 ExpandEnvironmentStrings(file, buf, len);
446 file = buf;
447 delete [] buf;
448 file = _T("\"")+file+_T("\"");
449 if (viewer.IsEmpty())
451 OPENFILENAME ofn = {0}; // common dialog box structure
452 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
453 // Initialize OPENFILENAME
454 ofn.lStructSize = sizeof(OPENFILENAME);
455 ofn.hwndOwner = NULL;
456 ofn.lpstrFile = szFile;
457 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
458 CString sFilter;
459 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
460 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
461 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
462 // Replace '|' delimiters with '\0's
463 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
464 while (ptr != pszFilters)
466 if (*ptr == '|')
467 *ptr = '\0';
468 ptr--;
470 ofn.lpstrFilter = pszFilters;
471 ofn.nFilterIndex = 1;
472 ofn.lpstrFileTitle = NULL;
473 ofn.nMaxFileTitle = 0;
474 ofn.lpstrInitialDir = NULL;
475 CString temp;
476 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
477 CStringUtils::RemoveAccelerators(temp);
478 ofn.lpstrTitle = temp;
479 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
481 // Display the Open dialog box.
483 if (GetOpenFileName(&ofn)==TRUE)
485 delete [] pszFilters;
486 viewer = CString(ofn.lpstrFile);
488 else
490 delete [] pszFilters;
491 return FALSE;
494 if (viewer.Find(_T("\"%1\"")) >= 0)
496 viewer.Replace(_T("\"%1\""), file);
498 else if (viewer.Find(_T("%1")) >= 0)
500 viewer.Replace(_T("%1"), file);
502 else
504 viewer += _T(" ");
505 viewer += file;
508 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
510 return FALSE;
512 return TRUE;
515 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
517 DWORD length = 0;
518 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
519 if (hFile == INVALID_HANDLE_VALUE)
520 return TRUE;
521 length = ::GetFileSize(hFile, NULL);
522 ::CloseHandle(hFile);
523 if (length < 4)
524 return TRUE;
525 return FALSE;
529 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
531 LOGFONT logFont;
532 HDC hScreenDC = ::GetDC(NULL);
533 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
534 ::ReleaseDC(NULL, hScreenDC);
535 logFont.lfWidth = 0;
536 logFont.lfEscapement = 0;
537 logFont.lfOrientation = 0;
538 logFont.lfWeight = FW_NORMAL;
539 logFont.lfItalic = 0;
540 logFont.lfUnderline = 0;
541 logFont.lfStrikeOut = 0;
542 logFont.lfCharSet = DEFAULT_CHARSET;
543 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
544 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
545 logFont.lfQuality = DRAFT_QUALITY;
546 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
547 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
548 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
551 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
553 STARTUPINFO startup;
554 PROCESS_INFORMATION process;
555 memset(&startup, 0, sizeof(startup));
556 startup.cb = sizeof(startup);
557 memset(&process, 0, sizeof(process));
559 CString cleanCommandLine(sCommandLine);
561 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, sOrigCWD, &startup, &process)==0)
563 if(idErrMessageFormat != 0)
565 LPVOID lpMsgBuf;
566 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
567 FORMAT_MESSAGE_FROM_SYSTEM |
568 FORMAT_MESSAGE_IGNORE_INSERTS,
569 NULL,
570 GetLastError(),
571 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
572 (LPTSTR) &lpMsgBuf,
574 NULL
576 CString temp;
577 temp.Format(idErrMessageFormat, lpMsgBuf);
578 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
579 LocalFree( lpMsgBuf );
581 return false;
584 if (bWaitForStartup)
586 WaitForInputIdle(process.hProcess, 10000);
589 CloseHandle(process.hThread);
590 CloseHandle(process.hProcess);
591 return true;
595 * Launch the external blame viewer
597 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
599 CString viewer = CPathUtils::GetAppDirectory();
600 viewer += _T("TortoiseGitBlame.exe");
601 viewer += _T(" \"") + sBlameFile + _T("\"");
602 //viewer += _T(" \"") + sLogFile + _T("\"");
603 //viewer += _T(" \"") + sOriginalFile + _T("\"");
604 if(!Rev.IsEmpty())
605 viewer += CString(_T(" /rev:"))+Rev;
606 viewer += _T(" ")+sParams;
608 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
611 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
613 CString sText;
614 if (pWnd == NULL)
615 return false;
616 bool bStyled = false;
617 pWnd->GetWindowText(sText);
618 // the rich edit control doesn't count the CR char!
619 // to be exact: CRLF is treated as one char.
620 sText.Replace(_T("\r"), _T(""));
622 // style each line separately
623 int offset = 0;
624 int nNewlinePos;
627 nNewlinePos = sText.Find('\n', offset);
628 CString sLine = sText.Mid(offset);
629 if (nNewlinePos>=0)
630 sLine = sLine.Left(nNewlinePos-offset);
631 int start = 0;
632 int end = 0;
633 while (FindStyleChars(sLine, '*', start, end))
635 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
636 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
637 CHARFORMAT2 format;
638 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
639 format.cbSize = sizeof(CHARFORMAT2);
640 format.dwMask = CFM_BOLD;
641 format.dwEffects = CFE_BOLD;
642 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
643 bStyled = true;
644 start = end;
646 start = 0;
647 end = 0;
648 while (FindStyleChars(sLine, '^', start, end))
650 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
651 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
652 CHARFORMAT2 format;
653 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
654 format.cbSize = sizeof(CHARFORMAT2);
655 format.dwMask = CFM_ITALIC;
656 format.dwEffects = CFE_ITALIC;
657 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
658 bStyled = true;
659 start = end;
661 start = 0;
662 end = 0;
663 while (FindStyleChars(sLine, '_', start, end))
665 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
666 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
667 CHARFORMAT2 format;
668 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
669 format.cbSize = sizeof(CHARFORMAT2);
670 format.dwMask = CFM_UNDERLINE;
671 format.dwEffects = CFE_UNDERLINE;
672 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
673 bStyled = true;
674 start = end;
676 offset = nNewlinePos+1;
677 } while(nNewlinePos>=0);
678 return bStyled;
681 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
683 int i=start;
684 bool bFoundMarker = false;
685 // find a starting marker
686 while (sText[i] != 0)
688 if (sText[i] == stylechar)
690 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
691 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
693 start = i+1;
694 i++;
695 bFoundMarker = true;
696 break;
699 i++;
701 if (!bFoundMarker)
702 return false;
703 // find ending marker
704 bFoundMarker = false;
705 while (sText[i] != 0)
707 if (sText[i] == stylechar)
709 if ((IsCharAlphaNumeric(sText[i-1])) &&
710 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
712 end = i;
713 i++;
714 bFoundMarker = true;
715 break;
718 i++;
720 return bFoundMarker;
723 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
725 #if 0
726 CString strUrl;
727 combo.GetWindowText(strUrl);
728 strUrl.Replace('\\', '/');
729 strUrl.Replace(_T("%"), _T("%25"));
730 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
731 if (strUrl.Left(7) == _T("file://"))
733 CString strFile(strUrl);
734 Git::UrlToPath(strFile);
736 Git svn;
737 if (svn.IsRepository(CTGitPath(strFile)))
739 // browse repository - show repository browser
740 Git::preparePath(strUrl);
741 CRepositoryBrowser browser(strUrl, rev, pParent);
742 if (browser.DoModal() == IDOK)
744 combo.SetCurSel(-1);
745 combo.SetWindowText(browser.GetPath());
746 rev = browser.GetRevision();
747 return true;
750 else
752 // browse local directories
753 CBrowseFolder folderBrowser;
754 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
755 // remove the 'file:///' so the shell can recognize the local path
756 Git::UrlToPath(strUrl);
757 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
759 Git::PathToUrl(strUrl);
761 combo.SetCurSel(-1);
762 combo.SetWindowText(strUrl);
763 return true;
767 else if ((strUrl.Left(7) == _T("http://")
768 ||(strUrl.Left(8) == _T("https://"))
769 ||(strUrl.Left(6) == _T("svn://"))
770 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
772 // browse repository - show repository browser
773 CRepositoryBrowser browser(strUrl, rev, pParent);
774 if (browser.DoModal() == IDOK)
776 combo.SetCurSel(-1);
777 combo.SetWindowText(browser.GetPath());
778 rev = browser.GetRevision();
779 return true;
782 else
784 // browse local directories
785 CBrowseFolder folderBrowser;
786 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
787 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
789 Git::PathToUrl(strUrl);
791 combo.SetCurSel(-1);
792 combo.SetWindowText(strUrl);
793 return true;
796 #endif
797 return false;
800 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
802 OPENFILENAME ofn = {0}; // common dialog box structure
803 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
804 ofn.lStructSize = sizeof(OPENFILENAME);
805 ofn.hwndOwner = hwndOwner;
806 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
807 ofn.lpstrFile = szFile;
808 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
809 CString sFilter;
810 TCHAR * pszFilters = NULL;
811 if (filter)
813 sFilter.LoadString(filter);
814 pszFilters = new TCHAR[sFilter.GetLength()+4];
815 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
816 // Replace '|' delimiters with '\0's
817 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
818 while (ptr != pszFilters)
820 if (*ptr == '|')
821 *ptr = '\0';
822 ptr--;
824 ofn.lpstrFilter = pszFilters;
826 ofn.nFilterIndex = 1;
827 ofn.lpstrFileTitle = NULL;
828 ofn.nMaxFileTitle = 0;
829 ofn.lpstrInitialDir = NULL;
830 CString temp;
831 if (title)
833 temp.LoadString(title);
834 CStringUtils::RemoveAccelerators(temp);
836 ofn.lpstrTitle = temp;
837 if (bOpen)
838 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
839 else
840 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
843 // Display the Open dialog box.
844 bool bRet = false;
845 if (bOpen)
847 bRet = !!GetOpenFileName(&ofn);
849 else
851 bRet = !!GetSaveFileName(&ofn);
853 if (bRet)
855 if (pszFilters)
856 delete [] pszFilters;
857 path = CString(ofn.lpstrFile);
858 if (filterindex)
859 *filterindex = ofn.nFilterIndex;
860 return true;
862 if (pszFilters)
863 delete [] pszFilters;
864 return false;
867 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
869 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
870 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
871 // create a bitmap from the icon
872 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
873 if (!hIcon)
874 return false;
876 RECT rect = {0};
877 rect.right = width;
878 rect.bottom = height;
879 HBITMAP bmp = NULL;
881 HWND desktop = ::GetDesktopWindow();
882 if (desktop)
884 HDC screen_dev = ::GetDC(desktop);
885 if (screen_dev)
887 // Create a compatible DC
888 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
889 if (dst_hdc)
891 // Create a new bitmap of icon size
892 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
893 if (bmp)
895 // Select it into the compatible DC
896 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
897 // Fill the background of the compatible DC with the given color
898 ::SetBkColor(dst_hdc, bkColor);
899 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
901 // Draw the icon into the compatible DC
902 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
903 ::SelectObject(dst_hdc, old_dst_bmp);
905 ::DeleteDC(dst_hdc);
908 ::ReleaseDC(desktop, screen_dev);
911 // Restore settings
912 DestroyIcon(hIcon);
914 if (bmp == NULL)
915 return false;
917 LVBKIMAGE lv;
918 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
919 lv.hbm = bmp;
920 lv.xOffsetPercent = 100;
921 lv.yOffsetPercent = 100;
922 ListView_SetBkImage(hListCtrl, &lv);
923 return true;
926 CString CAppUtils::GetProjectNameFromURL(CString url)
928 CString name;
929 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
930 (name.CompareNoCase(_T("tags"))==0) ||
931 (name.CompareNoCase(_T("trunk"))==0))
933 name = url.Mid(url.ReverseFind('/')+1);
934 url = url.Left(url.ReverseFind('/'));
936 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
938 // a name of svn or svnroot indicates that it's not really the project name. In that
939 // case, we try the first part of the URL
940 // of course, this won't work in all cases (but it works for Google project hosting)
941 url.Replace(_T("http://"), _T(""));
942 url.Replace(_T("https://"), _T(""));
943 url.Replace(_T("svn://"), _T(""));
944 url.Replace(_T("svn+ssh://"), _T(""));
945 url.TrimLeft(_T("/"));
946 name = url.Left(url.Find('.'));
948 return name;
951 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
952 const CTGitPath& url2, const git_revnum_t& rev2,
953 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
954 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
957 CString tempfile=GetTempFile();
958 CString cmd;
959 if(rev1 == GitRev::GetWorkingCopy())
961 cmd.Format(_T("git.exe diff --stat -p %s"),rev2);
962 }else
964 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
966 g_Git.RunLogFile(cmd,tempfile);
967 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
970 #if 0
971 CString sCmd;
972 sCmd.Format(_T("%s /command:showcompare /unified"),
973 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
974 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
975 if (rev1.IsValid())
976 sCmd += _T(" /revision1:") + rev1.ToString();
977 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
978 if (rev2.IsValid())
979 sCmd += _T(" /revision2:") + rev2.ToString();
980 if (peg.IsValid())
981 sCmd += _T(" /pegrevision:") + peg.ToString();
982 if (headpeg.IsValid())
983 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
985 if (bAlternateDiff)
986 sCmd += _T(" /alternatediff");
988 if (bIgnoreAncestry)
989 sCmd += _T(" /ignoreancestry");
991 if (hWnd)
993 sCmd += _T(" /hwnd:");
994 TCHAR buf[30];
995 _stprintf_s(buf, 30, _T("%d"), hWnd);
996 sCmd += buf;
999 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1000 #endif
1001 return TRUE;
1004 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1005 const CTGitPath& url2, const GitRev& rev2,
1006 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1007 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1009 #if 0
1010 CString sCmd;
1011 sCmd.Format(_T("%s /command:showcompare"),
1012 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1013 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1014 if (rev1.IsValid())
1015 sCmd += _T(" /revision1:") + rev1.ToString();
1016 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1017 if (rev2.IsValid())
1018 sCmd += _T(" /revision2:") + rev2.ToString();
1019 if (peg.IsValid())
1020 sCmd += _T(" /pegrevision:") + peg.ToString();
1021 if (headpeg.IsValid())
1022 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1023 if (bAlternateDiff)
1024 sCmd += _T(" /alternatediff");
1025 if (bIgnoreAncestry)
1026 sCmd += _T(" /ignoreancestry");
1027 if (blame)
1028 sCmd += _T(" /blame");
1030 if (hWnd)
1032 sCmd += _T(" /hwnd:");
1033 TCHAR buf[30];
1034 _stprintf_s(buf, 30, _T("%d"), hWnd);
1035 sCmd += buf;
1038 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1039 #endif
1040 return true;
1043 bool CAppUtils::Export(CString *BashHash)
1045 bool bRet = false;
1047 // ask from where the export has to be done
1048 CExportDlg dlg;
1049 if(BashHash)
1050 dlg.m_Revision=*BashHash;
1052 if (dlg.DoModal() == IDOK)
1054 CString cmd;
1055 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1056 dlg.m_VersionName);
1058 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1059 CProgressDlg pro;
1060 pro.m_GitCmd=cmd;
1061 pro.m_LogFile=dlg.m_strExportDirectory;
1062 pro.DoModal();
1063 return TRUE;
1065 return bRet;
1068 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1070 CCreateBranchTagDlg dlg;
1071 dlg.m_bIsTag=IsTag;
1072 if(CommitHash)
1073 dlg.m_Base = *CommitHash;
1075 if(dlg.DoModal()==IDOK)
1077 CString cmd;
1078 CString force;
1079 CString track;
1080 if(dlg.m_bTrack)
1081 track=_T(" --track ");
1083 if(dlg.m_bForce)
1084 force=_T(" -f ");
1086 if(IsTag)
1088 cmd.Format(_T("git.exe tag %s %s %s %s"),
1089 track,
1090 force,
1091 dlg.m_BranchTagName,
1092 dlg.m_VersionName
1096 }else
1098 cmd.Format(_T("git.exe branch %s %s %s %s"),
1099 track,
1100 force,
1101 dlg.m_BranchTagName,
1102 dlg.m_VersionName
1105 CString out;
1106 if(g_Git.Run(cmd,&out,CP_UTF8))
1108 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1110 if( !IsTag && dlg.m_bSwitch )
1112 // it is a new branch and the user has requested to switch to it
1113 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1114 g_Git.Run(cmd,&out,CP_UTF8);
1115 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1118 return TRUE;
1121 return FALSE;
1124 bool CAppUtils::Switch(CString *CommitHash)
1126 CGitSwitchDlg dlg;
1127 if(CommitHash)
1128 dlg.m_Base=*CommitHash;
1130 if (dlg.DoModal() == IDOK)
1132 CString cmd;
1133 CString track;
1134 CString base;
1135 CString force;
1136 CString branch;
1138 if(dlg.m_bBranch)
1139 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1140 if(dlg.m_bForce)
1141 force=_T("-f");
1142 if(dlg.m_bTrack)
1143 track=_T("--track");
1145 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1146 force,
1147 track,
1148 branch,
1149 dlg.m_VersionName);
1151 CProgressDlg progress;
1152 progress.m_GitCmd=cmd;
1153 if(progress.DoModal()==IDOK)
1154 return TRUE;
1157 return FALSE;
1160 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1162 CString ignorefile;
1163 ignorefile=g_Git.m_CurrentDir+_T("\\");
1165 if(IsMask)
1167 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1169 }else
1171 ignorefile+=_T("\\.gitignore");
1174 CStdioFile file;
1175 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1177 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1178 return FALSE;
1181 CString ignorelist;
1182 CString mask;
1185 //file.ReadString(ignorelist);
1186 file.SeekToEnd();
1187 for(int i=0;i<path.GetCount();i++)
1189 if(IsMask)
1191 mask=_T("*")+path[i].GetFileExtension();
1192 if(ignorelist.Find(mask)<0)
1193 ignorelist+=_T("\n")+mask;
1195 }else
1197 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1200 file.WriteString(ignorelist);
1202 file.Close();
1204 }catch(...)
1206 file.Close();
1207 return FALSE;
1210 return TRUE;
1214 bool CAppUtils::GitReset(CString *CommitHash,int type)
1216 CResetDlg dlg;
1217 dlg.m_ResetType=type;
1218 if (dlg.DoModal() == IDOK)
1220 CString cmd;
1221 CString type;
1222 switch(dlg.m_ResetType)
1224 case 0:
1225 type=_T("--soft");
1226 break;
1227 case 1:
1228 type=_T("--mixed");
1229 break;
1230 case 2:
1231 type=_T("--hard");
1232 break;
1233 default:
1234 type=_T("--mixed");
1235 break;
1237 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1239 CProgressDlg progress;
1240 progress.m_GitCmd=cmd;
1241 if(progress.DoModal()==IDOK)
1242 return TRUE;
1245 return FALSE;
1248 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1250 if(mode == FALSE)
1252 descript=_T("Deleted");
1253 return;
1255 if(base)
1257 descript=_T("Modified");
1258 return;
1260 descript=_T("Created");
1261 return;
1264 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1266 CString file;
1267 file=g_Git.m_CurrentDir+_T("\\")+merge.GetDirectory().GetWinPathString()+_T("\\")+merge.GetFilename()+_T(".")+type+merge.GetFileExtension();
1269 return file;
1272 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool)
1274 bool bRet = false;
1276 CTGitPath merge=path;
1277 CTGitPath directory = merge.GetDirectory();
1281 // we have the conflicted file (%merged)
1282 // now look for the other required files
1283 //GitStatus stat;
1284 //stat.GetStatus(merge);
1285 //if (stat.status == NULL)
1286 // return false;
1288 BYTE_VECTOR vector;
1290 CString cmd;
1291 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1293 if(g_Git.Run(cmd,&vector))
1295 return FALSE;
1298 CTGitPathList list;
1299 list.ParserFromLsFile(vector);
1301 if(list.GetCount() == 0)
1302 return FALSE;
1304 TCHAR szTempName[512];
1305 GetTempFileName(_T(""),_T(""),0,szTempName);
1306 CString temp(szTempName);
1307 temp=temp.Mid(1,temp.GetLength()-5);
1309 CTGitPath theirs;
1310 CTGitPath mine;
1311 CTGitPath base;
1314 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1315 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1316 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1318 CString format;
1320 format=_T("git.exe cat-file blob \":%d:%s\"");
1321 CFile tempfile;
1322 //create a empty file, incase stage is not three
1323 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1324 tempfile.Close();
1325 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1326 tempfile.Close();
1327 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1328 tempfile.Close();
1330 bool b_base=false, b_local=false, b_remote=false;
1332 for(int i=0;i<list.GetCount();i++)
1334 CString cmd;
1335 CString outfile;
1336 cmd.Format(format,list[i].m_Stage,list[i].GetGitPathString());
1338 if( list[i].m_Stage == 1)
1340 b_base = true;
1341 outfile=base.GetWinPathString();
1343 if( list[i].m_Stage == 2 )
1345 b_local = true;
1346 outfile=mine.GetWinPathString();
1348 if( list[i].m_Stage == 3 )
1350 b_remote = true;
1351 outfile=theirs.GetWinPathString();
1353 g_Git.RunLogFile(cmd,outfile);
1356 if(b_local && b_remote )
1358 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1359 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1361 }else
1363 CFile::Remove(mine.GetWinPathString());
1364 CFile::Remove(theirs.GetWinPathString());
1365 CFile::Remove(base.GetWinPathString());
1367 CDeleteConflictDlg dlg;
1368 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1369 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1370 dlg.m_bShowModifiedButton=b_base;
1371 dlg.m_File=merge.GetGitPathString();
1372 if(dlg.DoModal() == IDOK)
1374 CString cmd,out;
1375 if(dlg.m_bIsDelete)
1377 cmd.Format(_T("git.exe rm \"%s\""),merge.GetGitPathString());
1378 }else
1379 cmd.Format(_T("git.exe add \"%s\""),merge.GetGitPathString());
1381 if(g_Git.Run(cmd,&out,CP_ACP))
1383 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1384 return FALSE;
1386 return TRUE;
1388 else
1389 return FALSE;
1395 #if 0
1397 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1398 base, theirs, mine, merge);
1399 #endif
1400 #if 0
1401 if (stat.status->text_status == svn_wc_status_conflicted)
1403 // we have a text conflict, use our merge tool to resolve the conflict
1405 CTSVNPath theirs(directory);
1406 CTSVNPath mine(directory);
1407 CTSVNPath base(directory);
1408 bool bConflictData = false;
1410 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1412 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1413 bConflictData = true;
1415 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1417 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1418 bConflictData = true;
1420 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1422 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1423 bConflictData = true;
1425 else
1427 mine = merge;
1429 if (bConflictData)
1430 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1431 base, theirs, mine, merge);
1434 if (stat.status->prop_status == svn_wc_status_conflicted)
1436 // we have a property conflict
1437 CTSVNPath prej(directory);
1438 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1440 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1441 // there's a problem: the prej file contains a _description_ of the conflict, and
1442 // that description string might be translated. That means we have no way of parsing
1443 // the file to find out the conflicting values.
1444 // The only thing we can do: show a dialog with the conflict description, then
1445 // let the user either accept the existing property or open the property edit dialog
1446 // to manually change the properties and values. And a button to mark the conflict as
1447 // resolved.
1448 CEditPropConflictDlg dlg;
1449 dlg.SetPrejFile(prej);
1450 dlg.SetConflictedItem(merge);
1451 bRet = (dlg.DoModal() != IDCANCEL);
1455 if (stat.status->tree_conflict)
1457 // we have a tree conflict
1458 SVNInfo info;
1459 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1460 if (pInfoData)
1462 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1464 CTSVNPath theirs(directory);
1465 CTSVNPath mine(directory);
1466 CTSVNPath base(directory);
1467 bool bConflictData = false;
1469 if (pInfoData->treeconflict_theirfile)
1471 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1472 bConflictData = true;
1474 if (pInfoData->treeconflict_basefile)
1476 base.AppendPathString(pInfoData->treeconflict_basefile);
1477 bConflictData = true;
1479 if (pInfoData->treeconflict_myfile)
1481 mine.AppendPathString(pInfoData->treeconflict_myfile);
1482 bConflictData = true;
1484 else
1486 mine = merge;
1488 if (bConflictData)
1489 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1490 base, theirs, mine, merge);
1492 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1494 CString sConflictAction;
1495 CString sConflictReason;
1496 CString sResolveTheirs;
1497 CString sResolveMine;
1498 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1499 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1501 if (pInfoData->treeconflict_nodekind == svn_node_file)
1503 switch (pInfoData->treeconflict_operation)
1505 case svn_wc_operation_update:
1506 switch (pInfoData->treeconflict_action)
1508 case svn_wc_conflict_action_edit:
1509 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1510 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1511 break;
1512 case svn_wc_conflict_action_add:
1513 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1514 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1515 break;
1516 case svn_wc_conflict_action_delete:
1517 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1518 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1519 break;
1521 break;
1522 case svn_wc_operation_switch:
1523 switch (pInfoData->treeconflict_action)
1525 case svn_wc_conflict_action_edit:
1526 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1527 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1528 break;
1529 case svn_wc_conflict_action_add:
1530 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1531 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1532 break;
1533 case svn_wc_conflict_action_delete:
1534 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1535 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1536 break;
1538 break;
1539 case svn_wc_operation_merge:
1540 switch (pInfoData->treeconflict_action)
1542 case svn_wc_conflict_action_edit:
1543 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1544 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1545 break;
1546 case svn_wc_conflict_action_add:
1547 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1548 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1549 break;
1550 case svn_wc_conflict_action_delete:
1551 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1552 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1553 break;
1555 break;
1558 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1560 switch (pInfoData->treeconflict_operation)
1562 case svn_wc_operation_update:
1563 switch (pInfoData->treeconflict_action)
1565 case svn_wc_conflict_action_edit:
1566 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1567 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1568 break;
1569 case svn_wc_conflict_action_add:
1570 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1571 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1572 break;
1573 case svn_wc_conflict_action_delete:
1574 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1575 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1576 break;
1578 break;
1579 case svn_wc_operation_switch:
1580 switch (pInfoData->treeconflict_action)
1582 case svn_wc_conflict_action_edit:
1583 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1584 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1585 break;
1586 case svn_wc_conflict_action_add:
1587 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1588 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1589 break;
1590 case svn_wc_conflict_action_delete:
1591 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1592 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1593 break;
1595 break;
1596 case svn_wc_operation_merge:
1597 switch (pInfoData->treeconflict_action)
1599 case svn_wc_conflict_action_edit:
1600 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1601 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1602 break;
1603 case svn_wc_conflict_action_add:
1604 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1605 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1606 break;
1607 case svn_wc_conflict_action_delete:
1608 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1609 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1610 break;
1612 break;
1616 UINT uReasonID = 0;
1617 switch (pInfoData->treeconflict_reason)
1619 case svn_wc_conflict_reason_edited:
1620 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1621 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1622 break;
1623 case svn_wc_conflict_reason_obstructed:
1624 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1625 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1626 break;
1627 case svn_wc_conflict_reason_deleted:
1628 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1629 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1630 break;
1631 case svn_wc_conflict_reason_added:
1632 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1633 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1634 break;
1635 case svn_wc_conflict_reason_missing:
1636 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1637 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1638 break;
1639 case svn_wc_conflict_reason_unversioned:
1640 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1641 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1642 break;
1644 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1646 CTreeConflictEditorDlg dlg;
1647 dlg.SetConflictInfoText(sConflictReason);
1648 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1649 dlg.SetPath(treeConflictPath);
1650 INT_PTR dlgRet = dlg.DoModal();
1651 bRet = (dlgRet != IDCANCEL);
1655 #endif
1656 return bRet;
1660 * FUNCTION : FormatDateAndTime
1661 * DESCRIPTION : Generates a displayable string from a CTime object in
1662 * system short or long format or as a relative value
1663 * cTime - the time
1664 * option - DATE_SHORTDATE or DATE_LONGDATE
1665 * bIncluedeTime - whether to show time as well as date
1666 * bRelative - if true then relative time is shown if reasonable
1667 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1668 * rather than locale
1669 * RETURN : CString containing date/time
1671 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1672 bool bRelative /*=false*/)
1674 CString datetime;
1675 if ( bRelative )
1677 datetime = ToRelativeTimeString( cTime );
1679 else
1681 // should we use the locale settings for formatting the date/time?
1682 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1684 // yes
1685 SYSTEMTIME sysTime;
1686 cTime.GetAsSystemTime( sysTime );
1688 TCHAR buf[100];
1690 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1691 sizeof(buf)/sizeof(TCHAR)-1);
1692 datetime = buf;
1693 if ( bIncludeTime )
1695 datetime += _T(" ");
1696 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1697 datetime += buf;
1700 else
1702 // no, so fixed format
1703 if ( bIncludeTime )
1705 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1707 else
1709 datetime = cTime.Format(_T("%Y-%m-%d"));
1713 return datetime;
1717 * Converts a given time to a relative display string (relative to current time)
1718 * Given time must be in local timezone
1720 CString CAppUtils::ToRelativeTimeString(CTime time)
1722 CString answer;
1723 // convert to COleDateTime
1724 SYSTEMTIME sysTime;
1725 time.GetAsSystemTime( sysTime );
1726 COleDateTime oleTime( sysTime );
1727 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1728 return answer;
1732 * Generates a display string showing the relative time between the two given times as COleDateTimes
1734 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1736 CString answer;
1737 COleDateTimeSpan ts = RelativeTo - time;
1738 //years
1739 if(fabs(ts.GetTotalDays()) >= 3*365)
1741 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1743 //Months
1744 if(fabs(ts.GetTotalDays()) >= 60)
1746 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1747 return answer;
1749 //Weeks
1750 if(fabs(ts.GetTotalDays()) >= 14)
1752 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1753 return answer;
1755 //Days
1756 if(fabs(ts.GetTotalDays()) >= 2)
1758 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1759 return answer;
1761 //hours
1762 if(fabs(ts.GetTotalHours()) >= 2)
1764 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1765 return answer;
1767 //minutes
1768 if(fabs(ts.GetTotalMinutes()) >= 2)
1770 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1771 return answer;
1773 //seconds
1774 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1775 return answer;
1778 /**
1779 * Passed a value and two resource string ids
1780 * if count is 1 then FormatString is called with format_1 and the value
1781 * otherwise format_2 is used
1782 * the formatted string is returned
1784 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1786 CString answer;
1787 if ( count == 1 )
1789 answer.FormatMessage( format_1, count );
1791 else
1793 answer.FormatMessage( format_n, count );
1795 return answer;