1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - 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
23 #include "TortoiseProc.h"
24 #include "ProgressDlg.h"
27 #include "UnicodeUtils.h"
29 #include "LoglistCommonResource.h"
32 #include "SmartHandle.h"
33 #include "../TGitCache/CacheInterface.h"
34 #include "LoglistUtils.h"
36 // CProgressDlg dialog
38 IMPLEMENT_DYNAMIC(CProgressDlg
, CResizableStandAloneDialog
)
40 CProgressDlg::CProgressDlg(CWnd
* pParent
/*=NULL*/)
41 : CResizableStandAloneDialog(CProgressDlg::IDD
, pParent
), m_bShowCommand(true), m_bAutoCloseOnSuccess(false), m_bAbort(false), m_bDone(false), m_startTick(GetTickCount())
44 m_PostCmdCallback
= NULL
;
46 m_bAltAbortPress
=false;
50 CProgressDlg::~CProgressDlg()
58 void CProgressDlg::DoDataExchange(CDataExchange
* pDX
)
60 CDialog::DoDataExchange(pDX
);
61 DDX_Control(pDX
, IDC_CURRENT
, this->m_CurrentWork
);
62 DDX_Control(pDX
, IDC_TITLE_ANIMATE
, this->m_Animate
);
63 DDX_Control(pDX
, IDC_RUN_PROGRESS
, this->m_Progress
);
64 DDX_Control(pDX
, IDC_LOG
, this->m_Log
);
65 DDX_Control(pDX
, IDC_PROGRESS_BUTTON1
, this->m_ctrlPostCmd
);
68 BEGIN_MESSAGE_MAP(CProgressDlg
, CResizableStandAloneDialog
)
70 ON_MESSAGE(MSG_PROGRESSDLG_UPDATE_UI
, OnProgressUpdateUI
)
71 ON_BN_CLICKED(IDOK
, &CProgressDlg::OnBnClickedOk
)
72 ON_BN_CLICKED(IDC_PROGRESS_BUTTON1
,&CProgressDlg::OnBnClickedButton1
)
73 ON_REGISTERED_MESSAGE(WM_TASKBARBTNCREATED
, OnTaskbarBtnCreated
)
76 BOOL
CProgressDlg::OnInitDialog()
78 CResizableStandAloneDialog::OnInitDialog();
80 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
81 // do this, Explorer would be unable to send that message to our window if we
82 // were running elevated. It's OK to make the call all the time, since if we're
83 // not elevated, this is a no-op.
84 CHANGEFILTERSTRUCT cfs
= { sizeof(CHANGEFILTERSTRUCT
) };
85 typedef BOOL STDAPICALLTYPE
ChangeWindowMessageFilterExDFN(HWND hWnd
, UINT message
, DWORD action
, PCHANGEFILTERSTRUCT pChangeFilterStruct
);
86 CAutoLibrary hUser
= ::LoadLibrary(_T("user32.dll"));
89 ChangeWindowMessageFilterExDFN
*pfnChangeWindowMessageFilterEx
= (ChangeWindowMessageFilterExDFN
*)GetProcAddress(hUser
, "ChangeWindowMessageFilterEx");
90 if (pfnChangeWindowMessageFilterEx
)
92 pfnChangeWindowMessageFilterEx(m_hWnd
, WM_TASKBARBTNCREATED
, MSGFLT_ALLOW
, &cfs
);
95 m_pTaskbarList
.Release();
96 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
98 AddAnchor(IDC_TITLE_ANIMATE
, TOP_LEFT
, TOP_RIGHT
);
99 AddAnchor(IDC_RUN_PROGRESS
, TOP_LEFT
,TOP_RIGHT
);
100 AddAnchor(IDC_LOG
, TOP_LEFT
,BOTTOM_RIGHT
);
102 AddAnchor(IDOK
,BOTTOM_RIGHT
);
103 AddAnchor(IDCANCEL
,BOTTOM_RIGHT
);
104 AddAnchor(IDC_PROGRESS_BUTTON1
,BOTTOM_LEFT
);
105 AddAnchor(IDC_CURRENT
,TOP_LEFT
);
107 this->GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_HIDE
);
108 m_Animate
.Open(IDR_DOWNLOAD
);
111 CAppUtils::CreateFontForLogs(m_logFont
);
112 //GetDlgItem(IDC_CMD_LOG)->SetFont(&m_logFont);
113 m_Log
.SetFont(&m_logFont
);
116 if ( !m_PreText
.IsEmpty() )
118 InitialText
= m_PreText
+ _T("\r\n");
121 if (m_bShowCommand
&& (!m_GitCmd
.IsEmpty() ))
123 InitialText
+= m_GitCmd
+_T("\r\n\r\n");
126 m_Log
.SetWindowTextW(InitialText
);
127 m_CurrentWork
.SetWindowTextW(_T(""));
129 EnableSaveRestore(_T("ProgressDlg"));
131 m_pThread
= AfxBeginThread(ProgressThreadEntry
, this, THREAD_PRIORITY_NORMAL
,0,CREATE_SUSPENDED
);
134 // ReportError(CString(MAKEINTRESOURCE(IDS_ERR_THREADSTARTFAILED)));
138 m_pThread
->m_bAutoDelete
= FALSE
;
139 m_pThread
->ResumeThread();
142 if(!m_Title
.IsEmpty())
143 this->SetWindowText(m_Title
);
145 CString sWindowTitle
;
146 GetWindowText(sWindowTitle
);
147 CAppUtils::SetWindowTitle(m_hWnd
, g_Git
.m_CurrentDir
, sWindowTitle
);
152 UINT
CProgressDlg::ProgressThreadEntry(LPVOID pVoid
)
154 return ((CProgressDlg
*)pVoid
)->ProgressThread();
157 //static function, Share with SyncDialog
158 UINT
CProgressDlg::RunCmdList(CWnd
*pWnd
,std::vector
<CString
> &cmdlist
,bool bShowCommand
,CString
*pfilename
,bool *bAbort
,CGitByteArray
*pdata
)
162 PROCESS_INFORMATION pi
;
165 memset(&pi
,0,sizeof(PROCESS_INFORMATION
));
167 CBlockCacheForPath
cacheBlock(g_Git
.m_CurrentDir
);
169 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_START
,0);
174 for(int i
=0;i
<cmdlist
.size();i
++)
176 if(cmdlist
[i
].IsEmpty())
181 CStringA str
= CUnicodeUtils::GetMulti(cmdlist
[i
].Trim() + _T("\n\n"), CP_UTF8
);
182 for(int j
=0;j
<str
.GetLength();j
++)
186 pdata
->m_critSec
.Lock();
187 pdata
->push_back(str
[j
]);
188 pdata
->m_critSec
.Unlock();
191 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,str
[j
]);
194 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,0);
197 g_Git
.RunAsync(cmdlist
[i
].Trim(),&pi
, &hRead
, NULL
, pfilename
);
202 while(ReadFile(hRead
,&byte
,1,&readnumber
,NULL
))
209 pdata
->m_critSec
.Lock();
210 pdata
->push_back( byte
);
211 pdata
->m_critSec
.Unlock();
213 if(byte
== '\r' || byte
== '\n')
214 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,0);
217 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,byte
);
220 CloseHandle(pi
.hThread
);
222 WaitForSingleObject(pi
.hProcess
, INFINITE
);
225 if(!GetExitCodeProcess(pi
.hProcess
,&status
) || *bAbort
)
227 CloseHandle(pi
.hProcess
);
231 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
, MSG_PROGRESSDLG_FAILED
, status
);
232 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
237 CloseHandle(pi
.hProcess
);
241 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
, MSG_PROGRESSDLG_END
, ret
);
247 UINT
CProgressDlg::ProgressThread()
250 m_GitCmdList
.push_back(m_GitCmd
);
254 if(m_LogFile
.IsEmpty())
257 pfilename
=&m_LogFile
;
259 m_startTick
= GetTickCount();
260 m_GitStatus
= RunCmdList(this,m_GitCmdList
,m_bShowCommand
,pfilename
,&m_bAbort
,&this->m_Databuf
);;
264 LRESULT
CProgressDlg::OnProgressUpdateUI(WPARAM wParam
,LPARAM lParam
)
266 if(wParam
== MSG_PROGRESSDLG_START
)
269 m_Animate
.Play(0, INT_MAX
, INT_MAX
);
270 this->DialogEnableWindow(IDOK
,FALSE
);
273 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
274 m_pTaskbarList
->SetProgressValue(m_hWnd
, 0, 100);
277 if(wParam
== MSG_PROGRESSDLG_END
|| wParam
== MSG_PROGRESSDLG_FAILED
)
279 DWORD tickSpent
= GetTickCount() - m_startTick
;
280 CString strEndTime
= CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE
, true, false);
284 m_Databuf
.m_critSec
.Lock();
285 m_Databuf
.push_back(0);
286 m_Databuf
.m_critSec
.Unlock();
288 m_Databuf
.m_critSec
.Lock();
289 m_Log
.SetWindowText(Convert2UnionCode((char*)&m_Databuf
[0]));
290 m_Databuf
.m_critSec
.Unlock();
291 m_Log
.LineScroll(m_Log
.GetLineCount() - m_Log
.GetFirstVisibleLine() - 4);
294 m_Databuf
.m_critSec
.Lock();
295 this->m_Databuf
.clear();
296 m_Databuf
.m_critSec
.Unlock();
300 m_Progress
.SetPos(100);
301 this->DialogEnableWindow(IDOK
,TRUE
);
303 m_GitStatus
= (DWORD
)lParam
;
305 // detect crashes of perl when performing git svn actions
306 if (m_GitStatus
== 0 && m_GitCmd
.Find(_T(" svn ")) > 1)
309 m_Log
.GetWindowText(log
);
310 if (log
.GetLength() > 18 && log
.Mid(log
.GetLength() - 18) == _T("perl.exe.stackdump"))
311 m_GitStatus
= (DWORD
)-1;
314 if(this->m_GitStatus
)
318 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_ERROR
);
319 m_pTaskbarList
->SetProgressValue(m_hWnd
, 100, 100);
322 log
.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT
, m_GitStatus
);
324 err
.Format(_T("\r\n\r\n%s (%d ms @ %s)\r\n"), log
, tickSpent
, strEndTime
);
325 InsertColorText(this->m_Log
, err
, RGB(255,0,0));
329 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NOPROGRESS
);
331 temp
.LoadString(IDS_SUCCESS
);
333 log
.Format(_T("\r\n%s (%d ms @ %s)\r\n"), temp
, tickSpent
, strEndTime
);
334 InsertColorText(this->m_Log
, log
, RGB(0,0,255));
335 this->DialogEnableWindow(IDCANCEL
,FALSE
);
338 if (wParam
== MSG_PROGRESSDLG_END
)
340 if (m_PostCmdCallback
) // new handling method using callback
342 m_PostCmdCallback(this, m_caller
, m_GitStatus
);
344 if (m_PostCmdList
.GetCount() > 0)
346 m_ctrlPostCmd
.AddEntries(m_PostCmdList
);
347 GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_SHOW
);
350 else if (m_GitStatus
== 0) // default old behaviour on success
352 if (m_PostCmdList
.GetCount() > 0)
354 m_ctrlPostCmd
.AddEntries(m_PostCmdList
);
355 GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_SHOW
);
358 else // simple method to show buttons on failed
360 if (m_PostFailCmdList
.GetCount() > 0)
362 m_ctrlPostCmd
.AddEntries(m_PostFailCmdList
);
363 GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_SHOW
);
368 if(wParam
== MSG_PROGRESSDLG_END
&& m_GitStatus
== 0)
370 if(m_bAutoCloseOnSuccess
)
372 m_Log
.GetWindowText(this->m_LogText
);
382 m_Databuf
.m_critSec
.Lock();
383 for(int i
=this->m_BufStart
;i
<this->m_Databuf
.size();i
++)
385 char c
= this->m_Databuf
[m_BufStart
];
387 m_Databuf
.m_critSec
.Unlock();
390 m_Databuf
.m_critSec
.Lock();
395 m_Databuf
.erase(m_Databuf
.begin(), m_Databuf
.begin()+m_BufStart
);
398 m_Databuf
.m_critSec
.Unlock();
402 ParserCmdOutput((char)lParam
);
407 //static function, Share with SyncDialog
408 int CProgressDlg::FindPercentage(CString
&log
)
410 int s1
=log
.Find(_T('%'));
415 for(int i
=s1
-1;i
>=0;i
--)
417 if(log
[i
]>=_T('0') && log
[i
]<=_T('9'))
422 return _ttol(log
.Mid(s2
,s1
-s2
));
425 void CProgressDlg::ParserCmdOutput(char ch
)
427 ParserCmdOutput(this->m_Log
,this->m_Progress
,this->m_hWnd
,this->m_pTaskbarList
,this->m_LogTextA
,ch
,&this->m_CurrentWork
);
429 void CProgressDlg::ClearESC(CString
&str
)
431 // see http://ascii-table.com/ansi-escape-sequences.php and http://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html
432 str
.Replace(_T("\033[K"), _T("")); // erase until end of line; no need to care for this, because we always clear the whole line
437 int escapePosition
= str
.Find(_T('\033'));
438 if (escapePosition
>= 0 && str
.GetLength() >= escapePosition
+ 3)
440 if (str
.Mid(escapePosition
, 2) == _T("\033["))
442 int colorEnd
= str
.Find(_T('m'), escapePosition
+ 2);
446 for (int i
= escapePosition
+ 2; i
< colorEnd
; i
++)
448 if (str
[i
] != _T(';') && (str
[i
] < _T('0') && str
[i
] > _T('9')))
456 if (escapePosition
> 0)
457 str
= str
.Left(escapePosition
) + str
.Mid(colorEnd
+ 1);
459 str
= str
.Mid(colorEnd
);
468 void CProgressDlg::ParserCmdOutput(CRichEditCtrl
&log
,CProgressCtrl
&progressctrl
,HWND m_hWnd
,CComPtr
<ITaskbarList3
> m_pTaskbarList
,CStringA
&oneline
, char ch
, CWnd
*CurrentWork
)
470 //TRACE(_T("%c"),ch);
471 if( ch
== ('\r') || ch
== ('\n'))
475 // TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
476 // TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));
478 int lines
= log
.GetLineCount();
479 g_Git
.StringAppend(&str
, (BYTE
*)oneline
.GetBuffer(), CP_UTF8
);
481 // TRACE(_T("%s"), str);
487 int start
=log
.LineIndex(lines
-1);
488 log
.SetSel(start
, log
.GetTextLength());
493 int length
= log
.GetWindowTextLength();
494 log
.SetSel(length
, length
);
496 log
.ReplaceSel(_T("\r\n") + str
);
501 if (lines
> 500) //limited log length
503 int end
=log
.LineIndex(1);
505 log
.ReplaceSel(_T(""));
507 log
.LineScroll(log
.GetLineCount() - log
.GetFirstVisibleLine() - 4);
509 int s1
=oneline
.ReverseFind(_T(':'));
510 int s2
=oneline
.Find(_T('%'));
511 if (s1
> 0 && s2
> 0)
514 CurrentWork
->SetWindowTextW(str
.Left(s1
));
516 int pos
=FindPercentage(str
);
517 TRACE(_T("Pos %d\r\n"),pos
);
520 progressctrl
.SetPos(pos
);
523 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
524 m_pTaskbarList
->SetProgressValue(m_hWnd
, pos
, 100);
537 void CProgressDlg::RemoveLastLine(CString
&str
)
540 start
=str
.ReverseFind(_T('\n'));
545 // CProgressDlg message handlers
547 void CProgressDlg::OnBnClickedOk()
549 m_Log
.GetWindowText(this->m_LogText
);
553 void CProgressDlg::OnBnClickedButton1()
555 this->EndDialog((int)(IDC_PROGRESS_BUTTON1
+ this->m_ctrlPostCmd
.GetCurrentEntry()));
558 void CProgressDlg::OnClose()
560 DialogEnableWindow(IDCANCEL
, TRUE
);
564 void CProgressDlg::OnCancel()
569 CResizableStandAloneDialog::OnCancel();
573 if( g_Git
.m_CurrentGitPi
.hProcess
)
575 if(::GenerateConsoleCtrlEvent(CTRL_C_EVENT
,0))
577 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
584 KillProcessTree(g_Git
.m_CurrentGitPi
.dwProcessId
);
587 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
588 CResizableStandAloneDialog::OnCancel();
591 void CProgressDlg::KillProcessTree(DWORD dwProcessId
, unsigned int depth
)
593 // recursively kills a process tree
594 // This is not optimized, but works and isn't called very often ;)
596 if (!dwProcessId
|| depth
> 20)
600 memset(&pe
, 0, sizeof(PROCESSENTRY32
));
601 pe
.dwSize
= sizeof(PROCESSENTRY32
);
603 CAutoGeneralHandle hSnap
= ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
605 if (::Process32First(hSnap
, &pe
))
609 if (pe
.th32ParentProcessID
== dwProcessId
)
610 KillProcessTree(pe
.th32ProcessID
, depth
+ 1);
611 } while (::Process32Next(hSnap
, &pe
));
613 HANDLE hProc
= ::OpenProcess(PROCESS_TERMINATE
, FALSE
, dwProcessId
);
615 ::TerminateProcess(hProc
, 1);
619 void CProgressDlg::InsertCRLF()
621 m_Databuf
.m_critSec
.Lock();
622 for(int i
=0;i
<m_Databuf
.size();i
++)
624 if(m_Databuf
[i
]==('\n'))
626 if(i
==0 || m_Databuf
[i
-1]!= ('\r'))
628 m_Databuf
.insert(m_Databuf
.begin()+i
,('\r'));
633 m_Databuf
.m_critSec
.Unlock();
636 void CProgressDlg::InsertColorText(CRichEditCtrl
&edit
,CString text
,COLORREF rgb
)
639 edit
.GetDefaultCharFormat(cf
);
641 cf
.dwMask
|=CFM_COLOR
;
643 cf
.dwEffects
|=CFE_BOLD
;
644 cf
.dwEffects
&= ~CFE_AUTOCOLOR
;
645 edit
.SetSel(edit
.GetTextLength()-1,edit
.GetTextLength());
646 edit
.ReplaceSel(text
);
647 edit
.SetSel(edit
.LineIndex(edit
.GetLineCount()-2),edit
.GetTextLength());
648 edit
.SetSelectionCharFormat(cf
);
649 edit
.SetSel(edit
.GetTextLength(),edit
.GetTextLength());
650 edit
.SetDefaultCharFormat(old
);
651 edit
.LineScroll(edit
.GetLineCount() - edit
.GetFirstVisibleLine() - 4);
654 CString
CCommitProgressDlg::Convert2UnionCode(char *buff
, int size
)
661 cmd
=_T("git.exe config i18n.logOutputEncoding");
662 if (g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
))
666 output
=output
.Tokenize(_T("\n"),start
);
667 cp
=CUnicodeUtils::GetCPCode(output
);
671 size
= (int)strlen(buff
);
673 for(int i
=0;i
<size
;i
++)
677 if( start
>0 && buff
[i
] =='\n' )
685 g_Git
.StringAppend(&str
, (BYTE
*)buff
, cp
, start
);
686 g_Git
.StringAppend(&str
, (BYTE
*)buff
+ start
, CP_UTF8
, size
- start
);
693 LRESULT
CProgressDlg::OnTaskbarBtnCreated(WPARAM
/*wParam*/, LPARAM
/*lParam*/)
695 m_pTaskbarList
.Release();
696 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
700 BOOL
CProgressDlg::PreTranslateMessage(MSG
* pMsg
)
702 if (pMsg
->message
== WM_KEYDOWN
)
704 if (pMsg
->wParam
== VK_ESCAPE
)
706 // pressing the ESC key should close the dialog. But since we disabled the escape
707 // key (so the user doesn't get the idea that he could simply undo an e.g. update)
709 // So if the user presses the ESC key, change it to VK_RETURN so the dialog gets
710 // the impression that the OK button was pressed.
711 if ((!GetDlgItem(IDCANCEL
)->IsWindowEnabled())
712 &&(GetDlgItem(IDOK
)->IsWindowEnabled())&&(GetDlgItem(IDOK
)->IsWindowVisible()))
714 // since we convert ESC to RETURN, make sure the OK button has the focus.
715 GetDlgItem(IDOK
)->SetFocus();
716 pMsg
->wParam
= VK_RETURN
;
720 else if (pMsg
->message
== WM_CONTEXTMENU
|| pMsg
->message
== WM_RBUTTONDOWN
)
722 CWnd
* pWnd
= (CWnd
*) GetDlgItem(IDC_LOG
);
723 if (pWnd
== GetFocus())
726 if (popup
.CreatePopupMenu())
728 popup
.AppendMenuIcon(WM_COPY
, IDS_SCIEDIT_COPY
, IDI_COPYCLIP
);
729 if (m_Log
.GetSelText().IsEmpty())
730 popup
.EnableMenuItem(WM_COPY
, MF_BYCOMMAND
| MF_DISABLED
| MF_GRAYED
);
731 popup
.AppendMenu(MF_SEPARATOR
);
732 popup
.AppendMenuIcon(EM_SETSEL
, IDS_SCIEDIT_SELECTALL
);
733 int cmd
= popup
.TrackPopupMenu(TPM_RETURNCMD
| TPM_LEFTALIGN
| TPM_NONOTIFY
, pMsg
->pt
.x
, pMsg
->pt
.y
, this);
736 case 0: // no command selected
740 ::SendMessage(GetDlgItem(IDC_LOG
)->GetSafeHwnd(), cmd
, 0, -1);
747 return __super::PreTranslateMessage(pMsg
);