Merge branch 'scintilla-405'
[TortoiseGit.git] / src / TortoiseProc / GitProgressList.cpp
blobdf5f9f4b5b00556cac99f8a356450bc1cf8c8195
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - TortoiseGit
4 // Copyright (C) 2003-2008 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "GitProgressList.h"
22 #include "TortoiseProc.h"
23 #include "Git.h"
24 #include "registry.h"
25 #include "AppUtils.h"
26 #include "StringUtils.h"
27 #include "LogFile.h"
28 #include "LoglistUtils.h"
30 BOOL CGitProgressList::m_bAscending = FALSE;
31 int CGitProgressList::m_nSortedColumn = -1;
33 #define TRANSFERTIMER 100
34 #define VISIBLETIMER 101
35 // CGitProgressList
37 IMPLEMENT_DYNAMIC(CGitProgressList, CListCtrl)
39 CGitProgressList::CGitProgressList():CListCtrl()
40 , m_bCancelled(FALSE)
41 , m_pThread(nullptr)
42 , m_bErrorsOccurred(false)
43 , m_options(ProgOptNone)
44 , m_bSetTitle(false)
45 , m_pTaskbarList(nullptr)
46 , m_Command(nullptr)
47 , m_bThreadRunning(FALSE)
48 , iFirstResized(0)
49 , bSecondResized(false)
50 , nEnsureVisibleCount(0)
51 , m_TotalBytesTransferred(0)
52 , m_bFinishedItemAdded(false)
53 , m_bLastVisible(false)
54 , m_itemCount(-1)
55 , m_itemCountTotal(-1)
56 , m_nBackgroundImageID(0)
57 , m_pInfoCtrl(nullptr)
58 , m_pAnimate(nullptr)
59 , m_pProgControl(nullptr)
60 , m_pProgressLabelCtrl(nullptr)
61 , m_pPostWnd(nullptr)
63 m_columnbuf[0] = L'\0';
66 CGitProgressList::~CGitProgressList()
68 for (size_t i = 0; i < m_arData.size(); ++i)
69 delete m_arData[i];
70 delete m_pThread;
74 BEGIN_MESSAGE_MAP(CGitProgressList, CListCtrl)
75 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawSvnprogress)
76 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkSvnprogress)
77 ON_NOTIFY_REFLECT(HDN_ITEMCLICK, OnHdnItemclickSvnprogress)
78 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnLvnBegindragSvnprogress)
79 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoSvnprogress)
80 ON_MESSAGE(WM_SHOWCONFLICTRESOLVER, OnShowConflictResolver)
81 ON_WM_SIZE()
82 ON_WM_TIMER()
83 ON_WM_CONTEXTMENU()
84 ON_WM_CLOSE()
85 END_MESSAGE_MAP()
87 void CGitProgressList::Cancel()
89 m_bCancelled = TRUE;
94 // CGitProgressList message handlers
97 LRESULT CGitProgressList::OnShowConflictResolver(WPARAM /*wParam*/, LPARAM /*lParam*/)
99 #if 0
100 CConflictResolveDlg dlg(this);
101 const svn_wc_conflict_description_t *description = (svn_wc_conflict_description_t *)lParam;
102 if (description)
104 dlg.SetConflictDescription(description);
105 if (m_pTaskbarList)
107 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_PAUSED);
109 if (dlg.DoModal() == IDOK)
111 if (dlg.GetResult() == svn_wc_conflict_choose_postpone)
113 // if the result is conflicted and the dialog returned IDOK,
114 // that means we should not ask again in case of a conflict
115 m_AlwaysConflicted = true;
116 ::SendMessage(GetDlgItem(IDC_NONINTERACTIVE)->GetSafeHwnd(), BM_SETCHECK, BST_CHECKED, 0);
119 m_mergedfile = dlg.GetMergedFile();
120 m_bCancelled = dlg.IsCancelled();
121 if (m_pTaskbarList)
122 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_INDETERMINATE);
123 return dlg.GetResult();
126 return svn_wc_conflict_choose_postpone;
127 #endif
128 return 0;
130 #if 0
131 svn_wc_conflict_choice_t CGitProgressList::ConflictResolveCallback(const svn_wc_conflict_description_t *description, CString& mergedfile)
133 // we only bother the user when merging
134 if (((m_Command == GitProgress_Merge)||(m_Command == GitProgress_MergeAll)||(m_Command == GitProgress_MergeReintegrate))&&(!m_AlwaysConflicted)&&(description))
136 // we're in a worker thread here. That means we must not show a dialog from the thread
137 // but let the UI thread do it.
138 // To do that, we send a message to the UI thread and let it show the conflict resolver dialog.
139 LRESULT dlgResult = ::SendMessage(GetSafeHwnd(), WM_SHOWCONFLICTRESOLVER, 0, (LPARAM)description);
140 mergedfile = m_mergedfile;
141 return (svn_wc_conflict_choice_t)dlgResult;
144 return svn_wc_conflict_choose_postpone;
146 #endif
147 void CGitProgressList::AddItemToList()
149 int totalcount = GetItemCount();
151 SetItemCountEx(totalcount+1, LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL);
152 // make columns width fit
153 if (iFirstResized < 30)
155 // only resize the columns for the first 30 or so entries.
156 // after that, don't resize them anymore because that's an
157 // expensive function call and the columns will be sized
158 // close enough already.
159 ResizeColumns();
160 ++iFirstResized;
163 // Make sure the item is *entirely* visible even if the horizontal
164 // scroll bar is visible.
165 int count = GetCountPerPage();
166 if (totalcount <= (GetTopIndex() + count + nEnsureVisibleCount + 2))
168 ++nEnsureVisibleCount;
169 m_bLastVisible = true;
171 else
173 nEnsureVisibleCount = 0;
174 if (IsIconic() == 0)
175 m_bLastVisible = false;
179 CString CGitProgressList::BuildInfoString()
181 CString infotext;
182 m_Command->ShowInfo(infotext);
184 #if 0
186 int added = 0;
187 int copied = 0;
188 int deleted = 0;
189 int restored = 0;
190 int reverted = 0;
191 int resolved = 0;
192 int conflicted = 0;
193 int updated = 0;
194 int merged = 0;
195 int modified = 0;
196 int skipped = 0;
197 int replaced = 0;
199 for (size_t i=0; i<m_arData.size(); ++i)
201 const NotificationData * dat = m_arData[i];
202 switch (dat->action)
204 case svn_wc_notify_add:
205 case svn_wc_notify_update_add:
206 case svn_wc_notify_commit_added:
207 if (dat->bConflictedActionItem)
208 ++conflicted;
209 else
210 ++added;
211 break;
212 case svn_wc_notify_copy:
213 ++copied;
214 break;
215 case svn_wc_notify_delete:
216 case svn_wc_notify_update_delete:
217 case svn_wc_notify_commit_deleted:
218 ++deleted;
219 break;
220 case svn_wc_notify_restore:
221 ++restored;
222 break;
223 case svn_wc_notify_revert:
224 ++reverted;
225 break;
226 case svn_wc_notify_resolved:
227 ++resolved;
228 break;
229 case svn_wc_notify_update_update:
230 if (dat->bConflictedActionItem)
231 ++conflicted;
232 else if ((dat->content_state == svn_wc_notify_state_merged) || (dat->prop_state == svn_wc_notify_state_merged))
233 ++merged;
234 else
235 ++updated;
236 break;
237 case svn_wc_notify_commit_modified:
238 ++modified;
239 break;
240 case svn_wc_notify_skip:
241 ++skipped;
242 break;
243 case svn_wc_notify_commit_replaced:
244 ++replaced;
245 break;
248 if (conflicted)
250 temp.LoadString(IDS_SVNACTION_CONFLICTED);
251 infotext += temp;
252 temp.Format(L":%d ", conflicted);
253 infotext += temp;
255 if (skipped)
257 temp.LoadString(IDS_SVNACTION_SKIP);
258 infotext += temp;
259 infotext.AppendFormat(L":%d ", skipped);
261 if (merged)
263 temp.LoadString(IDS_SVNACTION_MERGED);
264 infotext += temp;
265 infotext.AppendFormat(L":%d ", merged);
267 if (added)
269 temp.LoadString(IDS_SVNACTION_ADD);
270 infotext += temp;
271 infotext.AppendFormat(L":%d ", added);
273 if (deleted)
275 temp.LoadString(IDS_SVNACTION_DELETE);
276 infotext += temp;
277 infotext.AppendFormat(L":%d ", deleted);
279 if (modified)
281 temp.LoadString(IDS_SVNACTION_MODIFIED);
282 infotext += temp;
283 infotext.AppendFormat(L":%d ", modified);
285 if (copied)
287 temp.LoadString(IDS_SVNACTION_COPY);
288 infotext += temp;
289 infotext.AppendFormat(L":%d ", copied);
291 if (replaced)
293 temp.LoadString(IDS_SVNACTION_REPLACED);
294 infotext += temp;
295 infotext.AppendFormat(L":%d ", replaced);
297 if (updated)
299 temp.LoadString(IDS_SVNACTION_UPDATE);
300 infotext += temp;
301 infotext.AppendFormat(L":%d ", updated);
303 if (restored)
305 temp.LoadString(IDS_SVNACTION_RESTORE);
306 infotext += temp;
307 infotext.AppendFormat(L":%d ", restored);
309 if (reverted)
311 temp.LoadString(IDS_SVNACTION_REVERT);
312 infotext += temp;
313 infotext.AppendFormat(L":%d ", reverted);
315 if (resolved)
317 temp.LoadString(IDS_SVNACTION_RESOLVE);
318 infotext += temp;
319 infotext.AppendFormat(L":%d ", resolved);
321 #endif
322 return infotext;
325 void CGitProgressList::ResizeColumns()
327 SetRedraw(FALSE);
329 TCHAR textbuf[MAX_PATH] = {0};
331 auto pHeaderCtrl = GetHeaderCtrl();
332 if (pHeaderCtrl)
334 int maxcol = pHeaderCtrl->GetItemCount()-1;
335 for (int col = 0; col <= maxcol; ++col)
337 // find the longest width of all items
338 int count = min((int)m_arData.size(), GetItemCount());
339 HDITEM hdi = {0};
340 hdi.mask = HDI_TEXT;
341 hdi.pszText = textbuf;
342 hdi.cchTextMax = _countof(textbuf);
343 pHeaderCtrl->GetItem(col, &hdi);
344 int cx = GetStringWidth(hdi.pszText)+20; // 20 pixels for col separator and margin
346 for (int index = 0; index<count; ++index)
348 // get the width of the string and add 12 pixels for the column separator and margins
349 int linewidth = cx;
350 switch (col)
352 case 0:
353 linewidth = GetStringWidth(m_arData[index]->sActionColumnText) + 12;
354 break;
355 case 1:
356 linewidth = GetStringWidth(m_arData[index]->sPathColumnText) + 12;
357 break;
359 if (cx < linewidth)
360 cx = linewidth;
362 SetColumnWidth(col, cx);
366 SetRedraw(TRUE);
369 bool CGitProgressList::SetBackgroundImage(UINT nID)
371 m_nBackgroundImageID = nID;
372 return CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), nID);
375 void CGitProgressList::ReportGitError()
377 ReportError(CGit::GetLibGit2LastErr());
380 void CGitProgressList::ReportUserCanceled()
382 ReportError(CString(MAKEINTRESOURCE(IDS_USERCANCELLED)));
385 void CGitProgressList::ReportError(const CString& sError)
387 if (CRegDWORD(L"Software\\TortoiseGit\\NoSounds", FALSE) == FALSE)
388 PlaySound((LPCTSTR)SND_ALIAS_SYSTEMEXCLAMATION, nullptr, SND_ALIAS_ID | SND_ASYNC);
389 ReportString(sError, CString(MAKEINTRESOURCE(IDS_ERR_ERROR)), m_Colors.GetColor(CColors::Conflict));
390 m_bErrorsOccurred = true;
393 void CGitProgressList::ReportWarning(const CString& sWarning)
395 if (CRegDWORD(L"Software\\TortoiseGit\\NoSounds", FALSE) == FALSE)
396 PlaySound((LPCTSTR)SND_ALIAS_SYSTEMDEFAULT, nullptr, SND_ALIAS_ID | SND_ASYNC);
397 ReportString(sWarning, CString(MAKEINTRESOURCE(IDS_WARN_WARNING)), m_Colors.GetColor(CColors::Conflict));
400 void CGitProgressList::ReportNotification(const CString& sNotification)
402 if (CRegDWORD(L"Software\\TortoiseGit\\NoSounds", FALSE) == FALSE)
403 PlaySound((LPCTSTR)SND_ALIAS_SYSTEMDEFAULT, nullptr, SND_ALIAS_ID | SND_ASYNC);
404 ReportString(sNotification, CString(MAKEINTRESOURCE(IDS_WARN_NOTE)));
407 void CGitProgressList::ReportCmd(const CString& sCmd)
409 ReportString(sCmd, CString(MAKEINTRESOURCE(IDS_PROGRS_CMDINFO)), m_Colors.GetColor(CColors::Cmd));
412 void CGitProgressList::ReportString(CString sMessage, const CString& sMsgKind, COLORREF color)
414 // instead of showing a dialog box with the error message or notification,
415 // just insert the error text into the list control.
416 // that way the user isn't 'interrupted' by a dialog box popping up!
418 // the message may be split up into different lines
419 // so add a new entry for each line of the message
420 while (!sMessage.IsEmpty())
422 NotificationData * data = new NotificationData();
423 data->bAuxItem = true;
424 data->sActionColumnText = sMsgKind;
425 if (sMessage.Find('\n')>=0)
426 data->sPathColumnText = sMessage.Left(sMessage.Find('\n'));
427 else
428 data->sPathColumnText = sMessage;
429 data->sPathColumnText.Trim(L"\n\r");
430 data->color = color;
431 if (sMessage.Find('\n')>=0)
433 sMessage = sMessage.Mid(sMessage.Find('\n'));
434 sMessage.Trim(L"\n\r");
436 else
437 sMessage.Empty();
438 AddNotify(data);
442 UINT CGitProgressList::ProgressThreadEntry(LPVOID pVoid)
444 return reinterpret_cast<CGitProgressList*>(pVoid)->ProgressThread();
447 UINT CGitProgressList::ProgressThread()
449 // The SetParams function should have loaded something for us
451 CString temp;
452 CString sWindowTitle;
453 bool bSuccess = false;
455 if(m_pPostWnd)
456 m_pPostWnd->PostMessage(WM_PROG_CMD_START, (WPARAM)m_Command);
458 if(m_pProgressLabelCtrl)
460 m_pProgressLabelCtrl->ShowWindow(SW_SHOW);
461 m_pProgressLabelCtrl->SetWindowText(L"");
464 // SetAndClearProgressInfo(m_hWnd);
465 m_itemCount = m_itemCountTotal;
467 InterlockedExchange(&m_bThreadRunning, TRUE);
468 iFirstResized = 0;
469 bSecondResized = FALSE;
470 m_bFinishedItemAdded = false;
471 auto startTime = GetTickCount64();
473 if (m_pTaskbarList && m_pPostWnd)
474 m_pTaskbarList->SetProgressState(m_pPostWnd->GetSafeHwnd(), TBPF_INDETERMINATE);
476 m_TotalBytesTransferred = 0;
477 if (m_Command)
478 bSuccess = m_Command->Run(this, sWindowTitle, m_itemCountTotal, m_itemCount);
479 else
480 bSuccess = false;
482 if (!bSuccess)
483 temp.LoadString(IDS_PROGRS_TITLEFAILED);
484 else
485 temp.LoadString(IDS_PROGRS_TITLEFIN);
486 sWindowTitle = sWindowTitle + L' ' + temp;
487 if (m_bSetTitle && m_pPostWnd)
488 ::SetWindowText(m_pPostWnd->GetSafeHwnd(), sWindowTitle);
490 KillTimer(TRANSFERTIMER);
491 KillTimer(VISIBLETIMER);
493 if (m_pTaskbarList && m_pPostWnd)
495 if (DidErrorsOccur())
497 m_pTaskbarList->SetProgressState(m_pPostWnd->GetSafeHwnd(), TBPF_ERROR);
498 m_pTaskbarList->SetProgressValue(m_pPostWnd->GetSafeHwnd(), 100, 100);
500 else
501 m_pTaskbarList->SetProgressState(m_pPostWnd->GetSafeHwnd(), TBPF_NOPROGRESS);
504 if (m_pInfoCtrl)
506 CString info;
507 if (!bSuccess)
508 info.LoadString(IDS_PROGRS_INFOFAILED);
509 else // this implies that command is not nullptr
510 info = BuildInfoString();
511 m_pInfoCtrl->SetWindowText(info);
514 ResizeColumns();
516 auto time = GetTickCount64() - startTime;
518 CString sFinalInfo;
519 if (!m_sTotalBytesTransferred.IsEmpty())
521 temp.Format(IDS_PROGRS_TIME, (DWORD)(time / 1000) / 60, (DWORD)(time / 1000) % 60);
522 sFinalInfo.Format(IDS_PROGRS_FINALINFO, (LPCTSTR)m_sTotalBytesTransferred, (LPCTSTR)temp);
523 if (m_pProgressLabelCtrl)
524 m_pProgressLabelCtrl->SetWindowText(sFinalInfo);
526 else
528 if (m_pProgressLabelCtrl)
529 m_pProgressLabelCtrl->ShowWindow(SW_HIDE);
532 if (m_pProgControl)
533 m_pProgControl->ShowWindow(SW_HIDE);
535 if (!m_bFinishedItemAdded)
537 CString log, str;
538 if (bSuccess)
539 str.LoadString(IDS_SUCCESS);
540 else
541 str.LoadString(IDS_FAIL);
542 log.Format(L"%s (%lu ms @ %s)", (LPCTSTR)str, time, (LPCTSTR)CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE, true, false));
544 // there's no "finished: xxx" line at the end. We add one here to make
545 // sure the user sees that the command is actually finished.
546 ReportString(log, CString(MAKEINTRESOURCE(IDS_PROGRS_FINISHED)), bSuccess? RGB(0,0,255) : RGB(255,0,0));
549 int count = GetItemCount();
550 if ((count > 0)&&(m_bLastVisible))
551 EnsureVisible(count-1, FALSE);
553 CLogFile logfile(g_Git.m_CurrentDir);
554 if (logfile.Open())
556 logfile.AddTimeLine();
557 for (size_t i = 0; i < m_arData.size(); ++i)
559 NotificationData * data = m_arData[i];
560 temp.Format(L"%-20s : %s", (LPCTSTR)data->sActionColumnText, (LPCTSTR)data->sPathColumnText);
561 logfile.AddLine(temp);
563 if (!sFinalInfo.IsEmpty())
564 logfile.AddLine(sFinalInfo);
565 logfile.Close();
568 m_bCancelled = TRUE;
569 InterlockedExchange(&m_bThreadRunning, FALSE);
571 if (m_pPostWnd)
572 m_pPostWnd->PostMessage(WM_PROG_CMD_FINISH, (WPARAM)m_Command, 0L);
574 //Don't do anything here which might cause messages to be sent to the window
575 //The window thread is probably now blocked in OnOK if we've done an auto close
576 return 0;
579 void CGitProgressList::OnLvnGetdispinfoSvnprogress(NMHDR *pNMHDR, LRESULT *pResult)
581 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
583 if (pDispInfo)
585 if (pDispInfo->item.mask & LVIF_TEXT)
587 if (pDispInfo->item.iItem < (int)m_arData.size())
589 const NotificationData * data = m_arData[pDispInfo->item.iItem];
590 switch (pDispInfo->item.iSubItem)
592 case 0:
593 lstrcpyn(m_columnbuf, data->sActionColumnText, MAX_PATH);
594 break;
595 case 1:
596 lstrcpyn(m_columnbuf, data->sPathColumnText, pDispInfo->item.cchTextMax - 1);
597 if (!data->bAuxItem)
599 int cWidth = GetColumnWidth(1);
600 cWidth = max(12, cWidth-12);
601 CDC * pDC = GetDC();
602 if (pDC)
604 CFont * pFont = pDC->SelectObject(GetFont());
605 PathCompactPath(pDC->GetSafeHdc(), m_columnbuf, cWidth);
606 pDC->SelectObject(pFont);
607 ReleaseDC(pDC);
610 break;
611 default:
612 m_columnbuf[0] = L'\0';
614 pDispInfo->item.pszText = m_columnbuf;
618 *pResult = 0;
621 void CGitProgressList::OnNMCustomdrawSvnprogress(NMHDR *pNMHDR, LRESULT *pResult)
623 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
625 // Take the default processing unless we set this to something else below.
626 *pResult = CDRF_DODEFAULT;
628 // First thing - check the draw stage. If it's the control's prepaint
629 // stage, then tell Windows we want messages for every item.
631 if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
633 *pResult = CDRF_NOTIFYITEMDRAW;
635 else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
637 // This is the prepaint stage for an item. Here's where we set the
638 // item's text color. Our return value will tell Windows to draw the
639 // item itself, but it will use the new color we set here.
641 // Tell Windows to paint the control itself.
642 *pResult = CDRF_DODEFAULT;
644 ASSERT(pLVCD->nmcd.dwItemSpec < m_arData.size());
645 if(pLVCD->nmcd.dwItemSpec >= m_arData.size())
647 return;
649 const NotificationData * data = m_arData[pLVCD->nmcd.dwItemSpec];
650 ASSERT(data);
651 if (!data)
652 return;
654 // Store the color back in the NMLVCUSTOMDRAW struct.
655 pLVCD->clrText = data->color;
659 void CGitProgressList::OnNMDblclkSvnprogress(NMHDR* pNMHDR, LRESULT* pResult)
661 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
662 *pResult = 0;
663 if (pNMLV->iItem < 0)
664 return;
665 if (m_options & ProgOptDryRun || m_bThreadRunning)
666 return; //don't do anything in a dry-run.
668 const NotificationData* data = m_arData[pNMLV->iItem];
669 if (!data)
670 return;
672 data->HandleDblClick();
675 void CGitProgressList::OnHdnItemclickSvnprogress(NMHDR *pNMHDR, LRESULT *pResult)
677 LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
678 if (m_bThreadRunning)
679 return;
680 if (m_nSortedColumn == phdr->iItem)
681 m_bAscending = !m_bAscending;
682 else
683 m_bAscending = TRUE;
684 m_nSortedColumn = phdr->iItem;
685 Sort();
687 CString temp;
688 SetRedraw(FALSE);
689 DeleteAllItems();
690 SetItemCountEx (static_cast<int>(m_arData.size()));
692 SetRedraw(TRUE);
694 *pResult = 0;
697 bool CGitProgressList::NotificationDataIsAux(const NotificationData* pData)
699 return pData->bAuxItem;
702 void CGitProgressList::AddNotify(NotificationData* data, CColors::Colors color)
704 if (color != CColors::COLOR_END)
705 data->color = m_Colors.GetColor(color);
706 else
707 data->SetColorCode(m_Colors);
709 m_arData.push_back(data);
710 AddItemToList();
712 if ((!data->bAuxItem) && (m_itemCount > 0))
714 if (m_pProgControl)
716 m_pProgControl->ShowWindow(SW_SHOW);
717 m_pProgControl->SetPos(m_itemCount);
718 m_pProgControl->SetRange32(0, m_itemCountTotal);
720 if (m_pTaskbarList && m_pPostWnd)
722 m_pTaskbarList->SetProgressState(m_pPostWnd->GetSafeHwnd(), TBPF_NORMAL);
723 m_pTaskbarList->SetProgressValue(m_pPostWnd->GetSafeHwnd(), m_itemCount, m_itemCountTotal);
727 // needed as long as RemoteProgressCommand::RemoteCompletionCallback never gets called by libgit2
728 if (m_pAnimate)
729 m_pAnimate->ShowWindow(SW_HIDE);
732 int CGitProgressList::UpdateProgress(const git_transfer_progress* stat)
734 static ULONGLONG start = 0;
735 auto dt = GetTickCount64() - start;
736 double speed = 0;
738 if (m_bCancelled)
740 giterr_set_str(GITERR_NONE, "User cancelled.");
741 return GIT_EUSER;
744 if (dt > 100)
746 start = GetTickCount64();
747 size_t ds = stat->received_bytes - m_TotalBytesTransferred;
748 speed = ds * 1000.0/dt;
749 m_TotalBytesTransferred = stat->received_bytes;
751 else
752 return 0;
754 int progress;
755 progress = stat->received_objects + stat->indexed_objects;
757 if ((stat->total_objects > 1000) && m_pProgControl && (!m_pProgControl->IsWindowVisible()))
758 m_pProgControl->ShowWindow(SW_SHOW);
760 if (m_pProgressLabelCtrl && m_pProgressLabelCtrl->IsWindowVisible())
761 m_pProgressLabelCtrl->ShowWindow(SW_SHOW);
763 if (m_pProgControl)
765 m_pProgControl->SetPos(progress);
766 m_pProgControl->SetRange32(0, 2 * stat->total_objects);
768 if (m_pTaskbarList && m_pPostWnd)
770 m_pTaskbarList->SetProgressState(m_pPostWnd->GetSafeHwnd(), TBPF_NORMAL);
771 m_pTaskbarList->SetProgressValue(m_pPostWnd->GetSafeHwnd(), progress, 2 * stat->total_objects);
774 CString progText;
775 if (stat->received_bytes < 1024)
776 m_sTotalBytesTransferred.Format(IDS_SVN_PROGRESS_TOTALBYTESTRANSFERRED, (int64_t)stat->received_bytes);
777 else if (stat->received_bytes < 1200000)
778 m_sTotalBytesTransferred.Format(IDS_SVN_PROGRESS_TOTALTRANSFERRED, (int64_t)stat->received_bytes / 1024);
779 else
780 m_sTotalBytesTransferred.Format(IDS_SVN_PROGRESS_TOTALMBTRANSFERRED, (double)((double)stat->received_bytes / 1048576.0));
782 CString str;
783 if(speed < 1024)
784 str.Format(L"%.0f B/s", speed);
785 else if(speed < 1024 * 1024)
786 str.Format(L"%.2f KiB/s", speed / 1024);
787 else
788 str.Format(L"%.2f MiB/s", speed / 1048576.0);
790 progText.Format(IDS_SVN_PROGRESS_TOTALANDSPEED, (LPCTSTR)m_sTotalBytesTransferred, (LPCTSTR)str);
791 if (m_pProgressLabelCtrl)
792 m_pProgressLabelCtrl->SetWindowText(progText);
794 SetTimer(TRANSFERTIMER, 2000, nullptr);
796 return 0;
799 void CGitProgressList::OnTimer(UINT_PTR nIDEvent)
801 if (nIDEvent == TRANSFERTIMER)
803 CString progText;
804 CString progSpeed = L"0 B/s";
805 progText.Format(IDS_SVN_PROGRESS_TOTALANDSPEED, (LPCTSTR)m_sTotalBytesTransferred, (LPCTSTR)progSpeed);
806 if (m_pProgressLabelCtrl)
807 m_pProgressLabelCtrl->SetWindowText(progText);
809 KillTimer(TRANSFERTIMER);
811 if (nIDEvent == VISIBLETIMER)
813 if (nEnsureVisibleCount)
814 EnsureVisible(GetItemCount()-1, false);
815 nEnsureVisibleCount = 0;
819 void CGitProgressList::Sort()
821 if(m_arData.size() < 2)
822 return;
824 // We need to sort the blocks which lie between the auxiliary entries
825 // This is so that any aux data stays where it was
826 NotificationDataVect::iterator actionBlockBegin;
827 NotificationDataVect::iterator actionBlockEnd = m_arData.begin(); // We start searching from here
829 for(;;)
831 // Search to the start of the non-aux entry in the next block
832 actionBlockBegin = std::find_if(actionBlockEnd, m_arData.end(), [](const auto& pData) { return !CGitProgressList::NotificationDataIsAux(pData); });
833 if(actionBlockBegin == m_arData.end())
835 // There are no more actions
836 break;
838 // Now search to find the end of the block
839 actionBlockEnd = std::find_if(actionBlockBegin + 1, m_arData.end(), [](const auto& pData) { return CGitProgressList::NotificationDataIsAux(pData); });
840 // Now sort the block
841 std::sort(actionBlockBegin, actionBlockEnd, &CGitProgressList::SortCompare);
845 bool CGitProgressList::SortCompare(const NotificationData * pData1, const NotificationData * pData2)
847 int result = 0;
848 switch (m_nSortedColumn)
850 case 0: //action column
851 result = pData1->sActionColumnText.Compare(pData2->sActionColumnText);
852 break;
853 case 1: //path column
854 // Compare happens after switch()
855 break;
856 default:
857 break;
860 // Sort by path if everything else is equal
861 if (result == 0)
862 result = CTGitPath::Compare(pData1->path, pData2->path);
864 if (!m_bAscending)
865 result = -result;
866 return result < 0;
869 void CGitProgressList::OnContextMenu(CWnd* pWnd, CPoint point)
871 if (m_options & ProgOptDryRun)
872 return; // don't do anything in a dry-run.
874 if (pWnd != this)
875 return;
877 int selIndex = GetSelectionMark();
878 if ((point.x == -1) && (point.y == -1))
880 // Menu was invoked from the keyboard rather than by right-clicking
881 CRect rect;
882 GetItemRect(selIndex, &rect, LVIR_LABEL);
883 ClientToScreen(&rect);
884 point = rect.CenterPoint();
887 if ((selIndex < 0) || m_bThreadRunning || GetSelectedCount() == 0)
888 return;
890 // entry is selected, thread has finished with updating so show the popup menu
891 CIconMenu popup;
892 if (!popup.CreatePopupMenu())
893 return;
895 ContextMenuActionList actions;
896 NotificationData* data = m_arData[selIndex];
897 if (data && GetSelectedCount() == 1)
898 data->GetContextMenu(popup, actions);
900 if (!actions.empty())
901 popup.AppendMenu(MF_SEPARATOR, NULL);
902 actions.push_back([&]()
904 CString sLines;
905 POSITION pos = GetFirstSelectedItemPosition();
906 while (pos)
908 int nItem = GetNextSelectedItem(pos);
909 NotificationData* data = m_arData[nItem];
910 if (data)
912 sLines += data->sPathColumnText;
913 sLines += L"\r\n";
916 sLines.TrimRight();
917 if (!sLines.IsEmpty())
918 CStringUtils::WriteAsciiStringToClipboard(sLines, GetSafeHwnd());
920 popup.AppendMenuIcon(actions.size(), IDS_LOG_POPUP_COPYTOCLIPBOARD, IDI_COPYCLIP);
922 if (actions.empty())
923 return;
925 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
927 if (cmd <= 0 || (size_t)cmd > actions.size())
928 return;
930 theApp.DoWaitCursor(1);
931 actions.at(cmd - 1)();
932 theApp.DoWaitCursor(-1);
935 void CGitProgressList::OnLvnBegindragSvnprogress(NMHDR* , LRESULT *pResult)
937 //LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
938 #if 0
939 int selIndex = GetSelectionMark();
940 if (selIndex < 0)
941 return;
943 CDropFiles dropFiles; // class for creating DROPFILES struct
945 int index;
946 POSITION pos = GetFirstSelectedItemPosition();
947 while ( (index = GetNextSelectedItem(pos)) >= 0 )
949 NotificationData * data = m_arData[index];
951 if ( data->kind==svn_node_file || data->kind==svn_node_dir )
953 CString sPath = GetPathFromColumnText(data->sPathColumnText);
955 dropFiles.AddFile( sPath );
959 if (!dropFiles.IsEmpty())
961 dropFiles.CreateStructure();
963 #endif
964 *pResult = 0;
967 void CGitProgressList::OnSize(UINT nType, int cx, int cy)
969 CListCtrl::OnSize(nType, cx, cy);
970 if ((nType == SIZE_RESTORED)&&(m_bLastVisible))
972 if(!m_hWnd)
973 return;
975 int count = GetItemCount();
976 if (count > 0)
977 EnsureVisible(count-1, false);
981 void CGitProgressList::Init()
983 SetExtendedStyle((CRegDWORD(L"Software\\TortoiseGit\\FullRowSelect", TRUE) ? LVS_EX_FULLROWSELECT : 0) | LVS_EX_DOUBLEBUFFER);
985 DeleteAllItems();
986 int c = GetHeaderCtrl()->GetItemCount()-1;
987 while (c>=0)
988 DeleteColumn(c--);
990 CString temp;
991 temp.LoadString(IDS_PROGRS_ACTION);
992 InsertColumn(0, temp);
993 temp.LoadString(IDS_PROGRS_PATH);
994 InsertColumn(1, temp);
996 m_pThread = AfxBeginThread(ProgressThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
997 if (!m_pThread)
998 ReportError(CString(MAKEINTRESOURCE(IDS_ERR_THREADSTARTFAILED)));
999 else
1001 m_pThread->m_bAutoDelete = FALSE;
1002 m_pThread->ResumeThread();
1005 // Call this early so that the column headings aren't hidden before any
1006 // text gets added.
1007 ResizeColumns();
1009 SetTimer(VISIBLETIMER, 300, nullptr);
1013 void CGitProgressList::OnClose()
1015 if (m_bCancelled)
1017 g_Git.KillRelatedThreads(m_pThread);
1018 InterlockedExchange(&m_bThreadRunning, FALSE);
1020 else
1022 m_bCancelled = TRUE;
1023 return;
1025 CListCtrl::OnClose();
1028 BOOL CGitProgressList::PreTranslateMessage(MSG* pMsg)
1030 if (pMsg->message == WM_KEYDOWN)
1032 if (pMsg->wParam == 'A')
1034 if (GetKeyState(VK_CONTROL)&0x8000)
1036 // Ctrl-A -> select all
1037 SetSelectionMark(0);
1038 for (int i=0; i<GetItemCount(); ++i)
1039 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
1042 if ((pMsg->wParam == 'C')||(pMsg->wParam == VK_INSERT))
1044 int selIndex = GetSelectionMark();
1045 if (selIndex >= 0)
1047 if (GetKeyState(VK_CONTROL)&0x8000)
1049 //Ctrl-C -> copy to clipboard
1050 CString sClipdata;
1051 POSITION pos = GetFirstSelectedItemPosition();
1052 if (pos)
1054 while (pos)
1056 int nItem = GetNextSelectedItem(pos);
1057 CString sAction = GetItemText(nItem, 0);
1058 CString sPath = GetItemText(nItem, 1);
1059 CString sMime = GetItemText(nItem, 2);
1060 sClipdata.AppendFormat(L"%s: %s %s\r\n", (LPCTSTR)sAction, (LPCTSTR)sPath, (LPCTSTR)sMime);
1062 CStringUtils::WriteAsciiStringToClipboard(sClipdata);
1067 } // if (pMsg->message == WM_KEYDOWN)
1068 return CListCtrl::PreTranslateMessage(pMsg);
1071 void CGitProgressList::SetWindowTitle(UINT id, const CString& urlorpath, CString& dialogname)
1073 if (!m_bSetTitle || !m_pPostWnd)
1074 return;
1076 dialogname.LoadString(id);
1077 CAppUtils::SetWindowTitle(m_pPostWnd->GetSafeHwnd(), urlorpath, dialogname);
1080 void CGitProgressList::ShowProgressBar()
1082 if (m_pProgControl)
1084 m_pProgControl->ShowWindow(SW_SHOW);
1085 m_pProgControl->SetPos(0);
1086 m_pProgControl->SetRange32(0, 1);
1090 void CGitProgressList::SetProgressLabelText(const CString& str)
1092 if (m_pProgressLabelCtrl)
1093 m_pProgressLabelCtrl->SetWindowText(str);
1096 CGitProgressList::WC_File_NotificationData::WC_File_NotificationData(const CTGitPath& path, git_wc_notify_action_t action)
1097 : NotificationData()
1098 , action(action)
1100 this->path = path;
1101 sPathColumnText = path.GetGitPathString();
1103 switch (action)
1105 case git_wc_notify_add:
1106 sActionColumnText.LoadString(IDS_SVNACTION_ADD);
1107 break;
1108 case git_wc_notify_resolved:
1109 sActionColumnText.LoadString(IDS_SVNACTION_RESOLVE);
1110 break;
1111 case git_wc_notify_revert:
1112 sActionColumnText.LoadString(IDS_SVNACTION_REVERT);
1113 break;
1114 case git_wc_notify_checkout:
1115 sActionColumnText.LoadString(IDS_PROGRS_CMD_CHECKOUT);
1116 break;
1117 default:
1118 break;
1122 void CGitProgressList::WC_File_NotificationData::SetColorCode(CColors& colors)
1124 switch (action)
1126 case git_wc_notify_checkout: // fall-through
1127 case git_wc_notify_add:
1128 color = colors.GetColor(CColors::Added);
1129 break;
1131 default:
1132 break;
1136 void CGitProgressList::WC_File_NotificationData::GetContextMenu(CIconMenu& popup, ContextMenuActionList& actions)
1138 if ((action == git_wc_notify_add) ||
1139 (action == git_wc_notify_revert) ||
1140 (action == git_wc_notify_resolved) ||
1141 (action == git_wc_notify_checkout))
1143 actions.push_back([&]()
1145 CString cmd = L"/command:log";
1146 CString sPath = g_Git.CombinePath(path);
1147 cmd += L" /path:\"" + sPath + L'"';
1148 CAppUtils::RunTortoiseGitProc(cmd);
1150 popup.AppendMenuIcon(actions.size(), IDS_MENULOG, IDI_LOG);
1152 popup.AppendMenu(MF_SEPARATOR, NULL);
1153 if (!PathIsDirectory(g_Git.CombinePath(path)))
1155 actions.push_back([&]{ CAppUtils::ShellOpen(g_Git.CombinePath(path)); });
1156 popup.AppendMenuIcon(actions.size(), IDS_LOG_POPUP_OPEN, IDI_OPEN);
1157 actions.push_back([&]{ CAppUtils::ShowOpenWithDialog(g_Git.CombinePath(path)); });
1158 popup.AppendMenuIcon(actions.size(), IDS_LOG_POPUP_OPENWITH, IDI_OPEN);
1161 actions.push_back([&]{ CAppUtils::ExploreTo(nullptr, g_Git.CombinePath(path)); });
1162 popup.AppendMenuIcon(actions.size(), IDS_STATUSLIST_CONTEXT_EXPLORE, IDI_EXPLORER);
1166 void CGitProgressList::WC_File_NotificationData::HandleDblClick() const
1168 CString sWinPath = g_Git.CombinePath(path);
1169 if (PathIsDirectory(sWinPath))
1171 CAppUtils::ExploreTo(nullptr, sWinPath);
1172 return;
1174 CAppUtils::ShellOpen(sWinPath);
1177 void CGitProgressList::OnSysColorChange()
1179 __super::OnSysColorChange();
1180 if (m_nBackgroundImageID)
1181 CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), m_nBackgroundImageID);
1184 ULONG CGitProgressList::GetGestureStatus(CPoint /*ptTouch*/)
1186 return 0;