Support negative log filter syntax (starts with an exclamation mark) also for regexps
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blobd3d70fe3d707f2921bfb54534daed937599d304e
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - TortoiseGit
4 // Copyright (C) 2005-2007 Marco Costalba
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 // GitLogList.cpp : implementation file
22 #include "stdafx.h"
23 #include "GitLogListBase.h"
24 #include "IconMenu.h"
25 #include "GitProgressDlg.h"
26 #include "ProgressDlg.h"
27 #include "MessageBox.h"
28 #include "LoglistUtils.h"
29 #include "StringUtils.h"
30 #include "UnicodeUtils.h"
31 #include "../TortoiseShell/Resource.h"
32 #include "CommonAppUtils.h"
33 #include "DPIAware.h"
35 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
39 const UINT CGitLogListBase::LOGLIST_RESET_WCREV = RegisterWindowMessage(L"TORTOISEGIT_LOG_RESET_WCREV");
41 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
43 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
44 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
45 ,m_nSearchIndex(0)
46 ,m_bNoDispUpdates(FALSE)
47 , m_bThreadRunning(FALSE)
48 , m_bStrictStopped(false)
49 , m_SelectedFilters(LOGFILTER_ALL)
50 , m_ShowFilter(FILTERSHOW_ALL)
51 , m_bShowWC(false)
52 , m_logEntries(&m_LogCache)
53 , m_pFindDialog(nullptr)
54 , m_dwDefaultColumns(0)
55 , m_arShownList(&m_critSec)
56 , m_hasWC(true)
57 , m_bNoHightlightHead(FALSE)
58 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
59 , m_bFullCommitMessageOnLogLine(false)
60 , m_OldTopIndex(-1)
61 , m_AsyncThreadRunning(FALSE)
62 , m_AsyncThreadExit(FALSE)
63 , m_bIsCherryPick(false)
64 , m_pMailmap(nullptr)
65 , m_bShowBugtraqColumn(false)
66 , m_IsIDReplaceAction(FALSE)
67 , m_ShowMask(0)
68 , m_LoadingThread(nullptr)
69 , m_bExitThread(FALSE)
70 , m_IsOldFirst(FALSE)
71 , m_IsRebaseReplaceGraph(FALSE)
72 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
73 , m_bDragndropEnabled(false)
74 , m_bDragging(FALSE)
75 , m_nDropIndex(-1)
76 , m_nDropMarkerLast(-1)
77 , m_nDropMarkerLastHot(-1)
79 // use the default GUI font, create a copy of it and
80 // change the copy to BOLD (leave the rest of the font
81 // the same)
83 this->m_critSec.Init();
84 ResetWcRev(false);
86 int cx = GetSystemMetrics(SM_CXSMICON);
87 int cy = GetSystemMetrics(SM_CYSMICON);
88 m_hModifiedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONMODIFIED, cx, cy);
89 m_hReplacedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONREPLACED, cx, cy);
90 m_hConflictedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONCONFLICTED, cx, cy);
91 m_hAddedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONADDED, cx, cy);
92 m_hDeletedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONDELETED, cx, cy);
93 m_hFetchIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONFETCHING, cx, cy);
95 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
96 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
98 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
99 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
101 CString key;
102 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
103 key.Replace(L':', L'_');
104 CString lastSelFromDate = CRegString(key);
105 if (lastSelFromDate.GetLength() == 10)
107 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
108 m_Filter.m_From = (DWORD)time.GetTime();
111 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
113 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
115 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
117 // get short/long datetime setting from registry
118 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
119 if ( RegUseShortDateFormat )
121 m_DateFormat = DATE_SHORTDATE;
123 else
125 m_DateFormat = DATE_LONGDATE;
127 // get relative time display setting from registry
128 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
129 m_bRelativeTimes = (regRelativeTimes != 0);
131 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
132 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
133 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
134 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
135 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
136 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
137 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
139 m_ColumnRegKey = L"log";
141 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
142 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
143 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
144 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
146 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
147 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
149 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
150 git_read_mailmap(&m_pMailmap);
152 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
153 m_AsynDiffListLock.Init();
154 StartAsyncDiffThread();
157 HWND CGitLogListBase::GetParentHWND()
159 auto owner = GetSafeOwner();
160 if (!owner)
161 return GetSafeHwnd();
162 return owner->GetSafeHwnd();
165 int CGitLogListBase::AsyncDiffThread()
167 while(!m_AsyncThreadExit)
169 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
171 GitRevLoglist* pRev = nullptr;
172 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
174 m_AsynDiffListLock.Lock();
175 pRev = m_AsynDiffList.back();
176 m_AsynDiffList.pop_back();
177 m_AsynDiffListLock.Unlock();
179 if( pRev->m_CommitHash.IsEmpty() )
181 if(pRev->m_IsDiffFiles)
182 continue;
184 CTGitPathList& files = pRev->GetFiles(this);
185 files.Clear();
186 pRev->m_ParentHash.clear();
187 pRev->m_ParentHash.push_back(m_HeadHash);
188 g_Git.RefreshGitIndex();
189 g_Git.GetWorkingTreeChanges(files);
190 auto& action = pRev->GetAction(this);
191 action = 0;
192 for (int j = 0; j < files.GetCount(); ++j)
193 action |= files[j].m_Action;
195 CString err;
196 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
198 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
199 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
200 return -1;
203 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
204 InterlockedExchange(&pRev->m_IsFull, TRUE);
206 CString body = L"\n";
207 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
208 pRev->GetBody() = body;
209 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
210 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
213 if (!pRev->CheckAndDiff())
214 { // fetch change file list
215 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
217 if (i < (int)m_arShownList.size())
219 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
220 if(data->m_CommitHash == pRev->m_CommitHash)
222 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
223 break;
228 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
230 POSITION pos = GetFirstSelectedItemPosition();
231 int nItem = GetNextSelectedItem(pos);
233 if(nItem>=0)
235 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
236 if(data)
237 if(data->m_CommitHash == pRev->m_CommitHash)
238 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
244 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
245 return 0;
247 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
249 if (exclusivelyShow)
250 m_ContextMenuMask &= hideMask;
251 else
252 m_ContextMenuMask &= ~hideMask;
255 CGitLogListBase::~CGitLogListBase()
257 InterlockedExchange(&m_bNoDispUpdates, TRUE);
258 this->m_arShownList.SafeRemoveAll();
260 DestroyIcon(m_hModifiedIcon);
261 DestroyIcon(m_hReplacedIcon);
262 DestroyIcon(m_hConflictedIcon);
263 DestroyIcon(m_hAddedIcon);
264 DestroyIcon(m_hDeletedIcon);
265 m_logEntries.ClearAll();
267 git_free_mailmap(m_pMailmap);
269 SafeTerminateThread();
270 SafeTerminateAsyncDiffThread();
272 if(m_AsyncDiffEvent)
273 CloseHandle(m_AsyncDiffEvent);
277 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
278 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
279 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
280 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
281 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
282 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
283 ON_WM_CONTEXTMENU()
284 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
285 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
286 ON_WM_CREATE()
287 ON_WM_DESTROY()
288 ON_MESSAGE(MSG_LOADED,OnLoad)
289 ON_WM_MEASUREITEM()
290 ON_WM_MEASUREITEM_REFLECT()
291 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
292 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
293 ON_WM_MOUSEMOVE()
294 ON_WM_LBUTTONUP()
295 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
296 END_MESSAGE_MAP()
298 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
300 //if (m_nRowHeight>0)
301 lpMeasureItemStruct->itemHeight = CDPIAware::Instance().ScaleY(50);
304 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
306 PreSubclassWindow();
307 return __super::OnCreate(lpCreateStruct);
310 void CGitLogListBase::SetStyle()
312 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
315 void CGitLogListBase::PreSubclassWindow()
317 SetStyle();
318 // load the icons for the action columns
319 // m_Theme.Open(m_hWnd, L"ListView");
320 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
321 __super::PreSubclassWindow();
324 CString CGitLogListBase::GetRebaseActionName(int action)
326 if (action & LOGACTIONS_REBASE_EDIT)
327 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
328 if (action & LOGACTIONS_REBASE_SQUASH)
329 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
330 if (action & LOGACTIONS_REBASE_PICK)
331 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
332 if (action & LOGACTIONS_REBASE_SKIP)
333 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
335 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
338 void CGitLogListBase::InsertGitColumn()
340 CString temp;
342 Init();
344 // use the default font, create a copy of it and
345 // change the copy to BOLD (leave the rest of the font
346 // the same)
347 LOGFONT lf = { 0 };
348 GetFont()->GetLogFont(&lf);
349 lf.lfWeight = FW_BOLD;
350 m_boldFont.CreateFontIndirect(&lf);
351 lf.lfWeight = FW_DONTCARE;
352 lf.lfItalic = TRUE;
353 m_FontItalics.CreateFontIndirect(&lf);
354 lf.lfWeight = FW_BOLD;
355 m_boldItalicsFont.CreateFontIndirect(&lf);
357 // only load properties if we have a repository
358 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
359 UpdateProjectProperties();
361 static UINT normal[] =
363 IDS_LOG_GRAPH,
364 IDS_LOG_REBASE,
365 IDS_LOG_ID,
366 IDS_LOG_HASH,
367 IDS_LOG_ACTIONS,
368 IDS_LOG_MESSAGE,
369 IDS_LOG_AUTHOR,
370 IDS_LOG_DATE,
371 IDS_LOG_EMAIL,
372 IDS_LOG_COMMIT_NAME,
373 IDS_LOG_COMMIT_EMAIL,
374 IDS_LOG_COMMIT_DATE,
375 IDS_LOG_BUGIDS,
376 IDS_LOG_SVNREV,
379 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
380 auto columnWidth = CDPIAware::Instance().ScaleX(ICONITEMBORDER + 16 * 4);
381 static int with[] =
383 columnWidth,
384 columnWidth,
385 columnWidth,
386 columnWidth,
387 2 * iconItemBorder + GetSystemMetrics(SM_CXSMICON) * 5,
388 CDPIAware::Instance().ScaleX(LOGLIST_MESSAGE_MIN),
389 columnWidth,
390 columnWidth,
391 columnWidth,
392 columnWidth,
393 columnWidth,
394 columnWidth,
395 columnWidth,
396 columnWidth,
398 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
400 DWORD hideColumns = 0;
401 if(this->m_IsRebaseReplaceGraph)
403 hideColumns |= GIT_LOG_GRAPH;
404 m_dwDefaultColumns |= GIT_LOG_REBASE;
406 else
407 hideColumns |= GIT_LOG_REBASE;
409 if(this->m_IsIDReplaceAction)
411 hideColumns |= GIT_LOG_ACTIONS;
412 m_dwDefaultColumns |= GIT_LOG_ID;
413 m_dwDefaultColumns |= GIT_LOG_HASH;
415 else
416 hideColumns |= GIT_LOG_ID;
417 if(this->m_bShowBugtraqColumn)
418 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
419 else
420 hideColumns |= GIT_LOGLIST_BUG;
421 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
422 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
423 else
424 hideColumns |= GIT_LOGLIST_SVNREV;
425 SetRedraw(false);
427 m_ColumnManager.SetNames(normal, _countof(normal));
428 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
429 m_ColumnManager.SetRightAlign(LOGLIST_ID);
431 if (!(hideColumns & GIT_LOG_ACTIONS))
433 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
434 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
435 // display's font height may be less than small icon height.
436 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
437 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
438 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
441 SetRedraw(true);
444 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
446 LVITEM rItem = { 0 };
447 rItem.mask = LVIF_STATE;
448 rItem.iItem = (int)Index;
449 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
450 GetItem(&rItem);
452 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
453 HBRUSH brush = nullptr;
455 if (!(rItem.state & LVIS_SELECTED))
457 int action = pLogEntry->GetRebaseAction();
458 if (action & LOGACTIONS_REBASE_SQUASH)
459 brush = ::CreateSolidBrush(RGB(156,156,156));
460 else if (action & LOGACTIONS_REBASE_EDIT)
461 brush = ::CreateSolidBrush(RGB(200,200,128));
463 else if (!IsAppThemed())
465 if (rItem.state & LVIS_SELECTED)
467 if (::GetFocus() == m_hWnd)
468 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
469 else
470 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
473 if (brush)
475 ::FillRect(hdc, &rect, brush);
476 ::DeleteObject(brush);
480 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
482 POINT point = { 4, 4 };
483 CRect rt2 = rect;
484 rt2.DeflateRect(1, 1);
485 rt2.OffsetRect(2, 2);
487 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
488 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
489 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
490 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
491 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
493 ::SelectObject(hdc, brush);
494 rt2.OffsetRect(-2, -2);
495 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
496 ::SelectObject(hdc, oldbrush);
497 ::SelectObject(hdc, oldpen);
498 ::DeleteObject(nullPen);
499 ::DeleteObject(darkBrush);
502 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
504 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
505 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
506 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
507 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
508 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
509 ::LineTo(hdc, rect.left, rect.top + 4);
510 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
511 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
512 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
513 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
514 ::SelectObject(hdc, oldpen);
515 ::DeleteObject(pen);
518 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
520 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
521 CRect rt=rect;
522 LVITEM rItem = { 0 };
523 rItem.mask = LVIF_STATE;
524 rItem.iItem = (int)index;
525 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
526 GetItem(&rItem);
528 CDC W_Dc;
529 W_Dc.Attach(hdc);
531 HTHEME hTheme = nullptr;
532 if (IsAppThemed())
533 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
535 SIZE oneSpaceSize;
536 if (m_bTagsBranchesOnRightSide)
538 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
539 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
540 SelectObject(hdc, oldFont);
541 rt.left += oneSpaceSize.cx * 2;
543 else
545 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
546 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
547 rt.left += oneSpaceSize.cx;
550 CString msg = MessageDisplayStr(data);
551 int action = data->GetRebaseAction();
552 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
553 if (IsAppThemed())
555 int txtState = LISS_NORMAL;
556 if (rItem.state & LVIS_SELECTED)
557 txtState = LISS_SELECTED;
559 DTTOPTS opts = { 0 };
560 opts.dwSize = sizeof(opts);
561 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
562 opts.dwFlags = DTT_TEXTCOLOR;
563 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
565 else
567 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
569 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
570 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
571 ::SetTextColor(hdc, clrOld);
573 else
575 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
576 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
577 ::SetTextColor(hdc, clrOld);
581 if (m_bTagsBranchesOnRightSide)
583 SIZE size;
584 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
586 rt.left += oneSpaceSize.cx + size.cx;
588 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
591 if (hTheme)
592 CloseThemeData(hTheme);
594 W_Dc.Detach();
597 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
599 for (unsigned int i = 0; i < refList.size(); ++i)
601 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
602 HBRUSH brush = 0;
603 COLORREF colRef = refList[i].color;
604 bool singleRemote = refList[i].singleRemote;
605 bool hasTracking = refList[i].hasTracking;
606 CGit::REF_TYPE refType = refList[i].refType;
608 //When row selected, ajust label color
609 if (!IsAppThemed())
611 if (rItem.state & LVIS_SELECTED)
612 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
615 brush = ::CreateSolidBrush(colRef);
617 if (!shortname.IsEmpty() && (rt.left < rect.right))
619 SIZE size = { 0 };
620 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
622 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
623 rt.right += 8;
625 int textpos = DT_CENTER;
627 if (rt.right > rect.right)
629 rt.right = rect.right;
630 textpos = 0;
633 CRect textRect = rt;
635 if (singleRemote)
637 rt.right += 5;
638 textRect.OffsetRect(5, 0);
641 if (hasTracking)
642 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
643 else
645 //Fill interior of ref label
646 ::FillRect(hdc, &rt, brush);
649 //Draw edge of label
650 CRect rectEdge = rt;
652 if (!hasTracking)
654 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
655 rectEdge.DeflateRect(1, 1);
656 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
659 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
661 rt.right += 8;
662 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
663 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
664 ::FillRgn(hdc, hrgn, brush);
665 ::DeleteObject(hrgn);
666 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
667 HPEN pen;
668 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
669 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
670 ::DeleteObject(pen);
671 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
672 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
673 ::DeleteObject(pen);
674 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
675 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
676 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
677 ::DeleteObject(pen);
678 SelectObject(hdc, oldpen);
681 //Draw text inside label
682 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
683 if (!customColor && IsAppThemed())
685 int txtState = LISS_NORMAL;
686 if (rItem.state & LVIS_SELECTED)
687 txtState = LISS_SELECTED;
689 DTTOPTS opts = { 0 };
690 opts.dwSize = sizeof(opts);
691 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
692 opts.dwFlags = DTT_TEXTCOLOR;
693 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
695 else
697 W_Dc.SetBkMode(TRANSPARENT);
698 if (customColor || (rItem.state & LVIS_SELECTED))
700 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
701 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
702 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
703 ::SetTextColor(hdc,clrOld);
705 else
707 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
708 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
709 ::SetTextColor(hdc, clrOld);
713 if (singleRemote)
715 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
716 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
717 CRect newRect;
718 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
719 DrawUpstream(hdc, newRect, color, bold);
722 if (!refList[i].fullName.IsEmpty())
723 m_RefLabelPosMap[refList[i].fullName] = rt;
725 rt.left = rt.right + 1;
727 if (brush)
728 ::DeleteObject(brush);
730 rt.right = rect.right;
733 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
734 // Returns ((256 - amount)*col1 + amount*col2) / 256;
735 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
736 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
737 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
740 Gdiplus::Color GetGdiColor(COLORREF col)
742 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
744 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
745 const COLORREF& col,const COLORREF& activeColor, int top
748 int h = laneHeight / 2;
749 int m = (x1 + x2) / 2;
750 int r = (x2 - x1) * m_NodeSize / 30;
751 int d = 2 * r;
753 #define P_CENTER m , h+top
754 #define P_0 x2, h+top
755 #define P_90 m , 0+top-1
756 #define P_180 x1, h+top
757 #define P_270 m , 2 * h+top +1
758 #define R_CENTER m - r, h - r+top, d, d
761 #define DELTA_UR_B 2*(x1 - m), 2*h +top
762 #define DELTA_UR_E 0*16, 90*16 +top // -,
764 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
765 #define DELTA_DR_E 270*16, 90*16 +top // -'
767 #define DELTA_UL_B 2*(x2 - m), 2*h +top
768 #define DELTA_UL_E 90*16, 90*16 +top // ,-
770 #define DELTA_DL_B 2*(x2 - m),2*-h +top
771 #define DELTA_DL_E 180*16, 90*16 // '-
773 #define CENTER_UR x1, 2*h, 225
774 #define CENTER_DR x1, 0 , 135
775 #define CENTER_UL x2, 2*h, 315
776 #define CENTER_DL x2, 0 , 45
779 Gdiplus::Graphics graphics( hdc );
781 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
783 // arc
784 switch (type) {
785 case Lanes::JOIN:
786 case Lanes::JOIN_R:
787 case Lanes::HEAD:
788 case Lanes::HEAD_R:
790 Gdiplus::LinearGradientBrush gradient(
791 Gdiplus::Point(x1-2, h+top-2),
792 Gdiplus::Point(P_270),
793 GetGdiColor(activeColor),GetGdiColor(col));
796 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
797 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
799 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
800 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
801 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
803 break;
805 case Lanes::JOIN_L:
807 Gdiplus::LinearGradientBrush gradient(
808 Gdiplus::Point(P_270),
809 Gdiplus::Point(x2+1, h+top-1),
810 GetGdiColor(col),GetGdiColor(activeColor));
813 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
814 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
816 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
817 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
818 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
821 break;
823 case Lanes::TAIL:
824 case Lanes::TAIL_R:
826 Gdiplus::LinearGradientBrush gradient(
827 Gdiplus::Point(x1-2, h+top-2),
828 Gdiplus::Point(P_90),
829 GetGdiColor(activeColor),GetGdiColor(col));
831 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
833 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
835 #if 0
836 QConicalGradient gradient(CENTER_DR);
837 gradient.setColorAt(0.375, activeCol);
838 gradient.setColorAt(0.625, col);
839 myPen.setBrush(gradient);
840 p->setPen(myPen);
841 p->drawArc(P_CENTER, DELTA_DR);
842 #endif
843 break;
845 default:
846 break;
850 //static QPen myPen(Qt::black, 2); // fast path here
851 CPen pen;
852 pen.CreatePen(PS_SOLID,2,col);
853 //myPen.setColor(col);
854 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
856 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
858 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
860 //p->setPen(myPen);
862 // vertical line
863 switch (type) {
864 case Lanes::ACTIVE:
865 case Lanes::NOT_ACTIVE:
866 case Lanes::MERGE_FORK:
867 case Lanes::MERGE_FORK_R:
868 case Lanes::MERGE_FORK_L:
869 case Lanes::JOIN:
870 case Lanes::JOIN_R:
871 case Lanes::JOIN_L:
872 case Lanes::CROSS:
873 //DrawLine(hdc,P_90,P_270);
874 graphics.DrawLine(&myPen,P_90,P_270);
875 //p->drawLine(P_90, P_270);
876 break;
877 case Lanes::HEAD_L:
878 case Lanes::BRANCH:
879 //DrawLine(hdc,P_CENTER,P_270);
880 graphics.DrawLine(&myPen,P_CENTER,P_270);
881 //p->drawLine(P_CENTER, P_270);
882 break;
883 case Lanes::TAIL_L:
884 case Lanes::INITIAL:
885 case Lanes::MERGE_FORK_L_INITIAL:
886 case Lanes::BOUNDARY:
887 case Lanes::BOUNDARY_C:
888 case Lanes::BOUNDARY_R:
889 case Lanes::BOUNDARY_L:
890 //DrawLine(hdc,P_90, P_CENTER);
891 graphics.DrawLine(&myPen,P_90,P_CENTER);
892 //p->drawLine(P_90, P_CENTER);
893 break;
894 default:
895 break;
898 myPen.SetColor(GetGdiColor(activeColor));
900 // horizontal line
901 switch (type) {
902 case Lanes::MERGE_FORK:
903 case Lanes::JOIN:
904 case Lanes::HEAD:
905 case Lanes::TAIL:
906 case Lanes::CROSS:
907 case Lanes::CROSS_EMPTY:
908 case Lanes::BOUNDARY_C:
909 //DrawLine(hdc,P_180,P_0);
910 graphics.DrawLine(&myPen,P_180,P_0);
911 //p->drawLine(P_180, P_0);
912 break;
913 case Lanes::MERGE_FORK_R:
914 case Lanes::BOUNDARY_R:
915 //DrawLine(hdc,P_180,P_CENTER);
916 graphics.DrawLine(&myPen,P_180,P_CENTER);
917 //p->drawLine(P_180, P_CENTER);
918 break;
919 case Lanes::MERGE_FORK_L:
920 case Lanes::MERGE_FORK_L_INITIAL:
921 case Lanes::HEAD_L:
922 case Lanes::TAIL_L:
923 case Lanes::BOUNDARY_L:
924 //DrawLine(hdc,P_CENTER,P_0);
925 graphics.DrawLine(&myPen,P_CENTER,P_0);
926 //p->drawLine(P_CENTER, P_0);
927 break;
928 default:
929 break;
932 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
934 CBrush brush;
935 brush.CreateSolidBrush(col);
936 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
938 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
939 // center symbol, e.g. rect or ellipse
940 switch (type) {
941 case Lanes::ACTIVE:
942 case Lanes::INITIAL:
943 case Lanes::BRANCH:
945 //p->setPen(Qt::NoPen);
946 //p->setBrush(col);
947 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
948 graphics.FillEllipse(&myBrush, R_CENTER);
949 //p->drawEllipse(R_CENTER);
950 break;
951 case Lanes::MERGE_FORK:
952 case Lanes::MERGE_FORK_R:
953 case Lanes::MERGE_FORK_L:
954 case Lanes::MERGE_FORK_L_INITIAL:
955 //p->setPen(Qt::NoPen);
956 //p->setBrush(col);
957 //p->drawRect(R_CENTER);
958 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
959 graphics.FillRectangle(&myBrush, R_CENTER);
960 break;
961 case Lanes::UNAPPLIED:
962 // Red minus sign
963 //p->setPen(Qt::NoPen);
964 //p->setBrush(Qt::red);
965 //p->drawRect(m - r, h - 1, d, 2);
966 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
967 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
968 break;
969 case Lanes::APPLIED:
970 // Green plus sign
971 //p->setPen(Qt::NoPen);
972 //p->setBrush(DARK_GREEN);
973 //p->drawRect(m - r, h - 1, d, 2);
974 //p->drawRect(m - 1, h - r, 2, d);
975 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
976 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
977 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
978 break;
979 case Lanes::BOUNDARY:
980 //p->setBrush(back);
981 //p->drawEllipse(R_CENTER);
982 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
983 graphics.DrawEllipse(&myPen, R_CENTER);
984 break;
985 case Lanes::BOUNDARY_C:
986 case Lanes::BOUNDARY_R:
987 case Lanes::BOUNDARY_L:
988 //p->setBrush(back);
989 //p->drawRect(R_CENTER);
990 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
991 graphics.FillRectangle(&myBrush,R_CENTER);
992 break;
993 default:
994 break;
997 ::SelectObject(hdc,oldpen);
998 ::SelectObject(hdc,oldbrush);
999 #undef P_CENTER
1000 #undef P_0
1001 #undef P_90
1002 #undef P_180
1003 #undef P_270
1004 #undef R_CENTER
1007 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
1009 // TODO: unfinished
1010 // return;
1011 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1012 if(data->m_CommitHash.IsEmpty())
1013 return;
1015 CRect rt=rect;
1016 LVITEM rItem = { 0 };
1017 rItem.mask = LVIF_STATE;
1018 rItem.iItem = (int)index;
1019 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1020 GetItem(&rItem);
1022 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1024 if (data->m_Lanes.empty())
1025 m_logEntries.setLane(data->m_CommitHash);
1027 std::vector<int>& lanes=data->m_Lanes;
1028 size_t laneNum = lanes.size();
1029 UINT activeLane = 0;
1030 for (UINT i = 0; i < laneNum; ++i)
1031 if (Lanes::isMerge(lanes[i])) {
1032 activeLane = i;
1033 break;
1036 int x2 = 0;
1037 int maxWidth = rect.Width();
1038 int lw = 3 * rect.Height() / 4; //laneWidth()
1040 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1041 //if (opt.state & QStyle::State_Selected)
1042 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1044 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1046 int x1 = x2;
1047 x2 += lw;
1049 int ln = lanes[i];
1050 if (ln == Lanes::EMPTY)
1051 continue;
1053 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1054 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1057 #if 0
1058 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1059 int x1 = x2;
1060 x2 += lw;
1062 int ln = lanes[i];
1063 if (ln == Lanes::EMPTY)
1064 continue;
1066 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1067 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1069 if (ln == Lanes::CROSS)
1071 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1072 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1074 else
1075 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1077 #endif
1080 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1082 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1083 // Take the default processing unless we set this to something else below.
1084 *pResult = CDRF_DODEFAULT;
1086 if (m_bNoDispUpdates)
1087 return;
1089 switch (pLVCD->nmcd.dwDrawStage)
1091 case CDDS_PREPAINT:
1093 *pResult = CDRF_NOTIFYITEMDRAW;
1094 return;
1096 break;
1097 case CDDS_ITEMPREPAINT:
1099 // This is the prepaint stage for an item. Here's where we set the
1100 // item's text color.
1102 // Tell Windows to send draw notifications for each subitem.
1103 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1105 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1107 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1109 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1110 if (data)
1112 HGDIOBJ hGdiObj = nullptr;
1113 int action = data->GetRebaseAction();
1114 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1115 crText = RGB(128,128,128);
1117 if (action & LOGACTIONS_REBASE_SQUASH)
1118 pLVCD->clrTextBk = RGB(156,156,156);
1119 else if (action & LOGACTIONS_REBASE_EDIT)
1120 pLVCD->clrTextBk = RGB(200,200,128);
1121 else
1122 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1124 if (action & LOGACTIONS_REBASE_CURRENT)
1125 hGdiObj = m_boldFont.GetSafeHandle();
1127 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1128 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1129 if (isHeadHash && isHighlight)
1130 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1131 else if (isHeadHash)
1132 hGdiObj = m_boldFont.GetSafeHandle();
1133 else if (isHighlight)
1134 hGdiObj = m_FontItalics.GetSafeHandle();
1136 if (hGdiObj)
1138 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1139 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1142 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1143 // crText = GetSysColor(COLOR_GRAYTEXT);
1145 if (data->m_CommitHash.IsEmpty())
1147 //crText = GetSysColor(RGB(200,200,0));
1148 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1149 // We changed the font, so we're returning CDRF_NEWFONT. This
1150 // tells the control to recalculate the extent of the text.
1151 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1155 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1157 if (m_bStrictStopped)
1158 crText = GetSysColor(COLOR_GRAYTEXT);
1160 // Store the color back in the NMLVCUSTOMDRAW struct.
1161 pLVCD->clrText = crText;
1162 return;
1164 break;
1165 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1167 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1169 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1172 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1174 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1176 CRect rect;
1177 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1179 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1180 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1182 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1183 if( !data ->m_CommitHash.IsEmpty())
1184 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1186 *pResult = CDRF_SKIPDEFAULT;
1187 return;
1191 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1193 // If the top index of list is changed, the position map of reference label is outdated.
1194 if (m_OldTopIndex != GetTopIndex())
1196 m_OldTopIndex = GetTopIndex();
1197 m_RefLabelPosMap.clear();
1200 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1202 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1204 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1206 CRect rect;
1207 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1209 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1210 // not in FillBackGround method, because this only affected the message subitem
1211 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1212 return;
1214 int index = (int)pLVCD->nmcd.dwItemSpec;
1215 int state = GetItemState(index, LVIS_SELECTED);
1216 int txtState = LISS_NORMAL;
1217 if (IsAppThemed() && GetHotItem() == (int)index)
1219 if (state & LVIS_SELECTED)
1220 txtState = LISS_HOTSELECTED;
1221 else
1222 txtState = LISS_HOT;
1224 else if (state & LVIS_SELECTED)
1226 if (::GetFocus() == m_hWnd)
1227 txtState = LISS_SELECTED;
1228 else
1229 txtState = LISS_SELECTEDNOTFOCUS;
1232 HTHEME hTheme = nullptr;
1233 if (IsAppThemed())
1234 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1236 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1237 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1238 else
1240 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1241 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1242 ::DeleteObject(brush);
1244 if (hTheme && txtState != LISS_NORMAL)
1246 CRect rt;
1247 // get rect of whole line
1248 GetItemRect(index, rt, LVIR_BOUNDS);
1249 CRect rect2 = rect;
1251 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1252 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1254 CloseThemeData(hTheme);
1256 // END: extended redraw
1258 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1260 std::vector<REFLABEL> refsToShow;
1261 STRING_VECTOR remoteTrackingList;
1262 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1263 for (unsigned int i = 0; i < refList.size(); ++i)
1265 CString str = refList[i];
1267 REFLABEL refLabel;
1268 refLabel.color = RGB(255, 255, 255);
1269 refLabel.singleRemote = false;
1270 refLabel.hasTracking = false;
1271 refLabel.sameName = false;
1272 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1273 refLabel.fullName = str;
1275 switch (refLabel.refType)
1277 case CGit::REF_TYPE::LOCAL_BRANCH:
1279 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1280 continue;
1281 if (refLabel.name == m_CurrentBranch)
1282 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1283 else
1284 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1286 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1287 CString pullRemote = trackingEntry.first;
1288 CString pullBranch = trackingEntry.second;
1289 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1291 CString defaultUpstream;
1292 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1293 refLabel.hasTracking = true;
1294 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1296 bool found = false;
1297 for (size_t j = i + 1; j < refList.size(); ++j)
1299 if (refList[j] == defaultUpstream)
1301 found = true;
1302 break;
1306 if (found)
1308 bool sameName = pullBranch == refLabel.name;
1309 refsToShow.push_back(refLabel);
1310 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1311 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1312 if (m_bSymbolizeRefNames)
1314 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1316 refLabel.simplifiedName = L'/';
1317 if (sameName)
1318 refLabel.simplifiedName += L'≡';
1319 else
1320 refLabel.simplifiedName += pullBranch;
1321 refLabel.singleRemote = true;
1323 else if (sameName)
1324 refLabel.simplifiedName = pullRemote + L"/≡";
1325 refLabel.sameName = sameName;
1327 refLabel.fullName = defaultUpstream;
1328 refsToShow.push_back(refLabel);
1329 remoteTrackingList.push_back(defaultUpstream);
1330 continue;
1334 break;
1336 case CGit::REF_TYPE::REMOTE_BRANCH:
1338 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1339 continue;
1340 bool found = false;
1341 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1343 if (remoteTrackingList[j] == str)
1345 found = true;
1346 break;
1349 if (found)
1350 continue;
1352 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1353 if (m_bSymbolizeRefNames)
1355 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1357 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1358 refLabel.singleRemote = true;
1361 break;
1363 case CGit::REF_TYPE::ANNOTATED_TAG:
1364 case CGit::REF_TYPE::TAG:
1365 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1366 continue;
1367 refLabel.color = m_Colors.GetColor(CColors::Tag);
1368 break;
1369 case CGit::REF_TYPE::STASH:
1370 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1371 continue;
1372 refLabel.color = m_Colors.GetColor(CColors::Stash);
1373 break;
1374 case CGit::REF_TYPE::BISECT_GOOD:
1375 case CGit::REF_TYPE::BISECT_BAD:
1376 case CGit::REF_TYPE::BISECT_SKIP:
1377 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1378 continue;
1379 refLabel.color = (refLabel.refType == CGit::REF_TYPE::BISECT_GOOD) ? m_Colors.GetColor(CColors::BisectGood) : ((refLabel.refType == CGit::REF_TYPE::BISECT_SKIP) ? m_Colors.GetColor(CColors::BisectSkip) : m_Colors.GetColor(CColors::BisectBad));
1380 break;
1381 case CGit::REF_TYPE::NOTES:
1382 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1383 continue;
1384 refLabel.color = m_Colors.GetColor(CColors::NoteNode);
1385 break;
1386 default:
1387 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1388 continue;
1389 refLabel.color = m_Colors.GetColor(CColors::OtherRef);
1390 break;
1392 refsToShow.push_back(refLabel);
1394 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1396 REFLABEL refLabel;
1397 refLabel.color = RGB(246, 153, 253);
1398 refLabel.singleRemote = false;
1399 refLabel.hasTracking = false;
1400 refLabel.sameName = false;
1401 refLabel.name = L"super-project-pointer";
1402 refLabel.fullName = "";
1403 refsToShow.push_back(refLabel);
1406 if (refsToShow.empty())
1408 *pResult = CDRF_DODEFAULT;
1409 return;
1412 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1414 *pResult = CDRF_SKIPDEFAULT;
1415 return;
1422 if (pLVCD->iSubItem == LOGLIST_ACTION)
1424 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1426 *pResult = CDRF_DODEFAULT;
1427 return;
1429 *pResult = CDRF_DODEFAULT;
1431 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1432 return;
1434 int nIcons = 0;
1435 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1436 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1438 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1439 CRect rect;
1440 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1441 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1442 // Get the selected state of the
1443 // item being drawn.
1445 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1446 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1448 // Fill the background if necessary
1449 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1451 // Draw the icon(s) into the compatible DC
1452 int action = pLogEntry->GetAction(this);
1453 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
1454 if (!pLogEntry->m_IsDiffFiles)
1456 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 *pResult = CDRF_SKIPDEFAULT;
1458 return;
1461 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1462 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1463 ++nIcons;
1465 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1466 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1467 ++nIcons;
1469 if (action & CTGitPath::LOGACTIONS_DELETED)
1470 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1471 ++nIcons;
1473 if (action & CTGitPath::LOGACTIONS_REPLACED)
1474 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1475 ++nIcons;
1477 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1478 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1479 ++nIcons;
1481 *pResult = CDRF_SKIPDEFAULT;
1482 return;
1485 break;
1487 *pResult = CDRF_DODEFAULT;
1490 CString FindSVNRev(const CString& msg)
1494 const std::wsregex_iterator end;
1495 std::wstring s = msg;
1496 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1497 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1499 const std::wsmatch match = *it;
1500 if (match.size() == 4)
1502 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1503 return std::wstring(match[2]).c_str();
1506 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1507 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1509 const std::wsmatch match = *it;
1510 if (match.size() == 3)
1512 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1513 return std::wstring(match[1]).c_str();
1517 catch (std::exception&) {}
1519 return L"";
1522 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1524 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1525 return pLogEntry->GetSubject();
1527 CString txt(pLogEntry->GetSubject());
1528 txt += L' ';
1529 txt += pLogEntry->GetBody();
1531 // Deal with CRLF
1532 txt.Replace(L'\n', L' ');
1533 txt.Replace(L'\r', L' ');
1535 return txt;
1538 // CGitLogListBase message handlers
1540 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1542 struct payload_struct { const CString* name; const char* authorName; };
1543 payload_struct payload = { &name, nullptr };
1544 const char* author1 = nullptr;
1545 const char* email1 = nullptr;
1546 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1547 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1548 free((void *)payload.authorName);
1549 if (returnEmail)
1550 return email1;
1551 return author1;
1554 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1556 if (mailmap)
1558 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1559 if (translated)
1561 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1562 return;
1565 if (returnEmail)
1566 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1567 else
1568 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1571 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1573 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1575 // Create a pointer to the item
1576 LV_ITEM* pItem = &(pDispInfo)->item;
1578 // Do the list need text information?
1579 if (!(pItem->mask & LVIF_TEXT))
1580 return;
1582 // By default, clear text buffer.
1583 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1585 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1587 *pResult = 0;
1588 if (m_bNoDispUpdates || bOutOfRange)
1589 return;
1591 // Which item number?
1592 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1594 CString temp;
1595 if(m_IsOldFirst)
1596 temp.Format(L"%d", pItem->iItem + 1);
1597 else
1598 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1600 if (!pLogEntry)
1601 return;
1603 // Which column?
1604 switch (pItem->iSubItem)
1606 case LOGLIST_GRAPH: //Graphic
1607 break;
1608 case LOGLIST_REBASE:
1609 if (m_IsRebaseReplaceGraph)
1610 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1611 break;
1612 case LOGLIST_ACTION: //action -- no text in the column
1613 break;
1614 case LOGLIST_HASH:
1615 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1616 break;
1617 case LOGLIST_ID:
1618 if (this->m_IsIDReplaceAction)
1619 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1620 break;
1621 case LOGLIST_MESSAGE: //Message
1622 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1623 break;
1624 case LOGLIST_AUTHOR: //Author
1625 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1626 break;
1627 case LOGLIST_DATE: //Date
1628 if (!pLogEntry->m_CommitHash.IsEmpty())
1629 lstrcpyn(pItem->pszText,
1630 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1631 pItem->cchTextMax - 1);
1632 break;
1634 case LOGLIST_EMAIL:
1635 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1636 break;
1638 case LOGLIST_COMMIT_NAME: //Commit
1639 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1640 break;
1642 case LOGLIST_COMMIT_EMAIL: //Commit Email
1643 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1644 break;
1646 case LOGLIST_COMMIT_DATE: //Commit Date
1647 if (!pLogEntry->m_CommitHash.IsEmpty())
1648 lstrcpyn(pItem->pszText,
1649 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1650 pItem->cchTextMax - 1);
1651 break;
1652 case LOGLIST_BUG: //Bug ID
1653 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1654 break;
1655 case LOGLIST_SVNREV: //SVN revision
1656 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1657 break;
1659 default:
1660 ASSERT(false);
1664 bool CGitLogListBase::IsOnStash(int index)
1666 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1667 if (IsStash(rev))
1668 return true;
1669 if (index > 0)
1671 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1672 if (IsStash(preRev))
1673 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1675 return false;
1678 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1680 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1681 if (refList == m_HashMap.cend())
1682 return false;
1683 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1686 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1688 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1689 if (refList == m_HashMap.cend())
1690 return false;
1691 return find_if((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1694 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1696 if (pRev->m_ParentHash.empty())
1698 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1699 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1701 parentHash = pRev->m_ParentHash;
1704 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1706 __super::OnContextMenu(pWnd, point);
1708 if (pWnd != this)
1709 return;
1711 int selIndex = GetSelectionMark();
1712 if (selIndex < 0)
1713 return; // nothing selected, nothing to do with a context menu
1715 // if the user selected the info text telling about not all revisions shown due to
1716 // the "stop on copy/rename" option, we also don't show the context menu
1717 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1718 return;
1720 // if the context menu is invoked through the keyboard, we have to use
1721 // a calculated position on where to anchor the menu on
1722 if ((point.x == -1) && (point.y == -1))
1724 CRect rect;
1725 GetItemRect(selIndex, &rect, LVIR_LABEL);
1726 ClientToScreen(&rect);
1727 point = rect.CenterPoint();
1729 m_nSearchIndex = selIndex;
1731 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1733 POSITION pos = GetFirstSelectedItemPosition();
1734 int FirstSelect = GetNextSelectedItem(pos);
1735 if (FirstSelect < 0)
1736 return;
1738 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1739 if (pSelLogEntry == nullptr)
1740 return;
1742 int LastSelect = -1;
1743 UINT selectedCount = 1;
1744 while (pos)
1746 LastSelect = GetNextSelectedItem(pos);
1747 ++selectedCount;
1750 ASSERT(GetSelectedCount() == selectedCount);
1752 #if 0
1753 GitRev revSelected = pSelLogEntry->Rev;
1754 GitRev revPrevious = git_revnum_t(revSelected)-1;
1755 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1757 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1759 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1760 if (changedpath->lCopyFromRev)
1761 revPrevious = changedpath->lCopyFromRev;
1764 GitRev revSelected2;
1765 if (pos)
1767 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1768 revSelected2 = pLogEntry->Rev;
1770 bool bAllFromTheSameAuthor = true;
1771 CString firstAuthor;
1772 CLogDataVector selEntries;
1773 GitRev revLowest, revHighest;
1774 GitRevRangeArray revisionRanges;
1776 POSITION pos = GetFirstSelectedItemPosition();
1777 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1778 revisionRanges.AddRevision(pLogEntry->Rev);
1779 selEntries.push_back(pLogEntry);
1780 firstAuthor = pLogEntry->sAuthor;
1781 revLowest = pLogEntry->Rev;
1782 revHighest = pLogEntry->Rev;
1783 while (pos)
1785 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1786 revisionRanges.AddRevision(pLogEntry->Rev);
1787 selEntries.push_back(pLogEntry);
1788 if (firstAuthor.Compare(pLogEntry->sAuthor))
1789 bAllFromTheSameAuthor = false;
1790 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1791 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1795 #endif
1797 //entry is selected, now show the popup menu
1798 CIconMenu popup;
1799 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1801 if (popup.CreatePopupMenu())
1803 CGitHash headHash;
1804 if (g_Git.GetHash(headHash, L"HEAD"))
1806 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1807 return;
1809 bool isHeadCommit = (pSelLogEntry->m_CommitHash == headHash);
1810 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1811 CTGitPath workingTree(g_Git.m_CurrentDir);
1812 bool isMergeActive = workingTree.IsMergeActive();
1813 bool isBisectActive = workingTree.IsBisectActive();
1814 bool isStash = IsOnStash(FirstSelect);
1815 GIT_REV_LIST parentHash;
1816 GetParentHashes(pSelLogEntry, parentHash);
1818 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1819 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1821 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SQUASH) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)) && FirstSelect != GetItemCount() - 1 && LastSelect != GetItemCount() - 1 && (m_bIsCherryPick || pSelLogEntry->ParentsCount() == 1))
1822 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1824 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1825 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1827 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1828 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1830 if (m_ContextMenuMask & (GetContextMenuBit(ID_REBASE_SKIP) | GetContextMenuBit(ID_REBASE_EDIT) | GetContextMenuBit(ID_REBASE_SQUASH) | GetContextMenuBit(ID_REBASE_PICK)) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1831 popup.AppendMenu(MF_SEPARATOR, NULL);
1833 if (selectedCount == 1)
1836 bool requiresSeparator = false;
1837 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1839 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1841 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1842 requiresSeparator = true;
1845 else
1847 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1849 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1850 requiresSeparator = true;
1852 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1854 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1855 requiresSeparator = true;
1859 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1861 if (parentHash.size() == 1)
1863 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1864 requiresSeparator = true;
1866 else if (parentHash.size() > 1)
1868 blamemenu.CreatePopupMenu();
1869 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1870 for (size_t i = 0; i < parentHash.size(); ++i)
1872 CString str;
1873 str.Format(IDS_PARENT, i + 1);
1874 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1876 requiresSeparator = true;
1880 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1882 if (parentHash.size() == 1)
1884 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1885 requiresSeparator = true;
1887 else if (parentHash.size() > 1)
1889 gnudiffmenu.CreatePopupMenu();
1890 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1892 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1893 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1894 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1896 for (size_t i = 0; i < parentHash.size(); ++i)
1898 CString str;
1899 str.Format(IDS_PARENT, i + 1);
1900 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1902 requiresSeparator = true;
1906 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1908 if (parentHash.size() == 1)
1910 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1911 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1912 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1913 requiresSeparator = true;
1915 else if (parentHash.size() > 1)
1917 diffmenu.CreatePopupMenu();
1918 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1919 for (size_t i = 0; i < parentHash.size(); ++i)
1921 CString str;
1922 str.Format(IDS_PARENT, i + 1);
1923 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1924 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1926 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1927 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1930 requiresSeparator = true;
1934 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1936 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1937 requiresSeparator = true;
1940 if (requiresSeparator)
1942 popup.AppendMenu(MF_SEPARATOR, NULL);
1943 requiresSeparator = false;
1946 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1948 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1950 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_SHELVE);
1951 requiresSeparator = true;
1955 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1957 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1959 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_UNSHELVE);
1960 requiresSeparator = true;
1963 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1965 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1966 requiresSeparator = true;
1970 if (requiresSeparator)
1972 popup.AppendMenu(MF_SEPARATOR, NULL);
1973 requiresSeparator = false;
1976 if (isBisectActive)
1978 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1979 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1981 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1982 requiresSeparator = true;
1985 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1987 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1988 requiresSeparator = true;
1990 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1992 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1993 requiresSeparator = true;
1997 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1999 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
2001 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
2002 requiresSeparator = true;
2006 if (requiresSeparator)
2008 popup.AppendMenu(MF_SEPARATOR, NULL);
2009 requiresSeparator = false;
2012 if (pSelLogEntry->m_CommitHash.IsEmpty())
2014 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
2015 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2017 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
2018 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_UPDATE);
2020 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2021 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2023 popup.AppendMenu(MF_SEPARATOR, NULL);
2025 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2026 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2028 popup.AppendMenu(MF_SEPARATOR, NULL);
2032 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2033 // {
2034 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2035 // }
2036 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2037 // {
2038 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2039 // }
2040 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2041 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2042 // {
2043 // popup.AppendMenu(MF_SEPARATOR, NULL);
2044 // }
2046 CString str;
2047 //if (m_hasWC)
2048 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2050 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2052 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2053 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2055 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2056 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2058 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2060 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2062 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2064 size_t index = (size_t)-1;
2065 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2066 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2067 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2070 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2072 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2073 popup.AppendMenuIcon(ID_RESET, str, IDI_RESET);
2076 // Add Switch Branch express Menu
2077 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2078 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2081 std::vector<const CString*> branchs;
2082 auto addCheck = [&](const CString& ref)
2084 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2085 return;
2086 branchs.push_back(&ref);
2088 size_t index = (size_t)-1;
2089 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2090 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2091 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2092 else
2093 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2095 CString str2;
2096 str2.LoadString(IDS_SWITCH_BRANCH);
2098 if(branchs.size() == 1)
2100 str2 += L' ';
2101 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2102 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2104 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2107 else if(branchs.size() > 1)
2109 subbranchmenu.CreatePopupMenu();
2110 for (size_t i = 0 ; i < branchs.size(); ++i)
2112 if (*branchs[i] != currentBranch)
2114 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2115 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2119 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2123 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2125 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2126 size_t index = (size_t)-1;
2127 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2128 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2129 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2132 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2134 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2136 size_t index = (size_t)-1;
2137 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2138 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2139 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2142 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2143 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2145 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2147 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2148 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2149 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2151 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2152 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2154 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2156 if (parentHash.size() == 1)
2157 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2158 else if (parentHash.size() > 1)
2160 revertmenu.CreatePopupMenu();
2161 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2163 for (size_t i = 0; i < parentHash.size(); ++i)
2165 CString str2;
2166 str2.Format(IDS_PARENT, i + 1);
2167 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2172 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2173 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2175 popup.AppendMenu(MF_SEPARATOR, NULL);
2179 if(!pSelLogEntry->m_Ref.IsEmpty())
2181 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2182 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2183 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_UNSHELVE);
2184 if (selectedCount <= 2)
2185 popup.AppendMenu(MF_SEPARATOR, NULL);
2188 if (selectedCount >= 2)
2190 bool bAddSeparator = false;
2191 if ((selectedCount == 2) || IsSelectionContinuous())
2193 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2195 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2196 bAddSeparator = true;
2200 if (selectedCount == 2)
2202 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2204 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2205 bAddSeparator = true;
2208 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2210 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2211 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2212 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2213 CString menu;
2214 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2215 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2216 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2217 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2218 bAddSeparator = true;
2222 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2224 bAddSeparator = true;
2225 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2228 if (bAddSeparator)
2230 popup.AppendMenu(MF_SEPARATOR, NULL);
2231 bAddSeparator = false;
2234 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2235 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2237 if (bAddSeparator)
2238 popup.AppendMenu(MF_SEPARATOR, NULL);
2241 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2243 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2244 popup.AppendMenu(MF_SEPARATOR, NULL);
2247 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2249 bool bAddSeparator = false;
2250 if (selectedCount >= 2 && IsSelectionContinuous())
2252 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2254 CString head;
2255 int headindex;
2256 headindex = this->GetHeadIndex();
2257 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2259 head.Format(L"HEAD~%d", FirstSelect - headindex);
2260 CGitHash hashFirst;
2261 int ret = g_Git.GetHash(hashFirst, head);
2262 head.Format(L"HEAD~%d",LastSelect-headindex);
2263 CGitHash hash;
2264 ret = ret || g_Git.GetHash(hash, head);
2265 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2266 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2267 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2269 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2270 bAddSeparator = true;
2275 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2276 if (selectedCount >= 2)
2277 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_PICK);
2278 else
2279 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_PICK);
2280 bAddSeparator = true;
2283 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2284 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2285 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2286 bAddSeparator = true;
2289 if (bAddSeparator)
2290 popup.AppendMenu(MF_SEPARATOR, NULL);
2293 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2295 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2296 popup.AppendMenu(MF_SEPARATOR, NULL);
2299 if (selectedCount == 1)
2301 bool bAddSeparator = false;
2302 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2304 // show the push-option only if the log entry has an associated local branch
2305 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2306 if (isLocal || showExtendedMenu)
2308 CString str;
2309 str.LoadString(IDS_MENUPUSH);
2311 CString branch;
2312 size_t index = (size_t)-1;
2313 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2314 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2315 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2316 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2318 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2320 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2321 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2323 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2324 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2326 bAddSeparator = true;
2329 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2331 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2332 bAddSeparator = true;
2336 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2338 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2340 std::vector<const CString*> branchs;
2341 auto addCheck = [&](const CString& ref)
2343 if (ref == currentBranch)
2344 return;
2345 branchs.push_back(&ref);
2347 size_t index = (size_t)-1;
2348 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2349 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2350 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2351 else
2352 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2354 CString str;
2355 if (branchs.size() == 1)
2357 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2358 str += L' ';
2359 str += *branchs[0];
2360 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2361 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2362 bAddSeparator = true;
2364 else if (branchs.size() > 1)
2366 str.LoadString(IDS_DELETE_BRANCHTAG);
2367 submenu.CreatePopupMenu();
2368 for (size_t i = 0; i < branchs.size(); ++i)
2370 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2371 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2373 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2374 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2376 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2377 bAddSeparator = true;
2380 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2381 if (bAddSeparator)
2382 popup.AppendMenu(MF_SEPARATOR, NULL);
2383 } // selectedCount == 1
2385 CIconMenu clipSubMenu;
2386 if (!clipSubMenu.CreatePopupMenu())
2387 return;
2388 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2390 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2391 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2392 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2393 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2394 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2395 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2396 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2397 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2398 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2400 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2401 size_t index = (size_t)-1;
2402 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2403 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2404 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2407 CString temp;
2408 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2409 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2412 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2413 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2415 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2416 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2418 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2419 // DialogEnableWindow(IDOK, FALSE);
2420 // SetPromptApp(&theApp);
2422 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2424 // EnableOKButton();
2425 } // if (popup.CreatePopupMenu())
2428 bool CGitLogListBase::IsSelectionContinuous()
2430 if ( GetSelectedCount()==1 )
2432 // if only one revision is selected, the selection is of course
2433 // continuous
2434 return true;
2437 POSITION pos = GetFirstSelectedItemPosition();
2438 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2439 if (bContinuous)
2441 int itemindex = GetNextSelectedItem(pos);
2442 while (pos)
2444 int nextindex = GetNextSelectedItem(pos);
2445 if (nextindex - itemindex > 1)
2447 bContinuous = false;
2448 break;
2450 itemindex = nextindex;
2453 return bContinuous;
2456 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2458 CString sClipdata;
2459 POSITION pos = GetFirstSelectedItemPosition();
2460 if (pos)
2462 CString sRev;
2463 sRev.LoadString(IDS_LOG_REVISION);
2464 CString sAuthor;
2465 sAuthor.LoadString(IDS_LOG_AUTHOR);
2466 CString sDate;
2467 sDate.LoadString(IDS_LOG_DATE);
2468 CString sMessage;
2469 sMessage.LoadString(IDS_LOG_MESSAGE);
2470 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2471 bool first = true;
2472 while (pos)
2474 CString sLogCopyText;
2475 CString sPaths;
2476 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2478 if (toCopy == ID_COPYCLIPBOARDFULL)
2480 sPaths = L"----\r\n";
2481 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2483 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2484 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2486 sPaths += L' ';
2487 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2489 sPaths += L"\r\n";
2491 sPaths.Trim();
2492 sPaths += L"\r\n";
2495 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2497 CString sNotesTags;
2498 if (!pLogEntry->m_Notes.IsEmpty())
2500 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2501 sNotesTags += L":\n";
2502 sNotesTags += pLogEntry->m_Notes;
2503 sNotesTags.Replace(L"\n", L"\r\n");
2505 CString tagInfo = GetTagInfo(pLogEntry);
2506 if (!tagInfo.IsEmpty())
2508 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2509 tagInfo.Replace(L"\n", L"\r\n");
2510 sNotesTags += tagInfo;
2513 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s%s\r\n",
2514 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2515 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2516 (LPCTSTR)sDate,
2517 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2518 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2519 (LPCTSTR)sNotesTags,
2520 (LPCTSTR)sPaths);
2521 sClipdata += sLogCopyText;
2523 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2525 if (!first)
2526 sClipdata += L"\r\n";
2527 sClipdata += pLogEntry->GetAuthorName();
2528 sClipdata += L" <";
2529 sClipdata += pLogEntry->GetAuthorEmail();
2530 sClipdata += L">";
2532 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2534 if (!first)
2535 sClipdata += L"\r\n";
2536 sClipdata += pLogEntry->GetAuthorName();
2538 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2540 if (!first)
2541 sClipdata += L"\r\n";
2542 sClipdata += pLogEntry->GetAuthorEmail();
2545 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2547 sClipdata += L"* ";
2548 sClipdata += pLogEntry->GetSubjectBody(true);
2549 sClipdata += L"\r\n\r\n";
2551 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2553 sClipdata += L"* ";
2554 sClipdata += pLogEntry->GetSubject().Trim();
2555 sClipdata += L"\r\n\r\n";
2557 else
2559 if (!first)
2560 sClipdata += L"\r\n";
2561 sClipdata += pLogEntry->m_CommitHash.ToString();
2564 first = false;
2566 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2570 void CGitLogListBase::DiffSelectedRevWithPrevious()
2572 if (m_bThreadRunning)
2573 return;
2575 int FirstSelect=-1, LastSelect=-1;
2576 POSITION pos = GetFirstSelectedItemPosition();
2577 FirstSelect = GetNextSelectedItem(pos);
2578 while(pos)
2579 LastSelect = GetNextSelectedItem(pos);
2581 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2584 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2586 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2587 *pResult = -1;
2589 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2590 return;
2591 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2592 return;
2593 if (!pFindInfo->lvfi.psz)
2594 return;
2595 #if 0
2596 CString sCmp = pFindInfo->lvfi.psz;
2597 CString sRev;
2598 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2600 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2601 sRev.Format(L"%ld", pLogEntry->Rev);
2602 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2604 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2606 *pResult = i;
2607 return;
2610 else
2612 if (sCmp.Compare(sRev)==0)
2614 *pResult = i;
2615 return;
2619 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2621 for (int i=0; i<pFindInfo->iStart; ++i)
2623 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2624 sRev.Format(L"%ld", pLogEntry->Rev);
2625 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2627 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2629 *pResult = i;
2630 return;
2633 else
2635 if (sCmp.Compare(sRev)==0)
2637 *pResult = i;
2638 return;
2643 #endif
2644 *pResult = -1;
2647 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2649 ClearText();
2651 this->m_arShownList.SafeRemoveAll();
2653 this->m_logEntries.ClearAll();
2654 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2655 return -1;
2657 SetItemCountEx((int)m_logEntries.size());
2659 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2661 if(m_IsOldFirst)
2663 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2664 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2666 else
2668 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2669 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2673 ReloadHashMap();
2675 if(path)
2676 m_Path=*path;
2677 return 0;
2680 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2682 ClearText();
2684 m_arShownList.SafeRemoveAll();
2686 m_logEntries.ClearAll();
2687 if (m_logEntries.Fill(hashes))
2688 return -1;
2690 SetItemCountEx((int)m_logEntries.size());
2692 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2694 if (m_IsOldFirst)
2696 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2697 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2699 else
2701 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2702 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2706 ReloadHashMap();
2708 return 0;
2711 int CGitLogListBase::BeginFetchLog()
2713 ClearText();
2715 this->m_arShownList.SafeRemoveAll();
2717 this->m_logEntries.ClearAll();
2719 this->m_LogCache.ClearAllParent();
2721 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2723 CTGitPath *path;
2724 if(this->m_Path.IsEmpty())
2725 path = nullptr;
2726 else
2727 path=&this->m_Path;
2729 int mask;
2730 mask = CGit::LOG_INFO_ONLY_HASH;
2731 if (m_bIncludeBoundaryCommits)
2732 mask |= CGit::LOG_INFO_BOUNDARY;
2733 // if(this->m_bAllBranch)
2734 mask |= m_ShowMask ;
2736 if(m_bShowWC)
2738 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2739 ResetWcRev();
2740 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2743 if (m_sRange.IsEmpty())
2744 m_sRange = L"HEAD";
2746 // follow does not work for directories
2747 if (!path || path->IsDirectory())
2748 mask &= ~CGit::LOG_INFO_FOLLOW;
2749 // follow does not work with all branches 8at least in TGit)
2750 if (mask & CGit::LOG_INFO_FOLLOW)
2751 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2753 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2755 //this->m_logEntries.ParserFromLog();
2756 if(IsInWorkingThread())
2758 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2760 else
2762 SetItemCountEx((int)m_logEntries.size());
2767 [] { git_init(); } ();
2769 catch (char* msg)
2771 CString err(msg);
2772 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2773 return -1;
2776 if (!g_Git.CanParseRev(m_sRange))
2778 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2779 return 0;
2781 // if show all branches, pick any ref as dummy entry ref
2782 STRING_VECTOR list;
2783 if (g_Git.GetRefList(list))
2784 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2785 if (list.empty())
2786 return 0;
2788 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2791 g_Git.m_critGitDllSec.Lock();
2792 try {
2793 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8)))
2795 g_Git.m_critGitDllSec.Unlock();
2796 return -1;
2799 catch (char* msg)
2801 g_Git.m_critGitDllSec.Unlock();
2802 CString err(msg);
2803 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2804 return -1;
2806 g_Git.m_critGitDllSec.Unlock();
2808 return 0;
2811 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2813 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2815 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2817 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2819 DiffSelectedRevWithPrevious();
2820 return TRUE;
2823 #if 0
2824 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2826 DiffSelectedFile();
2827 return TRUE;
2829 #endif
2831 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2833 // select all entries
2834 for (int i=0; i<GetItemCount(); ++i)
2835 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2836 return TRUE;
2839 #if 0
2840 if (m_hAccel && !bSkipAccelerator)
2842 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2843 if (ret)
2844 return TRUE;
2847 #endif
2848 //m_tooltips.RelayEvent(pMsg);
2849 return __super::PreTranslateMessage(pMsg);
2852 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2854 // a double click on an entry in the revision list has happened
2855 *pResult = 0;
2857 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2858 DiffSelectedRevWithPrevious();
2861 void CGitLogListBase::FetchLogAsync(void* data)
2863 ReloadHashMap();
2864 m_ProcData=data;
2865 StartLoadingThread();
2868 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2870 return ((CGitLogListBase*)pVoid)->LogThread();
2873 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2875 //CTime time;
2876 oldest=CTime::GetCurrentTime();
2877 latest=CTime(1971,1,2,0,0,0);
2878 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2880 if(m_logEntries[i].IsEmpty())
2881 continue;
2883 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2884 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2886 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2887 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2891 if(latest<oldest)
2892 latest=oldest;
2895 UINT CGitLogListBase::LogThread()
2897 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2899 ULONGLONG t1,t2;
2901 if(BeginFetchLog())
2903 InterlockedExchange(&m_bThreadRunning, FALSE);
2904 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2906 return 1;
2909 std::wregex pat;//(L"Remove", regex_constants::icase);
2910 bool bRegex = false;
2911 if (m_bFilterWithRegex)
2912 bRegex = ValidateRegexp(m_sFilterText[0] == '!' ? m_sFilterText.Mid(1) : m_sFilterText, pat, false);
2914 TRACE(L"\n===Begin===\n");
2915 //Update work copy item;
2917 if (!m_logEntries.empty())
2919 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2921 m_arShownList.SafeAdd(pRev);
2925 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2927 // store commit number of the last selected commit/line before the refresh or -1
2928 int lastSelectedHashNItem = -1;
2929 if (m_lastSelectedHash.IsEmpty())
2930 lastSelectedHashNItem = 0;
2932 int ret = 0;
2934 bool shouldWalk = true;
2935 if (!g_Git.CanParseRev(m_sRange))
2937 // walk revisions if show all branches and there exists any ref
2938 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2939 shouldWalk = false;
2940 else
2942 STRING_VECTOR list;
2943 if (g_Git.GetRefList(list))
2944 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2945 if (list.empty())
2946 shouldWalk = false;
2950 if (shouldWalk)
2952 g_Git.m_critGitDllSec.Lock();
2953 if (!m_DllGitLog)
2955 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2956 g_Git.m_critGitDllSec.Unlock();
2957 InterlockedExchange(&m_bThreadRunning, FALSE);
2958 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2959 return 1;
2961 int total = 0;
2964 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2965 total = git_get_log_estimate_commit_count(m_DllGitLog);
2967 catch (char* msg)
2969 CString err(msg);
2970 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2971 ret = -1;
2973 g_Git.m_critGitDllSec.Unlock();
2975 GIT_COMMIT commit;
2976 t2 = t1 = GetTickCount64();
2977 int oldprecentage = 0;
2978 size_t oldsize = m_logEntries.size();
2979 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2980 while (ret== 0 && !m_bExitThread)
2982 g_Git.m_critGitDllSec.Lock();
2985 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2987 catch (char* msg)
2989 g_Git.m_critGitDllSec.Unlock();
2990 CString err(msg);
2991 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2992 break;
2994 g_Git.m_critGitDllSec.Unlock();
2996 if(ret)
2998 if (ret != -2) // other than end of revision walking
2999 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
3000 break;
3003 if (commit.m_ignore == 1)
3005 git_free_commit(&commit);
3006 continue;
3009 //printf("%s\r\n",commit.GetSubject());
3010 if(m_bExitThread)
3011 break;
3013 CGitHash hash(commit.m_hash);
3015 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3016 pRev->m_GitCommit = commit;
3017 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3019 char* note = nullptr;
3020 g_Git.m_critGitDllSec.Lock();
3023 git_get_notes(commit.m_hash, &note);
3025 catch (char* msg)
3027 g_Git.m_critGitDllSec.Unlock();
3028 CString err(msg);
3029 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3030 break;
3032 g_Git.m_critGitDllSec.Unlock();
3034 if(note)
3036 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3037 free(note);
3038 note = nullptr;
3041 if(!pRev->m_IsDiffFiles)
3043 pRev->m_CallDiffAsync = DiffAsync;
3046 pRev->ParserParentFromCommit(&commit);
3047 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3049 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3051 const CGitHash &parentHash = pRev->m_ParentHash[i];
3052 auto it = commitChildren.find(parentHash);
3053 if (it == commitChildren.end())
3054 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3055 it->second.insert(pRev->m_CommitHash);
3059 #ifdef DEBUG
3060 pRev->DbgPrint();
3061 TRACE(L"\n");
3062 #endif
3064 bool visible = true;
3065 if (HasFilterText())
3067 if(!IsMatchFilter(bRegex,pRev,pat))
3068 visible = false;
3070 if (visible && !ShouldShowFilter(pRev, commitChildren))
3071 visible = false;
3072 this->m_critSec.Lock();
3073 m_logEntries.append(hash, visible);
3074 if (visible)
3075 m_arShownList.SafeAdd(pRev);
3076 this->m_critSec.Unlock();
3078 if (!visible)
3079 continue;
3081 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3082 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3084 t2 = GetTickCount64();
3086 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3088 //update UI
3089 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3090 if(percent > 99)
3091 percent =99;
3092 if(percent < GITLOG_START)
3093 percent = GITLOG_START +1;
3095 oldsize = m_logEntries.size();
3096 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3098 //if( percent > oldprecentage )
3100 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3101 oldprecentage = percent;
3104 if (lastSelectedHashNItem >= 0)
3105 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3107 t1 = t2;
3110 g_Git.m_critGitDllSec.Lock();
3111 git_close_log(m_DllGitLog);
3112 g_Git.m_critGitDllSec.Unlock();
3116 if (m_bExitThread)
3118 InterlockedExchange(&m_bThreadRunning, FALSE);
3119 return 0;
3122 //Update UI;
3123 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3125 if (lastSelectedHashNItem >= 0)
3126 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3128 if (this->m_hWnd)
3129 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3131 InterlockedExchange(&m_bThreadRunning, FALSE);
3133 return 0;
3136 void CGitLogListBase::FetchRemoteList()
3138 STRING_VECTOR remoteList;
3139 m_SingleRemote.Empty();
3140 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3141 m_SingleRemote = remoteList[0];
3144 void CGitLogListBase::FetchTrackingBranchList()
3146 m_TrackingMap.clear();
3147 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3149 for (const auto& ref : it->second)
3151 CString branchName;
3152 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3154 CString pullRemote, pullBranch;
3155 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3156 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3157 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3163 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3165 SafeTerminateThread();
3167 this->SetItemCountEx(0);
3168 this->Clear();
3170 ResetWcRev();
3172 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3174 if (m_pMailmap)
3176 git_free_mailmap(m_pMailmap);
3177 git_read_mailmap(&m_pMailmap);
3180 //Update branch and Tag info
3181 ReloadHashMap();
3182 if (m_pFindDialog)
3183 m_pFindDialog->RefreshList();
3184 //Assume Thread have exited
3185 //if(!m_bThreadRunning)
3187 m_logEntries.clear();
3189 if(IsCleanFilter)
3191 m_sFilterText.Empty();
3194 SafeTerminateAsyncDiffThread();
3195 m_AsynDiffListLock.Lock();
3196 m_AsynDiffList.clear();
3197 m_AsynDiffListLock.Unlock();
3198 StartAsyncDiffThread();
3200 StartLoadingThread();
3204 void CGitLogListBase::StartAsyncDiffThread()
3206 if (m_AsyncThreadExit)
3207 return;
3208 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3209 return;
3210 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3211 if (!m_DiffingThread)
3213 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3214 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3218 void CGitLogListBase::StartLoadingThread()
3220 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3221 return;
3222 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3223 InterlockedExchange(&m_bExitThread, FALSE);
3224 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3225 if (!m_LoadingThread)
3227 InterlockedExchange(&m_bThreadRunning, FALSE);
3228 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3229 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3233 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::wregex& pat, bool bMatchCase /* = false */)
3237 std::regex_constants::syntax_option_type type = std::regex_constants::ECMAScript;
3238 if (!bMatchCase)
3239 type |= std::regex_constants::icase;
3240 pat = std::wregex(regexp_str, type);
3241 return true;
3243 catch (std::exception&) {}
3244 return false;
3246 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::wregex& pat)
3248 BOOL result = m_sFilterText[0] == '!' ? FALSE : TRUE;
3249 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3250 CString sRev;
3252 if ((bRegex)&&(m_bFilterWithRegex))
3254 if (m_SelectedFilters & LOGFILTER_BUGID)
3256 if(this->m_bShowBugtraqColumn)
3258 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3260 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3261 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3262 return result;
3266 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3268 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3269 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3270 return result;
3273 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3275 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3276 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3277 return result;
3280 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3282 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3283 return result;
3285 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3286 return result;
3289 if (m_SelectedFilters & LOGFILTER_EMAILS)
3291 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3292 return result;
3294 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3295 return result;
3298 if (m_SelectedFilters & LOGFILTER_REVS)
3300 sRev = pRev->m_CommitHash.ToString();
3301 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3303 return result;
3307 if (m_SelectedFilters & LOGFILTER_NOTES)
3309 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3310 return result;
3313 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3315 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3316 for (const auto& ref : refs)
3318 if (std::regex_search(std::wstring(ref), pat, flags))
3319 return result;
3323 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3325 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3326 return result;
3329 if (m_SelectedFilters & LOGFILTER_PATHS)
3331 CTGitPathList* pathList = nullptr;
3332 if( pRev->m_IsDiffFiles)
3333 pathList = &pRev->GetFiles(this);
3334 else
3336 if(!pRev->m_IsSimpleListReady)
3337 pRev->SafeGetSimpleList(&g_Git);
3340 if(pathList)
3341 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3343 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3344 return result;
3345 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3346 return result;
3349 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3351 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3352 return result;
3356 else
3358 CString find = m_sFilterText;
3359 if (!m_bFilterCaseSensitively)
3360 find.MakeLower();
3361 result = find[0] == '!' ? FALSE : TRUE;
3362 if (!result)
3363 find = find.Mid(1);
3365 if (m_SelectedFilters & LOGFILTER_BUGID)
3367 if(this->m_bShowBugtraqColumn)
3369 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3371 if (!m_bFilterCaseSensitively)
3372 sBugIds.MakeLower();
3373 if ((sBugIds.Find(find) >= 0))
3374 return result;
3378 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3380 CString msg = pRev->GetSubject();
3382 if (!m_bFilterCaseSensitively)
3383 msg = msg.MakeLower();
3384 if ((msg.Find(find) >= 0))
3385 return result;
3388 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3390 CString msg = pRev->GetBody();
3392 if (!m_bFilterCaseSensitively)
3393 msg = msg.MakeLower();
3394 if ((msg.Find(find) >= 0))
3395 return result;
3398 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3400 CString msg = pRev->GetAuthorName();
3401 if (!m_bFilterCaseSensitively)
3402 msg = msg.MakeLower();
3403 if ((msg.Find(find) >= 0))
3404 return result;
3407 if (m_SelectedFilters & LOGFILTER_EMAILS)
3409 CString msg = pRev->GetAuthorEmail();
3410 if (!m_bFilterCaseSensitively)
3411 msg = msg.MakeLower();
3412 if ((msg.Find(find) >= 0))
3413 return result;
3416 if (m_SelectedFilters & LOGFILTER_NOTES)
3418 CString msg = pRev->m_Notes;
3419 if (!m_bFilterCaseSensitively)
3420 msg = msg.MakeLower();
3421 if ((msg.Find(find) >= 0))
3422 return result;
3425 if (m_SelectedFilters & LOGFILTER_REVS)
3427 sRev = pRev->m_CommitHash.ToString();
3428 if ((sRev.Find(find) >= 0))
3429 return result;
3432 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3434 CString msg = GetTagInfo(pRev);
3435 if (!m_bFilterCaseSensitively)
3436 msg = msg.MakeLower();
3437 if ((msg.Find(find) >= 0))
3438 return result;
3441 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3443 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3444 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3446 if (it->Find(find) >= 0)
3447 return result;
3451 if (m_SelectedFilters & LOGFILTER_PATHS)
3453 CTGitPathList* pathList = nullptr;
3454 if( pRev->m_IsDiffFiles)
3455 pathList = &pRev->GetFiles(this);
3456 else
3458 if(!pRev->m_IsSimpleListReady)
3459 pRev->SafeGetSimpleList(&g_Git);
3461 if(pathList)
3462 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3464 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3465 CString path = cpath->GetGitOldPathString();
3466 if (!m_bFilterCaseSensitively)
3467 path.MakeLower();
3468 if ((path.Find(find)>=0))
3469 return result;
3470 path = cpath->GetGitPathString();
3471 if (!m_bFilterCaseSensitively)
3472 path.MakeLower();
3473 if ((path.Find(find)>=0))
3474 return result;
3477 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3479 CString path = pRev->m_SimpleFileList[i];
3480 if (!m_bFilterCaseSensitively)
3481 path.MakeLower();
3482 if ((path.Find(find)>=0))
3483 return result;
3486 } // else (from if (bRegex))
3487 return !result;
3490 static bool CStringStartsWith(const CString &str, const CString &prefix)
3492 return str.Left(prefix.GetLength()) == prefix;
3494 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3496 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3497 return true;
3499 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3501 // Keep all refs.
3502 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3503 for (size_t i = 0; i < refList.size(); ++i)
3505 const CString &str = refList[i];
3506 if (CStringStartsWith(str, L"refs/heads/"))
3508 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3509 return true;
3511 else if (CStringStartsWith(str, L"refs/remotes/"))
3513 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3514 return true;
3516 else if (CStringStartsWith(str, L"refs/tags/"))
3518 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3519 return true;
3521 else if (CStringStartsWith(str, L"refs/stash"))
3523 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3524 return true;
3526 else if (CStringStartsWith(str, L"refs/bisect/"))
3528 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3529 return true;
3532 // Keep the head too.
3533 if (pRev->m_CommitHash == m_HeadHash)
3534 return true;
3537 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3539 if (pRev->ParentsCount() > 1)
3540 return true;
3541 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3542 if (childrenIt != commitChildren.end())
3544 const std::unordered_set<CGitHash> &children = childrenIt->second;
3545 if (children.size() > 1)
3546 return true;
3549 return false;
3552 void CGitLogListBase::ShowGraphColumn(bool bShow)
3554 // HACK to hide graph column
3555 if (bShow)
3556 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3557 else
3558 SetColumnWidth(0, 0);
3561 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3563 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3564 return L"";
3566 CString tagInfo;
3567 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3568 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3570 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3571 continue;
3572 if (!CStringUtils::EndsWith((*it), L"^{}"))
3573 continue;
3575 CString cmd;
3576 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3577 CString output;
3578 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3579 continue;
3581 // parse tag date
3584 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3585 int pos1 = output.Find(L'>');
3586 if (pos1 < 0)
3587 break;
3588 ++pos1;
3589 if (output[pos1] == L' ')
3590 ++pos1;
3591 int pos2 = output.Find(L'\n', pos1);
3592 if (pos2 < 0)
3593 break;
3595 CString str = output.Mid(pos1, pos2 - pos1);
3596 wchar_t* pEnd = nullptr;
3597 errno = 0;
3598 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3599 if (str.GetBuffer() == pEnd)
3600 break;
3601 if (errno == ERANGE)
3602 break;
3604 output.Delete(pos1, pos2 - pos1);
3605 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3606 } while (0);
3607 output.Trim().AppendChar(L'\n');
3608 tagInfo += output;
3610 return tagInfo;
3613 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3615 pShownlist->SafeRemoveAll();
3617 std::wregex pat;//(L"Remove", regex_constants::icase);
3618 bool bRegex = false;
3619 if (m_bFilterWithRegex)
3620 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3622 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3623 CString sRev;
3624 for (DWORD i=0; i<m_logEntries.size(); ++i)
3626 if ((bRegex)&&(m_bFilterWithRegex))
3628 #if 0
3629 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3631 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3632 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3634 pShownlist->SafeAdd(m_logEntries[i]);
3635 continue;
3638 #endif
3639 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3641 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3642 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3644 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3645 continue;
3648 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3650 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3651 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3653 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3654 continue;
3657 if (m_SelectedFilters & LOGFILTER_PATHS)
3659 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3661 bool bGoing = true;
3662 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3664 CTGitPath cpath = pathList[cpPathIndex];
3665 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3667 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3668 bGoing = false;
3669 continue;
3671 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3673 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3674 bGoing = false;
3675 continue;
3677 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3679 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3680 bGoing = false;
3681 continue;
3685 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3687 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3689 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3690 continue;
3693 if (m_SelectedFilters & LOGFILTER_EMAILS)
3695 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3697 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3698 continue;
3701 if (m_SelectedFilters & LOGFILTER_REVS)
3703 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3704 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3706 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3707 continue;
3710 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3712 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3713 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3715 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3717 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3718 continue;
3722 } // if (bRegex)
3723 else
3725 CString find = m_sFilterText;
3726 if (!m_bFilterCaseSensitively)
3727 find.MakeLower();
3728 #if 0
3729 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3731 CString sBugIDs = m_logEntries[i]->sBugIDs;
3733 if (!m_bFilterCaseSensitively)
3734 sBugIDs = sBugIDs.MakeLower();
3735 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3737 pShownlist->SafeAdd(m_logEntries[i]);
3738 continue;
3741 #endif
3742 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3744 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3746 if (!m_bFilterCaseSensitively)
3747 msg = msg.MakeLower();
3748 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3750 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3751 continue;
3754 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3756 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3758 if (!m_bFilterCaseSensitively)
3759 msg = msg.MakeLower();
3760 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3762 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3763 continue;
3766 if (m_SelectedFilters & LOGFILTER_PATHS)
3768 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3770 bool bGoing = true;
3771 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3773 CTGitPath cpath = pathList[cpPathIndex];
3774 CString path = cpath.GetGitOldPathString();
3775 if (!m_bFilterCaseSensitively)
3776 path.MakeLower();
3777 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3779 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3780 bGoing = false;
3781 continue;
3783 path = cpath.GetGitPathString();
3784 if (!m_bFilterCaseSensitively)
3785 path.MakeLower();
3786 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3788 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3789 bGoing = false;
3790 continue;
3792 path = cpath.GetActionName();
3793 if (!m_bFilterCaseSensitively)
3794 path.MakeLower();
3795 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3797 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3798 bGoing = false;
3799 continue;
3803 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3805 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3806 if (!m_bFilterCaseSensitively)
3807 msg = msg.MakeLower();
3808 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3810 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3811 continue;
3814 if (m_SelectedFilters & LOGFILTER_EMAILS)
3816 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3817 if (!m_bFilterCaseSensitively)
3818 msg = msg.MakeLower();
3819 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3821 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3822 continue;
3825 if (m_SelectedFilters & LOGFILTER_REVS)
3827 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3828 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3830 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3831 continue;
3834 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3836 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3837 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3839 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3841 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3842 continue;
3846 } // else (from if (bRegex))
3847 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3850 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3853 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3855 if(m_From == -1)
3856 if(m_To == -1)
3857 return true;
3858 else
3859 return time <= m_To;
3860 else
3861 if(m_To == -1)
3862 return time >= m_From;
3863 else
3864 return ((time >= m_From)&&(time <= m_To));
3866 return TRUE; /* git dll will filter time range */
3868 // return TRUE;
3871 void CGitLogListBase::StartFilter()
3873 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3874 RecalculateShownList(&m_arShownList);
3875 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3878 DeleteAllItems();
3879 SetItemCountEx(ShownCountWithStopped());
3880 RedrawItems(0, ShownCountWithStopped());
3881 Invalidate();
3884 void CGitLogListBase::RemoveFilter()
3886 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3888 m_arShownList.SafeRemoveAll();
3890 // reset the time filter too
3891 #if 0
3892 m_timFrom = (__time64_t(m_tFrom));
3893 m_timTo = (__time64_t(m_tTo));
3894 m_DateFrom.SetTime(&m_timFrom);
3895 m_DateTo.SetTime(&m_timTo);
3896 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3897 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3898 #endif
3900 for (DWORD i=0; i<m_logEntries.size(); ++i)
3902 if(this->m_IsOldFirst)
3903 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3904 else
3905 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3907 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3908 DeleteAllItems();
3909 SetItemCountEx(ShownCountWithStopped());
3910 RedrawItems(0, ShownCountWithStopped());
3912 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3915 void CGitLogListBase::Clear()
3917 m_arShownList.SafeRemoveAll();
3918 DeleteAllItems();
3920 m_logEntries.ClearAll();
3923 void CGitLogListBase::OnDestroy()
3925 SafeTerminateThread();
3926 SafeTerminateAsyncDiffThread();
3928 int retry = 0;
3929 while(m_LogCache.SaveCache())
3931 if(retry > 5)
3932 break;
3933 Sleep(1000);
3935 ++retry;
3937 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3938 // MB_YESNO) == IDNO)
3939 // break;
3942 __super::OnDestroy();
3945 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3947 CRect rect;
3948 int i=(int)wParam;
3949 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3950 this->InvalidateRect(rect);
3952 return 0;
3956 * Save column widths to the registry
3958 void CGitLogListBase::SaveColumnWidths()
3960 // HACK that graph column is always shown
3961 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3963 __super::SaveColumnWidths();
3966 int CGitLogListBase::GetHeadIndex()
3968 if(m_HeadHash.IsEmpty())
3969 return -1;
3971 for (size_t i = 0; i < m_arShownList.size(); ++i)
3973 GitRev* pRev = m_arShownList.SafeGetAt(i);
3974 if(pRev)
3976 if (pRev->m_CommitHash == m_HeadHash)
3977 return (int)i;
3980 return -1;
3982 void CGitLogListBase::OnFind()
3984 if (!m_pFindDialog)
3986 m_pFindDialog = new CFindDlg(this);
3987 m_pFindDialog->Create(this);
3991 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3993 if (GetSelectedCount() != 0)
3994 return 0;
3996 CGitHash theSelectedHash = m_lastSelectedHash;
3997 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3998 m_lastSelectedHash = theSelectedHash;
4000 int countPerPage = GetCountPerPage();
4001 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
4002 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
4003 EnsureVisible((int)itemToSelect, FALSE);
4004 return 0;
4007 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
4009 CString* ref = reinterpret_cast<CString*>(wParam);
4010 if (!ref || ref->IsEmpty())
4011 return 1;
4013 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4015 CGitHash hash;
4016 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4017 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4019 if (hash.IsEmpty())
4020 return 1;
4022 bool bFound = false;
4023 int cnt = (int)m_arShownList.size();
4024 int i;
4025 for (i = 0; i < cnt; ++i)
4027 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4028 if (pLogEntry && pLogEntry->m_CommitHash == hash)
4030 bFound = true;
4031 break;
4034 if (!bFound)
4035 return 1;
4037 EnsureVisible(i, FALSE);
4038 if (!bShift)
4040 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4041 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4042 SetSelectionMark(i);
4044 else
4046 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4047 if (pLogEntry)
4048 m_highlight = pLogEntry->m_CommitHash;
4050 Invalidate();
4051 UpdateData(FALSE);
4053 return 0;
4056 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4058 ASSERT(m_pFindDialog);
4059 bool bFound = false;
4060 int i=0;
4062 if (m_pFindDialog->IsTerminating())
4064 // invalidate the handle identifying the dialog box.
4065 m_pFindDialog = nullptr;
4066 return 0;
4069 int cnt = (int)m_arShownList.size();
4070 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4072 if(m_pFindDialog->IsRef())
4074 CString str;
4075 str=m_pFindDialog->GetFindString();
4077 CGitHash hash;
4079 if(!str.IsEmpty())
4081 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4082 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4085 if(!hash.IsEmpty())
4087 for (i = 0; i < cnt; ++i)
4089 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4090 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4092 bFound = true;
4093 break;
4097 if (!bFound)
4099 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4100 return 0;
4104 if (m_pFindDialog->FindNext() && !bFound)
4106 //read data from dialog
4107 CString findText = m_pFindDialog->GetFindString();
4108 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4110 std::wregex pat;
4111 bool bRegex = false;
4112 if (m_pFindDialog->Regex())
4113 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4115 std::regex_constants::match_flag_type flags = std::regex_constants::match_not_null;
4117 for (i = m_nSearchIndex + 1; ; ++i)
4119 if (i >= cnt)
4121 i = 0;
4122 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4124 if (m_nSearchIndex >= 0)
4126 if (i == m_nSearchIndex)
4128 ::MessageBeep(0xFFFFFFFF);
4129 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4130 break;
4134 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4136 CString str;
4137 str+=pLogEntry->m_CommitHash.ToString();
4138 str += L'\n';
4140 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4141 if (refList != m_HashMap.cend())
4143 for (const auto& ref : (*refList).second)
4145 str += ref;
4146 str += L'\n';
4150 str+=pLogEntry->GetAuthorEmail();
4151 str += L'\n';
4152 str+=pLogEntry->GetAuthorName();
4153 str += L'\n';
4154 str+=pLogEntry->GetBody();
4155 str += L'\n';
4156 str+=pLogEntry->GetCommitterEmail();
4157 str += L'\n';
4158 str+=pLogEntry->GetCommitterName();
4159 str += L'\n';
4160 str+=pLogEntry->GetSubject();
4161 str += L'\n';
4162 str+=pLogEntry->m_Notes;
4163 str += L'\n';
4164 str+=GetTagInfo(pLogEntry);
4165 str += L'\n';
4168 /*Because changed files list is loaded on demand when gui show,
4169 files will empty when files have not fetched.
4171 we can add it back by using one-way diff(with outnumber changed and rename detect.
4172 here just need changed filename list. one-way is much quicker.
4174 if(pLogEntry->m_IsFull)
4176 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4178 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4179 str += L'\n';
4180 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4181 str += L'\n';
4184 else
4186 if(!pLogEntry->m_IsSimpleListReady)
4187 pLogEntry->SafeGetSimpleList(&g_Git);
4189 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4191 str += pLogEntry->m_SimpleFileList[j];
4192 str += L'\n';
4196 if (bRegex)
4198 if (std::regex_search(std::wstring(str), pat, flags))
4200 bFound = true;
4201 break;
4204 else
4206 if (bMatchCase)
4208 if (str.Find(findText) >= 0)
4210 bFound = true;
4211 break;
4214 else
4216 CString msg = str;
4217 msg = msg.MakeLower();
4218 CString find = findText.MakeLower();
4219 if (msg.Find(find) >= 0)
4221 bFound = TRUE;
4222 break;
4226 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4228 } // if(m_pFindDialog->FindNext())
4229 //UpdateLogInfoLabel();
4231 if (bFound)
4233 m_nSearchIndex = i;
4234 EnsureVisible(i, FALSE);
4235 if (!bShift)
4237 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4238 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4239 SetSelectionMark(i);
4241 else
4243 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4244 if (pLogEntry)
4245 m_highlight = pLogEntry->m_CommitHash;
4247 Invalidate();
4248 //FillLogMessageCtrl();
4249 UpdateData(FALSE);
4252 return 0;
4255 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4257 LVHITTESTINFO lvhitTestInfo;
4259 lvhitTestInfo.pt = point;
4261 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4262 int nSubItem = lvhitTestInfo.iSubItem;
4264 UINT nFlags = lvhitTestInfo.flags;
4266 // nFlags is 0 if the SubItemHitTest fails
4267 // Therefore, 0 & <anything> will equal false
4268 if (nFlags & LVHT_ONITEM)
4270 // Get the client area occupied by this control
4271 RECT rcClient;
4272 GetClientRect(&rcClient);
4274 // Fill in the TOOLINFO structure
4275 pTI->hwnd = m_hWnd;
4276 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4277 pTI->lpszText = LPSTR_TEXTCALLBACK;
4278 pTI->rect = rcClient;
4280 return pTI->uId; // By returning a unique value per listItem,
4281 // we ensure that when the mouse moves over another list item,
4282 // the tooltip will change
4284 else
4286 // Otherwise, we aren't interested, so let the message propagate
4287 return -1;
4291 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4293 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4294 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4296 *pResult = 0;
4298 // Ignore messages from the built in tooltip, we are processing them internally
4299 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4300 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4301 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4302 return FALSE;
4304 // Get the mouse position
4305 const MSG* pMessage = GetCurrentMessage();
4307 CPoint pt;
4308 pt = pMessage->pt;
4309 ScreenToClient(&pt);
4311 // Check if the point falls onto a list item
4312 LVHITTESTINFO lvhitTestInfo;
4313 lvhitTestInfo.pt = pt;
4315 int nItem = SubItemHitTest(&lvhitTestInfo);
4317 if (lvhitTestInfo.flags & LVHT_ONITEM)
4319 // Get branch description first
4320 CString strTipText;
4321 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4323 CString branch;
4324 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4325 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4327 MAP_STRING_STRING descriptions;
4328 g_Git.GetBranchDescriptions(descriptions);
4329 if (descriptions.find(branch) != descriptions.cend())
4331 strTipText.LoadString(IDS_DESCRIPTION);
4332 strTipText += L":\n";
4333 strTipText += descriptions[branch];
4338 bool followMousePos = false;
4339 if (!strTipText.IsEmpty())
4340 followMousePos = true;
4341 else
4342 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4343 if (strTipText.IsEmpty())
4344 return FALSE;
4346 // we want multiline tooltips
4347 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4349 wcscpy_s(m_wszTip, strTipText);
4350 // handle Unicode as well as non-Unicode requests
4351 if (pNMHDR->code == TTN_NEEDTEXTA)
4353 pTTTA->hinst = nullptr;
4354 pTTTA->lpszText = m_szTip;
4355 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4357 else
4359 pTTTW->hinst = nullptr;
4360 pTTTW->lpszText = m_wszTip;
4363 CRect rect;
4364 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4365 if (followMousePos)
4366 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4367 ClientToScreen(rect);
4368 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4370 return TRUE; // We found a tool tip,
4371 // tell the framework this message has been handled
4374 return FALSE; // We didn't handle the message,
4375 // let the framework continue propagating the message
4378 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4380 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4382 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4383 if (pLogEntry == nullptr)
4384 return CString();
4385 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4386 return CString();
4387 return pLogEntry->GetSubject();
4389 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4391 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4392 if (pLogEntry == nullptr)
4393 return CString();
4394 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4396 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4398 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4399 if (pLogEntry == nullptr)
4400 return CString();
4401 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4403 else if (nSubItem == LOGLIST_ACTION)
4405 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4406 if (pLogEntry == nullptr)
4407 return CString();
4409 if (!pLogEntry->m_IsDiffFiles)
4410 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4412 int actions = pLogEntry->GetAction(this);
4413 CString sToolTipText;
4415 CString actionText;
4416 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4417 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4419 if (actions & CTGitPath::LOGACTIONS_ADDED)
4421 if (!actionText.IsEmpty())
4422 actionText += L"\r\n";
4423 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4426 if (actions & CTGitPath::LOGACTIONS_DELETED)
4428 if (!actionText.IsEmpty())
4429 actionText += L"\r\n";
4430 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4433 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4435 if (!actionText.IsEmpty())
4436 actionText += L"\r\n";
4437 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4440 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4442 if (!actionText.IsEmpty())
4443 actionText += L"\r\n";
4444 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4447 if (!actionText.IsEmpty())
4449 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4450 sToolTipText = sTitle + L":\r\n" + actionText;
4452 return sToolTipText;
4454 return CString();
4457 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4459 POINT pt = point;
4460 ScreenToClient(&pt);
4461 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4464 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4466 if (!pLogEntry)
4467 return false;
4469 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4470 if (refList == m_HashMap.cend())
4471 return false;
4473 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4475 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4476 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4477 continue;
4479 CGit::REF_TYPE foundType;
4480 if (pShortname)
4481 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4482 else
4483 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4484 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4485 return false;
4487 type = foundType;
4488 if (pIndex)
4489 *pIndex = i;
4490 return true;
4492 return false;
4495 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4497 *pResult = 0;
4499 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4500 return;
4502 m_bDragging = TRUE;
4503 m_nDropIndex = -1;
4504 m_nDropMarkerLast = -1;
4505 m_nDropMarkerLastHot = GetHotItem();
4506 SetCapture();
4509 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4511 __super::OnMouseMove(nFlags, point);
4513 if (!m_bDragging)
4514 return;
4516 CPoint dropPoint = point;
4517 ClientToScreen(&dropPoint);
4519 if (WindowFromPoint(dropPoint) != this)
4521 SetCursor(LoadCursor(nullptr, IDC_NO));
4522 m_nDropIndex = -1;
4523 DrawDropInsertMarker(m_nDropIndex);
4524 return;
4527 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4528 ScreenToClient(&dropPoint);
4530 dropPoint.y += 10;
4531 m_nDropIndex = HitTest(dropPoint);
4533 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4535 dropPoint.y -= 10;
4536 m_nDropIndex = HitTest(dropPoint);
4537 if (m_nDropIndex != -1)
4538 m_nDropIndex = GetItemCount();
4541 POSITION pos = GetFirstSelectedItemPosition();
4542 int first = GetNextSelectedItem(pos);
4543 int last = first;
4544 while (pos)
4545 last = GetNextSelectedItem(pos);
4546 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4548 SetCursor(LoadCursor(nullptr, IDC_NO));
4549 m_nDropIndex = -1;
4552 // handle auto scrolling
4553 int hotItem = GetHotItem();
4554 int topindex = GetTopIndex();
4555 if (hotItem == topindex && hotItem != 0)
4556 EnsureVisible(hotItem - 1, FALSE);
4557 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4558 EnsureVisible(hotItem + 1, FALSE);
4560 DrawDropInsertMarker(m_nDropIndex);
4563 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4565 if (m_bDragging)
4567 ::ReleaseCapture();
4568 SetCursor(LoadCursor(nullptr, IDC_HAND));
4569 m_bDragging = FALSE;
4571 CRect rect;
4572 GetItemRect(m_nDropMarkerLast, &rect, 0);
4573 rect.bottom = rect.top + 2;
4574 rect.top -= 2;
4575 InvalidateRect(&rect, 0);
4577 CPoint pt(point);
4578 ClientToScreen(&pt);
4579 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4580 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4583 __super::OnLButtonUp(nFlags, point);
4586 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4588 if (m_nDropMarkerLast != nIndex)
4590 CRect rect;
4591 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4593 rect.bottom = rect.top + 2;
4594 rect.top -= 2;
4595 InvalidateRect(&rect, 0);
4597 else if (m_nDropMarkerLast == GetItemCount())
4598 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4599 m_nDropMarkerLast = nIndex;
4601 if (nIndex < 0)
4602 return;
4604 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4606 else if (m_nDropMarkerLastHot != GetHotItem())
4608 m_nDropMarkerLastHot = GetHotItem();
4609 m_nDropMarkerLast = -1;
4613 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4615 CBrush* pBrush = CDC::GetHalftoneBrush();
4616 CDC* pDC = GetDC();
4618 CRect rect;
4619 if (nIndex < GetItemCount())
4621 GetItemRect(nIndex, &rect, 0);
4622 rect.bottom = rect.top + 2;
4623 rect.top -= 2;
4625 else
4627 GetItemRect(nIndex - 1, &rect, 0);
4628 rect.top = rect.bottom - 2;
4629 rect.bottom += 2;
4632 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4633 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4634 pDC->SelectObject(pBrushOld);
4636 ReleaseDC(pDC);
4639 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
4641 return 0;