Fixed issue #2096: Allow to disable blue text-label about git.exe execution timings...
[TortoiseGit.git] / src / TortoiseProc / ProgressDlg.cpp
blob127f7e824872072ccb0603ac2270739d2bb4f442
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 "SoundUtils.h"
36 #include "Win7.h"
37 #include "MessageBox.h"
38 #include "LogFile.h"
39 #include "CmdLineParser.h"
41 // CProgressDlg dialog
43 IMPLEMENT_DYNAMIC(CProgressDlg, CResizableStandAloneDialog)
45 CProgressDlg::CProgressDlg(CWnd* pParent /*=NULL*/)
46 : CResizableStandAloneDialog(CProgressDlg::IDD, pParent)
47 , m_bShowCommand(true)
48 , m_bAbort(false)
49 , m_bDone(false)
50 , m_startTick(GetTickCount())
51 , m_BufStart(0)
52 , m_Git(&g_Git)
54 m_pThread = NULL;
55 m_bBufferAll=false;
56 m_GitStatus = (DWORD)-1;
57 int autoClose = CRegDWORD(_T("Software\\TortoiseGit\\AutoCloseGitProgress"), 0);
58 CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);
59 if (parser.HasKey(_T("closeonend")))
60 autoClose = parser.GetLongVal(_T("closeonend"));
61 switch (autoClose)
63 case 1:
64 m_AutoClose = AUTOCLOSE_IF_NO_OPTIONS;
65 break;
66 case 2:
67 m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
68 break;
69 default:
70 m_AutoClose = AUTOCLOSE_NO;
71 break;
75 CProgressDlg::~CProgressDlg()
77 if(m_pThread != NULL)
79 delete m_pThread;
83 void CProgressDlg::DoDataExchange(CDataExchange* pDX)
85 CDialog::DoDataExchange(pDX);
86 DDX_Control(pDX, IDC_CURRENT, this->m_CurrentWork);
87 DDX_Control(pDX, IDC_TITLE_ANIMATE, this->m_Animate);
88 DDX_Control(pDX, IDC_RUN_PROGRESS, this->m_Progress);
89 DDX_Control(pDX, IDC_LOG, this->m_Log);
90 DDX_Control(pDX, IDC_PROGRESS_BUTTON1, this->m_ctrlPostCmd);
93 BEGIN_MESSAGE_MAP(CProgressDlg, CResizableStandAloneDialog)
94 ON_WM_CLOSE()
95 ON_MESSAGE(MSG_PROGRESSDLG_UPDATE_UI, OnProgressUpdateUI)
96 ON_BN_CLICKED(IDOK, &CProgressDlg::OnBnClickedOk)
97 ON_BN_CLICKED(IDC_PROGRESS_BUTTON1,&CProgressDlg::OnBnClickedButton1)
98 ON_REGISTERED_MESSAGE(WM_TASKBARBTNCREATED, OnTaskbarBtnCreated)
99 END_MESSAGE_MAP()
101 BOOL CProgressDlg::OnInitDialog()
103 CResizableStandAloneDialog::OnInitDialog();
105 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
106 // do this, Explorer would be unable to send that message to our window if we
107 // were running elevated. It's OK to make the call all the time, since if we're
108 // not elevated, this is a no-op.
109 CHANGEFILTERSTRUCT cfs = { sizeof(CHANGEFILTERSTRUCT) };
110 typedef BOOL STDAPICALLTYPE ChangeWindowMessageFilterExDFN(HWND hWnd, UINT message, DWORD action, PCHANGEFILTERSTRUCT pChangeFilterStruct);
111 CAutoLibrary hUser = AtlLoadSystemLibraryUsingFullPath(_T("user32.dll"));
112 if (hUser)
114 ChangeWindowMessageFilterExDFN *pfnChangeWindowMessageFilterEx = (ChangeWindowMessageFilterExDFN*)GetProcAddress(hUser, "ChangeWindowMessageFilterEx");
115 if (pfnChangeWindowMessageFilterEx)
117 pfnChangeWindowMessageFilterEx(m_hWnd, WM_TASKBARBTNCREATED, MSGFLT_ALLOW, &cfs);
120 m_pTaskbarList.Release();
121 if (FAILED(m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList)))
122 m_pTaskbarList = nullptr;
124 AddAnchor(IDC_TITLE_ANIMATE, TOP_LEFT, TOP_RIGHT);
125 AddAnchor(IDC_RUN_PROGRESS, TOP_LEFT,TOP_RIGHT);
126 AddAnchor(IDC_LOG, TOP_LEFT,BOTTOM_RIGHT);
128 AddAnchor(IDOK,BOTTOM_RIGHT);
129 AddAnchor(IDCANCEL,BOTTOM_RIGHT);
130 AddAnchor(IDC_PROGRESS_BUTTON1,BOTTOM_LEFT);
131 AddAnchor(IDC_CURRENT,TOP_LEFT);
133 this->GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_HIDE);
134 m_Animate.Open(IDR_DOWNLOAD);
136 CFont m_logFont;
137 CAppUtils::CreateFontForLogs(m_logFont);
138 //GetDlgItem(IDC_CMD_LOG)->SetFont(&m_logFont);
139 m_Log.SetFont(&m_logFont);
141 CString InitialText;
142 if ( !m_PreText.IsEmpty() )
144 InitialText = m_PreText + _T("\r\n");
146 #if 0
147 if (m_bShowCommand && (!m_GitCmd.IsEmpty() ))
149 InitialText += m_GitCmd+_T("\r\n\r\n");
151 #endif
152 m_Log.SetWindowTextW(InitialText);
153 m_CurrentWork.SetWindowTextW(_T(""));
155 EnableSaveRestore(_T("ProgressDlg"));
157 m_pThread = AfxBeginThread(ProgressThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
158 if (m_pThread==NULL)
160 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
161 DialogEnableWindow(IDCANCEL, TRUE);
163 else
165 m_pThread->m_bAutoDelete = FALSE;
166 m_pThread->ResumeThread();
169 CString sWindowTitle;
170 GetWindowText(sWindowTitle);
171 CAppUtils::SetWindowTitle(m_hWnd, m_Git->m_CurrentDir, sWindowTitle);
173 // Make sure this dialog is shown in foreground (see issue #1536)
174 SetForegroundWindow();
176 return TRUE;
179 static void EnsurePostMessage(CWnd *pWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
181 redo:
182 if (!pWnd->PostMessage(Msg, wParam, lParam))
184 if (GetLastError() == ERROR_NOT_ENOUGH_QUOTA)
186 Sleep(20);
187 goto redo;
189 else
190 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Message %d-%d could not be sent (error %d; %s)\n"), wParam, lParam, GetLastError(), (CString)CFormatMessageWrapper());
194 UINT CProgressDlg::ProgressThreadEntry(LPVOID pVoid)
196 return ((CProgressDlg*)pVoid)->ProgressThread();
199 //static function, Share with SyncDialog
200 UINT CProgressDlg::RunCmdList(CWnd *pWnd, STRING_VECTOR &cmdlist, STRING_VECTOR &dirlist, bool bShowCommand, CString *pfilename, bool *bAbort, CGitByteArray *pdata, CGit *git)
202 UINT ret=0;
204 std::vector<std::unique_ptr<CBlockCacheForPath>> cacheBlockList;
205 std::vector<std::unique_ptr<CGit>> gitList;
206 if (dirlist.empty())
207 cacheBlockList.push_back(std::unique_ptr<CBlockCacheForPath>(new CBlockCacheForPath(git->m_CurrentDir)));
208 else
210 for (auto dir : dirlist)
212 CGit *pGit = new CGit;
213 pGit->m_CurrentDir = dir;
214 gitList.push_back(std::unique_ptr<CGit>(pGit));
215 cacheBlockList.push_back(std::unique_ptr<CBlockCacheForPath>(new CBlockCacheForPath(dir)));
219 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_START, 0);
221 if(pdata)
222 pdata->clear();
224 for (size_t i = 0; i < cmdlist.size(); ++i)
226 if(cmdlist[i].IsEmpty())
227 continue;
229 if (bShowCommand)
231 CStringA str;
232 if (gitList.empty() || gitList.size() == 1 && gitList[0]->m_CurrentDir == git->m_CurrentDir)
233 str = CUnicodeUtils::GetMulti(cmdlist[i].Trim() + _T("\r\n\r\n"), CP_UTF8);
234 else
235 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);
236 for (int j = 0; j < str.GetLength(); ++j)
238 if(pdata)
240 pdata->m_critSec.Lock();
241 pdata->push_back(str[j]);
242 pdata->m_critSec.Unlock();
244 else
245 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,str[j]);
247 if(pdata)
248 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,0);
251 PROCESS_INFORMATION pi;
252 CAutoGeneralHandle hRead;
253 int runAsyncRet = -1;
254 if (gitList.empty())
255 runAsyncRet = git->RunAsync(cmdlist[i].Trim(), &pi, hRead.GetPointer(), nullptr, pfilename);
256 else
257 runAsyncRet = gitList[i]->RunAsync(cmdlist[i].Trim(), &pi, hRead.GetPointer(), nullptr, pfilename);
258 if (runAsyncRet)
260 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_FAILED, -1 * runAsyncRet);
261 return runAsyncRet;
264 CAutoGeneralHandle piProcess(pi.hProcess);
265 CAutoGeneralHandle piThread(pi.hThread);
266 DWORD readnumber;
267 char lastByte = '\0';
268 char byte;
269 CString output;
270 while(ReadFile(hRead,&byte,1,&readnumber,NULL))
272 if(pdata)
274 if(byte == 0)
275 byte = '\n';
277 pdata->m_critSec.Lock();
278 if (byte == '\n' && lastByte != '\r')
279 pdata->push_back('\r');
280 pdata->push_back( byte);
281 lastByte = byte;
282 pdata->m_critSec.Unlock();
284 if(byte == '\r' || byte == '\n')
285 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,0);
287 else
288 pWnd->PostMessage(MSG_PROGRESSDLG_UPDATE_UI,MSG_PROGRESSDLG_RUN,byte);
290 if (pdata)
292 pdata->m_critSec.Lock();
293 bool post = !pdata->empty();
294 pdata->m_critSec.Unlock();
295 if (post)
296 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_RUN, 0);
299 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": waiting for process to finish (%s), aborted: %d\n"), cmdlist[i], *bAbort);
301 WaitForSingleObject(pi.hProcess, INFINITE);
303 DWORD status=0;
304 if(!GetExitCodeProcess(pi.hProcess,&status) || *bAbort)
306 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);
308 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_FAILED, status);
309 return TGIT_GIT_ERROR_GET_EXIT_CODE;
311 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process %s finished with code %d\n"), cmdlist[i], status);
312 ret |= status;
315 EnsurePostMessage(pWnd, MSG_PROGRESSDLG_UPDATE_UI, MSG_PROGRESSDLG_END, ret);
317 return ret;
320 UINT CProgressDlg::ProgressThread()
323 m_GitCmdList.push_back(m_GitCmd);
325 CString *pfilename;
327 if(m_LogFile.IsEmpty())
328 pfilename=NULL;
329 else
330 pfilename=&m_LogFile;
332 m_startTick = GetTickCount();
333 m_GitStatus = RunCmdList(this, m_GitCmdList, m_GitDirList, m_bShowCommand, pfilename, &m_bAbort, &this->m_Databuf, m_Git);
334 return 0;
337 LRESULT CProgressDlg::OnProgressUpdateUI(WPARAM wParam,LPARAM lParam)
339 if(wParam == MSG_PROGRESSDLG_START)
341 m_BufStart = 0 ;
342 m_Animate.Play(0, INT_MAX, INT_MAX);
343 DialogEnableWindow(IDCANCEL, TRUE);
344 if (m_pTaskbarList)
346 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
347 m_pTaskbarList->SetProgressValue(m_hWnd, 0, 100);
350 if(wParam == MSG_PROGRESSDLG_END || wParam == MSG_PROGRESSDLG_FAILED)
352 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": got message: %d\n"), wParam);
353 DWORD tickSpent = GetTickCount() - m_startTick;
354 CString strEndTime = CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE, true, false);
356 if(m_bBufferAll)
358 m_Databuf.m_critSec.Lock();
359 m_Databuf.push_back(0);
360 m_Log.SetWindowText(Convert2UnionCode((char*)&m_Databuf[0]));
361 m_Databuf.m_critSec.Unlock();
362 m_Log.LineScroll(m_Log.GetLineCount() - m_Log.GetFirstVisibleLine() - 4);
364 m_BufStart=0;
365 m_Databuf.m_critSec.Lock();
366 this->m_Databuf.clear();
367 m_Databuf.m_critSec.Unlock();
369 m_bDone = true;
370 m_Animate.Stop();
371 m_Progress.SetPos(100);
372 this->DialogEnableWindow(IDOK,TRUE);
374 m_GitStatus = (DWORD)lParam;
376 // detect crashes of perl when performing git svn actions
377 if (m_GitStatus == 0 && m_GitCmd.Find(_T(" svn ")) > 1)
379 CString log;
380 m_Log.GetWindowText(log);
381 if (log.GetLength() > 18 && log.Mid(log.GetLength() - 18) == _T("perl.exe.stackdump"))
382 m_GitStatus = (DWORD)-1;
385 if(this->m_GitStatus)
387 if (m_pTaskbarList)
389 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
390 m_pTaskbarList->SetProgressValue(m_hWnd, 100, 100);
392 CString log;
393 log.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT, m_GitStatus);
394 CString err;
395 if (CRegDWORD(_T("Software\\TortoiseGit\\ShowGitexeTimings"), TRUE))
396 err.Format(_T("\r\n\r\n%s (%lu ms @ %s)\r\n"), log, tickSpent, strEndTime);
397 else
398 err.Format(_T("\r\n\r\n%s\r\n"), log);
399 InsertColorText(this->m_Log, err, RGB(255,0,0));
400 CSoundUtils::PlayTGitError();
402 else {
403 if (m_pTaskbarList)
404 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
405 CString temp;
406 temp.LoadString(IDS_SUCCESS);
407 CString log;
408 if (CRegDWORD(_T("Software\\TortoiseGit\\ShowGitexeTimings"), TRUE))
409 log.Format(_T("\r\n%s (%lu ms @ %s)\r\n"), temp, tickSpent, strEndTime);
410 else
411 log.Format(_T("\r\n%s\r\n"), temp);
412 InsertColorText(this->m_Log, log, RGB(0,0,255));
413 this->DialogEnableWindow(IDCANCEL,FALSE);
416 if (wParam == MSG_PROGRESSDLG_END)
418 if (m_PostCmdCallback) // new handling method using callback
420 m_PostCmdCallback();
422 if (!m_PostCmdList.IsEmpty())
424 m_ctrlPostCmd.AddEntries(m_PostCmdList);
425 GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
428 else if (m_GitStatus == 0) // default old behaviour on success
430 if (!m_PostCmdList.IsEmpty())
432 m_ctrlPostCmd.AddEntries(m_PostCmdList);
433 GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
436 else // simple method to show buttons on failed
438 if (!m_PostFailCmdList.IsEmpty())
440 m_ctrlPostCmd.AddEntries(m_PostFailCmdList);
441 GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
446 if(wParam == MSG_PROGRESSDLG_END && m_GitStatus == 0)
448 if (m_AutoClose == AUTOCLOSE_IF_NO_OPTIONS && m_PostCmdList.IsEmpty() || m_AutoClose == AUTOCLOSE_IF_NO_ERRORS)
449 PostMessage(WM_COMMAND, 1, (LPARAM)GetDlgItem(IDOK)->m_hWnd);
453 if(!m_bBufferAll)
455 if(lParam == 0)
457 m_Databuf.m_critSec.Lock();
458 for (size_t i = this->m_BufStart; i < this->m_Databuf.size(); ++i)
460 char c = this->m_Databuf[m_BufStart];
461 ++m_BufStart;
462 m_Databuf.m_critSec.Unlock();
463 ParserCmdOutput(c);
465 m_Databuf.m_critSec.Lock();
468 if(m_BufStart>1000)
470 m_Databuf.erase(m_Databuf.begin(), m_Databuf.begin()+m_BufStart);
471 m_BufStart =0;
473 m_Databuf.m_critSec.Unlock();
476 else
477 ParserCmdOutput((char)lParam);
479 return 0;
482 //static function, Share with SyncDialog
483 int CProgressDlg::FindPercentage(CString &log)
485 int s1=log.Find(_T('%'));
486 if(s1<0)
487 return -1;
489 int s2=s1-1;
490 for(int i=s1-1;i>=0;i--)
492 if(log[i]>=_T('0') && log[i]<=_T('9'))
493 s2=i;
494 else
495 break;
497 return _ttol(log.Mid(s2,s1-s2));
500 void CProgressDlg::ParserCmdOutput(char ch)
502 ParserCmdOutput(this->m_Log,this->m_Progress,this->m_hWnd,this->m_pTaskbarList,this->m_LogTextA,ch,&this->m_CurrentWork);
504 void CProgressDlg::ClearESC(CString &str)
506 // see http://ascii-table.com/ansi-escape-sequences.php and http://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html
507 str.Replace(_T("\033[K"), _T("")); // erase until end of line; no need to care for this, because we always clear the whole line
509 // drop colors
510 while (true)
512 int escapePosition = str.Find(_T('\033'));
513 if (escapePosition >= 0 && str.GetLength() >= escapePosition + 3)
515 if (str.Mid(escapePosition, 2) == _T("\033["))
517 int colorEnd = str.Find(_T('m'), escapePosition + 2);
518 if (colorEnd > 0)
520 bool found = true;
521 for (int i = escapePosition + 2; i < colorEnd; ++i)
523 if (str[i] != _T(';') && (str[i] < _T('0') && str[i] > _T('9')))
525 found = false;
526 break;
529 if (found)
531 if (escapePosition > 0)
532 str = str.Left(escapePosition) + str.Mid(colorEnd + 1);
533 else
534 str = str.Mid(colorEnd);
535 continue;
540 break;
543 void CProgressDlg::ParserCmdOutput(CRichEditCtrl &log,CProgressCtrl &progressctrl,HWND m_hWnd,CComPtr<ITaskbarList3> m_pTaskbarList,CStringA &oneline, char ch, CWnd *CurrentWork)
545 //TRACE(_T("%c"),ch);
546 if( ch == ('\r') || ch == ('\n'))
548 CString str;
550 // TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
551 // TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));
553 int lines = log.GetLineCount();
554 g_Git.StringAppend(&str, (BYTE*)oneline.GetBuffer(), CP_UTF8);
555 str.Trim();
556 // TRACE(_T("%s"), str);
558 ClearESC(str);
560 if(ch == ('\r'))
562 int start=log.LineIndex(lines-1);
563 log.SetSel(start, log.GetTextLength());
564 log.ReplaceSel(str);
566 else
568 int length = log.GetWindowTextLength();
569 log.SetSel(length, length);
570 if (length > 0)
571 log.ReplaceSel(_T("\r\n") + str);
572 else
573 log.ReplaceSel(str);
576 if (lines > 500) //limited log length
578 int end=log.LineIndex(1);
579 log.SetSel(0,end);
580 log.ReplaceSel(_T(""));
582 log.LineScroll(log.GetLineCount() - log.GetFirstVisibleLine() - 4);
584 int s1=oneline.ReverseFind(_T(':'));
585 int s2=oneline.Find(_T('%'));
586 if (s1 > 0 && s2 > 0)
588 if(CurrentWork)
589 CurrentWork->SetWindowTextW(str.Left(s1));
591 int pos=FindPercentage(str);
592 TRACE(_T("Pos %d\r\n"),pos);
593 if(pos>0)
595 progressctrl.SetPos(pos);
596 if (m_pTaskbarList)
598 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
599 m_pTaskbarList->SetProgressValue(m_hWnd, pos, 100);
604 oneline="";
607 else
609 oneline+=ch;
612 void CProgressDlg::RemoveLastLine(CString &str)
614 int start;
615 start=str.ReverseFind(_T('\n'));
616 if(start>0)
617 str=str.Left(start);
618 return;
620 // CProgressDlg message handlers
622 void CProgressDlg::WriteLog() const
624 CLogFile logfile(g_Git.m_CurrentDir);
625 if (logfile.Open())
627 logfile.AddTimeLine();
628 CString text = GetLogText();
629 LPTSTR psz_string = text.GetBuffer();
630 while (*psz_string)
632 if (*psz_string == '\r')
634 ++psz_string;
635 continue;
637 size_t i_len = wcscspn(psz_string, L"\n");
638 logfile.AddLine(CString(psz_string, (int)i_len));
639 psz_string += i_len;
640 if (*psz_string == '\n')
641 ++psz_string;
643 if (m_bAbort)
645 CString canceled;
646 canceled.LoadString(IDS_SVN_USERCANCELLED);
647 logfile.AddLine(canceled);
649 logfile.Close();
653 void CProgressDlg::OnBnClickedOk()
655 if (m_pThread) // added here because Close-button is "called" from thread by PostMessage
656 ::WaitForSingleObject(m_pThread->m_hThread, 5000);
657 m_Log.GetWindowText(this->m_LogText);
658 WriteLog();
659 OnOK();
662 void CProgressDlg::OnBnClickedButton1()
664 WriteLog();
665 this->EndDialog((int)(IDC_PROGRESS_BUTTON1 + this->m_ctrlPostCmd.GetCurrentEntry()));
668 void CProgressDlg::OnClose()
670 DialogEnableWindow(IDCANCEL, TRUE);
671 __super::OnClose();
674 void CProgressDlg::OnCancel()
676 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": User canceled\n"));
677 m_bAbort = true;
678 if(m_bDone)
680 WriteLog();
681 CResizableStandAloneDialog::OnCancel();
682 return;
685 if( m_Git->m_CurrentGitPi.hProcess )
687 DWORD dwConfirmKillProcess = CRegDWORD(_T("Software\\TortoiseGit\\ConfirmKillProcess"));
688 if (dwConfirmKillProcess && CMessageBox::Show(m_hWnd, IDS_PROC_CONFIRMKILLPROCESS, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) != IDYES)
689 return;
690 if(::GenerateConsoleCtrlEvent(CTRL_C_EVENT,0))
692 ::WaitForSingleObject(m_Git->m_CurrentGitPi.hProcess ,10000);
695 KillProcessTree(m_Git->m_CurrentGitPi.dwProcessId);
698 ::WaitForSingleObject(m_Git->m_CurrentGitPi.hProcess ,10000);
699 if (m_pThread)
700 ::WaitForSingleObject(m_pThread->m_hThread, 5000);
701 WriteLog();
702 CResizableStandAloneDialog::OnCancel();
705 void CProgressDlg::KillProcessTree(DWORD dwProcessId, unsigned int depth)
707 // recursively kills a process tree
708 // This is not optimized, but works and isn't called very often ;)
710 if (!dwProcessId || depth > 20)
711 return;
713 PROCESSENTRY32 pe;
714 memset(&pe, 0, sizeof(PROCESSENTRY32));
715 pe.dwSize = sizeof(PROCESSENTRY32);
717 CAutoGeneralHandle hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
719 if (::Process32First(hSnap, &pe))
723 if (pe.th32ParentProcessID == dwProcessId)
724 KillProcessTree(pe.th32ProcessID, depth + 1);
725 } while (::Process32Next(hSnap, &pe));
727 CAutoGeneralHandle hProc = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);
728 if (hProc)
729 ::TerminateProcess(hProc, 1);
733 void CProgressDlg::InsertColorText(CRichEditCtrl &edit,CString text,COLORREF rgb)
735 CHARFORMAT old,cf;
736 edit.GetDefaultCharFormat(cf);
737 old=cf;
738 cf.dwMask|=CFM_COLOR;
739 cf.crTextColor=rgb;
740 cf.dwEffects|=CFE_BOLD;
741 cf.dwEffects &= ~CFE_AUTOCOLOR ;
742 edit.SetSel(edit.GetTextLength()-1,edit.GetTextLength());
743 edit.ReplaceSel(text);
744 edit.SetSel(edit.LineIndex(edit.GetLineCount()-2),edit.GetTextLength());
745 edit.SetSelectionCharFormat(cf);
746 edit.SetSel(edit.GetTextLength(),edit.GetTextLength());
747 edit.SetDefaultCharFormat(old);
748 edit.LineScroll(edit.GetLineCount() - edit.GetFirstVisibleLine() - 4);
751 CString CCommitProgressDlg::Convert2UnionCode(char *buff, int size)
753 int start=0;
754 if(size == -1)
755 size = (int)strlen(buff);
757 for (int i = 0; i < size; ++i)
759 if(buff[i] == ']')
760 start = i;
761 if( start >0 && buff[i] =='\n' )
763 start =i;
764 break;
768 CString str;
769 g_Git.StringAppend(&str, (BYTE*)buff, g_Git.m_LogEncode, start);
770 g_Git.StringAppend(&str, (BYTE*)buff + start, CP_UTF8, size - start);
772 ClearESC(str);
774 return str;
777 LRESULT CProgressDlg::OnTaskbarBtnCreated(WPARAM /*wParam*/, LPARAM /*lParam*/)
779 m_pTaskbarList.Release();
780 m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList);
781 SetUUIDOverlayIcon(m_hWnd);
782 return 0;
785 BOOL CProgressDlg::PreTranslateMessage(MSG* pMsg)
787 if (pMsg->message == WM_KEYDOWN)
789 if (pMsg->wParam == VK_ESCAPE)
791 // pressing the ESC key should close the dialog. But since we disabled the escape
792 // key (so the user doesn't get the idea that he could simply undo an e.g. update)
793 // this won't work.
794 // So if the user presses the ESC key, change it to VK_RETURN so the dialog gets
795 // the impression that the OK button was pressed.
796 if ((!GetDlgItem(IDCANCEL)->IsWindowEnabled())
797 &&(GetDlgItem(IDOK)->IsWindowEnabled())&&(GetDlgItem(IDOK)->IsWindowVisible()))
799 // since we convert ESC to RETURN, make sure the OK button has the focus.
800 GetDlgItem(IDOK)->SetFocus();
801 pMsg->wParam = VK_RETURN;
805 else if (pMsg->message == WM_CONTEXTMENU || pMsg->message == WM_RBUTTONDOWN)
807 CWnd * pWnd = (CWnd*) GetDlgItem(IDC_LOG);
808 if (pWnd == GetFocus())
810 CIconMenu popup;
811 if (popup.CreatePopupMenu())
813 popup.AppendMenuIcon(WM_COPY, IDS_SCIEDIT_COPY, IDI_COPYCLIP);
814 if (m_Log.GetSelText().IsEmpty())
815 popup.EnableMenuItem(WM_COPY, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
816 popup.AppendMenu(MF_SEPARATOR);
817 popup.AppendMenuIcon(EM_SETSEL, IDS_SCIEDIT_SELECTALL);
818 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, pMsg->pt.x, pMsg->pt.y, this);
819 switch (cmd)
821 case 0: // no command selected
822 break;
823 case EM_SETSEL:
824 case WM_COPY:
825 ::SendMessage(GetDlgItem(IDC_LOG)->GetSafeHwnd(), cmd, 0, -1);
826 break;
828 return TRUE;
832 return __super::PreTranslateMessage(pMsg);