git fetch show progress
[TortoiseGit.git] / src / TortoiseProc / ProgressDlg.cpp
blob025709377a48cfbab9cc4ce1a775f50522623865
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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 // ProgressDlg.cpp : implementation file
22 #include "stdafx.h"
23 #include "TortoiseProc.h"
24 #include "ProgressDlg.h"
25 #include "Git.h"
26 #include "atlconv.h"
27 #include "UnicodeUtils.h"
28 #include "IconMenu.h"
29 #include "LoglistCommonResource.h"
30 #include <Tlhelp32.h>
31 #include "AppUtils.h"
32 #include "SmartHandle.h"
33 #include "../TGitCache/CacheInterface.h"
34 #include "LoglistUtils.h"
35 #include "Win7.h"
36 #include "MessageBox.h"
37 #include "LogFile.h"
38 #include "CmdLineParser.h"
40 // CProgressDlg dialog
42 IMPLEMENT_DYNAMIC(CProgressDlg, CResizableStandAloneDialog)
44 CProgressDlg::CProgressDlg(CWnd* pParent /*=NULL*/)
45 : CResizableStandAloneDialog(CProgressDlg::IDD, pParent)
46 , m_bShowCommand(true)
47 , m_bAbort(false)
48 , m_bDone(false)
49 , m_startTick(GetTickCount())
50 , m_BufStart(0)
51 , m_Git(&g_Git)
53 m_pThread = NULL;
54 m_bBufferAll=false;
55 m_GitStatus = (DWORD)-1;
56 int autoClose = CRegDWORD(_T("Software\\TortoiseGit\\AutoCloseGitProgress"), 0);
57 CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);
58 if (parser.HasKey(_T("closeonend")))
59 autoClose = parser.GetLongVal(_T("closeonend"));
60 switch (autoClose)
62 case 1:
63 m_AutoClose = AUTOCLOSE_IF_NO_OPTIONS;
64 break;
65 case 2:
66 m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
67 break;
68 default:
69 m_AutoClose = AUTOCLOSE_NO;
70 break;
74 CProgressDlg::~CProgressDlg()
76 if(m_pThread != NULL)
78 delete m_pThread;
82 void CProgressDlg::DoDataExchange(CDataExchange* pDX)
84 CDialog::DoDataExchange(pDX);
85 DDX_Control(pDX, IDC_CURRENT, this->m_CurrentWork);
86 DDX_Control(pDX, IDC_TITLE_ANIMATE, this->m_Animate);
87 DDX_Control(pDX, IDC_RUN_PROGRESS, this->m_Progress);
88 DDX_Control(pDX, IDC_LOG, this->m_Log);
89 DDX_Control(pDX, IDC_PROGRESS_BUTTON1, this->m_ctrlPostCmd);
92 BEGIN_MESSAGE_MAP(CProgressDlg, CResizableStandAloneDialog)
93 ON_WM_CLOSE()
94 ON_MESSAGE(MSG_PROGRESSDLG_UPDATE_UI, OnProgressUpdateUI)
95 ON_BN_CLICKED(IDOK, &CProgressDlg::OnBnClickedOk)
96 ON_BN_CLICKED(IDC_PROGRESS_BUTTON1,&CProgressDlg::OnBnClickedButton1)
97 ON_REGISTERED_MESSAGE(WM_TASKBARBTNCREATED, OnTaskbarBtnCreated)
98 END_MESSAGE_MAP()
100 BOOL CProgressDlg::OnInitDialog()
102 CResizableStandAloneDialog::OnInitDialog();
104 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
105 // do this, Explorer would be unable to send that message to our window if we
106 // were running elevated. It's OK to make the call all the time, since if we're
107 // not elevated, this is a no-op.
108 CHANGEFILTERSTRUCT cfs = { sizeof(CHANGEFILTERSTRUCT) };
109 typedef BOOL STDAPICALLTYPE ChangeWindowMessageFilterExDFN(HWND hWnd, UINT message, DWORD action, PCHANGEFILTERSTRUCT pChangeFilterStruct);
110 CAutoLibrary hUser = AtlLoadSystemLibraryUsingFullPath(_T("user32.dll"));
111 if (hUser)
113 ChangeWindowMessageFilterExDFN *pfnChangeWindowMessageFilterEx = (ChangeWindowMessageFilterExDFN*)GetProcAddress(hUser, "ChangeWindowMessageFilterEx");
114 if (pfnChangeWindowMessageFilterEx)
116 pfnChangeWindowMessageFilterEx(m_hWnd, WM_TASKBARBTNCREATED, MSGFLT_ALLOW, &cfs);
119 m_pTaskbarList.Release();
120 if (FAILED(m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList)))
121 m_pTaskbarList = nullptr;
123 AddAnchor(IDC_TITLE_ANIMATE, TOP_LEFT, TOP_RIGHT);
124 AddAnchor(IDC_RUN_PROGRESS, TOP_LEFT,TOP_RIGHT);
125 AddAnchor(IDC_LOG, TOP_LEFT,BOTTOM_RIGHT);
127 AddAnchor(IDOK,BOTTOM_RIGHT);
128 AddAnchor(IDCANCEL,BOTTOM_RIGHT);
129 AddAnchor(IDC_PROGRESS_BUTTON1,BOTTOM_LEFT);
130 AddAnchor(IDC_CURRENT,TOP_LEFT);
132 this->GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_HIDE);
133 m_Animate.Open(IDR_DOWNLOAD);
135 CFont m_logFont;
136 CAppUtils::CreateFontForLogs(m_logFont);
137 //GetDlgItem(IDC_CMD_LOG)->SetFont(&m_logFont);
138 m_Log.SetFont(&m_logFont);
140 CString InitialText;
141 if ( !m_PreText.IsEmpty() )
143 InitialText = m_PreText + _T("\r\n");
145 #if 0
146 if (m_bShowCommand && (!m_GitCmd.IsEmpty() ))
148 InitialText += m_GitCmd+_T("\r\n\r\n");
150 #endif
151 m_Log.SetWindowTextW(InitialText);
152 m_CurrentWork.SetWindowTextW(_T(""));
154 EnableSaveRestore(_T("ProgressDlg"));
156 m_pThread = AfxBeginThread(ProgressThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
157 if (m_pThread==NULL)
159 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
160 DialogEnableWindow(IDCANCEL, TRUE);
162 else
164 m_pThread->m_bAutoDelete = FALSE;
165 m_pThread->ResumeThread();
168 CString sWindowTitle;
169 GetWindowText(sWindowTitle);
170 CAppUtils::SetWindowTitle(m_hWnd, m_Git->m_CurrentDir, sWindowTitle);
172 // Make sure this dialog is shown in foreground (see issue #1536)
173 SetForegroundWindow();
175 return TRUE;
178 static void EnsurePostMessage(CWnd *pWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
180 redo:
181 if (!pWnd->PostMessage(Msg, wParam, lParam))
183 if (GetLastError() == ERROR_NOT_ENOUGH_QUOTA)
185 Sleep(20);
186 goto redo;
188 else
189 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Message %d-%d could not be sent (error %d; %s)\n"), wParam, lParam, GetLastError(), (CString)CFormatMessageWrapper());
193 UINT CProgressDlg::ProgressThreadEntry(LPVOID pVoid)
195 return ((CProgressDlg*)pVoid)->ProgressThread();
198 //static function, Share with SyncDialog
199 UINT CProgressDlg::RunCmdList(CWnd *pWnd, STRING_VECTOR &cmdlist, STRING_VECTOR &dirlist, bool bShowCommand, CString *pfilename, bool *bAbort, CGitByteArray *pdata, CGit *git)
201 UINT ret=0;
203 std::vector<std::unique_ptr<CBlockCacheForPath>> cacheBlockList;
204 std::vector<std::unique_ptr<CGit>> gitList;
205 if (dirlist.empty())
206 cacheBlockList.push_back(std::unique_ptr<CBlockCacheForPath>(new CBlockCacheForPath(git->m_CurrentDir)));
207 else
209 for (auto dir : dirlist)
211 CGit *pGit = new CGit;
212 pGit->m_CurrentDir = dir;
213 gitList.push_back(std::unique_ptr<CGit>(pGit));
214 cacheBlockList.push_back(std::unique_ptr<CBlockCacheForPath>(new CBlockCacheForPath(dir)));
218 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_START, 0);
220 if(pdata)
221 pdata->clear();
223 for (size_t i = 0; i < cmdlist.size(); ++i)
225 if(cmdlist[i].IsEmpty())
226 continue;
228 if (bShowCommand)
230 CStringA str;
231 if (gitList.empty() || gitList.size() == 1 && gitList[0]->m_CurrentDir == git->m_CurrentDir)
232 str = CUnicodeUtils::GetMulti(cmdlist[i].Trim() + _T("\r\n\r\n"), CP_UTF8);
233 else
234 str = CUnicodeUtils::GetMulti((i > 0 ? _T("\r\n") : _T("")) + gitList[i]->m_CurrentDir + _T("\r\n") + cmdlist[i].Trim() + _T("\r\n\r\n"), CP_UTF8);
235 for (int j = 0; j < str.GetLength(); ++j)
237 if(pdata)
239 pdata->m_critSec.Lock();
240 pdata->push_back(str[j]);
241 pdata->m_critSec.Unlock();
243 else
244 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,str[j]);
246 if(pdata)
247 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,0);
250 PROCESS_INFORMATION pi;
251 CAutoGeneralHandle hRead;
252 int runAsyncRet = -1;
253 if (gitList.empty())
254 runAsyncRet = git->RunAsync(cmdlist[i].Trim(), &pi, hRead.GetPointer(), nullptr, pfilename);
255 else
256 runAsyncRet = gitList[i]->RunAsync(cmdlist[i].Trim(), &pi, hRead.GetPointer(), nullptr, pfilename);
257 if (runAsyncRet)
259 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_FAILED, -1 * runAsyncRet);
260 return runAsyncRet;
263 CAutoGeneralHandle piProcess(pi.hProcess);
264 CAutoGeneralHandle piThread(pi.hThread);
265 DWORD readnumber;
266 char lastByte = '\0';
267 char byte;
268 CString output;
269 while(ReadFile(hRead,&byte,1,&readnumber,NULL))
271 if(pdata)
273 if(byte == 0)
274 byte = '\n';
276 pdata->m_critSec.Lock();
277 if (byte == '\n' && lastByte != '\r')
278 pdata->push_back('\r');
279 pdata->push_back( byte);
280 lastByte = byte;
281 pdata->m_critSec.Unlock();
283 if(byte == '\r' || byte == '\n')
284 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,0);
286 else
287 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,byte);
289 if (pdata)
291 pdata->m_critSec.Lock();
292 bool post = !pdata->empty();
293 pdata->m_critSec.Unlock();
294 if (post)
295 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_RUN, 0);
298 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": waiting for process to finish (%s), aborted: %d\n"), cmdlist[i], *bAbort);
300 WaitForSingleObject(pi.hProcess, INFINITE);
302 DWORD status=0;
303 if(!GetExitCodeProcess(pi.hProcess,&status) || *bAbort)
305 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process %s finished, status code could not be fetched, (error %d; %s), aborted: %d\n"), cmdlist[i], GetLastError(), (CString)CFormatMessageWrapper(), *bAbort);
307 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_FAILED, status);
308 return TGIT_GIT_ERROR_GET_EXIT_CODE;
310 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process %s finished with code %d\n"), cmdlist[i], status);
311 ret |= status;
314 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_END, ret);
316 return ret;
319 UINT CProgressDlg::ProgressThread()
322 m_GitCmdList.push_back(m_GitCmd);
324 CString *pfilename;
326 if(m_LogFile.IsEmpty())
327 pfilename=NULL;
328 else
329 pfilename=&m_LogFile;
331 m_startTick = GetTickCount();
332 m_GitStatus = RunCmdList(this, m_GitCmdList, m_GitDirList, m_bShowCommand, pfilename, &m_bAbort, &this->m_Databuf, m_Git);
333 return 0;
336 LRESULT CProgressDlg::OnProgressUpdateUI(WPARAM wParam,LPARAM lParam)
338 if(wParam == MSG_PROGRESSDLG_START)
340 m_BufStart = 0 ;
341 m_Animate.Play(0, INT_MAX, INT_MAX);
342 DialogEnableWindow(IDCANCEL, TRUE);
343 if (m_pTaskbarList)
345 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
346 m_pTaskbarList->SetProgressValue(m_hWnd, 0, 100);
349 if(wParam == MSG_PROGRESSDLG_END || wParam == MSG_PROGRESSDLG_FAILED)
351 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": got message: %d\n"), wParam);
352 DWORD tickSpent = GetTickCount() - m_startTick;
353 CString strEndTime = CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE, true, false);
355 if(m_bBufferAll)
357 m_Databuf.m_critSec.Lock();
358 m_Databuf.push_back(0);
359 m_Log.SetWindowText(Convert2UnionCode((char*)&m_Databuf[0]));
360 m_Databuf.m_critSec.Unlock();
361 m_Log.LineScroll(m_Log.GetLineCount() - m_Log.GetFirstVisibleLine() - 4);
363 m_BufStart=0;
364 m_Databuf.m_critSec.Lock();
365 this->m_Databuf.clear();
366 m_Databuf.m_critSec.Unlock();
368 m_bDone = true;
369 m_Animate.Stop();
370 m_Progress.SetPos(100);
371 this->DialogEnableWindow(IDOK,TRUE);
373 m_GitStatus = (DWORD)lParam;
375 // detect crashes of perl when performing git svn actions
376 if (m_GitStatus == 0 && m_GitCmd.Find(_T(" svn ")) > 1)
378 CString log;
379 m_Log.GetWindowText(log);
380 if (log.GetLength() > 18 && log.Mid(log.GetLength() - 18) == _T("perl.exe.stackdump"))
381 m_GitStatus = (DWORD)-1;
384 if(this->m_GitStatus)
386 if (m_pTaskbarList)
388 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
389 m_pTaskbarList->SetProgressValue(m_hWnd, 100, 100);
391 CString log;
392 log.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT, m_GitStatus);
393 CString err;
394 if (CRegDWORD(_T("Software\\TortoiseGit\\ShowGitexeTimings"), TRUE))
395 err.Format(_T("\r\n\r\n%s (%lu ms @ %s)\r\n"), log, tickSpent, strEndTime);
396 else
397 err.Format(_T("\r\n\r\n%s\r\n"), log);
398 InsertColorText(this->m_Log, err, RGB(255,0,0));
399 PlaySound((LPCTSTR)SND_ALIAS_SYSTEMEXCLAMATION, NULL, SND_ALIAS_ID | SND_ASYNC);
401 else {
402 if (m_pTaskbarList)
403 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
404 CString temp;
405 temp.LoadString(IDS_SUCCESS);
406 CString log;
407 if (CRegDWORD(_T("Software\\TortoiseGit\\ShowGitexeTimings"), TRUE))
408 log.Format(_T("\r\n%s (%lu ms @ %s)\r\n"), temp, tickSpent, strEndTime);
409 else
410 log.Format(_T("\r\n%s\r\n"), temp);
411 InsertColorText(this->m_Log, log, RGB(0,0,255));
412 this->DialogEnableWindow(IDCANCEL,FALSE);
415 if (wParam == MSG_PROGRESSDLG_END)
417 if (m_PostCmdCallback) // new handling method using callback
419 m_PostCmdCallback(m_GitStatus, m_PostCmdList);
421 if (!m_PostCmdList.empty())
423 for (auto it = m_PostCmdList.cbegin(); it != m_PostCmdList.cend(); ++it)
424 m_ctrlPostCmd.AddEntry((*it).icon, (*it).label);
425 GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
430 if(wParam == MSG_PROGRESSDLG_END && m_GitStatus == 0)
432 if (m_AutoClose == AUTOCLOSE_IF_NO_OPTIONS && m_PostCmdList.empty() || m_AutoClose == AUTOCLOSE_IF_NO_ERRORS)
433 PostMessage(WM_COMMAND, 1, (LPARAM)GetDlgItem(IDOK)->m_hWnd);
437 if(!m_bBufferAll)
439 if(lParam == 0)
441 m_Databuf.m_critSec.Lock();
442 for (size_t i = this->m_BufStart; i < this->m_Databuf.size(); ++i)
444 char c = this->m_Databuf[m_BufStart];
445 ++m_BufStart;
446 m_Databuf.m_critSec.Unlock();
447 ParserCmdOutput(c);
449 m_Databuf.m_critSec.Lock();
452 if(m_BufStart>1000)
454 m_Databuf.erase(m_Databuf.begin(), m_Databuf.begin()+m_BufStart);
455 m_BufStart =0;
457 m_Databuf.m_critSec.Unlock();
460 else
461 ParserCmdOutput((char)lParam);
463 return 0;
466 //static function, Share with SyncDialog
467 int CProgressDlg::FindPercentage(CString &log)
469 int s1=log.Find(_T('%'));
470 if(s1<0)
471 return -1;
473 int s2=s1-1;
474 for(int i=s1-1;i>=0;i--)
476 if(log[i]>=_T('0') && log[i]<=_T('9'))
477 s2=i;
478 else
479 break;
481 return _ttol(log.Mid(s2,s1-s2));
484 void CProgressDlg::ParserCmdOutput(char ch)
486 ParserCmdOutput(this->m_Log,this->m_Progress,this->m_hWnd,this->m_pTaskbarList,this->m_LogTextA,ch,&this->m_CurrentWork);
488 void CProgressDlg::ClearESC(CString &str)
490 // see http://ascii-table.com/ansi-escape-sequences.php and http://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html
491 str.Replace(_T("\033[K"), _T("")); // erase until end of line; no need to care for this, because we always clear the whole line
493 // drop colors
494 while (true)
496 int escapePosition = str.Find(_T('\033'));
497 if (escapePosition >= 0 && str.GetLength() >= escapePosition + 3)
499 if (str.Mid(escapePosition, 2) == _T("\033["))
501 int colorEnd = str.Find(_T('m'), escapePosition + 2);
502 if (colorEnd > 0)
504 bool found = true;
505 for (int i = escapePosition + 2; i < colorEnd; ++i)
507 if (str[i] != _T(';') && (str[i] < _T('0') && str[i] > _T('9')))
509 found = false;
510 break;
513 if (found)
515 if (escapePosition > 0)
516 str = str.Left(escapePosition) + str.Mid(colorEnd + 1);
517 else
518 str = str.Mid(colorEnd);
519 continue;
524 break;
527 void CProgressDlg::ParserCmdOutput(CRichEditCtrl &log,CProgressCtrl &progressctrl,HWND m_hWnd,CComPtr<ITaskbarList3> m_pTaskbarList,CStringA &oneline, char ch, CWnd *CurrentWork)
529 //TRACE(_T("%c"),ch);
530 if( ch == ('\r') || ch == ('\n'))
532 CString str;
534 // TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
535 // TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));
537 int lines = log.GetLineCount();
538 g_Git.StringAppend(&str, (BYTE*)oneline.GetBuffer(), CP_UTF8);
539 str.Trim();
540 // TRACE(_T("%s"), str);
542 ClearESC(str);
544 if(ch == ('\r'))
546 int start=log.LineIndex(lines-1);
547 log.SetSel(start, log.GetTextLength());
548 log.ReplaceSel(str);
550 else
552 int length = log.GetWindowTextLength();
553 log.SetSel(length, length);
554 if (length > 0)
555 log.ReplaceSel(_T("\r\n") + str);
556 else
557 log.ReplaceSel(str);
560 if (lines > 500) //limited log length
562 int end=log.LineIndex(1);
563 log.SetSel(0,end);
564 log.ReplaceSel(_T(""));
566 log.LineScroll(log.GetLineCount() - log.GetFirstVisibleLine() - 4);
568 int s1=oneline.ReverseFind(_T(':'));
569 int s2=oneline.Find(_T('%'));
570 if (s1 > 0 && s2 > 0)
572 if(CurrentWork)
573 CurrentWork->SetWindowTextW(str.Left(s1));
575 int pos=FindPercentage(str);
576 TRACE(_T("Pos %d\r\n"),pos);
577 if(pos>0)
579 progressctrl.SetPos(pos);
580 if (m_pTaskbarList)
582 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
583 m_pTaskbarList->SetProgressValue(m_hWnd, pos, 100);
588 oneline="";
591 else
593 oneline+=ch;
596 void CProgressDlg::RemoveLastLine(CString &str)
598 int start;
599 start=str.ReverseFind(_T('\n'));
600 if(start>0)
601 str=str.Left(start);
602 return;
604 // CProgressDlg message handlers
606 void CProgressDlg::WriteLog() const
608 CLogFile logfile(g_Git.m_CurrentDir);
609 if (logfile.Open())
611 logfile.AddTimeLine();
612 CString text = GetLogText();
613 LPTSTR psz_string = text.GetBuffer();
614 while (*psz_string)
616 if (*psz_string == '\r')
618 ++psz_string;
619 continue;
621 size_t i_len = wcscspn(psz_string, L"\n");
622 logfile.AddLine(CString(psz_string, (int)i_len));
623 psz_string += i_len;
624 if (*psz_string == '\n')
625 ++psz_string;
627 if (m_bAbort)
629 CString canceled;
630 canceled.LoadString(IDS_SVN_USERCANCELLED);
631 logfile.AddLine(canceled);
633 logfile.Close();
637 void CProgressDlg::OnBnClickedOk()
639 if (m_pThread) // added here because Close-button is "called" from thread by PostMessage
640 ::WaitForSingleObject(m_pThread->m_hThread, 5000);
641 m_Log.GetWindowText(this->m_LogText);
642 WriteLog();
643 OnOK();
646 void CProgressDlg::OnBnClickedButton1()
648 WriteLog();
649 ShowWindow(SW_HIDE);
650 m_PostCmdList.at(m_ctrlPostCmd.GetCurrentEntry()).action();
651 EndDialog(IDOK);
654 void CProgressDlg::OnClose()
656 DialogEnableWindow(IDCANCEL, TRUE);
657 __super::OnClose();
660 void CProgressDlg::OnCancel()
662 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": User canceled\n"));
663 m_bAbort = true;
664 if(m_bDone)
666 WriteLog();
667 CResizableStandAloneDialog::OnCancel();
668 return;
671 if( m_Git->m_CurrentGitPi.hProcess )
673 DWORD dwConfirmKillProcess = CRegDWORD(_T("Software\\TortoiseGit\\ConfirmKillProcess"));
674 if (dwConfirmKillProcess && CMessageBox::Show(m_hWnd, IDS_PROC_CONFIRMKILLPROCESS, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) != IDYES)
675 return;
676 if(::GenerateConsoleCtrlEvent(CTRL_C_EVENT,0))
678 ::WaitForSingleObject(m_Git->m_CurrentGitPi.hProcess ,10000);
681 KillProcessTree(m_Git->m_CurrentGitPi.dwProcessId);
684 ::WaitForSingleObject(m_Git->m_CurrentGitPi.hProcess ,10000);
685 if (m_pThread)
686 ::WaitForSingleObject(m_pThread->m_hThread, 5000);
687 WriteLog();
688 CResizableStandAloneDialog::OnCancel();
691 void CProgressDlg::KillProcessTree(DWORD dwProcessId, unsigned int depth)
693 // recursively kills a process tree
694 // This is not optimized, but works and isn't called very often ;)
696 if (!dwProcessId || depth > 20)
697 return;
699 PROCESSENTRY32 pe;
700 memset(&pe, 0, sizeof(PROCESSENTRY32));
701 pe.dwSize = sizeof(PROCESSENTRY32);
703 CAutoGeneralHandle hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
705 if (::Process32First(hSnap, &pe))
709 if (pe.th32ParentProcessID == dwProcessId)
710 KillProcessTree(pe.th32ProcessID, depth + 1);
711 } while (::Process32Next(hSnap, &pe));
713 CAutoGeneralHandle hProc = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);
714 if (hProc)
715 ::TerminateProcess(hProc, 1);
719 void CProgressDlg::InsertColorText(CRichEditCtrl &edit,CString text,COLORREF rgb)
721 CHARFORMAT old,cf;
722 edit.GetDefaultCharFormat(cf);
723 old=cf;
724 cf.dwMask|=CFM_COLOR;
725 cf.crTextColor=rgb;
726 cf.dwEffects|=CFE_BOLD;
727 cf.dwEffects &= ~CFE_AUTOCOLOR ;
728 edit.SetSel(edit.GetTextLength()-1,edit.GetTextLength());
729 edit.ReplaceSel(text);
730 edit.SetSel(edit.LineIndex(edit.GetLineCount()-2),edit.GetTextLength());
731 edit.SetSelectionCharFormat(cf);
732 edit.SetSel(edit.GetTextLength(),edit.GetTextLength());
733 edit.SetDefaultCharFormat(old);
734 edit.LineScroll(edit.GetLineCount() - edit.GetFirstVisibleLine() - 4);
737 CString CCommitProgressDlg::Convert2UnionCode(char *buff, int size)
739 int start=0;
740 if(size == -1)
741 size = (int)strlen(buff);
743 for (int i = 0; i < size; ++i)
745 if(buff[i] == ']')
746 start = i;
747 if( start >0 && buff[i] =='\n' )
749 start =i;
750 break;
754 CString str;
755 g_Git.StringAppend(&str, (BYTE*)buff, g_Git.m_LogEncode, start);
756 g_Git.StringAppend(&str, (BYTE*)buff + start, CP_UTF8, size - start);
758 ClearESC(str);
760 return str;
763 LRESULT CProgressDlg::OnTaskbarBtnCreated(WPARAM /*wParam*/, LPARAM /*lParam*/)
765 m_pTaskbarList.Release();
766 m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList);
767 SetUUIDOverlayIcon(m_hWnd);
768 return 0;
771 BOOL CProgressDlg::PreTranslateMessage(MSG* pMsg)
773 if (pMsg->message == WM_KEYDOWN)
775 if (pMsg->wParam == VK_ESCAPE)
777 // pressing the ESC key should close the dialog. But since we disabled the escape
778 // key (so the user doesn't get the idea that he could simply undo an e.g. update)
779 // this won't work.
780 // So if the user presses the ESC key, change it to VK_RETURN so the dialog gets
781 // the impression that the OK button was pressed.
782 if ((!GetDlgItem(IDCANCEL)->IsWindowEnabled())
783 &&(GetDlgItem(IDOK)->IsWindowEnabled())&&(GetDlgItem(IDOK)->IsWindowVisible()))
785 // since we convert ESC to RETURN, make sure the OK button has the focus.
786 GetDlgItem(IDOK)->SetFocus();
787 pMsg->wParam = VK_RETURN;
791 else if (pMsg->message == WM_CONTEXTMENU || pMsg->message == WM_RBUTTONDOWN)
793 CWnd * pWnd = (CWnd*) GetDlgItem(IDC_LOG);
794 if (pWnd == GetFocus())
796 CIconMenu popup;
797 if (popup.CreatePopupMenu())
799 long start = -1, end = -1;
800 auto pEdit = (CRichEditCtrl *)GetDlgItem(IDC_LOG);
801 pEdit->GetSel(start, end);
802 popup.AppendMenuIcon(WM_COPY, IDS_SCIEDIT_COPY, IDI_COPYCLIP);
803 if (start >= end)
804 popup.EnableMenuItem(WM_COPY, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
805 popup.AppendMenu(MF_SEPARATOR);
806 popup.AppendMenuIcon(EM_SETSEL, IDS_STATUSLIST_CONTEXT_COPYEXT, IDI_COPYCLIP);
807 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, pMsg->pt.x, pMsg->pt.y, this);
808 switch (cmd)
810 case 0: // no command selected
811 break;
812 case EM_SETSEL:
814 pEdit->SetRedraw(FALSE);
815 int oldLine = pEdit->GetFirstVisibleLine();
816 pEdit->SetSel(0, -1);
817 pEdit->Copy();
818 pEdit->SetSel(start, end);
819 int newLine = pEdit->GetFirstVisibleLine();
820 pEdit->LineScroll(oldLine - newLine);
821 pEdit->SetRedraw(TRUE);
822 pEdit->RedrawWindow();
824 break;
825 case WM_COPY:
826 ::SendMessage(GetDlgItem(IDC_LOG)->GetSafeHwnd(), cmd, 0, -1);
827 break;
829 return TRUE;
833 return __super::PreTranslateMessage(pMsg);