Rename a lot of SVN references to GIT
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob026cae108a79ab75171bdc31d4ea965e0d6bf513
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - TortoiseGit
4 // Copyright (C) 2003-2011 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "StdAfx.h"
21 #include "resource.h"
22 #include "TortoiseProc.h"
23 #include "PathUtils.h"
24 #include "AppUtils.h"
25 //#include "GitProperties.h"
26 #include "StringUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "TGitPath.h"
30 #include "Git.h"
31 //#include "RepositoryBrowser.h"
32 //#include "BrowseFolder.h"
33 #include "UnicodeUtils.h"
34 #include "ExportDlg.h"
35 #include "ProgressDlg.h"
36 #include "GitAdminDir.h"
37 #include "ProgressDlg.h"
38 #include "BrowseFolder.h"
39 #include "DirFileEnum.h"
40 #include "MessageBox.h"
41 #include "GitStatus.h"
42 #include "CreateBranchTagDlg.h"
43 #include "GitSwitchDlg.h"
44 #include "ResetDlg.h"
45 #include "DeleteConflictDlg.h"
46 #include "ChangedDlg.h"
47 #include "SendMailDlg.h"
48 #include "GITProgressDlg.h"
49 #include "PushDlg.h"
50 #include "CommitDlg.h"
51 #include "MergeDlg.h"
52 #include "hooks.h"
53 #include "..\Settings\Settings.h"
54 #include "InputDlg.h"
55 #include "SVNDCommitDlg.h"
56 #include "requestpulldlg.h"
57 #include "PullFetchDlg.h"
58 #include "RebaseDlg.h"
59 #include "PropKey.h"
61 CAppUtils::CAppUtils(void)
65 CAppUtils::~CAppUtils(void)
69 int CAppUtils::StashApply(CString ref)
71 CString cmd,out;
72 cmd = _T("git.exe stash apply ");
73 if (ref.Find(_T("refs/")) == 0)
74 ref = ref.Mid(5);
75 if (ref.Find(_T("stash{")) == 0)
76 ref = _T("stash@") + ref.Mid(5);
77 cmd += ref;
79 if(g_Git.Run(cmd,&out,CP_ACP))
81 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
83 else
85 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
86 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
88 CChangedDlg dlg;
89 dlg.m_pathList.AddPath(CTGitPath());
90 dlg.DoModal();
92 return 0;
94 return -1;
97 int CAppUtils::StashPop()
99 CString cmd,out;
100 cmd=_T("git.exe stash pop ");
102 if(g_Git.Run(cmd,&out,CP_ACP))
104 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
107 else
109 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
110 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
112 CChangedDlg dlg;
113 dlg.m_pathList.AddPath(CTGitPath());
114 dlg.DoModal();
116 return 0;
118 return -1;
121 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
123 #if 0
124 GitProperties props(file, GitRev::REV_WC, false);
125 for (int i = 0; i < props.GetCount(); ++i)
127 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
129 mimetype = props.GetItemValue(i).c_str();
130 return true;
133 #endif
134 return false;
137 BOOL CAppUtils::StartExtMerge(
138 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
139 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
142 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
143 CString ext = mergedfile.GetFileExtension();
144 CString com = regCom;
145 bool bInternal = false;
147 CString mimetype;
148 if (ext != "")
150 // is there an extension specific merge tool?
151 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
152 if (CString(mergetool) != "")
154 com = mergetool;
157 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
159 // is there a mime type specific merge tool?
160 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
161 if (CString(mergetool) != "")
163 com = mergetool;
167 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
169 // use TortoiseMerge
170 bInternal = true;
171 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
172 com = tortoiseMergePath;
173 if (com.IsEmpty())
175 com = CPathUtils::GetAppDirectory();
176 com += _T("TortoiseMerge.exe");
178 com = _T("\"") + com + _T("\"");
179 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
180 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
182 // check if the params are set. If not, just add the files to the command line
183 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
185 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
186 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
187 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
188 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
190 if (basefile.IsEmpty())
192 com.Replace(_T("/base:%base"), _T(""));
193 com.Replace(_T("%base"), _T(""));
195 else
196 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
197 if (theirfile.IsEmpty())
199 com.Replace(_T("/theirs:%theirs"), _T(""));
200 com.Replace(_T("%theirs"), _T(""));
202 else
203 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
204 if (yourfile.IsEmpty())
206 com.Replace(_T("/mine:%mine"), _T(""));
207 com.Replace(_T("%mine"), _T(""));
209 else
210 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
211 if (mergedfile.IsEmpty())
213 com.Replace(_T("/merged:%merged"), _T(""));
214 com.Replace(_T("%merged"), _T(""));
216 else
217 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
218 if (basename.IsEmpty())
220 if (basefile.IsEmpty())
222 com.Replace(_T("/basename:%bname"), _T(""));
223 com.Replace(_T("%bname"), _T(""));
225 else
227 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
230 else
231 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
232 if (theirname.IsEmpty())
234 if (theirfile.IsEmpty())
236 com.Replace(_T("/theirsname:%tname"), _T(""));
237 com.Replace(_T("%tname"), _T(""));
239 else
241 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
244 else
245 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
246 if (yourname.IsEmpty())
248 if (yourfile.IsEmpty())
250 com.Replace(_T("/minename:%yname"), _T(""));
251 com.Replace(_T("%yname"), _T(""));
253 else
255 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
258 else
259 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
260 if (mergedname.IsEmpty())
262 if (mergedfile.IsEmpty())
264 com.Replace(_T("/mergedname:%mname"), _T(""));
265 com.Replace(_T("%mname"), _T(""));
267 else
269 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
272 else
273 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
275 if ((bReadOnly)&&(bInternal))
276 com += _T(" /readonly");
278 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
280 return FALSE;
283 return TRUE;
286 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
288 CString viewer;
289 // use TortoiseMerge
290 viewer = CPathUtils::GetAppDirectory();
291 viewer += _T("TortoiseMerge.exe");
293 viewer = _T("\"") + viewer + _T("\"");
294 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
295 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
296 if (bReversed)
297 viewer += _T(" /reversedpatch");
298 if (!sOriginalDescription.IsEmpty())
299 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
300 if (!sPatchedDescription.IsEmpty())
301 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
302 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
304 return FALSE;
306 return TRUE;
309 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
311 // Is there a mime type specific diff tool?
312 CString mimetype;
313 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
315 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
316 if (!difftool.IsEmpty())
317 return difftool;
320 // Is there an extension specific diff tool?
321 CString ext = file2.GetFileExtension().MakeLower();
322 if (!ext.IsEmpty())
324 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
325 if (!difftool.IsEmpty())
326 return difftool;
327 // Maybe we should use TortoiseIDiff?
328 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
329 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
330 (ext == _T(".png")) || (ext == _T(".ico")) ||
331 (ext == _T(".dib")) || (ext == _T(".emf")))
333 return
334 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
335 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
339 // Finally, pick a generic external diff tool
340 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
341 return difftool;
344 bool CAppUtils::StartExtDiff(
345 const CString& file1, const CString& file2,
346 const CString& sName1, const CString& sName2,
347 const DiffFlags& flags)
349 CString viewer;
351 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
352 if (!flags.bBlame || !(DWORD)blamediff)
354 viewer = PickDiffTool(file1, file2);
355 // If registry entry for a diff program is commented out, use TortoiseMerge.
356 bool bCommentedOut = viewer.Left(1) == _T("#");
357 if (flags.bAlternativeTool)
359 // Invert external vs. internal diff tool selection.
360 if (bCommentedOut)
361 viewer.Delete(0); // uncomment
362 else
363 viewer = "";
365 else if (bCommentedOut)
366 viewer = "";
369 bool bInternal = viewer.IsEmpty();
370 if (bInternal)
372 viewer =
373 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
374 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
375 if (flags.bBlame)
376 viewer += _T(" /blame");
378 // check if the params are set. If not, just add the files to the command line
379 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
381 viewer += _T(" \"")+file1+_T("\"");
382 viewer += _T(" \"")+file2+_T("\"");
384 if (viewer.Find(_T("%base")) >= 0)
386 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
388 if (viewer.Find(_T("%mine")) >= 0)
390 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
393 if (sName1.IsEmpty())
394 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
395 else
396 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
398 if (sName2.IsEmpty())
399 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
400 else
401 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
403 if (flags.bReadOnly && bInternal)
404 viewer += _T(" /readonly");
406 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
409 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
411 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
412 CString viewer = diffpropsexe;
413 bool bInternal = false;
414 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
416 //no registry entry (or commented out) for a diff program
417 //use TortoiseMerge
418 bInternal = true;
419 viewer = CPathUtils::GetAppDirectory();
420 viewer += _T("TortoiseMerge.exe");
421 viewer = _T("\"") + viewer + _T("\"");
422 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
424 // check if the params are set. If not, just add the files to the command line
425 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
427 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
428 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
430 if (viewer.Find(_T("%base")) >= 0)
432 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
434 if (viewer.Find(_T("%mine")) >= 0)
436 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
439 if (sName1.IsEmpty())
440 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
441 else
442 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
444 if (sName2.IsEmpty())
445 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
446 else
447 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
449 if ((bReadOnly)&&(bInternal))
450 viewer += _T(" /readonly");
452 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
454 return FALSE;
456 return TRUE;
459 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
461 CString viewer;
462 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
463 viewer = v;
464 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
466 // use TortoiseUDiff
467 viewer = CPathUtils::GetAppDirectory();
468 viewer += _T("TortoiseUDiff.exe");
469 // enquote the path to TortoiseUDiff
470 viewer = _T("\"") + viewer + _T("\"");
471 // add the params
472 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
475 if (viewer.Find(_T("%1"))>=0)
477 if (viewer.Find(_T("\"%1\"")) >= 0)
478 viewer.Replace(_T("%1"), patchfile);
479 else
480 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
482 else
483 viewer += _T(" \"") + patchfile + _T("\"");
484 if (viewer.Find(_T("%title")) >= 0)
486 viewer.Replace(_T("%title"), title);
489 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
491 return FALSE;
493 return TRUE;
496 BOOL CAppUtils::StartTextViewer(CString file)
498 CString viewer;
499 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
500 viewer = txt;
501 viewer = viewer + _T("\\Shell\\Open\\Command\\");
502 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
503 viewer = txtexe;
505 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
506 TCHAR * buf = new TCHAR[len+1];
507 ExpandEnvironmentStrings(viewer, buf, len);
508 viewer = buf;
509 delete [] buf;
510 len = ExpandEnvironmentStrings(file, NULL, 0);
511 buf = new TCHAR[len+1];
512 ExpandEnvironmentStrings(file, buf, len);
513 file = buf;
514 delete [] buf;
515 file = _T("\"")+file+_T("\"");
516 if (viewer.IsEmpty())
518 OPENFILENAME ofn = {0}; // common dialog box structure
519 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
520 // Initialize OPENFILENAME
521 ofn.lStructSize = sizeof(OPENFILENAME);
522 ofn.hwndOwner = NULL;
523 ofn.lpstrFile = szFile;
524 ofn.nMaxFile = _countof(szFile);
525 CString sFilter;
526 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
527 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
528 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
529 // Replace '|' delimiters with '\0's
530 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
531 while (ptr != pszFilters)
533 if (*ptr == '|')
534 *ptr = '\0';
535 ptr--;
537 ofn.lpstrFilter = pszFilters;
538 ofn.nFilterIndex = 1;
539 ofn.lpstrFileTitle = NULL;
540 ofn.nMaxFileTitle = 0;
541 ofn.lpstrInitialDir = NULL;
542 CString temp;
543 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
544 CStringUtils::RemoveAccelerators(temp);
545 ofn.lpstrTitle = temp;
546 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
548 // Display the Open dialog box.
550 if (GetOpenFileName(&ofn)==TRUE)
552 delete [] pszFilters;
553 viewer = CString(ofn.lpstrFile);
555 else
557 delete [] pszFilters;
558 return FALSE;
561 if (viewer.Find(_T("\"%1\"")) >= 0)
563 viewer.Replace(_T("\"%1\""), file);
565 else if (viewer.Find(_T("%1")) >= 0)
567 viewer.Replace(_T("%1"), file);
569 else
571 viewer += _T(" ");
572 viewer += file;
575 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
577 return FALSE;
579 return TRUE;
582 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
584 DWORD length = 0;
585 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
586 if (hFile == INVALID_HANDLE_VALUE)
587 return TRUE;
588 length = ::GetFileSize(hFile, NULL);
589 ::CloseHandle(hFile);
590 if (length < 4)
591 return TRUE;
592 return FALSE;
596 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
598 LOGFONT logFont;
599 HDC hScreenDC = ::GetDC(NULL);
600 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
601 ::ReleaseDC(NULL, hScreenDC);
602 logFont.lfWidth = 0;
603 logFont.lfEscapement = 0;
604 logFont.lfOrientation = 0;
605 logFont.lfWeight = FW_NORMAL;
606 logFont.lfItalic = 0;
607 logFont.lfUnderline = 0;
608 logFont.lfStrikeOut = 0;
609 logFont.lfCharSet = DEFAULT_CHARSET;
610 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
611 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
612 logFont.lfQuality = DRAFT_QUALITY;
613 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
614 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
615 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
618 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
620 STARTUPINFO startup;
621 PROCESS_INFORMATION process;
622 memset(&startup, 0, sizeof(startup));
623 startup.cb = sizeof(startup);
624 memset(&process, 0, sizeof(process));
626 CString cleanCommandLine(sCommandLine);
628 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
630 if(idErrMessageFormat != 0)
632 LPVOID lpMsgBuf;
633 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
634 FORMAT_MESSAGE_FROM_SYSTEM |
635 FORMAT_MESSAGE_IGNORE_INSERTS,
636 NULL,
637 GetLastError(),
638 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
639 (LPTSTR) &lpMsgBuf,
641 NULL
643 CString temp;
644 temp.Format(idErrMessageFormat, lpMsgBuf);
645 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
646 LocalFree( lpMsgBuf );
648 return false;
651 if (bWaitForStartup)
653 WaitForInputIdle(process.hProcess, 10000);
656 CloseHandle(process.hThread);
657 CloseHandle(process.hProcess);
658 return true;
660 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
662 CString key,remote;
663 CString cmd,out;
664 if( pRemote == NULL)
666 remote=_T("origin");
668 else
670 remote=*pRemote;
672 if(keyfile == NULL)
674 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
675 key = g_Git.GetConfigValue(cmd);
676 int start=0;
677 key = key.Tokenize(_T("\n"),start);
679 else
680 key=*keyfile;
682 if(key.IsEmpty())
683 return false;
685 CString proc=CPathUtils::GetAppDirectory();
686 proc += _T("pageant.exe \"");
687 proc += key;
688 proc += _T("\"");
690 CString tempfile = GetTempFile();
691 ::DeleteFile(tempfile);
693 proc += _T(" -c \"");
694 proc += CPathUtils::GetAppDirectory();
695 proc += _T("touch.exe\"");
696 proc += _T(" \"");
697 proc += tempfile;
698 proc += _T("\"");
700 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
701 if(!b)
702 return b;
704 int i=0;
705 while(!::PathFileExists(tempfile))
707 Sleep(100);
708 i++;
709 if(i>10*60*5)
710 break; //timeout 5 minutes
713 if( i== 10*60*5)
715 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
717 ::DeleteFile(tempfile);
718 return true;
720 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
722 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
723 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
724 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
727 CString sCmd;
728 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
730 LaunchApplication(sCmd, NULL, false);
731 return true;
733 bool CAppUtils::LaunchRemoteSetting()
735 CTGitPath path(g_Git.m_CurrentDir);
736 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
737 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
738 //dlg.SetTreeWidth(220);
739 dlg.m_DefaultPage = _T("gitremote");
741 dlg.DoModal();
742 dlg.HandleRestart();
743 return true;
746 * Launch the external blame viewer
748 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
750 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
751 viewer += _T("TortoiseGitBlame.exe");
752 viewer += _T("\" \"") + sBlameFile + _T("\"");
753 //viewer += _T(" \"") + sLogFile + _T("\"");
754 //viewer += _T(" \"") + sOriginalFile + _T("\"");
755 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
756 viewer += CString(_T(" /rev:"))+Rev;
757 viewer += _T(" ")+sParams;
759 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
762 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
764 CString sText;
765 if (pWnd == NULL)
766 return false;
767 bool bStyled = false;
768 pWnd->GetWindowText(sText);
769 // the rich edit control doesn't count the CR char!
770 // to be exact: CRLF is treated as one char.
771 sText.Remove('\r');
773 // style each line separately
774 int offset = 0;
775 int nNewlinePos;
778 nNewlinePos = sText.Find('\n', offset);
779 CString sLine = sText.Mid(offset);
780 if (nNewlinePos>=0)
781 sLine = sLine.Left(nNewlinePos-offset);
782 int start = 0;
783 int end = 0;
784 while (FindStyleChars(sLine, '*', start, end))
786 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
787 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
788 CHARFORMAT2 format;
789 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
790 format.cbSize = sizeof(CHARFORMAT2);
791 format.dwMask = CFM_BOLD;
792 format.dwEffects = CFE_BOLD;
793 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
794 bStyled = true;
795 start = end;
797 start = 0;
798 end = 0;
799 while (FindStyleChars(sLine, '^', start, end))
801 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
802 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
803 CHARFORMAT2 format;
804 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
805 format.cbSize = sizeof(CHARFORMAT2);
806 format.dwMask = CFM_ITALIC;
807 format.dwEffects = CFE_ITALIC;
808 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
809 bStyled = true;
810 start = end;
812 start = 0;
813 end = 0;
814 while (FindStyleChars(sLine, '_', start, end))
816 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
817 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
818 CHARFORMAT2 format;
819 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
820 format.cbSize = sizeof(CHARFORMAT2);
821 format.dwMask = CFM_UNDERLINE;
822 format.dwEffects = CFE_UNDERLINE;
823 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
824 bStyled = true;
825 start = end;
827 offset = nNewlinePos+1;
828 } while(nNewlinePos>=0);
829 return bStyled;
832 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
834 int i=start;
835 bool bFoundMarker = false;
836 // find a starting marker
837 while (sText[i] != 0)
839 if (sText[i] == stylechar)
841 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
842 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
844 start = i+1;
845 i++;
846 bFoundMarker = true;
847 break;
850 i++;
852 if (!bFoundMarker)
853 return false;
854 // find ending marker
855 bFoundMarker = false;
856 while (sText[i] != 0)
858 if (sText[i] == stylechar)
860 if ((IsCharAlphaNumeric(sText[i-1])) &&
861 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
863 end = i;
864 i++;
865 bFoundMarker = true;
866 break;
869 i++;
871 return bFoundMarker;
874 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
876 OPENFILENAME ofn = {0}; // common dialog box structure
877 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
878 ofn.lStructSize = sizeof(OPENFILENAME);
879 ofn.hwndOwner = hwndOwner;
880 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
881 ofn.lpstrFile = szFile;
882 ofn.nMaxFile = _countof(szFile);
883 CString sFilter;
884 TCHAR * pszFilters = NULL;
885 if (filter)
887 sFilter.LoadString(filter);
888 pszFilters = new TCHAR[sFilter.GetLength()+4];
889 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
890 // Replace '|' delimiters with '\0's
891 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
892 while (ptr != pszFilters)
894 if (*ptr == '|')
895 *ptr = '\0';
896 ptr--;
898 ofn.lpstrFilter = pszFilters;
900 ofn.nFilterIndex = 1;
901 ofn.lpstrFileTitle = NULL;
902 ofn.nMaxFileTitle = 0;
903 ofn.lpstrInitialDir = NULL;
904 CString temp;
905 if (title)
907 temp.LoadString(title);
908 CStringUtils::RemoveAccelerators(temp);
910 ofn.lpstrTitle = temp;
911 if (bOpen)
912 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
913 else
914 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
917 // Display the Open dialog box.
918 bool bRet = false;
919 if (bOpen)
921 bRet = !!GetOpenFileName(&ofn);
923 else
925 bRet = !!GetSaveFileName(&ofn);
927 if (bRet)
929 if (pszFilters)
930 delete [] pszFilters;
931 path = CString(ofn.lpstrFile);
932 if (filterindex)
933 *filterindex = ofn.nFilterIndex;
934 return true;
936 if (pszFilters)
937 delete [] pszFilters;
938 return false;
941 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
943 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
944 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
945 // create a bitmap from the icon
946 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
947 if (!hIcon)
948 return false;
950 RECT rect = {0};
951 rect.right = width;
952 rect.bottom = height;
953 HBITMAP bmp = NULL;
955 HWND desktop = ::GetDesktopWindow();
956 if (desktop)
958 HDC screen_dev = ::GetDC(desktop);
959 if (screen_dev)
961 // Create a compatible DC
962 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
963 if (dst_hdc)
965 // Create a new bitmap of icon size
966 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
967 if (bmp)
969 // Select it into the compatible DC
970 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
971 // Fill the background of the compatible DC with the given color
972 ::SetBkColor(dst_hdc, bkColor);
973 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
975 // Draw the icon into the compatible DC
976 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
977 ::SelectObject(dst_hdc, old_dst_bmp);
979 ::DeleteDC(dst_hdc);
982 ::ReleaseDC(desktop, screen_dev);
985 // Restore settings
986 DestroyIcon(hIcon);
988 if (bmp == NULL)
989 return false;
991 LVBKIMAGE lv;
992 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
993 lv.hbm = bmp;
994 lv.xOffsetPercent = 100;
995 lv.yOffsetPercent = 100;
996 ListView_SetBkImage(hListCtrl, &lv);
997 return true;
1000 CString CAppUtils::GetProjectNameFromURL(CString url)
1002 CString name;
1003 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1004 (name.CompareNoCase(_T("tags"))==0) ||
1005 (name.CompareNoCase(_T("trunk"))==0))
1007 name = url.Mid(url.ReverseFind('/')+1);
1008 url = url.Left(url.ReverseFind('/'));
1010 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1012 // a name of svn or svnroot indicates that it's not really the project name. In that
1013 // case, we try the first part of the URL
1014 // of course, this won't work in all cases (but it works for Google project hosting)
1015 url.Replace(_T("http://"), _T(""));
1016 url.Replace(_T("https://"), _T(""));
1017 url.Replace(_T("svn://"), _T(""));
1018 url.Replace(_T("svn+ssh://"), _T(""));
1019 url.TrimLeft(_T("/"));
1020 name = url.Left(url.Find('.'));
1022 return name;
1025 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1026 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1027 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1028 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1031 CString tempfile=GetTempFile();
1032 CString cmd;
1033 if(rev1 == GitRev::GetWorkingCopy())
1035 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1037 else
1039 CString merge;
1040 if(bMerge)
1041 merge = _T("-c");
1043 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1046 if( !url1.IsEmpty() )
1048 cmd += _T(" \"");
1049 cmd += url1.GetGitPathString();
1050 cmd += _T("\" ");
1052 g_Git.RunLogFile(cmd,tempfile);
1053 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1056 #if 0
1057 CString sCmd;
1058 sCmd.Format(_T("%s /command:showcompare /unified"),
1059 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1060 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1061 if (rev1.IsValid())
1062 sCmd += _T(" /revision1:") + rev1.ToString();
1063 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1064 if (rev2.IsValid())
1065 sCmd += _T(" /revision2:") + rev2.ToString();
1066 if (peg.IsValid())
1067 sCmd += _T(" /pegrevision:") + peg.ToString();
1068 if (headpeg.IsValid())
1069 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1071 if (bAlternateDiff)
1072 sCmd += _T(" /alternatediff");
1074 if (bIgnoreAncestry)
1075 sCmd += _T(" /ignoreancestry");
1077 if (hWnd)
1079 sCmd += _T(" /hwnd:");
1080 TCHAR buf[30];
1081 _stprintf_s(buf, 30, _T("%d"), hWnd);
1082 sCmd += buf;
1085 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1086 #endif
1087 return TRUE;
1091 bool CAppUtils::Export(CString *BashHash)
1093 bool bRet = false;
1095 // ask from where the export has to be done
1096 CExportDlg dlg;
1097 if(BashHash)
1098 dlg.m_Revision=*BashHash;
1100 if (dlg.DoModal() == IDOK)
1102 CString cmd;
1103 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1104 g_Git.FixBranchName(dlg.m_VersionName));
1106 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1107 CProgressDlg pro;
1108 pro.m_GitCmd=cmd;
1109 pro.m_LogFile=dlg.m_strExportDirectory;
1110 pro.DoModal();
1111 return TRUE;
1113 return bRet;
1116 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1118 CCreateBranchTagDlg dlg;
1119 dlg.m_bIsTag=IsTag;
1120 dlg.m_bSwitch=switch_new_brach;
1122 if(CommitHash)
1123 dlg.m_Base = *CommitHash;
1125 if(dlg.DoModal()==IDOK)
1127 CString cmd;
1128 CString force;
1129 CString track;
1130 if(dlg.m_bTrack)
1131 track=_T(" --track ");
1133 if(dlg.m_bForce)
1134 force=_T(" -f ");
1136 if(IsTag)
1138 CString sign;
1139 if(dlg.m_bSign)
1140 sign=_T("-s");
1142 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1143 track,
1144 force,
1145 sign,
1146 dlg.m_BranchTagName,
1147 g_Git.FixBranchName(dlg.m_VersionName)
1150 CString tempfile=::GetTempFile();
1151 if(!dlg.m_Message.Trim().IsEmpty())
1153 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1154 cmd += _T(" -F ")+tempfile;
1157 else
1159 cmd.Format(_T("git.exe branch %s %s %s %s"),
1160 track,
1161 force,
1162 dlg.m_BranchTagName,
1163 g_Git.FixBranchName(dlg.m_VersionName)
1166 CString out;
1167 if(g_Git.Run(cmd,&out,CP_UTF8))
1169 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1171 if( !IsTag && dlg.m_bSwitch )
1173 // it is a new branch and the user has requested to switch to it
1174 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1175 g_Git.Run(cmd,&out,CP_UTF8);
1176 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1179 return TRUE;
1181 return FALSE;
1184 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1186 CGitSwitchDlg dlg;
1187 if(CommitHash)
1188 dlg.m_Base=*CommitHash;
1189 if(!initialRefName.IsEmpty())
1190 dlg.m_initialRefName = initialRefName;
1192 if (dlg.DoModal() == IDOK)
1194 CString branch;
1195 if (dlg.m_bBranch)
1196 branch = dlg.m_NewBranch;
1198 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1200 return FALSE;
1203 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1205 CString cmd;
1206 CString track;
1207 CString force;
1208 CString branch;
1210 if(!sNewBranch.IsEmpty()){
1211 if (bBranchOverride)
1213 branch.Format(_T("-B %s"), sNewBranch);
1215 else
1217 branch.Format(_T("-b %s"), sNewBranch);
1219 if (bTrack)
1220 track = _T("--track");
1222 if (bForce)
1223 force = _T("-f");
1225 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1226 force,
1227 track,
1228 branch,
1229 g_Git.FixBranchName(ref));
1231 CProgressDlg progress;
1232 progress.m_bAutoCloseOnSuccess = autoClose;
1233 progress.m_GitCmd = cmd;
1235 CTGitPath gitPath = g_Git.m_CurrentDir;
1236 if (gitPath.HasSubmodules())
1237 progress.m_PostCmdList.Add(_T("Update Submodules"));
1239 int ret = progress.DoModal();
1240 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1242 CString sCmd;
1243 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1245 LaunchApplication(sCmd, NULL, false);
1246 return TRUE;
1248 else if (ret == IDOK)
1249 return TRUE;
1251 return FALSE;
1254 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1256 CString ignorefile;
1257 ignorefile=g_Git.m_CurrentDir+_T("\\");
1259 if(IsMask)
1261 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1264 else
1266 ignorefile += _T("\\.gitignore");
1269 CStdioFile file;
1270 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1272 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1273 return FALSE;
1276 CString ignorelist;
1277 CString mask;
1280 //file.ReadString(ignorelist);
1281 file.SeekToEnd();
1282 for(int i=0;i<path.GetCount();i++)
1284 if(IsMask)
1286 mask=_T("*")+path[i].GetFileExtension();
1287 if(ignorelist.Find(mask)<0)
1288 ignorelist += _T("\n")+mask;
1290 else
1292 ignorelist += _T("\n/")+path[i].GetGitPathString();
1295 file.WriteString(ignorelist);
1297 file.Close();
1299 }catch(...)
1301 file.Close();
1302 return FALSE;
1305 return TRUE;
1309 bool CAppUtils::GitReset(CString *CommitHash,int type)
1311 CResetDlg dlg;
1312 dlg.m_ResetType=type;
1313 dlg.m_ResetToVersion=*CommitHash;
1314 if (dlg.DoModal() == IDOK)
1316 CString cmd;
1317 CString type;
1318 switch(dlg.m_ResetType)
1320 case 0:
1321 type=_T("--soft");
1322 break;
1323 case 1:
1324 type=_T("--mixed");
1325 break;
1326 case 2:
1327 type=_T("--hard");
1328 break;
1329 default:
1330 type=_T("--mixed");
1331 break;
1333 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1335 CProgressDlg progress;
1336 progress.m_GitCmd=cmd;
1338 CTGitPath gitPath = g_Git.m_CurrentDir;
1339 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1340 progress.m_PostCmdList.Add(_T("Update Submodules"));
1342 int ret = progress.DoModal();
1343 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1345 CString sCmd;
1346 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1348 LaunchApplication(sCmd, NULL, false);
1349 return TRUE;
1351 else if (ret == IDOK)
1352 return TRUE;
1355 return FALSE;
1358 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1360 if(mode == FALSE)
1362 descript=_T("Deleted");
1363 return;
1365 if(base)
1367 descript=_T("Modified");
1368 return;
1370 descript=_T("Created");
1371 return;
1374 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1376 CString tempmergefile;
1379 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1380 CFile::Remove(tempmergefile);
1381 }catch(...)
1387 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1388 CFile::Remove(tempmergefile);
1389 }catch(...)
1395 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1396 CFile::Remove(tempmergefile);
1397 }catch(...)
1401 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1403 CString file;
1404 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1406 return file;
1409 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1411 bool bRet = false;
1413 CTGitPath merge=path;
1414 CTGitPath directory = merge.GetDirectory();
1416 // we have the conflicted file (%merged)
1417 // now look for the other required files
1418 //GitStatus stat;
1419 //stat.GetStatus(merge);
1420 //if (stat.status == NULL)
1421 // return false;
1423 BYTE_VECTOR vector;
1425 CString cmd;
1426 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1428 if (g_Git.Run(cmd, &vector))
1430 return FALSE;
1433 CTGitPathList list;
1434 list.ParserFromLsFile(vector);
1436 if(list.GetCount() == 0)
1437 return FALSE;
1439 CTGitPath theirs;
1440 CTGitPath mine;
1441 CTGitPath base;
1443 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1444 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1445 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1447 CString format;
1449 //format=_T("git.exe cat-file blob \":%d:%s\"");
1450 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1451 CFile tempfile;
1452 //create a empty file, incase stage is not three
1453 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1454 tempfile.Close();
1455 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1456 tempfile.Close();
1457 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1458 tempfile.Close();
1460 bool b_base=false, b_local=false, b_remote=false;
1462 for(int i=0;i<list.GetCount();i++)
1464 CString cmd;
1465 CString outfile;
1466 cmd.Empty();
1467 outfile.Empty();
1469 if( list[i].m_Stage == 1)
1471 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1472 b_base = true;
1473 outfile = base.GetWinPathString();
1476 if( list[i].m_Stage == 2 )
1478 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1479 b_local = true;
1480 outfile = mine.GetWinPathString();
1483 if( list[i].m_Stage == 3 )
1485 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1486 b_remote = true;
1487 outfile = theirs.GetWinPathString();
1489 CString output, err;
1490 if(!outfile.IsEmpty())
1491 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1493 CString file;
1494 int start =0 ;
1495 file = output.Tokenize(_T("\t"), start);
1496 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1498 else
1500 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1504 if(b_local && b_remote )
1506 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1507 if( revertTheirMy )
1508 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1509 else
1510 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1513 else
1515 CFile::Remove(mine.GetWinPathString());
1516 CFile::Remove(theirs.GetWinPathString());
1517 CFile::Remove(base.GetWinPathString());
1519 CDeleteConflictDlg dlg;
1520 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1521 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1522 dlg.m_bShowModifiedButton=b_base;
1523 dlg.m_File=merge.GetGitPathString();
1524 if(dlg.DoModal() == IDOK)
1526 CString cmd,out;
1527 if(dlg.m_bIsDelete)
1529 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1531 else
1532 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1534 if(g_Git.Run(cmd,&out,CP_ACP))
1536 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1537 return FALSE;
1539 return TRUE;
1541 else
1542 return FALSE;
1545 #if 0
1546 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1547 base, theirs, mine, merge);
1548 #endif
1549 #if 0
1550 if (stat.status->text_status == svn_wc_status_conflicted)
1552 // we have a text conflict, use our merge tool to resolve the conflict
1554 CTSVNPath theirs(directory);
1555 CTSVNPath mine(directory);
1556 CTSVNPath base(directory);
1557 bool bConflictData = false;
1559 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1561 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1562 bConflictData = true;
1564 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1566 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1567 bConflictData = true;
1569 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1571 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1572 bConflictData = true;
1574 else
1576 mine = merge;
1578 if (bConflictData)
1579 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1580 base, theirs, mine, merge);
1583 if (stat.status->prop_status == svn_wc_status_conflicted)
1585 // we have a property conflict
1586 CTSVNPath prej(directory);
1587 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1589 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1590 // there's a problem: the prej file contains a _description_ of the conflict, and
1591 // that description string might be translated. That means we have no way of parsing
1592 // the file to find out the conflicting values.
1593 // The only thing we can do: show a dialog with the conflict description, then
1594 // let the user either accept the existing property or open the property edit dialog
1595 // to manually change the properties and values. And a button to mark the conflict as
1596 // resolved.
1597 CEditPropConflictDlg dlg;
1598 dlg.SetPrejFile(prej);
1599 dlg.SetConflictedItem(merge);
1600 bRet = (dlg.DoModal() != IDCANCEL);
1604 if (stat.status->tree_conflict)
1606 // we have a tree conflict
1607 SVNInfo info;
1608 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1609 if (pInfoData)
1611 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1613 CTSVNPath theirs(directory);
1614 CTSVNPath mine(directory);
1615 CTSVNPath base(directory);
1616 bool bConflictData = false;
1618 if (pInfoData->treeconflict_theirfile)
1620 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1621 bConflictData = true;
1623 if (pInfoData->treeconflict_basefile)
1625 base.AppendPathString(pInfoData->treeconflict_basefile);
1626 bConflictData = true;
1628 if (pInfoData->treeconflict_myfile)
1630 mine.AppendPathString(pInfoData->treeconflict_myfile);
1631 bConflictData = true;
1633 else
1635 mine = merge;
1637 if (bConflictData)
1638 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1639 base, theirs, mine, merge);
1641 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1643 CString sConflictAction;
1644 CString sConflictReason;
1645 CString sResolveTheirs;
1646 CString sResolveMine;
1647 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1648 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1650 if (pInfoData->treeconflict_nodekind == svn_node_file)
1652 switch (pInfoData->treeconflict_operation)
1654 case svn_wc_operation_update:
1655 switch (pInfoData->treeconflict_action)
1657 case svn_wc_conflict_action_edit:
1658 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1659 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1660 break;
1661 case svn_wc_conflict_action_add:
1662 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1663 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1664 break;
1665 case svn_wc_conflict_action_delete:
1666 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1667 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1668 break;
1670 break;
1671 case svn_wc_operation_switch:
1672 switch (pInfoData->treeconflict_action)
1674 case svn_wc_conflict_action_edit:
1675 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1676 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1677 break;
1678 case svn_wc_conflict_action_add:
1679 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1680 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1681 break;
1682 case svn_wc_conflict_action_delete:
1683 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1684 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1685 break;
1687 break;
1688 case svn_wc_operation_merge:
1689 switch (pInfoData->treeconflict_action)
1691 case svn_wc_conflict_action_edit:
1692 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1693 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1694 break;
1695 case svn_wc_conflict_action_add:
1696 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1697 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1698 break;
1699 case svn_wc_conflict_action_delete:
1700 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1701 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1702 break;
1704 break;
1707 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1709 switch (pInfoData->treeconflict_operation)
1711 case svn_wc_operation_update:
1712 switch (pInfoData->treeconflict_action)
1714 case svn_wc_conflict_action_edit:
1715 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1716 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1717 break;
1718 case svn_wc_conflict_action_add:
1719 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1720 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1721 break;
1722 case svn_wc_conflict_action_delete:
1723 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1724 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1725 break;
1727 break;
1728 case svn_wc_operation_switch:
1729 switch (pInfoData->treeconflict_action)
1731 case svn_wc_conflict_action_edit:
1732 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1733 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1734 break;
1735 case svn_wc_conflict_action_add:
1736 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1737 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1738 break;
1739 case svn_wc_conflict_action_delete:
1740 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1741 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1742 break;
1744 break;
1745 case svn_wc_operation_merge:
1746 switch (pInfoData->treeconflict_action)
1748 case svn_wc_conflict_action_edit:
1749 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1750 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1751 break;
1752 case svn_wc_conflict_action_add:
1753 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1754 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1755 break;
1756 case svn_wc_conflict_action_delete:
1757 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1758 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1759 break;
1761 break;
1765 UINT uReasonID = 0;
1766 switch (pInfoData->treeconflict_reason)
1768 case svn_wc_conflict_reason_edited:
1769 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1770 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1771 break;
1772 case svn_wc_conflict_reason_obstructed:
1773 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1774 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1775 break;
1776 case svn_wc_conflict_reason_deleted:
1777 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1778 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1779 break;
1780 case svn_wc_conflict_reason_added:
1781 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1782 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1783 break;
1784 case svn_wc_conflict_reason_missing:
1785 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1786 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1787 break;
1788 case svn_wc_conflict_reason_unversioned:
1789 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1790 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1791 break;
1793 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1795 CTreeConflictEditorDlg dlg;
1796 dlg.SetConflictInfoText(sConflictReason);
1797 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1798 dlg.SetPath(treeConflictPath);
1799 INT_PTR dlgRet = dlg.DoModal();
1800 bRet = (dlgRet != IDCANCEL);
1804 #endif
1805 return bRet;
1809 * FUNCTION : FormatDateAndTime
1810 * DESCRIPTION : Generates a displayable string from a CTime object in
1811 * system short or long format or as a relative value
1812 * cTime - the time
1813 * option - DATE_SHORTDATE or DATE_LONGDATE
1814 * bIncluedeTime - whether to show time as well as date
1815 * bRelative - if true then relative time is shown if reasonable
1816 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1817 * rather than locale
1818 * RETURN : CString containing date/time
1820 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1821 bool bRelative /*=false*/)
1823 CString datetime;
1824 if ( bRelative )
1826 datetime = ToRelativeTimeString( cTime );
1828 else
1830 // should we use the locale settings for formatting the date/time?
1831 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1833 // yes
1834 SYSTEMTIME sysTime;
1835 cTime.GetAsSystemTime( sysTime );
1837 TCHAR buf[100];
1839 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1840 _countof(buf) - 1);
1841 datetime = buf;
1842 if ( bIncludeTime )
1844 datetime += _T(" ");
1845 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1846 datetime += buf;
1849 else
1851 // no, so fixed format
1852 if ( bIncludeTime )
1854 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1856 else
1858 datetime = cTime.Format(_T("%Y-%m-%d"));
1862 return datetime;
1866 * Converts a given time to a relative display string (relative to current time)
1867 * Given time must be in local timezone
1869 CString CAppUtils::ToRelativeTimeString(CTime time)
1871 CString answer;
1872 // convert to COleDateTime
1873 SYSTEMTIME sysTime;
1874 time.GetAsSystemTime( sysTime );
1875 COleDateTime oleTime( sysTime );
1876 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1877 return answer;
1881 * Generates a display string showing the relative time between the two given times as COleDateTimes
1883 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1885 CString answer;
1886 COleDateTimeSpan ts = RelativeTo - time;
1887 //years
1888 if(fabs(ts.GetTotalDays()) >= 3*365)
1890 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1892 //Months
1893 if(fabs(ts.GetTotalDays()) >= 60)
1895 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1896 return answer;
1898 //Weeks
1899 if(fabs(ts.GetTotalDays()) >= 14)
1901 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1902 return answer;
1904 //Days
1905 if(fabs(ts.GetTotalDays()) >= 2)
1907 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1908 return answer;
1910 //hours
1911 if(fabs(ts.GetTotalHours()) >= 2)
1913 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1914 return answer;
1916 //minutes
1917 if(fabs(ts.GetTotalMinutes()) >= 2)
1919 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1920 return answer;
1922 //seconds
1923 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1924 return answer;
1928 * Passed a value and two resource string ids
1929 * if count is 1 then FormatString is called with format_1 and the value
1930 * otherwise format_2 is used
1931 * the formatted string is returned
1933 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1935 CString answer;
1936 if ( count == 1 )
1938 answer.FormatMessage( format_1, count );
1940 else
1942 answer.FormatMessage( format_n, count );
1944 return answer;
1947 bool CAppUtils::IsSSHPutty()
1949 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1950 sshclient=sshclient.MakeLower();
1951 if(sshclient.Find(_T("plink.exe"),0)>=0)
1953 return true;
1955 return false;
1958 CString CAppUtils::GetClipboardLink()
1960 if (!OpenClipboard(NULL))
1961 return CString();
1963 CString sClipboardText;
1964 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1965 if (hglb)
1967 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1968 sClipboardText = CString(lpstr);
1969 GlobalUnlock(hglb);
1971 hglb = GetClipboardData(CF_UNICODETEXT);
1972 if (hglb)
1974 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1975 sClipboardText = lpstr;
1976 GlobalUnlock(hglb);
1978 CloseClipboard();
1980 if(!sClipboardText.IsEmpty())
1982 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1983 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1985 if(sClipboardText.Find( _T("http://")) == 0)
1986 return sClipboardText;
1988 if(sClipboardText.Find( _T("https://")) == 0)
1989 return sClipboardText;
1991 if(sClipboardText.Find( _T("git://")) == 0)
1992 return sClipboardText;
1994 if(sClipboardText.Find( _T("ssh://")) == 0)
1995 return sClipboardText;
1997 if(sClipboardText.GetLength()>=2)
1998 if( sClipboardText[1] == _T(':') )
1999 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2000 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2001 return sClipboardText;
2004 return CString(_T(""));
2007 CString CAppUtils::ChooseRepository(CString *path)
2009 CBrowseFolder browseFolder;
2010 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2012 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2013 CString strCloneDirectory;
2014 if(path)
2015 strCloneDirectory=*path;
2016 else
2018 strCloneDirectory = regLastResopitory;
2021 CString title;
2022 title.LoadString(IDS_CHOOSE_REPOSITORY);
2024 browseFolder.SetInfo(title);
2026 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2028 regLastResopitory = strCloneDirectory;
2029 return strCloneDirectory;
2031 else
2033 return CString();
2037 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2039 CSendMailDlg dlg;
2041 dlg.m_PathList = list;
2043 if(dlg.DoModal()==IDOK)
2045 if(dlg.m_PathList.GetCount() == 0)
2046 return FALSE;
2048 CGitProgressDlg progDlg;
2050 theApp.m_pMainWnd = &progDlg;
2051 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2053 progDlg.SetAutoClose(autoclose);
2055 progDlg.SetPathList(dlg.m_PathList);
2056 //ProjectProperties props;
2057 //props.ReadPropsPathList(dlg.m_pathList);
2058 //progDlg.SetProjectProperties(props);
2059 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2061 DWORD flags =0;
2062 if(dlg.m_bAttachment)
2063 flags |= SENDMAIL_ATTACHMENT;
2064 if(dlg.m_bCombine)
2065 flags |= SENDMAIL_COMBINED;
2066 if(dlg.m_bUseMAPI)
2067 flags |= SENDMAIL_MAPI;
2069 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2071 progDlg.DoModal();
2073 return true;
2075 return false;
2078 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2080 CTGitPathList list;
2081 CString log=formatpatchoutput;
2082 int start=log.Find(cmd);
2083 if(start >=0)
2084 CString one=log.Tokenize(_T("\n"),start);
2085 else
2086 start = 0;
2088 while(start>=0)
2090 CString one=log.Tokenize(_T("\n"),start);
2091 one=one.Trim();
2092 if(one.IsEmpty() || one == _T("Success"))
2093 continue;
2094 one.Replace(_T('/'),_T('\\'));
2095 CTGitPath path;
2096 path.SetFromWin(one);
2097 list.AddPath(path);
2099 if (list.GetCount() > 0)
2101 return SendPatchMail(list, autoclose);
2103 else
2105 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2106 return true;
2111 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2113 CString cmd,output;
2114 int start=0;
2116 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2117 if(output.IsEmpty())
2119 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2120 if(output.IsEmpty())
2121 return CP_UTF8;
2123 int start=0;
2124 output=output.Tokenize(_T("\n"),start);
2125 return CUnicodeUtils::GetCPCode(output);
2128 else
2130 output=output.Tokenize(_T("\n"),start);
2131 return CUnicodeUtils::GetCPCode(output);
2134 int CAppUtils::GetCommitTemplate(CString &temp)
2136 CString cmd,output;
2138 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2139 if( output.IsEmpty() )
2140 return -1;
2142 if( output.GetLength()<1)
2143 return -1;
2145 if( output[0] == _T('/'))
2147 if(output.GetLength()>=3)
2148 if(output[2] == _T('/'))
2150 output.GetBuffer()[0] = output[1];
2151 output.GetBuffer()[1] = _T(':');
2155 int start=0;
2156 output=output.Tokenize(_T("\n"),start);
2158 output.Replace(_T('/'),_T('\\'));
2162 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2163 CString str;
2164 while(file.ReadString(str))
2166 temp+=str+_T("\n");
2169 }catch(...)
2171 return -1;
2173 return 0;
2175 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2177 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2178 CString cmd,output;
2179 int cp=CP_UTF8;
2181 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2182 if(output.IsEmpty())
2183 cp=CP_UTF8;
2185 int start=0;
2186 output=output.Tokenize(_T("\n"),start);
2187 cp=CUnicodeUtils::GetCPCode(output);
2189 int len=message.GetLength();
2191 char * buf;
2192 buf = new char[len*4 + 4];
2193 SecureZeroMemory(buf, (len*4 + 4));
2195 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2197 file.Write(buf,lengthIncTerminator-1);
2198 file.Close();
2199 delete buf;
2200 return 0;
2203 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2205 CPullFetchDlg dlg;
2206 dlg.m_PreSelectRemote = remoteName;
2207 dlg.m_bAllowRebase = allowRebase;
2208 dlg.m_IsPull=FALSE;
2210 if(dlg.DoModal()==IDOK)
2212 if(dlg.m_bAutoLoad)
2214 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2217 CString url;
2218 url=dlg.m_RemoteURL;
2219 CString cmd;
2220 CString arg;
2222 int ver = CAppUtils::GetMsysgitVersion();
2224 if(ver >= 0x01070203) //above 1.7.0.2
2225 arg = _T("--progress ");
2227 if (dlg.m_bPrune) {
2228 arg += _T("--prune ");
2231 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2232 CProgressDlg progress;
2234 progress.m_bAutoCloseOnSuccess = autoClose;
2236 if(!dlg.m_bRebase)
2238 progress.m_PostCmdList.Add(_T("&Rebase"));
2241 progress.m_GitCmd=cmd;
2242 int userResponse=progress.DoModal();
2244 if( (userResponse==IDC_PROGRESS_BUTTON1) || ( progress.m_GitStatus ==0 && dlg.m_bRebase) )
2246 while(1)
2248 CRebaseDlg dlg;
2249 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2250 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2251 int response = dlg.DoModal();
2252 if(response == IDOK)
2254 return TRUE;
2256 if(response == IDC_REBASE_POST_BUTTON )
2258 CString cmd, out, err;
2259 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2260 g_Git.m_CurrentDir,
2261 g_Git.FixBranchName(dlg.m_Upstream),
2262 g_Git.FixBranchName(dlg.m_Branch));
2263 if (g_Git.Run(cmd, &out, &err, CP_ACP))
2265 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2266 return FALSE;
2269 CAppUtils::SendPatchMail(cmd,out);
2270 return TRUE;
2273 if(response == IDC_REBASE_POST_BUTTON +1 )
2274 continue;
2276 if(response == IDCANCEL)
2277 return FALSE;
2279 return TRUE;
2282 return FALSE;
2285 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2287 CPushDlg dlg;
2288 dlg.m_BranchSourceName = selectLocalBranch;
2289 CString error;
2290 DWORD exitcode = 0xFFFFFFFF;
2291 CTGitPathList list;
2292 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2293 if (CHooks::Instance().PrePush(list,exitcode, error))
2295 if (exitcode)
2297 CString temp;
2298 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2299 //ReportError(temp);
2300 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2301 return false;
2305 if(dlg.DoModal()==IDOK)
2307 CString cmd;
2308 CString arg;
2310 if(dlg.m_bAutoLoad)
2312 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2315 if(dlg.m_bPack)
2316 arg += _T("--thin ");
2317 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2318 arg += _T("--tags ");
2319 if(dlg.m_bForce)
2320 arg += _T("--force ");
2322 int ver = CAppUtils::GetMsysgitVersion();
2324 if(ver >= 0x01070203) //above 1.7.0.2
2325 arg += _T("--progress ");
2327 if (dlg.m_bPushAllBranches)
2329 cmd.Format(_T("git.exe push --all %s \"%s\""),
2330 arg,
2331 dlg.m_URL);
2333 else
2335 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2336 arg,
2337 dlg.m_URL,
2338 dlg.m_BranchSourceName);
2339 if (!dlg.m_BranchRemoteName.IsEmpty())
2341 cmd += _T(":") + dlg.m_BranchRemoteName;
2345 CProgressDlg progress;
2346 progress.m_bAutoCloseOnSuccess=autoClose;
2347 progress.m_GitCmd=cmd;
2348 progress.m_PostCmdList.Add(_T("&Request pull"));
2349 progress.m_PostCmdList.Add(_T("Re&Push"));
2350 int ret = progress.DoModal();
2352 if(!progress.m_GitStatus)
2354 if (CHooks::Instance().PostPush(list,exitcode, error))
2356 if (exitcode)
2358 CString temp;
2359 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2360 //ReportError(temp);
2361 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2362 return false;
2365 if(ret == IDC_PROGRESS_BUTTON1)
2367 RequestPull(dlg.m_BranchRemoteName);
2369 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2371 Push();
2373 return TRUE;
2377 return FALSE;
2380 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2382 CRequestPullDlg dlg;
2383 dlg.m_RepositoryURL = repositoryUrl;
2384 dlg.m_EndRevision = endrevision;
2385 if (dlg.DoModal()==IDOK)
2387 CString cmd;
2388 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2390 CProgressDlg progress;
2391 progress.m_GitCmd=cmd;
2392 progress.DoModal();
2394 return true;
2397 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2399 CString strDir(szPath);
2400 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2402 strDir.AppendChar(_T('\\'));
2404 std::vector<CString> vPath;
2405 CString strTemp;
2406 bool bSuccess = false;
2408 for (int i=0;i<strDir.GetLength();++i)
2410 if (strDir.GetAt(i) != _T('\\'))
2412 strTemp.AppendChar(strDir.GetAt(i));
2414 else
2416 vPath.push_back(strTemp);
2417 strTemp.AppendChar(_T('\\'));
2421 std::vector<CString>::const_iterator vIter;
2422 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2424 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2427 return bSuccess;
2430 void CAppUtils::RemoveTrailSlash(CString &path)
2432 if(path.IsEmpty())
2433 return ;
2435 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2437 path=path.Left(path.GetLength()-1);
2438 if(path.IsEmpty())
2439 return;
2443 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2444 CTGitPathList &pathList,
2445 CTGitPathList &selectedList,
2446 bool bSelectFilesForCommit,
2447 bool autoClose)
2449 bool bFailed = true;
2451 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2453 if(CMessageBox::Show(NULL,_T("User name and email must be set before commit.\r\n Do you want to set these now?\r\n"),
2454 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2456 CTGitPath path(g_Git.m_CurrentDir);
2457 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2458 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2459 dlg.SetTreeWidth(220);
2460 dlg.m_DefaultPage = _T("gitconfig");
2462 dlg.DoModal();
2463 dlg.HandleRestart();
2466 else
2467 return false;
2470 while (bFailed)
2472 bFailed = false;
2473 CCommitDlg dlg;
2474 dlg.m_sBugID = bugid;
2476 dlg.m_bWholeProject = bWholeProject;
2478 dlg.m_sLogMessage = sLogMsg;
2479 dlg.m_pathList = pathList;
2480 dlg.m_checkedPathList = selectedList;
2481 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2482 dlg.m_bAutoClose = autoClose;
2483 if (dlg.DoModal() == IDOK)
2485 if (dlg.m_pathList.GetCount()==0)
2486 return false;
2487 // if the user hasn't changed the list of selected items
2488 // we don't use that list. Because if we would use the list
2489 // of pre-checked items, the dialog would show different
2490 // checked items on the next startup: it would only try
2491 // to check the parent folder (which might not even show)
2492 // instead, we simply use an empty list and let the
2493 // default checking do its job.
2494 if (!dlg.m_pathList.IsEqual(pathList))
2495 selectedList = dlg.m_pathList;
2496 pathList = dlg.m_updatedPathList;
2497 sLogMsg = dlg.m_sLogMessage;
2498 bSelectFilesForCommit = true;
2500 if( dlg.m_bPushAfterCommit )
2502 switch(dlg.m_PostCmd)
2504 case GIT_POST_CMD_DCOMMIT:
2505 CAppUtils::SVNDCommit();
2506 break;
2507 default:
2508 CAppUtils::Push();
2511 // CGitProgressDlg progDlg;
2512 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2513 // if (parser.HasVal(_T("closeonend")))
2514 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2515 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2516 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2517 // progDlg.SetPathList(dlg.m_pathList);
2518 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2519 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2520 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2521 // progDlg.SetItemCount(dlg.m_itemsCount);
2522 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2523 // progDlg.DoModal();
2524 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2525 // err = (DWORD)progDlg.DidErrorsOccur();
2526 // bFailed = progDlg.DidErrorsOccur();
2527 // bRet = progDlg.DidErrorsOccur();
2528 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2529 // if (DWORD(bFailRepeat)==0)
2530 // bFailed = false; // do not repeat if the user chose not to in the settings.
2533 return true;
2537 BOOL CAppUtils::SVNDCommit()
2539 CSVNDCommitDlg dcommitdlg;
2540 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2541 if (gitSetting == _T("")) {
2542 if (dcommitdlg.DoModal() != IDOK)
2544 return false;
2546 else
2548 if (dcommitdlg.m_remember)
2550 if (dcommitdlg.m_rmdir)
2552 gitSetting = _T("true");
2554 else
2556 gitSetting = _T("false");
2558 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2560 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2566 BOOL IsStash = false;
2567 if(!g_Git.CheckCleanWorkTree())
2569 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2571 CString cmd,out;
2572 cmd=_T("git.exe stash");
2573 if(g_Git.Run(cmd,&out,CP_ACP))
2575 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2576 return false;
2578 IsStash =true;
2581 else
2583 return false;
2587 CProgressDlg progress;
2588 if (dcommitdlg.m_rmdir)
2590 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2592 else
2594 progress.m_GitCmd=_T("git.exe svn dcommit");
2596 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2598 if( IsStash)
2600 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2602 CString cmd,out;
2603 cmd=_T("git.exe stash pop");
2604 if(g_Git.Run(cmd,&out,CP_ACP))
2606 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2607 return false;
2611 else
2613 return false;
2616 return TRUE;
2618 return FALSE;
2621 BOOL CAppUtils::Merge(CString *commit)
2623 CMergeDlg dlg;
2624 if(commit)
2625 dlg.m_initialRefName = *commit;
2627 if(dlg.DoModal()==IDOK)
2629 CString cmd;
2630 CString noff;
2631 CString squash;
2632 CString nocommit;
2633 CString msg;
2635 if(dlg.m_bNoFF)
2636 noff=_T("--no-ff");
2638 if(dlg.m_bSquash)
2639 squash=_T("--squash");
2641 if(dlg.m_bNoCommit)
2642 nocommit=_T("--no-commit");
2644 if(!dlg.m_strLogMesage.IsEmpty())
2646 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2648 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2649 msg,
2650 noff,
2651 squash,
2652 nocommit,
2653 g_Git.FixBranchName(dlg.m_VersionName));
2655 CProgressDlg Prodlg;
2656 Prodlg.m_GitCmd = cmd;
2658 if (dlg.m_bNoCommit)
2659 Prodlg.m_PostCmdList.Add(_T("Commit"));
2661 int ret = Prodlg.DoModal();
2663 if (ret == IDC_PROGRESS_BUTTON1)
2664 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2666 return !Prodlg.m_GitStatus;
2668 return false;
2671 void CAppUtils::EditNote(GitRev *rev)
2673 CInputDlg dlg;
2674 dlg.m_sHintText=_T("Edit Notes");
2675 dlg.m_sInputText = rev->m_Notes;
2676 dlg.m_sTitle=_T("Edit Notes");
2677 //dlg.m_pProjectProperties = &m_ProjectProperties;
2678 dlg.m_bUseLogWidth = true;
2679 if(dlg.DoModal() == IDOK)
2681 CString cmd,output;
2682 cmd=_T("notes add -f -F \"");
2684 CString tempfile=::GetTempFile();
2685 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2686 cmd += tempfile;
2687 cmd += _T("\" ");
2688 cmd += rev->m_CommitHash.ToString();
2692 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2694 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2697 else
2699 rev->m_Notes = dlg.m_sInputText;
2701 }catch(...)
2703 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2705 CFile::Remove(tempfile);
2710 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2712 CString cmd;
2713 CString progressarg;
2714 CString version;
2716 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2717 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2719 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2721 __int64 time=0;
2722 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2724 if((DWORD)time == regTime)
2726 return regVersion;
2730 if(versionstr)
2731 version = *versionstr;
2732 else
2734 CString err;
2735 cmd = _T("git.exe --version");
2736 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2738 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2739 return false;
2743 int start=0;
2744 int ver;
2746 CString str=version.Tokenize(_T("."),start);
2747 int space = str.ReverseFind(_T(' '));
2748 str=str.Mid(space+1,start);
2749 ver = _ttol(str);
2750 ver <<=24;
2752 version = version.Mid(start);
2753 start = 0;
2754 str = version.Tokenize(_T("."),start);
2756 ver |= (_ttol(str)&0xFF)<<16;
2758 str = version.Tokenize(_T("."),start);
2759 ver |= (_ttol(str)&0xFF)<<8;
2761 str = version.Tokenize(_T("."),start);
2762 ver |= (_ttol(str)&0xFF);
2764 regTime = time&0xFFFFFFFF;
2765 regVersion = ver;
2767 return ver;
2770 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2772 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2774 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2776 if (hShell) {
2777 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2778 if (pfnSHGPSFW) {
2779 IPropertyStore *pps;
2780 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2781 if (SUCCEEDED(hr)) {
2782 PROPVARIANT var;
2783 var.vt = VT_BOOL;
2784 var.boolVal = VARIANT_TRUE;
2785 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2786 pps->Release();
2789 FreeLibrary(hShell);
2793 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2795 ASSERT(dialogname.GetLength() < 70);
2796 ASSERT(urlorpath.GetLength() < MAX_PATH);
2797 WCHAR pathbuf[MAX_PATH] = {0};
2799 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2801 wcscat_s(pathbuf, L" - ");
2802 wcscat_s(pathbuf, dialogname);
2803 wcscat_s(pathbuf, L" - ");
2804 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2805 SetWindowText(hWnd, pathbuf);