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"
35 // CProgressDlg dialog
37 IMPLEMENT_DYNAMIC(CProgressDlg
, CResizableStandAloneDialog
)
39 CProgressDlg::CProgressDlg(CWnd
* pParent
/*=NULL*/)
40 : CResizableStandAloneDialog(CProgressDlg::IDD
, pParent
), m_bShowCommand(true), m_bAutoCloseOnSuccess(false), m_bAbort(false), m_bDone(false)
43 m_bAltAbortPress
=false;
47 CProgressDlg::~CProgressDlg()
55 void CProgressDlg::DoDataExchange(CDataExchange
* pDX
)
57 CDialog::DoDataExchange(pDX
);
58 DDX_Control(pDX
, IDC_CURRENT
, this->m_CurrentWork
);
59 DDX_Control(pDX
, IDC_TITLE_ANIMATE
, this->m_Animate
);
60 DDX_Control(pDX
, IDC_RUN_PROGRESS
, this->m_Progress
);
61 DDX_Control(pDX
, IDC_LOG
, this->m_Log
);
62 DDX_Control(pDX
, IDC_PROGRESS_BUTTON1
, this->m_ctrlPostCmd
);
65 BEGIN_MESSAGE_MAP(CProgressDlg
, CResizableStandAloneDialog
)
67 ON_MESSAGE(MSG_PROGRESSDLG_UPDATE_UI
, OnProgressUpdateUI
)
68 ON_BN_CLICKED(IDOK
, &CProgressDlg::OnBnClickedOk
)
69 ON_BN_CLICKED(IDC_PROGRESS_BUTTON1
,&CProgressDlg::OnBnClickedButton1
)
70 ON_REGISTERED_MESSAGE(WM_TASKBARBTNCREATED
, OnTaskbarBtnCreated
)
73 BOOL
CProgressDlg::OnInitDialog()
75 CResizableStandAloneDialog::OnInitDialog();
77 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
78 // do this, Explorer would be unable to send that message to our window if we
79 // were running elevated. It's OK to make the call all the time, since if we're
80 // not elevated, this is a no-op.
81 CHANGEFILTERSTRUCT cfs
= { sizeof(CHANGEFILTERSTRUCT
) };
82 typedef BOOL STDAPICALLTYPE
ChangeWindowMessageFilterExDFN(HWND hWnd
, UINT message
, DWORD action
, PCHANGEFILTERSTRUCT pChangeFilterStruct
);
83 CAutoLibrary hUser
= ::LoadLibrary(_T("user32.dll"));
86 ChangeWindowMessageFilterExDFN
*pfnChangeWindowMessageFilterEx
= (ChangeWindowMessageFilterExDFN
*)GetProcAddress(hUser
, "ChangeWindowMessageFilterEx");
87 if (pfnChangeWindowMessageFilterEx
)
89 pfnChangeWindowMessageFilterEx(m_hWnd
, WM_TASKBARBTNCREATED
, MSGFLT_ALLOW
, &cfs
);
92 m_pTaskbarList
.Release();
93 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
95 AddAnchor(IDC_TITLE_ANIMATE
, TOP_LEFT
, TOP_RIGHT
);
96 AddAnchor(IDC_RUN_PROGRESS
, TOP_LEFT
,TOP_RIGHT
);
97 AddAnchor(IDC_LOG
, TOP_LEFT
,BOTTOM_RIGHT
);
99 AddAnchor(IDOK
,BOTTOM_RIGHT
);
100 AddAnchor(IDCANCEL
,BOTTOM_RIGHT
);
101 AddAnchor(IDC_PROGRESS_BUTTON1
,BOTTOM_LEFT
);
102 AddAnchor(IDC_CURRENT
,TOP_LEFT
);
104 this->GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_HIDE
);
105 m_Animate
.Open(IDR_DOWNLOAD
);
108 CAppUtils::CreateFontForLogs(m_logFont
);
109 //GetDlgItem(IDC_CMD_LOG)->SetFont(&m_logFont);
110 m_Log
.SetFont(&m_logFont
);
113 if ( !m_PreText
.IsEmpty() )
115 InitialText
= m_PreText
+ _T("\r\n");
118 if (m_bShowCommand
&& (!m_GitCmd
.IsEmpty() ))
120 InitialText
+= m_GitCmd
+_T("\r\n\r\n");
123 m_Log
.SetWindowTextW(InitialText
);
124 m_CurrentWork
.SetWindowTextW(_T(""));
126 EnableSaveRestore(_T("ProgressDlg"));
128 m_pThread
= AfxBeginThread(ProgressThreadEntry
, this, THREAD_PRIORITY_NORMAL
,0,CREATE_SUSPENDED
);
131 // ReportError(CString(MAKEINTRESOURCE(IDS_ERR_THREADSTARTFAILED)));
135 m_pThread
->m_bAutoDelete
= FALSE
;
136 m_pThread
->ResumeThread();
139 if(!m_Title
.IsEmpty())
140 this->SetWindowText(m_Title
);
142 CString sWindowTitle
;
143 GetWindowText(sWindowTitle
);
144 CAppUtils::SetWindowTitle(m_hWnd
, g_Git
.m_CurrentDir
, sWindowTitle
);
146 if(m_PostCmdList
.GetCount()>0)
147 m_ctrlPostCmd
.AddEntries(m_PostCmdList
);
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_GitStatus
= RunCmdList(this,m_GitCmdList
,m_bShowCommand
,pfilename
,&m_bAbort
,&this->m_Databuf
);;
263 LRESULT
CProgressDlg::OnProgressUpdateUI(WPARAM wParam
,LPARAM lParam
)
265 if(wParam
== MSG_PROGRESSDLG_START
)
268 m_Animate
.Play(0,-1,-1);
269 this->DialogEnableWindow(IDOK
,FALSE
);
272 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
273 m_pTaskbarList
->SetProgressValue(m_hWnd
, 0, 100);
276 if(wParam
== MSG_PROGRESSDLG_END
|| wParam
== MSG_PROGRESSDLG_FAILED
)
280 m_Databuf
.m_critSec
.Lock();
281 m_Databuf
.push_back(0);
282 m_Databuf
.m_critSec
.Unlock();
284 m_Databuf
.m_critSec
.Lock();
285 m_Log
.SetWindowText(Convert2UnionCode((char*)&m_Databuf
[0]));
286 m_Databuf
.m_critSec
.Unlock();
287 m_Log
.LineScroll(m_Log
.GetLineCount() - m_Log
.GetFirstVisibleLine() - 4);
290 m_Databuf
.m_critSec
.Lock();
291 this->m_Databuf
.clear();
292 m_Databuf
.m_critSec
.Unlock();
296 m_Progress
.SetPos(100);
297 this->DialogEnableWindow(IDOK
,TRUE
);
299 m_GitStatus
= lParam
;
301 // detect crashes of perl when performing git svn actions
302 if (m_GitStatus
== 0 && m_GitCmd
.Find(_T(" svn ")) > 1)
305 m_Log
.GetWindowText(log
);
306 if (log
.GetLength() > 18 && log
.Mid(log
.GetLength() - 18) == _T("perl.exe.stackdump"))
310 if(this->m_GitStatus
)
314 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_ERROR
);
315 m_pTaskbarList
->SetProgressValue(m_hWnd
, 100, 100);
318 log
.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT
, m_GitStatus
);
320 err
.Format(_T("\r\n\r\n%s\r\n"), log
);
321 InsertColorText(this->m_Log
, err
, RGB(255,0,0));
325 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NOPROGRESS
);
327 temp
.LoadString(IDS_SUCCESS
);
329 log
.Format(_T("\r\n%s\r\n"), temp
);
330 InsertColorText(this->m_Log
, log
, RGB(0,0,255));
331 this->DialogEnableWindow(IDCANCEL
,FALSE
);
334 if(wParam
== MSG_PROGRESSDLG_END
&& m_GitStatus
== 0)
336 if(m_bAutoCloseOnSuccess
)
338 m_Log
.GetWindowText(this->m_LogText
);
342 if(m_PostCmdList
.GetCount() > 0)
344 //GetDlgItem(IDC_PROGRESS_BUTTON1)->SetWindowText(m_changeAbortButtonOnSuccessTo);
345 GetDlgItem(IDC_PROGRESS_BUTTON1
)->ShowWindow(SW_SHOW
);
346 //GetDlgItem(IDCANCEL)->ShowWindow(SW_HIDE);
347 //Set default button is "close" rather than "push"
348 this->SendMessage(WM_NEXTDLGCTL
, (WPARAM
)GetDlgItem(IDOK
)->m_hWnd
, TRUE
);
357 m_Databuf
.m_critSec
.Lock();
358 for(int i
=this->m_BufStart
;i
<this->m_Databuf
.size();i
++)
360 char c
= this->m_Databuf
[m_BufStart
];
362 m_Databuf
.m_critSec
.Unlock();
365 m_Databuf
.m_critSec
.Lock();
370 m_Databuf
.erase(m_Databuf
.begin(), m_Databuf
.begin()+m_BufStart
);
373 m_Databuf
.m_critSec
.Unlock();
377 ParserCmdOutput((char)lParam
);
382 //static function, Share with SyncDialog
383 int CProgressDlg::FindPercentage(CString
&log
)
385 int s1
=log
.Find(_T('%'));
390 for(int i
=s1
-1;i
>=0;i
--)
392 if(log
[i
]>=_T('0') && log
[i
]<=_T('9'))
397 return _ttol(log
.Mid(s2
,s1
-s2
));
400 void CProgressDlg::ParserCmdOutput(char ch
)
402 ParserCmdOutput(this->m_Log
,this->m_Progress
,this->m_hWnd
,this->m_pTaskbarList
,this->m_LogTextA
,ch
,&this->m_CurrentWork
);
404 void CProgressDlg::ClearESC(CString
&str
)
406 // see http://ascii-table.com/ansi-escape-sequences.php and http://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html
407 str
.Replace(_T("\033[K"), _T("")); // erase until end of line; no need to care for this, because we always clear the whole line
412 int escapePosition
= str
.Find(_T('\033'));
413 if (escapePosition
>= 0 && str
.GetLength() >= escapePosition
+ 3)
415 if (str
.Mid(escapePosition
, 2) == _T("\033["))
417 int colorEnd
= str
.Find(_T('m'), escapePosition
+ 2);
421 for (int i
= escapePosition
+ 2; i
< colorEnd
; i
++)
423 if (str
[i
] != _T(';') && (str
[i
] < _T('0') && str
[i
] > _T('9')))
431 if (escapePosition
> 0)
432 str
= str
.Left(escapePosition
) + str
.Mid(colorEnd
+ 1);
434 str
= str
.Mid(colorEnd
);
443 void CProgressDlg::ParserCmdOutput(CRichEditCtrl
&log
,CProgressCtrl
&progressctrl
,HWND m_hWnd
,CComPtr
<ITaskbarList3
> m_pTaskbarList
,CStringA
&oneline
, char ch
, CWnd
*CurrentWork
)
445 //TRACE(_T("%c"),ch);
446 if( ch
== ('\r') || ch
== ('\n'))
450 // TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
451 // TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));
453 int lines
= log
.GetLineCount();
454 g_Git
.StringAppend(&str
, (BYTE
*)oneline
.GetBuffer(), CP_UTF8
);
456 // TRACE(_T("%s"), str);
462 int start
=log
.LineIndex(lines
-1);
463 log
.SetSel(start
, log
.GetTextLength());
468 int length
= log
.GetWindowTextLength();
469 log
.SetSel(length
, length
);
471 log
.ReplaceSel(_T("\r\n") + str
);
476 if (lines
> 500) //limited log length
478 int end
=log
.LineIndex(1);
480 log
.ReplaceSel(_T(""));
482 log
.LineScroll(log
.GetLineCount() - log
.GetFirstVisibleLine() - 4);
484 int s1
=oneline
.ReverseFind(_T(':'));
485 int s2
=oneline
.Find(_T('%'));
486 if (s1
> 0 && s2
> 0)
489 CurrentWork
->SetWindowTextW(str
.Left(s1
));
491 int pos
=FindPercentage(str
);
492 TRACE(_T("Pos %d\r\n"),pos
);
495 progressctrl
.SetPos(pos
);
498 m_pTaskbarList
->SetProgressState(m_hWnd
, TBPF_NORMAL
);
499 m_pTaskbarList
->SetProgressValue(m_hWnd
, pos
, 100);
512 void CProgressDlg::RemoveLastLine(CString
&str
)
515 start
=str
.ReverseFind(_T('\n'));
520 // CProgressDlg message handlers
522 void CProgressDlg::OnBnClickedOk()
524 m_Log
.GetWindowText(this->m_LogText
);
528 void CProgressDlg::OnBnClickedButton1()
530 this->EndDialog(IDC_PROGRESS_BUTTON1
+ this->m_ctrlPostCmd
.GetCurrentEntry());
533 void CProgressDlg::OnClose()
535 DialogEnableWindow(IDCANCEL
, TRUE
);
539 void CProgressDlg::OnCancel()
544 CResizableStandAloneDialog::OnCancel();
548 if( g_Git
.m_CurrentGitPi
.hProcess
)
550 if(::GenerateConsoleCtrlEvent(CTRL_C_EVENT
,0))
552 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
559 KillProcessTree(g_Git
.m_CurrentGitPi
.dwProcessId
);
562 ::WaitForSingleObject(g_Git
.m_CurrentGitPi
.hProcess
,10000);
563 CResizableStandAloneDialog::OnCancel();
566 void CProgressDlg::KillProcessTree(DWORD dwProcessId
)
568 // recursively kills a process tree
569 // This is not optimized, but works and isn't called very often ;)
571 memset(&pe
, 0, sizeof(PROCESSENTRY32
));
572 pe
.dwSize
= sizeof(PROCESSENTRY32
);
574 HANDLE hSnap
= ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
576 if (::Process32First(hSnap
, &pe
))
580 if (pe
.th32ParentProcessID
== dwProcessId
)
581 KillProcessTree(pe
.th32ProcessID
);
582 } while (::Process32Next(hSnap
, &pe
));
584 HANDLE hProc
= ::OpenProcess(PROCESS_TERMINATE
, FALSE
, dwProcessId
);
587 ::TerminateProcess(hProc
, 1);
588 ::CloseHandle(hProc
);
591 ::CloseHandle(hSnap
);
594 void CProgressDlg::InsertCRLF()
596 m_Databuf
.m_critSec
.Lock();
597 for(int i
=0;i
<m_Databuf
.size();i
++)
599 if(m_Databuf
[i
]==('\n'))
601 if(i
==0 || m_Databuf
[i
-1]!= ('\r'))
603 m_Databuf
.insert(m_Databuf
.begin()+i
,('\r'));
608 m_Databuf
.m_critSec
.Unlock();
611 void CProgressDlg::InsertColorText(CRichEditCtrl
&edit
,CString text
,COLORREF rgb
)
614 edit
.GetDefaultCharFormat(cf
);
616 cf
.dwMask
|=CFM_COLOR
;
618 cf
.dwEffects
|=CFE_BOLD
;
619 cf
.dwEffects
&= ~CFE_AUTOCOLOR
;
620 edit
.SetSel(edit
.GetTextLength()-1,edit
.GetTextLength());
621 edit
.ReplaceSel(text
);
622 edit
.SetSel(edit
.LineIndex(edit
.GetLineCount()-2),edit
.GetTextLength());
623 edit
.SetSelectionCharFormat(cf
);
624 edit
.SetSel(edit
.GetTextLength(),edit
.GetTextLength());
625 edit
.SetDefaultCharFormat(old
);
626 edit
.LineScroll(edit
.GetLineCount() - edit
.GetFirstVisibleLine() - 4);
629 CString
CCommitProgressDlg::Convert2UnionCode(char *buff
, int size
)
636 cmd
=_T("git.exe config i18n.logOutputEncoding");
637 if (g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
))
641 output
=output
.Tokenize(_T("\n"),start
);
642 cp
=CUnicodeUtils::GetCPCode(output
);
648 for(int i
=0;i
<size
;i
++)
652 if( start
>0 && buff
[i
] =='\n' )
660 g_Git
.StringAppend(&str
, (BYTE
*)buff
, cp
, start
);
661 g_Git
.StringAppend(&str
, (BYTE
*)buff
+ start
, CP_UTF8
, size
- start
);
668 LRESULT
CProgressDlg::OnTaskbarBtnCreated(WPARAM
/*wParam*/, LPARAM
/*lParam*/)
670 m_pTaskbarList
.Release();
671 m_pTaskbarList
.CoCreateInstance(CLSID_TaskbarList
);
675 BOOL
CProgressDlg::PreTranslateMessage(MSG
* pMsg
)
677 if (pMsg
->message
== WM_KEYDOWN
)
679 if (pMsg
->wParam
== VK_ESCAPE
)
681 // pressing the ESC key should close the dialog. But since we disabled the escape
682 // key (so the user doesn't get the idea that he could simply undo an e.g. update)
684 // So if the user presses the ESC key, change it to VK_RETURN so the dialog gets
685 // the impression that the OK button was pressed.
686 if ((!GetDlgItem(IDCANCEL
)->IsWindowEnabled())
687 &&(GetDlgItem(IDOK
)->IsWindowEnabled())&&(GetDlgItem(IDOK
)->IsWindowVisible()))
689 // since we convert ESC to RETURN, make sure the OK button has the focus.
690 GetDlgItem(IDOK
)->SetFocus();
691 pMsg
->wParam
= VK_RETURN
;
695 else if (pMsg
->message
== WM_CONTEXTMENU
|| pMsg
->message
== WM_RBUTTONDOWN
)
697 CWnd
* pWnd
= (CWnd
*) GetDlgItem(IDC_LOG
);
698 if (pWnd
== GetFocus())
701 if (popup
.CreatePopupMenu())
703 popup
.AppendMenuIcon(WM_COPY
, IDS_SCIEDIT_COPY
, IDI_COPYCLIP
);
704 if (m_Log
.GetSelText().IsEmpty())
705 popup
.EnableMenuItem(WM_COPY
, MF_BYCOMMAND
| MF_DISABLED
| MF_GRAYED
);
706 popup
.AppendMenu(MF_SEPARATOR
);
707 popup
.AppendMenuIcon(EM_SETSEL
, IDS_SCIEDIT_SELECTALL
);
708 int cmd
= popup
.TrackPopupMenu(TPM_RETURNCMD
| TPM_LEFTALIGN
| TPM_NONOTIFY
, pMsg
->pt
.x
, pMsg
->pt
.y
, this);
711 case 0: // no command selected
715 ::SendMessage(GetDlgItem(IDC_LOG
)->GetSafeHwnd(), cmd
, 0, -1);
722 return __super::PreTranslateMessage(pMsg
);