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_bAltAbortPress
=false;
48 CProgressDlg::~CProgressDlg()
56 void CProgressDlg::DoDataExchange(CDataExchange
* pDX
)
58 CDialog::DoDataExchange(pDX
);
59 DDX_Control(pDX
, IDC_CURRENT
, this->m_CurrentWork
);
60 DDX_Control(pDX
, IDC_TITLE_ANIMATE
, this->m_Animate
);
61 DDX_Control(pDX
, IDC_RUN_PROGRESS
, this->m_Progress
);
62 DDX_Control(pDX
, IDC_LOG
, this->m_Log
);
63 DDX_Control(pDX
, IDC_PROGRESS_BUTTON1
, this->m_ctrlPostCmd
);
66 BEGIN_MESSAGE_MAP(CProgressDlg
, CResizableStandAloneDialog
)
68 ON_MESSAGE(MSG_PROGRESSDLG_UPDATE_UI
, OnProgressUpdateUI
)
69 ON_BN_CLICKED(IDOK
, &CProgressDlg::OnBnClickedOk
)
70 ON_BN_CLICKED(IDC_PROGRESS_BUTTON1
,&CProgressDlg::OnBnClickedButton1
)
71 ON_REGISTERED_MESSAGE(WM_TASKBARBTNCREATED
, OnTaskbarBtnCreated
)
74 BOOL
CProgressDlg::OnInitDialog()
76 CResizableStandAloneDialog::OnInitDialog();
78 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
79 // do this, Explorer would be unable to send that message to our window if we
80 // were running elevated. It's OK to make the call all the time, since if we're
81 // not elevated, this is a no-op.
82 CHANGEFILTERSTRUCT cfs
= { sizeof(CHANGEFILTERSTRUCT
) };
83 typedef BOOL STDAPICALLTYPE
ChangeWindowMessageFilterExDFN(HWND hWnd
, UINT message
, DWORD action
, PCHANGEFILTERSTRUCT pChangeFilterStruct
);
84 CAutoLibrary hUser
= ::LoadLibrary(_T("user32.dll"));
87 ChangeWindowMessageFilterExDFN
*pfnChangeWindowMessageFilterEx
= (ChangeWindowMessageFilterExDFN
*)GetProcAddress(hUser
, "ChangeWindowMessageFilterEx");
88 if (pfnChangeWindowMessageFilterEx
)
90 pfnChangeWindowMessageFilterEx(m_hWnd
, WM_TASKBARBTNCREATED
, MSGFLT_ALLOW
, &cfs
);
93 m_pTaskbarList
.Release();
94 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
96 AddAnchor(IDC_TITLE_ANIMATE
, TOP_LEFT
, TOP_RIGHT
);
97 AddAnchor(IDC_RUN_PROGRESS
, TOP_LEFT
,TOP_RIGHT
);
98 AddAnchor(IDC_LOG
, TOP_LEFT
,BOTTOM_RIGHT
);
100 AddAnchor(IDOK
,BOTTOM_RIGHT
);
101 AddAnchor(IDCANCEL
,BOTTOM_RIGHT
);
102 AddAnchor(IDC_PROGRESS_BUTTON1
,BOTTOM_LEFT
);
103 AddAnchor(IDC_CURRENT
,TOP_LEFT
);
105 this->GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_HIDE
);
106 m_Animate
.Open(IDR_DOWNLOAD
);
109 CAppUtils::CreateFontForLogs(m_logFont
);
110 //GetDlgItem(IDC_CMD_LOG)->SetFont(&m_logFont);
111 m_Log
.SetFont(&m_logFont
);
114 if ( !m_PreText
.IsEmpty() )
116 InitialText
= m_PreText
+ _T("\r\n");
119 if (m_bShowCommand
&& (!m_GitCmd
.IsEmpty() ))
121 InitialText
+= m_GitCmd
+_T("\r\n\r\n");
124 m_Log
.SetWindowTextW(InitialText
);
125 m_CurrentWork
.SetWindowTextW(_T(""));
127 EnableSaveRestore(_T("ProgressDlg"));
129 m_pThread
= AfxBeginThread(ProgressThreadEntry
, this, THREAD_PRIORITY_NORMAL
,0,CREATE_SUSPENDED
);
132 // ReportError(CString(MAKEINTRESOURCE(IDS_ERR_THREADSTARTFAILED)));
136 m_pThread
->m_bAutoDelete
= FALSE
;
137 m_pThread
->ResumeThread();
140 if(!m_Title
.IsEmpty())
141 this->SetWindowText(m_Title
);
143 CString sWindowTitle
;
144 GetWindowText(sWindowTitle
);
145 CAppUtils::SetWindowTitle(m_hWnd
, g_Git
.m_CurrentDir
, sWindowTitle
);
147 if(m_PostCmdList
.GetCount()>0)
148 m_ctrlPostCmd
.AddEntries(m_PostCmdList
);
153 UINT
CProgressDlg::ProgressThreadEntry(LPVOID pVoid
)
155 return ((CProgressDlg
*)pVoid
)->ProgressThread();
158 //static function, Share with SyncDialog
159 UINT
CProgressDlg::RunCmdList(CWnd
*pWnd
,std::vector
<CString
> &cmdlist
,bool bShowCommand
,CString
*pfilename
,bool *bAbort
,CGitByteArray
*pdata
)
163 PROCESS_INFORMATION pi
;
166 memset(&pi
,0,sizeof(PROCESS_INFORMATION
));
168 CBlockCacheForPath
cacheBlock(g_Git
.m_CurrentDir
);
170 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_START
,0);
175 for(int i
=0;i
<cmdlist
.size();i
++)
177 if(cmdlist
[i
].IsEmpty())
182 CStringA str
= CUnicodeUtils::GetMulti(cmdlist
[i
].Trim() + _T("\n\n"), CP_UTF8
);
183 for(int j
=0;j
<str
.GetLength();j
++)
187 pdata
->m_critSec
.Lock();
188 pdata
->push_back(str
[j
]);
189 pdata
->m_critSec
.Unlock();
192 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,str
[j
]);
195 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,0);
198 g_Git
.RunAsync(cmdlist
[i
].Trim(),&pi
, &hRead
, NULL
, pfilename
);
203 while(ReadFile(hRead
,&byte
,1,&readnumber
,NULL
))
210 pdata
->m_critSec
.Lock();
211 pdata
->push_back( byte
);
212 pdata
->m_critSec
.Unlock();
214 if(byte
== '\r' || byte
== '\n')
215 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,0);
218 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
,MSG_PROGRESSDLG_RUN
,byte
);
221 CloseHandle(pi
.hThread
);
223 WaitForSingleObject(pi
.hProcess
, INFINITE
);
226 if(!GetExitCodeProcess(pi
.hProcess
,&status
) || *bAbort
)
228 CloseHandle(pi
.hProcess
);
232 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
, MSG_PROGRESSDLG_FAILED
, status
);
233 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
238 CloseHandle(pi
.hProcess
);
242 pWnd
->PostMessage(MSG_PROGRESSDLG_UPDATE_UI
, MSG_PROGRESSDLG_END
, ret
);
248 UINT
CProgressDlg::ProgressThread()
251 m_GitCmdList
.push_back(m_GitCmd
);
255 if(m_LogFile
.IsEmpty())
258 pfilename
=&m_LogFile
;
260 m_startTick
= GetTickCount();
261 m_GitStatus
= RunCmdList(this,m_GitCmdList
,m_bShowCommand
,pfilename
,&m_bAbort
,&this->m_Databuf
);;
265 LRESULT
CProgressDlg::OnProgressUpdateUI(WPARAM wParam
,LPARAM lParam
)
267 if(wParam
== MSG_PROGRESSDLG_START
)
270 m_Animate
.Play(0, INT_MAX
, INT_MAX
);
271 this->DialogEnableWindow(IDOK
,FALSE
);
274 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
275 m_pTaskbarList
->SetProgressValue(m_hWnd
, 0, 100);
278 if(wParam
== MSG_PROGRESSDLG_END
|| wParam
== MSG_PROGRESSDLG_FAILED
)
280 DWORD tickSpent
= GetTickCount() - m_startTick
;
281 CString strEndTime
= CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE
, true, false);
285 m_Databuf
.m_critSec
.Lock();
286 m_Databuf
.push_back(0);
287 m_Databuf
.m_critSec
.Unlock();
289 m_Databuf
.m_critSec
.Lock();
290 m_Log
.SetWindowText(Convert2UnionCode((char*)&m_Databuf
[0]));
291 m_Databuf
.m_critSec
.Unlock();
292 m_Log
.LineScroll(m_Log
.GetLineCount() - m_Log
.GetFirstVisibleLine() - 4);
295 m_Databuf
.m_critSec
.Lock();
296 this->m_Databuf
.clear();
297 m_Databuf
.m_critSec
.Unlock();
301 m_Progress
.SetPos(100);
302 this->DialogEnableWindow(IDOK
,TRUE
);
304 m_GitStatus
= (DWORD
)lParam
;
306 // detect crashes of perl when performing git svn actions
307 if (m_GitStatus
== 0 && m_GitCmd
.Find(_T(" svn ")) > 1)
310 m_Log
.GetWindowText(log
);
311 if (log
.GetLength() > 18 && log
.Mid(log
.GetLength() - 18) == _T("perl.exe.stackdump"))
312 m_GitStatus
= (DWORD
)-1;
315 if(this->m_GitStatus
)
319 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_ERROR
);
320 m_pTaskbarList
->SetProgressValue(m_hWnd
, 100, 100);
323 log
.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT
, m_GitStatus
);
325 err
.Format(_T("\r\n\r\n%s (%d ms @ %s)\r\n"), log
, tickSpent
, strEndTime
);
326 InsertColorText(this->m_Log
, err
, RGB(255,0,0));
330 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NOPROGRESS
);
332 temp
.LoadString(IDS_SUCCESS
);
334 log
.Format(_T("\r\n%s (%d ms @ %s)\r\n"), temp
, tickSpent
, strEndTime
);
335 InsertColorText(this->m_Log
, log
, RGB(0,0,255));
336 this->DialogEnableWindow(IDCANCEL
,FALSE
);
339 if(wParam
== MSG_PROGRESSDLG_END
&& m_GitStatus
== 0)
341 if(m_bAutoCloseOnSuccess
)
343 m_Log
.GetWindowText(this->m_LogText
);
347 if(m_PostCmdList
.GetCount() > 0)
348 GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_SHOW
);
356 m_Databuf
.m_critSec
.Lock();
357 for(int i
=this->m_BufStart
;i
<this->m_Databuf
.size();i
++)
359 char c
= this->m_Databuf
[m_BufStart
];
361 m_Databuf
.m_critSec
.Unlock();
364 m_Databuf
.m_critSec
.Lock();
369 m_Databuf
.erase(m_Databuf
.begin(), m_Databuf
.begin()+m_BufStart
);
372 m_Databuf
.m_critSec
.Unlock();
376 ParserCmdOutput((char)lParam
);
381 //static function, Share with SyncDialog
382 int CProgressDlg::FindPercentage(CString
&log
)
384 int s1
=log
.Find(_T('%'));
389 for(int i
=s1
-1;i
>=0;i
--)
391 if(log
[i
]>=_T('0') && log
[i
]<=_T('9'))
396 return _ttol(log
.Mid(s2
,s1
-s2
));
399 void CProgressDlg::ParserCmdOutput(char ch
)
401 ParserCmdOutput(this->m_Log
,this->m_Progress
,this->m_hWnd
,this->m_pTaskbarList
,this->m_LogTextA
,ch
,&this->m_CurrentWork
);
403 void CProgressDlg::ClearESC(CString
&str
)
405 // see http://ascii-table.com/ansi-escape-sequences.php and http://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html
406 str
.Replace(_T("\033[K"), _T("")); // erase until end of line; no need to care for this, because we always clear the whole line
411 int escapePosition
= str
.Find(_T('\033'));
412 if (escapePosition
>= 0 && str
.GetLength() >= escapePosition
+ 3)
414 if (str
.Mid(escapePosition
, 2) == _T("\033["))
416 int colorEnd
= str
.Find(_T('m'), escapePosition
+ 2);
420 for (int i
= escapePosition
+ 2; i
< colorEnd
; i
++)
422 if (str
[i
] != _T(';') && (str
[i
] < _T('0') && str
[i
] > _T('9')))
430 if (escapePosition
> 0)
431 str
= str
.Left(escapePosition
) + str
.Mid(colorEnd
+ 1);
433 str
= str
.Mid(colorEnd
);
442 void CProgressDlg::ParserCmdOutput(CRichEditCtrl
&log
,CProgressCtrl
&progressctrl
,HWND m_hWnd
,CComPtr
<ITaskbarList3
> m_pTaskbarList
,CStringA
&oneline
, char ch
, CWnd
*CurrentWork
)
444 //TRACE(_T("%c"),ch);
445 if( ch
== ('\r') || ch
== ('\n'))
449 // TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
450 // TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));
452 int lines
= log
.GetLineCount();
453 g_Git
.StringAppend(&str
, (BYTE
*)oneline
.GetBuffer(), CP_UTF8
);
455 // TRACE(_T("%s"), str);
461 int start
=log
.LineIndex(lines
-1);
462 log
.SetSel(start
, log
.GetTextLength());
467 int length
= log
.GetWindowTextLength();
468 log
.SetSel(length
, length
);
470 log
.ReplaceSel(_T("\r\n") + str
);
475 if (lines
> 500) //limited log length
477 int end
=log
.LineIndex(1);
479 log
.ReplaceSel(_T(""));
481 log
.LineScroll(log
.GetLineCount() - log
.GetFirstVisibleLine() - 4);
483 int s1
=oneline
.ReverseFind(_T(':'));
484 int s2
=oneline
.Find(_T('%'));
485 if (s1
> 0 && s2
> 0)
488 CurrentWork
->SetWindowTextW(str
.Left(s1
));
490 int pos
=FindPercentage(str
);
491 TRACE(_T("Pos %d\r\n"),pos
);
494 progressctrl
.SetPos(pos
);
497 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
498 m_pTaskbarList
->SetProgressValue(m_hWnd
, pos
, 100);
511 void CProgressDlg::RemoveLastLine(CString
&str
)
514 start
=str
.ReverseFind(_T('\n'));
519 // CProgressDlg message handlers
521 void CProgressDlg::OnBnClickedOk()
523 m_Log
.GetWindowText(this->m_LogText
);
527 void CProgressDlg::OnBnClickedButton1()
529 this->EndDialog((int)(IDC_PROGRESS_BUTTON1
+ this->m_ctrlPostCmd
.GetCurrentEntry()));
532 void CProgressDlg::OnClose()
534 DialogEnableWindow(IDCANCEL
, TRUE
);
538 void CProgressDlg::OnCancel()
543 CResizableStandAloneDialog::OnCancel();
547 if( g_Git
.m_CurrentGitPi
.hProcess
)
549 if(::GenerateConsoleCtrlEvent(CTRL_C_EVENT
,0))
551 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
558 KillProcessTree(g_Git
.m_CurrentGitPi
.dwProcessId
);
561 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
562 CResizableStandAloneDialog::OnCancel();
565 void CProgressDlg::KillProcessTree(DWORD dwProcessId
, unsigned int depth
)
567 // recursively kills a process tree
568 // This is not optimized, but works and isn't called very often ;)
570 if (!dwProcessId
|| depth
> 20)
574 memset(&pe
, 0, sizeof(PROCESSENTRY32
));
575 pe
.dwSize
= sizeof(PROCESSENTRY32
);
577 CAutoGeneralHandle hSnap
= ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
579 if (::Process32First(hSnap
, &pe
))
583 if (pe
.th32ParentProcessID
== dwProcessId
)
584 KillProcessTree(pe
.th32ProcessID
, depth
+ 1);
585 } while (::Process32Next(hSnap
, &pe
));
587 HANDLE hProc
= ::OpenProcess(PROCESS_TERMINATE
, FALSE
, dwProcessId
);
589 ::TerminateProcess(hProc
, 1);
593 void CProgressDlg::InsertCRLF()
595 m_Databuf
.m_critSec
.Lock();
596 for(int i
=0;i
<m_Databuf
.size();i
++)
598 if(m_Databuf
[i
]==('\n'))
600 if(i
==0 || m_Databuf
[i
-1]!= ('\r'))
602 m_Databuf
.insert(m_Databuf
.begin()+i
,('\r'));
607 m_Databuf
.m_critSec
.Unlock();
610 void CProgressDlg::InsertColorText(CRichEditCtrl
&edit
,CString text
,COLORREF rgb
)
613 edit
.GetDefaultCharFormat(cf
);
615 cf
.dwMask
|=CFM_COLOR
;
617 cf
.dwEffects
|=CFE_BOLD
;
618 cf
.dwEffects
&= ~CFE_AUTOCOLOR
;
619 edit
.SetSel(edit
.GetTextLength()-1,edit
.GetTextLength());
620 edit
.ReplaceSel(text
);
621 edit
.SetSel(edit
.LineIndex(edit
.GetLineCount()-2),edit
.GetTextLength());
622 edit
.SetSelectionCharFormat(cf
);
623 edit
.SetSel(edit
.GetTextLength(),edit
.GetTextLength());
624 edit
.SetDefaultCharFormat(old
);
625 edit
.LineScroll(edit
.GetLineCount() - edit
.GetFirstVisibleLine() - 4);
628 CString
CCommitProgressDlg::Convert2UnionCode(char *buff
, int size
)
635 cmd
=_T("git.exe config i18n.logOutputEncoding");
636 if (g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
))
640 output
=output
.Tokenize(_T("\n"),start
);
641 cp
=CUnicodeUtils::GetCPCode(output
);
645 size
= (int)strlen(buff
);
647 for(int i
=0;i
<size
;i
++)
651 if( start
>0 && buff
[i
] =='\n' )
659 g_Git
.StringAppend(&str
, (BYTE
*)buff
, cp
, start
);
660 g_Git
.StringAppend(&str
, (BYTE
*)buff
+ start
, CP_UTF8
, size
- start
);
667 LRESULT
CProgressDlg::OnTaskbarBtnCreated(WPARAM
/*wParam*/, LPARAM
/*lParam*/)
669 m_pTaskbarList
.Release();
670 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
674 BOOL
CProgressDlg::PreTranslateMessage(MSG
* pMsg
)
676 if (pMsg
->message
== WM_KEYDOWN
)
678 if (pMsg
->wParam
== VK_ESCAPE
)
680 // pressing the ESC key should close the dialog. But since we disabled the escape
681 // key (so the user doesn't get the idea that he could simply undo an e.g. update)
683 // So if the user presses the ESC key, change it to VK_RETURN so the dialog gets
684 // the impression that the OK button was pressed.
685 if ((!GetDlgItem(IDCANCEL
)->IsWindowEnabled())
686 &&(GetDlgItem(IDOK
)->IsWindowEnabled())&&(GetDlgItem(IDOK
)->IsWindowVisible()))
688 // since we convert ESC to RETURN, make sure the OK button has the focus.
689 GetDlgItem(IDOK
)->SetFocus();
690 pMsg
->wParam
= VK_RETURN
;
694 else if (pMsg
->message
== WM_CONTEXTMENU
|| pMsg
->message
== WM_RBUTTONDOWN
)
696 CWnd
* pWnd
= (CWnd
*) GetDlgItem(IDC_LOG
);
697 if (pWnd
== GetFocus())
700 if (popup
.CreatePopupMenu())
702 popup
.AppendMenuIcon(WM_COPY
, IDS_SCIEDIT_COPY
, IDI_COPYCLIP
);
703 if (m_Log
.GetSelText().IsEmpty())
704 popup
.EnableMenuItem(WM_COPY
, MF_BYCOMMAND
| MF_DISABLED
| MF_GRAYED
);
705 popup
.AppendMenu(MF_SEPARATOR
);
706 popup
.AppendMenuIcon(EM_SETSEL
, IDS_SCIEDIT_SELECTALL
);
707 int cmd
= popup
.TrackPopupMenu(TPM_RETURNCMD
| TPM_LEFTALIGN
| TPM_NONOTIFY
, pMsg
->pt
.x
, pMsg
->pt
.y
, this);
710 case 0: // no command selected
714 ::SendMessage(GetDlgItem(IDC_LOG
)->GetSafeHwnd(), cmd
, 0, -1);
721 return __super::PreTranslateMessage(pMsg
);