Constify
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blob0cdaabb90155adebb2abd50a90d308659e603c0d
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2020 - 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 long volatile CGitLogListBase::s_bThreadRunning = FALSE;
43 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
45 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
46 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
47 ,m_nSearchIndex(0)
48 ,m_bNoDispUpdates(FALSE)
49 , m_ShowFilter(FILTERSHOW_ALL)
50 , m_bShowWC(false)
51 , m_logEntries(&m_LogCache)
52 , m_pFindDialog(nullptr)
53 , m_dwDefaultColumns(0)
54 , m_arShownList(&m_critSec)
55 , m_hasWC(true)
56 , m_bNoHightlightHead(FALSE)
57 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
58 , m_bFullCommitMessageOnLogLine(false)
59 , m_OldTopIndex(-1)
60 , m_AsyncThreadRunning(FALSE)
61 , m_AsyncThreadExit(FALSE)
62 , m_DiffingThread(nullptr)
63 , m_bIsCherryPick(false)
64 , m_bShowBugtraqColumn(false)
65 , m_IsIDReplaceAction(FALSE)
66 , m_ShowMask(0)
67 , m_LoadingThread(nullptr)
68 , m_bExitThread(FALSE)
69 , m_IsOldFirst(FALSE)
70 , m_IsRebaseReplaceGraph(FALSE)
71 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
72 , m_bDragndropEnabled(false)
73 , m_bDragging(FALSE)
74 , m_nDropIndex(-1)
75 , m_nDropMarkerLast(-1)
76 , m_nDropMarkerLastHot(-1)
77 , m_LogFilter(std::make_shared<CLogDlgFilter>())
78 , m_HashMap(std::make_shared<MAP_HASH_NAME>())
80 // use the default GUI font, create a copy of it and
81 // change the copy to BOLD (leave the rest of the font
82 // the same)
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_Filter.m_NumberOfLogsScale = CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
96 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
98 CString key;
99 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", static_cast<LPCTSTR>(g_Git.m_CurrentDir));
100 key.Replace(L':', L'_');
101 CString lastSelFromDate = CRegString(key);
102 if (lastSelFromDate.GetLength() == 10)
104 CTime time = CTime(_wtoi(static_cast<LPCTSTR>(lastSelFromDate.Left(4))), _wtoi(static_cast<LPCTSTR>(lastSelFromDate.Mid(5, 2))), _wtoi(static_cast<LPCTSTR>(lastSelFromDate.Mid(8, 2))), 0, 0, 0);
105 m_Filter.m_From = static_cast<DWORD>(time.GetTime());
108 m_Filter.m_NumberOfLogs = CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
110 // get short/long datetime setting from registry
111 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
112 if ( RegUseShortDateFormat )
114 m_DateFormat = DATE_SHORTDATE;
116 else
118 m_DateFormat = DATE_LONGDATE;
120 // get relative time display setting from registry
121 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
122 m_bRelativeTimes = (regRelativeTimes != 0);
124 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
125 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
126 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
127 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
128 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
129 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
130 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
132 m_ColumnRegKey = L"log";
134 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
135 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
136 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
137 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
139 m_LineWidth = max(1, static_cast<int>(CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2)));
140 m_NodeSize = max(1, static_cast<int>(CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10)));
142 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
143 StartAsyncDiffThread();
146 HWND CGitLogListBase::GetParentHWND()
148 auto owner = GetSafeOwner();
149 if (!owner)
150 return GetSafeHwnd();
151 return owner->GetSafeHwnd();
154 int CGitLogListBase::AsyncDiffThread()
156 while(!m_AsyncThreadExit)
158 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
160 GitRevLoglist* pRev = nullptr;
161 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
163 m_AsynDiffListLock.Lock();
164 pRev = m_AsynDiffList.back();
165 m_AsynDiffList.pop_back();
166 m_AsynDiffListLock.Unlock();
168 if( pRev->m_CommitHash.IsEmpty() )
170 if(pRev->m_IsDiffFiles)
171 continue;
173 auto filesWrapper = pRev->GetFilesWriter();
174 auto& files = filesWrapper.m_files;
175 files.Clear();
176 pRev->m_ParentHash.clear();
177 pRev->m_ParentHash.push_back(m_HeadHash);
178 g_Git.RefreshGitIndex();
179 g_Git.GetWorkingTreeChanges(files, false, nullptr, true); // filtering is done in LogDlg.cpp
180 auto& action = pRev->GetAction(this);
181 action = 0;
182 for (int j = 0; j < files.GetCount(); ++j)
183 action |= files[j].m_Action;
185 if (CString err; pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
187 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
188 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
189 return -1;
192 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
194 CString body = L"\n";
195 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
196 pRev->GetBody() = body;
197 ::PostMessage(m_hWnd, MSG_LOADED, 0, 0);
198 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
199 continue;
202 if (!pRev->CheckAndDiff())
203 { // fetch change file list
204 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
206 if (i < static_cast<int>(m_arShownList.size()))
208 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
209 if(data->m_CommitHash == pRev->m_CommitHash)
211 ::PostMessage(m_hWnd, MSG_LOADED, i, 0);
212 break;
217 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
219 POSITION pos = GetFirstSelectedItemPosition();
220 int nItem = GetNextSelectedItem(pos);
222 if(nItem>=0)
224 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
225 if(data)
226 if(data->m_CommitHash == pRev->m_CommitHash)
227 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
233 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
234 return 0;
236 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
238 if (exclusivelyShow)
239 m_ContextMenuMask &= hideMask;
240 else
241 m_ContextMenuMask &= ~hideMask;
244 CGitLogListBase::~CGitLogListBase()
246 InterlockedExchange(&m_bNoDispUpdates, TRUE);
247 this->m_arShownList.SafeRemoveAll();
249 m_logEntries.ClearAll();
251 SafeTerminateThread();
252 SafeTerminateAsyncDiffThread();
254 if(m_AsyncDiffEvent)
255 CloseHandle(m_AsyncDiffEvent);
259 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
260 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
261 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
262 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
263 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
264 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
265 ON_WM_CONTEXTMENU()
266 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
267 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
268 ON_WM_CREATE()
269 ON_WM_DESTROY()
270 ON_MESSAGE(MSG_LOADED,OnLoad)
271 ON_WM_MEASUREITEM()
272 ON_WM_MEASUREITEM_REFLECT()
273 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
274 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
275 ON_WM_MOUSEMOVE()
276 ON_WM_LBUTTONUP()
277 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
278 END_MESSAGE_MAP()
280 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
282 //if (m_nRowHeight>0)
283 lpMeasureItemStruct->itemHeight = CDPIAware::Instance().ScaleY(50);
286 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
288 PreSubclassWindow();
289 return __super::OnCreate(lpCreateStruct);
292 void CGitLogListBase::SetStyle()
294 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
297 void CGitLogListBase::PreSubclassWindow()
299 SetStyle();
300 // load the icons for the action columns
301 // m_Theme.Open(m_hWnd, L"ListView");
302 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
303 __super::PreSubclassWindow();
306 CString CGitLogListBase::GetRebaseActionName(int action)
308 if (action & LOGACTIONS_REBASE_EDIT)
309 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
310 if (action & LOGACTIONS_REBASE_SQUASH)
311 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
312 if (action & LOGACTIONS_REBASE_PICK)
313 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
314 if (action & LOGACTIONS_REBASE_SKIP)
315 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
317 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
320 void CGitLogListBase::InsertGitColumn()
322 CString temp;
324 Init();
325 if (CRegDWORD(L"Software\\TortoiseGit\\LogFontForLogCtrl", FALSE))
327 CCommonAppUtils::CreateFontForLogs(m_Font);
328 SetFont(&m_Font);
331 // use the default font, create a copy of it and
332 // change the copy to BOLD (leave the rest of the font
333 // the same)
334 LOGFONT lf = { 0 };
335 GetFont()->GetLogFont(&lf);
336 lf.lfWeight = FW_BOLD;
337 m_boldFont.CreateFontIndirect(&lf);
338 lf.lfWeight = FW_DONTCARE;
339 lf.lfItalic = TRUE;
340 m_FontItalics.CreateFontIndirect(&lf);
341 lf.lfWeight = FW_BOLD;
342 m_boldItalicsFont.CreateFontIndirect(&lf);
344 // only load properties if we have a repository
345 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
346 UpdateProjectProperties();
348 static UINT normal[] =
350 IDS_LOG_GRAPH,
351 IDS_LOG_REBASE,
352 IDS_LOG_ID,
353 IDS_LOG_HASH,
354 IDS_LOG_ACTIONS,
355 IDS_LOG_MESSAGE,
356 IDS_LOG_AUTHOR,
357 IDS_LOG_DATE,
358 IDS_LOG_EMAIL,
359 IDS_LOG_COMMIT_NAME,
360 IDS_LOG_COMMIT_EMAIL,
361 IDS_LOG_COMMIT_DATE,
362 IDS_LOG_BUGIDS,
363 IDS_LOG_SVNREV,
366 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
367 auto columnWidth = CDPIAware::Instance().ScaleX(ICONITEMBORDER + 16 * 4);
368 static int with[] =
370 columnWidth,
371 columnWidth,
372 columnWidth,
373 columnWidth,
374 2 * iconItemBorder + GetSystemMetrics(SM_CXSMICON) * 5,
375 CDPIAware::Instance().ScaleX(LOGLIST_MESSAGE_MIN),
376 columnWidth,
377 columnWidth,
378 columnWidth,
379 columnWidth,
380 columnWidth,
381 columnWidth,
382 columnWidth,
383 columnWidth,
385 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
387 DWORD hideColumns = 0;
388 if(this->m_IsRebaseReplaceGraph)
390 hideColumns |= GIT_LOG_GRAPH;
391 m_dwDefaultColumns |= GIT_LOG_REBASE;
393 else
394 hideColumns |= GIT_LOG_REBASE;
396 if(this->m_IsIDReplaceAction)
398 hideColumns |= GIT_LOG_ACTIONS;
399 m_dwDefaultColumns |= GIT_LOG_ID;
400 m_dwDefaultColumns |= GIT_LOG_HASH;
402 else
403 hideColumns |= GIT_LOG_ID;
404 if(this->m_bShowBugtraqColumn)
405 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
406 else
407 hideColumns |= GIT_LOGLIST_BUG;
408 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
409 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
410 else
411 hideColumns |= GIT_LOGLIST_SVNREV;
412 SetRedraw(false);
414 m_ColumnManager.SetNames(normal, _countof(normal));
415 constexpr int columnVersion = 6; // adjust when changing number/names/etc. of columns
416 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", columnVersion, _countof(normal), with);
417 m_ColumnManager.SetRightAlign(LOGLIST_ID);
419 if (!(hideColumns & GIT_LOG_ACTIONS))
421 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
422 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
423 // display's font height may be less than small icon height.
424 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
425 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
426 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
429 SetRedraw(true);
432 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
434 LVITEM rItem = { 0 };
435 rItem.mask = LVIF_STATE;
436 rItem.iItem = static_cast<int>(Index);
437 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
438 GetItem(&rItem);
440 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
441 HBRUSH brush = nullptr;
443 if (!(rItem.state & LVIS_SELECTED))
445 int action = pLogEntry->GetRebaseAction();
446 if (action & LOGACTIONS_REBASE_SQUASH)
447 brush = ::CreateSolidBrush(RGB(156,156,156));
448 else if (action & LOGACTIONS_REBASE_EDIT)
449 brush = ::CreateSolidBrush(RGB(200,200,128));
451 else if (!IsAppThemed())
453 if (rItem.state & LVIS_SELECTED)
455 if (::GetFocus() == m_hWnd)
456 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
457 else
458 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
461 if (brush)
463 ::FillRect(hdc, &rect, brush);
464 ::DeleteObject(brush);
468 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
470 POINT point = { 4, 4 };
471 CRect rt2 = rect;
472 rt2.DeflateRect(1, 1);
473 rt2.OffsetRect(2, 2);
475 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
476 HPEN oldpen = static_cast<HPEN>(::SelectObject(hdc, nullPen));
477 HBRUSH darkBrush = static_cast<HBRUSH>(::CreateSolidBrush(darkColor));
478 HBRUSH oldbrush = static_cast<HBRUSH>(::SelectObject(hdc, darkBrush));
479 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
481 ::SelectObject(hdc, brush);
482 rt2.OffsetRect(-2, -2);
483 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
484 ::SelectObject(hdc, oldbrush);
485 ::SelectObject(hdc, oldpen);
486 ::DeleteObject(nullPen);
487 ::DeleteObject(darkBrush);
490 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
492 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
493 HPEN oldpen = static_cast<HPEN>(::SelectObject(hdc, pen));
494 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
495 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
496 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
497 ::LineTo(hdc, rect.left, rect.top + 4);
498 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
499 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
500 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
501 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
502 ::SelectObject(hdc, oldpen);
503 ::DeleteObject(pen);
506 void CGitLogListBase::DrawTagBranchMessage(NMLVCUSTOMDRAW* pLVCD, const CRect& rect, INT_PTR index, const std::vector<REFLABEL>& refList)
508 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
509 CRect rt=rect;
510 LVITEM rItem = { 0 };
511 rItem.mask = LVIF_STATE;
512 rItem.iItem = static_cast<int>(index);
513 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
514 GetItem(&rItem);
516 CDC W_Dc;
517 W_Dc.Attach(pLVCD->nmcd.hdc);
519 CAutoThemeData hTheme;
520 if (IsAppThemed())
521 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
523 SIZE oneSpaceSize;
524 if (m_bTagsBranchesOnRightSide)
526 HFONT oldFont = static_cast<HFONT>(SelectObject(pLVCD->nmcd.hdc, GetStockObject(DEFAULT_GUI_FONT)));
527 GetTextExtentPoint32(pLVCD->nmcd.hdc, L" ", 1, &oneSpaceSize);
528 SelectObject(pLVCD->nmcd.hdc, oldFont);
529 rt.left += oneSpaceSize.cx * 2;
531 else
533 GetTextExtentPoint32(pLVCD->nmcd.hdc, L" ", 1, &oneSpaceSize);
534 DrawTagBranch(pLVCD->nmcd.hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
535 rt.left += oneSpaceSize.cx;
538 CString msg = MessageDisplayStr(data);
539 int action = data->GetRebaseAction();
540 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
541 std::vector<CHARRANGE> ranges;
542 auto filter = m_LogFilter;
543 if ((filter->GetSelectedFilters() & (LOGFILTER_SUBJECT | (m_bFullCommitMessageOnLogLine ? LOGFILTER_MESSAGES : 0))) && filter->IsFilterActive())
544 filter->GetMatchRanges(ranges, msg, 0);
545 if (hTheme)
547 int txtState = LISS_NORMAL;
548 if (rItem.state & LVIS_SELECTED)
549 txtState = LISS_SELECTED;
551 if (!ranges.empty())
552 DrawListItemWithMatchesRect(pLVCD, ranges, rt, msg, m_Colors, hTheme, txtState);
553 else
555 DTTOPTS opts = { 0 };
556 opts.dwSize = sizeof(opts);
557 opts.crText = skip ? RGB(128, 128, 128) : CTheme::Instance().IsDarkTheme() ? CTheme::darkTextColor : GetSysColor(COLOR_WINDOWTEXT);
558 opts.dwFlags = DTT_TEXTCOLOR;
559 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
562 else
564 if ((rItem.state & LVIS_SELECTED) && ::GetFocus() == m_hWnd)
565 pLVCD->clrText = skip ? RGB(128, 128, 128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT);
566 else
567 pLVCD->clrText = skip ? RGB(128, 128, 128) : CTheme::Instance().IsDarkTheme() ? CTheme::darkTextColor : GetSysColor(COLOR_WINDOWTEXT);
568 if (!ranges.empty())
569 DrawListItemWithMatchesRect(pLVCD, ranges, rt, msg, m_Colors);
570 else
572 COLORREF clrOld = ::SetTextColor(pLVCD->nmcd.hdc, pLVCD->clrText);
573 ::DrawText(pLVCD->nmcd.hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
574 ::SetTextColor(pLVCD->nmcd.hdc, clrOld);
578 if (m_bTagsBranchesOnRightSide)
580 SIZE size;
581 GetTextExtentPoint32(pLVCD->nmcd.hdc, msg, msg.GetLength(), &size);
583 rt.left += oneSpaceSize.cx + size.cx;
585 DrawTagBranch(pLVCD->nmcd.hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
588 W_Dc.Detach();
591 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, const CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, const std::vector<REFLABEL>& refList)
593 for (unsigned int i = 0; i < refList.size(); ++i)
595 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
596 HBRUSH brush = 0;
597 COLORREF colRef = refList[i].color;
598 bool singleRemote = refList[i].singleRemote;
599 bool hasTracking = refList[i].hasTracking;
600 CGit::REF_TYPE refType = refList[i].refType;
602 //When row selected, ajust label color
603 if (!IsAppThemed())
605 if (rItem.state & LVIS_SELECTED)
606 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
609 brush = ::CreateSolidBrush(colRef);
611 if (!shortname.IsEmpty() && (rt.left < rect.right))
613 SIZE size = { 0 };
614 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
616 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
617 rt.right += 8;
619 int textpos = DT_CENTER;
621 if (rt.right > rect.right)
623 rt.right = rect.right;
624 textpos = 0;
627 CRect textRect = rt;
629 if (singleRemote)
631 rt.right += 5;
632 textRect.OffsetRect(5, 0);
635 if (hasTracking)
636 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
637 else
639 //Fill interior of ref label
640 ::FillRect(hdc, &rt, brush);
643 //Draw edge of label
644 CRect rectEdge = rt;
646 if (!hasTracking)
648 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
649 rectEdge.DeflateRect(1, 1);
650 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
653 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
655 rt.right += 8;
656 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
657 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
658 ::FillRgn(hdc, hrgn, brush);
659 ::DeleteObject(hrgn);
660 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
661 HPEN pen;
662 HPEN oldpen = static_cast<HPEN>(SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50))));
663 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
664 ::DeleteObject(pen);
665 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
666 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
667 ::DeleteObject(pen);
668 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
669 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
670 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
671 ::DeleteObject(pen);
672 SelectObject(hdc, oldpen);
675 //Draw text inside label
676 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
677 if (!customColor && IsAppThemed())
679 int txtState = LISS_NORMAL;
680 if (rItem.state & LVIS_SELECTED)
681 txtState = LISS_SELECTED;
683 DTTOPTS opts = { 0 };
684 opts.dwSize = sizeof(opts);
685 opts.crText = GetSysColor(COLOR_WINDOWTEXT);
686 opts.dwFlags = DTT_TEXTCOLOR;
687 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
689 else
691 W_Dc.SetBkMode(TRANSPARENT);
692 if (customColor || (rItem.state & LVIS_SELECTED))
694 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
695 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
696 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
697 ::SetTextColor(hdc,clrOld);
699 else
701 COLORREF clrOld = ::SetTextColor(hdc, CTheme::Instance().IsDarkTheme() ? CTheme::darkTextColor : GetSysColor(COLOR_WINDOWTEXT));
702 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
703 ::SetTextColor(hdc, clrOld);
707 if (singleRemote)
709 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
710 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
711 CRect newRect;
712 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
713 DrawUpstream(hdc, newRect, color, bold);
716 if (!refList[i].fullName.IsEmpty())
717 m_RefLabelPosMap[refList[i].fullName] = rt;
719 rt.left = rt.right + 1;
721 if (brush)
722 ::DeleteObject(brush);
724 rt.right = rect.right;
727 Gdiplus::Color GetGdiColor(COLORREF col)
729 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
731 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
732 const COLORREF& col,const COLORREF& activeColor, int top
735 int h = laneHeight / 2;
736 int m = (x1 + x2) / 2;
737 int r = (x2 - x1) * m_NodeSize / 30;
738 int d = 2 * r;
740 #define P_CENTER m , h+top
741 #define P_0 x2, h+top
742 #define P_90 m , 0+top-1
743 #define P_180 x1, h+top
744 #define P_270 m , 2 * h+top +1
745 #define R_CENTER m - r, h - r+top, d, d
748 #define DELTA_UR_B 2*(x1 - m), 2*h +top
749 #define DELTA_UR_E 0*16, 90*16 +top // -,
751 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
752 #define DELTA_DR_E 270*16, 90*16 +top // -'
754 #define DELTA_UL_B 2*(x2 - m), 2*h +top
755 #define DELTA_UL_E 90*16, 90*16 +top // ,-
757 #define DELTA_DL_B 2*(x2 - m),2*-h +top
758 #define DELTA_DL_E 180*16, 90*16 // '-
760 #define CENTER_UR x1, 2*h, 225
761 #define CENTER_DR x1, 0 , 135
762 #define CENTER_UL x2, 2*h, 315
763 #define CENTER_DL x2, 0 , 45
766 Gdiplus::Graphics graphics( hdc );
768 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
770 // arc
771 switch (type) {
772 case Lanes::JOIN:
773 case Lanes::JOIN_R:
774 case Lanes::HEAD:
775 case Lanes::HEAD_R:
777 Gdiplus::LinearGradientBrush gradient(
778 Gdiplus::Point(x1-2, h+top-2),
779 Gdiplus::Point(P_270),
780 GetGdiColor(activeColor),GetGdiColor(col));
783 Gdiplus::Pen mypen(&gradient, static_cast<Gdiplus::REAL>(m_LineWidth));
784 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
786 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
787 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
788 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
790 break;
792 case Lanes::JOIN_L:
794 Gdiplus::LinearGradientBrush gradient(
795 Gdiplus::Point(P_270),
796 Gdiplus::Point(x2+1, h+top-1),
797 GetGdiColor(col),GetGdiColor(activeColor));
800 Gdiplus::Pen mypen(&gradient, static_cast<Gdiplus::REAL>(m_LineWidth));
801 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
803 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
804 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
805 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
808 break;
810 case Lanes::TAIL:
811 case Lanes::TAIL_R:
813 Gdiplus::LinearGradientBrush gradient(
814 Gdiplus::Point(x1-2, h+top-2),
815 Gdiplus::Point(P_90),
816 GetGdiColor(activeColor),GetGdiColor(col));
818 Gdiplus::Pen mypen(&gradient, static_cast<Gdiplus::REAL>(m_LineWidth));
820 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
822 #if 0
823 QConicalGradient gradient(CENTER_DR);
824 gradient.setColorAt(0.375, activeCol);
825 gradient.setColorAt(0.625, col);
826 myPen.setBrush(gradient);
827 p->setPen(myPen);
828 p->drawArc(P_CENTER, DELTA_DR);
829 #endif
830 break;
832 default:
833 break;
837 //static QPen myPen(Qt::black, 2); // fast path here
838 CPen pen;
839 pen.CreatePen(PS_SOLID,2,col);
840 //myPen.setColor(col);
841 HPEN oldpen = static_cast<HPEN>(::SelectObject(hdc, pen));
843 Gdiplus::Pen myPen(GetGdiColor(col), static_cast<Gdiplus::REAL>(m_LineWidth));
845 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
847 //p->setPen(myPen);
849 // vertical line
850 switch (type) {
851 case Lanes::ACTIVE:
852 case Lanes::NOT_ACTIVE:
853 case Lanes::MERGE_FORK:
854 case Lanes::MERGE_FORK_R:
855 case Lanes::MERGE_FORK_L:
856 case Lanes::JOIN:
857 case Lanes::JOIN_R:
858 case Lanes::JOIN_L:
859 case Lanes::CROSS:
860 //DrawLine(hdc,P_90,P_270);
861 graphics.DrawLine(&myPen,P_90,P_270);
862 //p->drawLine(P_90, P_270);
863 break;
864 case Lanes::HEAD_L:
865 case Lanes::BRANCH:
866 //DrawLine(hdc,P_CENTER,P_270);
867 graphics.DrawLine(&myPen,P_CENTER,P_270);
868 //p->drawLine(P_CENTER, P_270);
869 break;
870 case Lanes::TAIL_L:
871 case Lanes::INITIAL:
872 case Lanes::MERGE_FORK_L_INITIAL:
873 case Lanes::BOUNDARY:
874 case Lanes::BOUNDARY_C:
875 case Lanes::BOUNDARY_R:
876 case Lanes::BOUNDARY_L:
877 //DrawLine(hdc,P_90, P_CENTER);
878 graphics.DrawLine(&myPen,P_90,P_CENTER);
879 //p->drawLine(P_90, P_CENTER);
880 break;
881 default:
882 break;
885 myPen.SetColor(GetGdiColor(activeColor));
887 // horizontal line
888 switch (type) {
889 case Lanes::MERGE_FORK:
890 case Lanes::JOIN:
891 case Lanes::HEAD:
892 case Lanes::TAIL:
893 case Lanes::CROSS:
894 case Lanes::CROSS_EMPTY:
895 case Lanes::BOUNDARY_C:
896 //DrawLine(hdc,P_180,P_0);
897 graphics.DrawLine(&myPen,P_180,P_0);
898 //p->drawLine(P_180, P_0);
899 break;
900 case Lanes::MERGE_FORK_R:
901 case Lanes::BOUNDARY_R:
902 //DrawLine(hdc,P_180,P_CENTER);
903 graphics.DrawLine(&myPen,P_180,P_CENTER);
904 //p->drawLine(P_180, P_CENTER);
905 break;
906 case Lanes::MERGE_FORK_L:
907 case Lanes::MERGE_FORK_L_INITIAL:
908 case Lanes::HEAD_L:
909 case Lanes::TAIL_L:
910 case Lanes::BOUNDARY_L:
911 //DrawLine(hdc,P_CENTER,P_0);
912 graphics.DrawLine(&myPen,P_CENTER,P_0);
913 //p->drawLine(P_CENTER, P_0);
914 break;
915 default:
916 break;
919 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
921 CBrush brush;
922 brush.CreateSolidBrush(col);
923 HBRUSH oldbrush = static_cast<HBRUSH>(::SelectObject(hdc, brush));
925 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
926 // center symbol, e.g. rect or ellipse
927 switch (type) {
928 case Lanes::ACTIVE:
929 case Lanes::INITIAL:
930 case Lanes::BRANCH:
932 //p->setPen(Qt::NoPen);
933 //p->setBrush(col);
934 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
935 graphics.FillEllipse(&myBrush, R_CENTER);
936 //p->drawEllipse(R_CENTER);
937 break;
938 case Lanes::MERGE_FORK:
939 case Lanes::MERGE_FORK_R:
940 case Lanes::MERGE_FORK_L:
941 case Lanes::MERGE_FORK_L_INITIAL:
942 //p->setPen(Qt::NoPen);
943 //p->setBrush(col);
944 //p->drawRect(R_CENTER);
945 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
946 graphics.FillRectangle(&myBrush, R_CENTER);
947 break;
948 case Lanes::UNAPPLIED:
949 // Red minus sign
950 //p->setPen(Qt::NoPen);
951 //p->setBrush(Qt::red);
952 //p->drawRect(m - r, h - 1, d, 2);
953 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
954 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
955 break;
956 case Lanes::APPLIED:
957 // Green plus sign
958 //p->setPen(Qt::NoPen);
959 //p->setBrush(DARK_GREEN);
960 //p->drawRect(m - r, h - 1, d, 2);
961 //p->drawRect(m - 1, h - r, 2, d);
962 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
963 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
964 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
965 break;
966 case Lanes::BOUNDARY:
967 //p->setBrush(back);
968 //p->drawEllipse(R_CENTER);
969 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
970 graphics.DrawEllipse(&myPen, R_CENTER);
971 break;
972 case Lanes::BOUNDARY_C:
973 case Lanes::BOUNDARY_R:
974 case Lanes::BOUNDARY_L:
975 //p->setBrush(back);
976 //p->drawRect(R_CENTER);
977 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
978 graphics.FillRectangle(&myBrush,R_CENTER);
979 break;
980 default:
981 break;
984 ::SelectObject(hdc,oldpen);
985 ::SelectObject(hdc,oldbrush);
986 #undef P_CENTER
987 #undef P_0
988 #undef P_90
989 #undef P_180
990 #undef P_270
991 #undef R_CENTER
994 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
996 // TODO: unfinished
997 // return;
998 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
999 if(data->m_CommitHash.IsEmpty())
1000 return;
1002 CRect rt=rect;
1003 LVITEM rItem = { 0 };
1004 rItem.mask = LVIF_STATE;
1005 rItem.iItem = static_cast<int>(index);
1006 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1007 GetItem(&rItem);
1009 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1011 if (data->m_Lanes.empty())
1012 m_logEntries.setLane(data->m_CommitHash);
1014 std::vector<int>& lanes=data->m_Lanes;
1015 size_t laneNum = lanes.size();
1016 UINT activeLane = 0;
1017 for (UINT i = 0; i < laneNum; ++i)
1018 if (Lanes::isMerge(lanes[i])) {
1019 activeLane = i;
1020 break;
1023 int x2 = 0;
1024 int maxWidth = rect.Width();
1025 int lw = 3 * rect.Height() / 4; //laneWidth()
1027 COLORREF activeColor = CTheme::Instance().GetThemeColor(m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1 + (activeLane % Lanes::COLORS_NUM))), true);
1029 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1031 int x1 = x2;
1032 x2 += lw;
1034 int ln = lanes[i];
1035 if (ln == Lanes::EMPTY)
1036 continue;
1038 COLORREF color = i == activeLane ? activeColor : CTheme::Instance().GetThemeColor(m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1 + (i % Lanes::COLORS_NUM))), true);
1039 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1042 #if 0
1043 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1044 int x1 = x2;
1045 x2 += lw;
1047 int ln = lanes[i];
1048 if (ln == Lanes::EMPTY)
1049 continue;
1051 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1052 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1054 if (ln == Lanes::CROSS)
1056 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1057 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1059 else
1060 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1062 #endif
1065 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1067 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1068 // Take the default processing unless we set this to something else below.
1069 *pResult = CDRF_DODEFAULT;
1071 if (m_bNoDispUpdates)
1072 return;
1074 switch (pLVCD->nmcd.dwDrawStage)
1076 case CDDS_PREPAINT:
1078 *pResult = CDRF_NOTIFYITEMDRAW;
1079 return;
1081 break;
1082 case CDDS_ITEMPREPAINT:
1084 // This is the prepaint stage for an item. Here's where we set the
1085 // item's text color.
1087 // Tell Windows to send draw notifications for each subitem.
1088 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1090 COLORREF crText = CTheme::Instance().IsDarkTheme() ? CTheme::darkTextColor : GetSysColor(COLOR_WINDOWTEXT);
1092 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1094 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1095 if (data)
1097 HGDIOBJ hGdiObj = nullptr;
1098 int action = data->GetRebaseAction();
1099 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1100 crText = RGB(128, 128, 128);
1102 if (action & LOGACTIONS_REBASE_SQUASH)
1103 pLVCD->clrTextBk = RGB(156, 156, 156);
1104 else if (action & LOGACTIONS_REBASE_EDIT)
1105 pLVCD->clrTextBk = CTheme::Instance().GetThemeColor(RGB(200, 200, 128));
1106 else
1107 pLVCD->clrTextBk = CTheme::Instance().IsDarkTheme() ? CTheme::darkBkColor : GetSysColor(COLOR_WINDOW);
1109 if (action & LOGACTIONS_REBASE_CURRENT)
1110 hGdiObj = m_boldFont.GetSafeHandle();
1112 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1113 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1114 if (isHeadHash && isHighlight)
1115 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1116 else if (isHeadHash)
1117 hGdiObj = m_boldFont.GetSafeHandle();
1118 else if (isHighlight)
1119 hGdiObj = m_FontItalics.GetSafeHandle();
1121 if (hGdiObj)
1123 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1124 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1127 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1128 // crText = GetSysColor(COLOR_GRAYTEXT);
1130 if (data->m_CommitHash.IsEmpty())
1132 //crText = GetSysColor(RGB(200,200,0));
1133 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1134 // We changed the font, so we're returning CDRF_NEWFONT. This
1135 // tells the control to recalculate the extent of the text.
1136 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1140 // Store the color back in the NMLVCUSTOMDRAW struct.
1141 pLVCD->clrText = crText;
1142 return;
1144 break;
1146 case CDDS_ITEMPREPAINT | CDDS_ITEM | CDDS_SUBITEM:
1148 switch (pLVCD->iSubItem)
1150 case LOGLIST_GRAPH:
1151 if ((m_ShowFilter & FILTERSHOW_MERGEPOINTS) && !m_LogFilter->IsFilterActive())
1153 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1155 CRect rect;
1156 GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_LABEL, rect);
1158 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1159 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1161 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1162 if( !data ->m_CommitHash.IsEmpty())
1163 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1165 *pResult = CDRF_SKIPDEFAULT;
1166 return;
1169 break;
1171 case LOGLIST_MESSAGE:
1172 // If the top index of list is changed, the position map of reference label is outdated.
1173 if (m_OldTopIndex != GetTopIndex())
1175 m_OldTopIndex = GetTopIndex();
1176 m_RefLabelPosMap.clear();
1179 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1181 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1183 auto hashMapSharedPtr = m_HashMap;
1184 const auto& hashMap = *hashMapSharedPtr;
1185 if ((hashMap.find(data->m_CommitHash) != hashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1187 CRect rect;
1188 GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_BOUNDS, rect);
1190 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1191 // not in FillBackGround method, because this only affected the message subitem
1192 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1193 return;
1195 int index = static_cast<int>(pLVCD->nmcd.dwItemSpec);
1196 int state = GetItemState(index, LVIS_SELECTED);
1197 int txtState = LISS_NORMAL;
1198 if (IsAppThemed() && GetHotItem() == static_cast<int>(index))
1200 if (state & LVIS_SELECTED)
1201 txtState = LISS_HOTSELECTED;
1202 else
1203 txtState = LISS_HOT;
1205 else if (state & LVIS_SELECTED)
1207 if (::GetFocus() == m_hWnd)
1208 txtState = LISS_SELECTED;
1209 else
1210 txtState = LISS_SELECTEDNOTFOCUS;
1213 CAutoThemeData hTheme;
1214 if (IsAppThemed())
1216 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1218 // make sure the column separator/border is not overpainted
1219 int borderWidth = 0;
1220 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
1221 InflateRect(&rect, -(2 * borderWidth), 0);
1224 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1225 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1226 else
1228 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1229 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1230 ::DeleteObject(brush);
1232 if (hTheme && txtState != LISS_NORMAL)
1234 CRect rt;
1235 // get rect of whole line
1236 GetItemRect(index, rt, LVIR_BOUNDS);
1237 CRect rect2 = rect;
1239 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1240 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1242 hTheme.CloseHandle();
1243 // END: extended redraw
1245 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec, rect);
1247 std::vector<REFLABEL> refsToShow;
1248 STRING_VECTOR remoteTrackingList;
1249 std::vector<CString>::const_iterator refListIt;
1250 std::vector<CString>::const_iterator refListItEnd;
1251 auto commitRefsIt = hashMap.find(data->m_CommitHash);
1252 if (commitRefsIt != hashMap.cend())
1254 refListIt = (*commitRefsIt).second.cbegin();
1255 refListItEnd = (*commitRefsIt).second.cend();
1257 for (; refListIt != refListItEnd; ++refListIt)
1259 REFLABEL refLabel;
1260 refLabel.color = RGB(255, 255, 255);
1261 refLabel.singleRemote = false;
1262 refLabel.hasTracking = false;
1263 refLabel.sameName = false;
1264 refLabel.name = CGit::GetShortName(*refListIt, &refLabel.refType);
1265 refLabel.fullName = *refListIt;
1267 switch (refLabel.refType)
1269 case CGit::REF_TYPE::LOCAL_BRANCH:
1271 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1272 continue;
1273 if (refLabel.name == m_CurrentBranch)
1274 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::CurrentBranch), true);
1275 else
1276 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::LocalBranch), true);
1278 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1279 CString pullRemote = trackingEntry.first;
1280 CString pullBranch = trackingEntry.second;
1281 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1283 CString defaultUpstream;
1284 defaultUpstream.Format(L"refs/remotes/%s/%s", static_cast<LPCTSTR>(pullRemote), static_cast<LPCTSTR>(pullBranch));
1285 refLabel.hasTracking = true;
1286 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1288 bool found = false;
1289 for (auto it2 = refListIt + 1; it2 != refListItEnd; ++it2)
1291 if (*it2 == defaultUpstream)
1293 found = true;
1294 break;
1298 if (found)
1300 bool sameName = pullBranch == refLabel.name;
1301 refsToShow.push_back(refLabel);
1302 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1303 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::RemoteBranch), true);
1304 if (m_bSymbolizeRefNames)
1306 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1308 refLabel.simplifiedName = L'/';
1309 if (sameName)
1310 refLabel.simplifiedName += L'≡';
1311 else
1312 refLabel.simplifiedName += pullBranch;
1313 refLabel.singleRemote = true;
1315 else if (sameName)
1316 refLabel.simplifiedName = pullRemote + L"/≡";
1317 refLabel.sameName = sameName;
1319 refLabel.fullName = defaultUpstream;
1320 refsToShow.push_back(refLabel);
1321 remoteTrackingList.push_back(defaultUpstream);
1322 continue;
1326 break;
1328 case CGit::REF_TYPE::REMOTE_BRANCH:
1330 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1331 continue;
1332 bool found = false;
1333 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1335 if (remoteTrackingList[j] == *refListIt)
1337 found = true;
1338 break;
1341 if (found)
1342 continue;
1344 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::RemoteBranch), true);
1345 if (m_bSymbolizeRefNames)
1347 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1349 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1350 refLabel.singleRemote = true;
1353 break;
1355 case CGit::REF_TYPE::ANNOTATED_TAG:
1356 [[fallthrough]];
1357 case CGit::REF_TYPE::TAG:
1358 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1359 continue;
1360 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::Tag), true);
1361 break;
1363 case CGit::REF_TYPE::STASH:
1364 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1365 continue;
1366 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::Stash), true);
1367 break;
1369 case CGit::REF_TYPE::BISECT_GOOD:
1370 [[fallthrough]];
1371 case CGit::REF_TYPE::BISECT_BAD:
1372 [[fallthrough]];
1373 case CGit::REF_TYPE::BISECT_SKIP:
1374 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1375 continue;
1376 refLabel.color = CTheme::Instance().GetThemeColor((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)), true);
1377 break;
1379 case CGit::REF_TYPE::NOTES:
1380 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1381 continue;
1382 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::NoteNode), true);
1383 break;
1385 default:
1386 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1387 continue;
1388 refLabel.color = CTheme::Instance().GetThemeColor(m_Colors.GetColor(CColors::OtherRef), true);
1389 break;
1391 refsToShow.push_back(refLabel);
1393 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1395 REFLABEL refLabel;
1396 refLabel.color = CTheme::Instance().GetThemeColor(RGB(246, 153, 253), true);
1397 refLabel.singleRemote = false;
1398 refLabel.hasTracking = false;
1399 refLabel.sameName = false;
1400 refLabel.name = L"super-project-pointer";
1401 refLabel.fullName = "";
1402 refsToShow.push_back(refLabel);
1405 if (refsToShow.empty())
1407 *pResult = CDRF_DODEFAULT;
1408 return;
1411 DrawTagBranchMessage(pLVCD, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1413 *pResult = CDRF_SKIPDEFAULT;
1414 return;
1416 else if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_SUBJECT | LOGFILTER_MESSAGES, pLVCD, pResult))//from here
1417 return;
1419 break;
1421 case LOGLIST_ACTION:
1423 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1425 *pResult = CDRF_DODEFAULT;
1426 return;
1428 *pResult = CDRF_DODEFAULT;
1430 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1431 return;
1433 int nIcons = 0;
1434 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1435 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1437 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1438 CRect rect;
1439 GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_BOUNDS, rect);
1440 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1441 // Get the selected state of the
1442 // item being drawn.
1444 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1445 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1447 // Fill the background if necessary
1448 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1450 // Draw the icon(s) into the compatible DC
1451 int action = pLogEntry->GetAction(this);
1452 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
1453 if (!pLogEntry->m_IsDiffFiles)
1455 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1456 *pResult = CDRF_SKIPDEFAULT;
1457 return;
1460 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1461 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1462 ++nIcons;
1464 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1465 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1466 ++nIcons;
1468 if (action & CTGitPath::LOGACTIONS_DELETED)
1469 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1470 ++nIcons;
1472 if (action & CTGitPath::LOGACTIONS_REPLACED)
1473 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1474 ++nIcons;
1476 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1477 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1478 ++nIcons;
1480 *pResult = CDRF_SKIPDEFAULT;
1481 return;
1484 case LOGLIST_HASH:
1485 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_REVS, pLVCD, pResult))
1486 return;
1487 break;
1489 case LOGLIST_AUTHOR:
1490 case LOGLIST_COMMIT_NAME:
1491 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_AUTHORS, pLVCD, pResult))
1492 return;
1493 break;
1495 case LOGLIST_EMAIL:
1496 case LOGLIST_COMMIT_EMAIL:
1497 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_EMAILS, pLVCD, pResult))
1498 return;
1499 break;
1501 case LOGLIST_BUG:
1502 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_BUGID, pLVCD, pResult))
1503 return;
1504 break;
1507 break;
1509 *pResult = CDRF_DODEFAULT;
1512 CString FindSVNRev(const CString& msg)
1516 const std::wsregex_iterator end;
1517 std::wstring s = msg;
1518 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1519 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1521 const std::wsmatch match = *it;
1522 if (match.size() == 4)
1524 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1525 return std::wstring(match[2]).c_str();
1528 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1529 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1531 const std::wsmatch match = *it;
1532 if (match.size() == 3)
1534 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1535 return std::wstring(match[1]).c_str();
1539 catch (std::exception&) {}
1541 return L"";
1544 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1546 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1547 return pLogEntry->GetSubject();
1549 CString txt(pLogEntry->GetSubject());
1550 txt += L' ';
1551 txt += pLogEntry->GetBody();
1553 // Deal with CRLF
1554 txt.Replace(L'\n', L' ');
1555 txt.Replace(L'\r', L' ');
1557 return txt;
1560 // CGitLogListBase message handlers
1562 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1564 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1566 // Create a pointer to the item
1567 LV_ITEM* pItem = &(pDispInfo)->item;
1569 // Do the list need text information?
1570 if (!(pItem->mask & LVIF_TEXT))
1571 return;
1573 // By default, clear text buffer.
1574 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1576 bool bOutOfRange = pItem->iItem >= static_cast<int>(m_arShownList.size());
1578 *pResult = 0;
1579 if (m_bNoDispUpdates || bOutOfRange)
1580 return;
1582 // Which item number?
1583 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1585 CString temp;
1586 if(m_IsOldFirst)
1587 temp.Format(L"%d", pItem->iItem + 1);
1588 else
1589 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1591 if (!pLogEntry)
1592 return;
1594 // Which column?
1595 switch (pItem->iSubItem)
1597 case LOGLIST_GRAPH: //Graphic
1598 break;
1599 case LOGLIST_REBASE:
1600 if (m_IsRebaseReplaceGraph)
1601 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1602 break;
1603 case LOGLIST_ACTION: //action -- no text in the column
1604 break;
1605 case LOGLIST_HASH:
1606 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1607 break;
1608 case LOGLIST_ID:
1609 if (this->m_IsIDReplaceAction)
1610 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1611 break;
1612 case LOGLIST_MESSAGE: //Message
1613 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(MessageDisplayStr(pLogEntry)), pItem->cchTextMax - 1);
1614 break;
1615 case LOGLIST_AUTHOR: //Author
1616 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(pLogEntry->GetAuthorName()), pItem->cchTextMax - 1);
1617 break;
1618 case LOGLIST_DATE: //Date
1619 if (!pLogEntry->m_CommitHash.IsEmpty())
1620 lstrcpyn(pItem->pszText,
1621 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1622 pItem->cchTextMax - 1);
1623 break;
1625 case LOGLIST_EMAIL:
1626 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(pLogEntry->GetAuthorEmail()), pItem->cchTextMax - 1);
1627 break;
1629 case LOGLIST_COMMIT_NAME: //Commit
1630 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(pLogEntry->GetCommitterName()), pItem->cchTextMax - 1);
1631 break;
1633 case LOGLIST_COMMIT_EMAIL: //Commit Email
1634 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(pLogEntry->GetCommitterEmail()), pItem->cchTextMax - 1);
1635 break;
1637 case LOGLIST_COMMIT_DATE: //Commit Date
1638 if (!pLogEntry->m_CommitHash.IsEmpty())
1639 lstrcpyn(pItem->pszText,
1640 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1641 pItem->cchTextMax - 1);
1642 break;
1643 case LOGLIST_BUG: //Bug ID
1644 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody())), pItem->cchTextMax - 1);
1645 break;
1646 case LOGLIST_SVNREV: //SVN revision
1647 lstrcpyn(pItem->pszText, static_cast<LPCTSTR>(FindSVNRev(pLogEntry->GetSubjectBody())), pItem->cchTextMax - 1);
1648 break;
1650 default:
1651 ASSERT(false);
1655 bool CGitLogListBase::IsOnStash(int index)
1657 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1658 if (IsStash(rev))
1659 return true;
1660 if (index > 0)
1662 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1663 if (IsStash(preRev))
1664 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1666 return false;
1669 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1671 auto hashMap = m_HashMap;
1672 const auto refList = hashMap.get()->find(pSelLogEntry->m_CommitHash);
1673 if (refList == hashMap.get()->cend())
1674 return false;
1675 return any_of((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; });
1678 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1680 auto hashMap = m_HashMap;
1681 const auto refList = hashMap->find(pSelLogEntry->m_CommitHash);
1682 if (refList == hashMap->cend())
1683 return false;
1684 return any_of((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); });
1687 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1689 if (pRev->m_ParentHash.empty() && !pRev->m_CommitHash.IsEmpty())
1691 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1692 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1694 parentHash = pRev->m_ParentHash;
1697 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1699 __super::OnContextMenu(pWnd, point);
1701 if (pWnd != this)
1702 return;
1704 int selIndex = GetSelectionMark();
1705 if (selIndex < 0)
1706 return; // nothing selected, nothing to do with a context menu
1708 // if the context menu is invoked through the keyboard, we have to use
1709 // a calculated position on where to anchor the menu on
1710 if ((point.x == -1) && (point.y == -1))
1712 CRect rect;
1713 GetItemRect(selIndex, &rect, LVIR_LABEL);
1714 ClientToScreen(&rect);
1715 point = rect.CenterPoint();
1717 m_nSearchIndex = selIndex;
1719 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1721 POSITION pos = GetFirstSelectedItemPosition();
1722 int FirstSelect = GetNextSelectedItem(pos);
1723 if (FirstSelect < 0)
1724 return;
1726 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1727 if (pSelLogEntry == nullptr)
1728 return;
1730 int LastSelect = -1;
1731 UINT selectedCount = 1;
1732 while (pos)
1734 LastSelect = GetNextSelectedItem(pos);
1735 ++selectedCount;
1738 ASSERT(GetSelectedCount() == selectedCount);
1740 //entry is selected, now show the popup menu
1741 CIconMenu popup;
1742 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1744 if (popup.CreatePopupMenu())
1746 CGitHash headHash;
1747 if (g_Git.GetHash(headHash, L"HEAD"))
1749 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1750 return;
1752 auto hashMapSharedPtr = m_HashMap;
1753 const auto& hashMap = *hashMapSharedPtr;
1754 bool isHeadCommit = (pSelLogEntry->m_CommitHash == headHash);
1755 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1756 CTGitPath workingTree(g_Git.m_CurrentDir);
1757 bool isMergeActive = workingTree.IsMergeActive();
1758 bool isBisectActive = workingTree.IsBisectActive();
1759 bool isStash = IsOnStash(FirstSelect);
1760 GIT_REV_LIST parentHash;
1761 GetParentHashes(pSelLogEntry, parentHash);
1762 STRING_VECTOR parentInfo;
1763 for (size_t i = 0; i < parentHash.size(); ++i)
1765 CString str;
1766 str.Format(IDS_PARENT, i + 1);
1767 GitRev rev;
1768 if (rev.GetCommit(parentHash[i].ToString()) == 0)
1770 CString commitTitle = rev.GetSubject();
1771 if (commitTitle.GetLength() > 20)
1773 commitTitle.Truncate(20);
1774 commitTitle += L"...";
1776 str.AppendFormat(L": \"%s\" (%s)", static_cast<LPCTSTR>(commitTitle), static_cast<LPCTSTR>(parentHash[i].ToString(g_Git.GetShortHASHLength())));
1778 else
1779 str.AppendFormat(L" (%s)", static_cast<LPCTSTR>(parentHash[i].ToString(g_Git.GetShortHASHLength())));
1780 parentInfo.push_back(str);
1783 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1784 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1786 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))
1787 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1789 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1790 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1792 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1793 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1795 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)))
1796 popup.AppendMenu(MF_SEPARATOR, NULL);
1798 if (selectedCount == 1)
1801 bool requiresSeparator = false;
1802 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1804 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1806 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1807 requiresSeparator = true;
1810 else
1812 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1814 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1815 requiresSeparator = true;
1817 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1819 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1820 requiresSeparator = true;
1824 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1826 if (parentHash.size() == 1)
1828 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1829 requiresSeparator = true;
1831 else if (parentHash.size() > 1)
1833 blamemenu.CreatePopupMenu();
1834 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1835 for (size_t i = 0; i < parentInfo.size(); ++i)
1837 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS + ((i + 1) << 16), parentInfo[i]);
1839 requiresSeparator = true;
1843 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1845 if (parentHash.size() == 1)
1847 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1848 requiresSeparator = true;
1850 else if (parentHash.size() > 1)
1852 gnudiffmenu.CreatePopupMenu();
1853 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1855 gnudiffmenu.AppendMenuIcon(static_cast<UINT_PTR>(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1856 gnudiffmenu.AppendMenuIcon(static_cast<UINT_PTR>(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1857 gnudiffmenu.AppendMenuIcon(static_cast<UINT_PTR>(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1859 for (size_t i = 0; i < parentInfo.size(); ++i)
1861 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1 + ((i + 1) << 16), parentInfo[i]);
1863 requiresSeparator = true;
1867 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1869 if (parentHash.size() == 1)
1871 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1872 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE) && m_ColumnRegKey != L"reflog")
1873 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1874 requiresSeparator = true;
1876 else if (parentHash.size() > 1)
1878 diffmenu.CreatePopupMenu();
1879 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1880 for (size_t i = 0; i < parentInfo.size(); ++i)
1882 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16), parentInfo[i]);
1883 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE) && m_ColumnRegKey != L"reflog")
1885 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1886 diffmenu.SetDefaultItem(static_cast<UINT>(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1889 requiresSeparator = true;
1893 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1895 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1896 requiresSeparator = true;
1899 if (requiresSeparator)
1901 popup.AppendMenu(MF_SEPARATOR, NULL);
1902 requiresSeparator = false;
1905 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1907 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1909 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_SHELVE);
1910 requiresSeparator = true;
1914 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1916 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1918 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_UNSHELVE);
1919 requiresSeparator = true;
1922 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1924 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1925 requiresSeparator = true;
1929 if (requiresSeparator)
1931 popup.AppendMenu(MF_SEPARATOR, NULL);
1932 requiresSeparator = false;
1935 if (isBisectActive)
1937 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1938 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1940 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1941 requiresSeparator = true;
1944 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1946 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1947 requiresSeparator = true;
1949 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1951 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1952 requiresSeparator = true;
1956 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1958 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1960 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1961 requiresSeparator = true;
1965 if (requiresSeparator)
1967 popup.AppendMenu(MF_SEPARATOR, NULL);
1968 requiresSeparator = false;
1971 if (pSelLogEntry->m_CommitHash.IsEmpty())
1973 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
1974 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
1976 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
1977 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_UPDATE);
1979 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
1980 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
1982 popup.AppendMenu(MF_SEPARATOR, NULL);
1984 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
1985 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
1987 popup.AppendMenu(MF_SEPARATOR, NULL);
1991 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
1992 // {
1993 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
1994 // }
1995 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
1996 // {
1997 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
1998 // }
1999 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2000 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2001 // {
2002 // popup.AppendMenu(MF_SEPARATOR, NULL);
2003 // }
2005 CString str;
2006 //if (m_hasWC)
2007 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2009 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2011 if (m_ContextMenuMask & GetContextMenuBit(ID_LOG))
2013 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2014 if (m_ColumnRegKey == L"reflog")
2015 popup.SetDefaultItem(ID_LOG, FALSE);
2018 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2019 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2021 str.Format(IDS_LOG_POPUP_MERGEREV, static_cast<LPCTSTR>(g_Git.GetCurrentBranch()));
2023 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2025 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2027 size_t index = static_cast<size_t>(-1);
2028 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2029 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2030 popup.SetMenuItemData(ID_MERGEREV, reinterpret_cast<LONG_PTR>(&hashMap.find(pSelLogEntry->m_CommitHash)->second[index]));
2033 str.Format(IDS_RESET_TO_THIS_FORMAT, static_cast<LPCTSTR>(g_Git.GetCurrentBranch()));
2035 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2036 popup.AppendMenuIcon(ID_RESET, str, IDI_RESET);
2039 // Add Switch Branch express Menu
2040 if (hashMap.find(pSelLogEntry->m_CommitHash) != hashMap.end()
2041 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2044 std::vector<const CString*> branchs;
2045 auto addCheck = [&](const CString& ref)
2047 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2048 return;
2049 branchs.push_back(&ref);
2051 size_t index = static_cast<size_t>(-1);
2052 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2053 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2054 addCheck(hashMap.find(pSelLogEntry->m_CommitHash)->second[index]);
2055 else
2056 for_each(hashMap.find(pSelLogEntry->m_CommitHash)->second, addCheck);
2058 CString str2;
2059 str2.LoadString(IDS_SWITCH_BRANCH);
2061 if(branchs.size() == 1)
2063 str2 += L' ';
2064 str2 += L'"' + branchs[0]->Mid(static_cast<int>(wcslen(L"refs/heads/"))) + L'"';
2065 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2067 popup.SetMenuItemData(ID_SWITCHBRANCH, reinterpret_cast<LONG_PTR>(branchs[0]));
2070 else if(branchs.size() > 1)
2072 subbranchmenu.CreatePopupMenu();
2073 for (size_t i = 0 ; i < branchs.size(); ++i)
2075 if (*branchs[i] != currentBranch)
2077 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH + (i << 16), branchs[i]->Mid(static_cast<int>(wcslen(L"refs/heads/"))));
2078 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), reinterpret_cast<LONG_PTR>(branchs[i]));
2082 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2086 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2088 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2089 size_t index = static_cast<size_t>(-1);
2090 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2091 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2092 popup.SetMenuItemData(ID_SWITCHTOREV, reinterpret_cast<LONG_PTR>(&hashMap.find(pSelLogEntry->m_CommitHash)->second[index]));
2095 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2097 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2099 size_t index = static_cast<size_t>(-1);
2100 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2101 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2102 popup.SetMenuItemData(ID_CREATE_BRANCH, reinterpret_cast<LONG_PTR>(&hashMap.find(pSelLogEntry->m_CommitHash)->second[index]));
2105 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2106 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2108 str.Format(IDS_REBASE_THIS_FORMAT, static_cast<LPCTSTR>(g_Git.GetCurrentBranch()));
2110 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2111 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2112 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2114 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2115 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2117 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2119 if (parentHash.size() == 1)
2120 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2121 else if (parentHash.size() > 1)
2123 revertmenu.CreatePopupMenu();
2124 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2126 for (size_t i = 0; i < parentInfo.size(); ++i)
2128 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), parentInfo[i]);
2133 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2134 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2136 popup.AppendMenu(MF_SEPARATOR, NULL);
2140 if(!pSelLogEntry->m_Ref.IsEmpty())
2142 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2143 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2144 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_UNSHELVE);
2145 if (selectedCount <= 2)
2146 popup.AppendMenu(MF_SEPARATOR, NULL);
2149 if (selectedCount >= 2)
2151 bool bAddSeparator = false;
2152 if ((selectedCount == 2) || IsSelectionContinuous())
2154 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2156 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2157 bAddSeparator = true;
2161 if (selectedCount == 2)
2163 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2165 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2166 bAddSeparator = true;
2169 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2171 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString(g_Git.GetShortHASHLength());
2172 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2173 CString lastSelHash = pLastEntry->m_CommitHash.ToString(g_Git.GetShortHASHLength());
2174 CString menu;
2175 menu.Format(IDS_SHOWLOG_OF, static_cast<LPCTSTR>(lastSelHash + L".." + firstSelHash));
2176 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2177 menu.Format(IDS_SHOWLOG_OF, static_cast<LPCTSTR>(lastSelHash + L"..." + firstSelHash));
2178 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2179 bAddSeparator = true;
2183 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2185 bAddSeparator = true;
2186 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2189 if (bAddSeparator)
2191 popup.AppendMenu(MF_SEPARATOR, NULL);
2192 bAddSeparator = false;
2195 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2196 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2198 if (bAddSeparator)
2199 popup.AppendMenu(MF_SEPARATOR, NULL);
2202 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2204 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2205 popup.AppendMenu(MF_SEPARATOR, NULL);
2208 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2210 bool bAddSeparator = false;
2211 if (selectedCount >= 2 && IsSelectionContinuous())
2213 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2215 int headindex = this->GetHeadIndex();
2216 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2218 CString head;
2219 head.Format(L"HEAD~%d", FirstSelect - headindex);
2220 CGitHash hashFirst;
2221 int ret = g_Git.GetHash(hashFirst, head);
2222 head.Format(L"HEAD~%d",LastSelect-headindex);
2223 CGitHash hash;
2224 ret = ret || g_Git.GetHash(hash, head);
2225 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2226 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2227 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2229 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2230 bAddSeparator = true;
2235 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2236 if (selectedCount >= 2)
2237 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_PICK);
2238 else
2239 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_PICK);
2240 bAddSeparator = true;
2243 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2244 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2245 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2246 bAddSeparator = true;
2249 if (bAddSeparator)
2250 popup.AppendMenu(MF_SEPARATOR, NULL);
2253 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2255 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2256 popup.AppendMenu(MF_SEPARATOR, NULL);
2259 if (selectedCount == 1)
2261 bool bAddSeparator = false;
2262 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && hashMap.find(pSelLogEntry->m_CommitHash) != hashMap.cend()) || showExtendedMenu))
2264 // show the push-option only if the log entry has an associated local branch
2265 bool isLocal = hashMap.find(pSelLogEntry->m_CommitHash) != hashMap.cend() && any_of(hashMap.find(pSelLogEntry->m_CommitHash)->second, [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); });
2266 if (isLocal || showExtendedMenu)
2268 CString str;
2269 str.LoadString(IDS_MENUPUSH);
2271 CString branch;
2272 size_t index = static_cast<size_t>(-1);
2273 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2274 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, &branch, &index))
2275 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2276 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2278 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2280 if (auto refList = hashMap.find(pSelLogEntry->m_CommitHash); index != static_cast<size_t>(-1) && index < refList->second.size())
2281 popup.SetMenuItemData(ID_PUSH, reinterpret_cast<LONG_PTR>(&refList->second[index]));
2283 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2284 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2286 bAddSeparator = true;
2289 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2291 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2292 bAddSeparator = true;
2296 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2298 if (auto refList = hashMap.find(pSelLogEntry->m_CommitHash); refList != hashMap.end() )
2300 std::vector<const CString*> branchs;
2301 auto addCheck = [&](const CString& ref)
2303 if (ref == currentBranch)
2304 return;
2305 branchs.push_back(&ref);
2307 size_t index = static_cast<size_t>(-1);
2308 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2309 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2310 addCheck(refList->second[index]);
2311 else
2312 for_each(refList->second, addCheck);
2314 CString str;
2315 if (branchs.size() == 1)
2317 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2318 str += L' ';
2319 str += *branchs[0];
2320 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2321 popup.SetMenuItemData(ID_DELETE, reinterpret_cast<LONG_PTR>(branchs[0]));
2322 bAddSeparator = true;
2324 else if (branchs.size() > 1)
2326 str.LoadString(IDS_DELETE_BRANCHTAG);
2327 submenu.CreatePopupMenu();
2328 for (size_t i = 0; i < branchs.size(); ++i)
2330 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2331 submenu.SetMenuItemData(ID_DELETE + (i << 16), reinterpret_cast<LONG_PTR>(branchs[i]));
2333 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2334 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), reinterpret_cast<LONG_PTR>(MAKEINTRESOURCE(IDS_ALL)));
2336 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2337 bAddSeparator = true;
2340 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2341 if (bAddSeparator)
2342 popup.AppendMenu(MF_SEPARATOR, NULL);
2343 } // selectedCount == 1
2345 CIconMenu clipSubMenu;
2346 if (!clipSubMenu.CreatePopupMenu())
2347 return;
2348 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD) && m_ColumnRegKey != L"reflog")
2350 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2351 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2352 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2353 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2354 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2355 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2356 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2357 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2358 if (hashMap.find(pSelLogEntry->m_CommitHash) != hashMap.cend() && selectedCount == 1)
2360 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2361 size_t index = static_cast<size_t>(-1);
2362 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2363 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, hashMap, nullptr, &index))
2364 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, reinterpret_cast<LONG_PTR>(&hashMap.find(pSelLogEntry->m_CommitHash)->second[index]));
2367 CString temp;
2368 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2369 popup.InsertMenu(static_cast<UINT>(-1), MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(clipSubMenu.m_hMenu), temp);
2371 else if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD) && m_ColumnRegKey == L"reflog")
2373 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2374 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2375 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2377 CString temp;
2378 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2379 popup.InsertMenu(static_cast<UINT>(-1), MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(clipSubMenu.m_hMenu), temp);
2382 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2383 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2385 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2386 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2388 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2389 // DialogEnableWindow(IDOK, FALSE);
2390 // SetPromptApp(&theApp);
2392 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup, hashMap);
2394 // EnableOKButton();
2395 } // if (popup.CreatePopupMenu())
2398 bool CGitLogListBase::IsSelectionContinuous()
2400 if ( GetSelectedCount()==1 )
2402 // if only one revision is selected, the selection is of course
2403 // continuous
2404 return true;
2407 POSITION pos = GetFirstSelectedItemPosition();
2408 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2409 if (bContinuous)
2411 int itemindex = GetNextSelectedItem(pos);
2412 while (pos)
2414 int nextindex = GetNextSelectedItem(pos);
2415 if (nextindex - itemindex > 1)
2417 bContinuous = false;
2418 break;
2420 itemindex = nextindex;
2423 return bContinuous;
2426 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2428 CString sClipdata;
2429 POSITION pos = GetFirstSelectedItemPosition();
2430 if (pos)
2432 CString sRev;
2433 sRev.LoadString(IDS_LOG_REVISION);
2434 CString sAuthor;
2435 sAuthor.LoadString(IDS_LOG_AUTHOR);
2436 CString sDate;
2437 sDate.LoadString(IDS_LOG_DATE);
2438 CString sMessage;
2439 sMessage.LoadString(IDS_LOG_MESSAGE);
2440 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2441 bool first = true;
2442 while (pos)
2444 CString sLogCopyText;
2445 CString sPaths;
2446 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2448 if (toCopy == ID_COPYCLIPBOARDFULL)
2450 sPaths = L"----\r\n";
2451 auto files = pLogEntry->GetFiles(nullptr);
2452 for (int cpPathIndex = 0; cpPathIndex < files.GetCount(); ++cpPathIndex)
2454 auto& file = files[cpPathIndex];
2455 sPaths += file.GetActionName() + L": " + file.GetGitPathString();
2456 if (file.m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !file.GetGitOldPathString().IsEmpty())
2458 sPaths += L' ';
2459 sPaths.AppendFormat(from, static_cast<LPCTSTR>(file.GetGitOldPathString()));
2461 sPaths += L"\r\n";
2463 sPaths.Trim();
2464 sPaths += L"\r\n";
2467 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2469 CString sNotesTags;
2470 if (!pLogEntry->m_Notes.IsEmpty())
2472 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2473 sNotesTags += L":\n";
2474 sNotesTags += pLogEntry->m_Notes;
2475 sNotesTags.Replace(L"\n", L"\r\n");
2477 CString tagInfo = GetTagInfo(pLogEntry);
2478 if (!tagInfo.IsEmpty())
2480 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2481 tagInfo.Replace(L"\n", L"\r\n");
2482 sNotesTags += tagInfo;
2485 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",
2486 static_cast<LPCTSTR>(sRev), static_cast<LPCTSTR>(pLogEntry->m_CommitHash.ToString()),
2487 static_cast<LPCTSTR>(sAuthor), static_cast<LPCTSTR>(pLogEntry->GetAuthorName()), static_cast<LPCTSTR>(pLogEntry->GetAuthorEmail()),
2488 static_cast<LPCTSTR>(sDate),
2489 static_cast<LPCTSTR>(CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes)),
2490 static_cast<LPCTSTR>(sMessage), static_cast<LPCTSTR>(pLogEntry->GetSubjectBody(true)),
2491 static_cast<LPCTSTR>(sNotesTags),
2492 static_cast<LPCTSTR>(sPaths));
2493 sClipdata += sLogCopyText;
2495 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2497 if (!first)
2498 sClipdata += L"\r\n";
2499 sClipdata += pLogEntry->GetAuthorName();
2500 sClipdata += L" <";
2501 sClipdata += pLogEntry->GetAuthorEmail();
2502 sClipdata += L">";
2504 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2506 if (!first)
2507 sClipdata += L"\r\n";
2508 sClipdata += pLogEntry->GetAuthorName();
2510 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2512 if (!first)
2513 sClipdata += L"\r\n";
2514 sClipdata += pLogEntry->GetAuthorEmail();
2517 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2519 sClipdata += L"* ";
2520 sClipdata += pLogEntry->GetSubjectBody(true);
2521 sClipdata += L"\r\n\r\n";
2523 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2525 sClipdata += L"* ";
2526 sClipdata += pLogEntry->GetSubject().Trim();
2527 sClipdata += L"\r\n\r\n";
2529 else
2531 if (!first)
2532 sClipdata += L"\r\n";
2533 sClipdata += pLogEntry->m_CommitHash.ToString();
2536 first = false;
2538 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2542 void CGitLogListBase::DiffSelectedRevWithPrevious()
2544 if (s_bThreadRunning)
2545 return;
2547 POSITION pos = GetFirstSelectedItemPosition();
2548 auto FirstSelect = GetNextSelectedItem(pos);
2549 int LastSelect = -1;
2550 while (pos)
2551 LastSelect = GetNextSelectedItem(pos);
2553 auto hashMap = m_HashMap;
2554 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr, *hashMap.get());
2557 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2559 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2560 *pResult = -1;
2562 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2563 return;
2564 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= static_cast<int>(m_arShownList.size()))
2565 return;
2566 if (!pFindInfo->lvfi.psz)
2567 return;
2568 #if 0
2569 CString sCmp = pFindInfo->lvfi.psz;
2570 CString sRev;
2571 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2573 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2574 sRev.Format(L"%ld", pLogEntry->Rev);
2575 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2577 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2579 *pResult = i;
2580 return;
2583 else
2585 if (sCmp.Compare(sRev)==0)
2587 *pResult = i;
2588 return;
2592 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2594 for (int i=0; i<pFindInfo->iStart; ++i)
2596 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2597 sRev.Format(L"%ld", pLogEntry->Rev);
2598 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2600 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2602 *pResult = i;
2603 return;
2606 else
2608 if (sCmp.Compare(sRev)==0)
2610 *pResult = i;
2611 return;
2616 #endif
2617 *pResult = -1;
2620 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2622 ClearText();
2624 this->m_arShownList.SafeRemoveAll();
2626 this->m_logEntries.ClearAll();
2627 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2628 return -1;
2630 SetItemCountEx(static_cast<int>(m_logEntries.size()));
2632 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2634 if(m_IsOldFirst)
2635 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2636 else
2637 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2640 m_critSec.Lock();
2641 std::for_each(m_arShownList.begin(), m_arShownList.end(), [](auto entry) { entry->m_CallDiffAsync = DiffAsync; });
2642 m_critSec.Unlock();
2644 ReloadHashMap();
2646 if(path)
2647 m_Path=*path;
2648 return 0;
2651 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2653 ClearText();
2655 m_arShownList.SafeRemoveAll();
2657 m_logEntries.ClearAll();
2658 if (m_logEntries.Fill(hashes))
2659 return -1;
2661 SetItemCountEx(static_cast<int>(m_logEntries.size()));
2663 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2665 if (m_IsOldFirst)
2666 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2667 else
2668 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2671 m_critSec.Lock();
2672 std::for_each(m_arShownList.begin(), m_arShownList.end(), [](auto entry) { entry->m_CallDiffAsync = DiffAsync; });
2673 m_critSec.Unlock();
2675 ReloadHashMap();
2677 return 0;
2680 int CGitLogListBase::BeginFetchLog()
2682 ATLASSERT(IsInWorkingThread());
2683 ClearText();
2685 this->m_arShownList.SafeRemoveAll();
2687 this->m_logEntries.ClearAll();
2689 this->m_LogCache.ClearAllParent();
2691 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2693 CTGitPath *path;
2694 if(this->m_Path.IsEmpty())
2695 path = nullptr;
2696 else
2697 path=&this->m_Path;
2699 int mask = CGit::LOG_INFO_ONLY_HASH;
2700 if (m_bIncludeBoundaryCommits)
2701 mask |= CGit::LOG_INFO_BOUNDARY;
2702 // if(this->m_bAllBranch)
2703 mask |= m_ShowMask ;
2705 if(m_bShowWC)
2707 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2708 ResetWcRev();
2709 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2712 CString range;
2714 Locker lock(m_critSec);
2715 range = m_sRange;
2717 if (range.IsEmpty())
2718 range = L"HEAD";
2720 // follow does not work for directories
2721 if (!path || path->IsDirectory())
2722 mask &= ~CGit::LOG_INFO_FOLLOW;
2723 // follow does not work with all branches 8at least in TGit)
2724 if (mask & CGit::LOG_INFO_FOLLOW)
2725 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2727 CString cmd = g_Git.GetLogCmd(range, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2729 PostMessage(LVM_SETITEMCOUNT, m_logEntries.size(), LVSICF_NOINVALIDATEALL);
2733 CAutoLocker lock(g_Git.m_critGitDllSec);
2734 g_Git.CheckAndInitDll();
2736 catch (char* msg)
2738 CString err(msg);
2739 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2740 return -1;
2743 if (!g_Git.CanParseRev(range))
2745 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2746 return 0;
2748 // if show all branches, pick any ref as dummy entry ref
2749 STRING_VECTOR list;
2750 if (g_Git.GetRefList(list))
2751 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2752 if (list.empty())
2753 return 0;
2755 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2758 g_Git.m_critGitDllSec.Lock();
2759 try {
2760 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetUTF8(cmd)))
2762 g_Git.m_critGitDllSec.Unlock();
2763 return -1;
2766 catch (char* msg)
2768 g_Git.m_critGitDllSec.Unlock();
2769 CString err(msg);
2770 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2771 return -1;
2773 g_Git.m_critGitDllSec.Unlock();
2775 return 0;
2778 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2780 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2782 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2784 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2786 DiffSelectedRevWithPrevious();
2787 return TRUE;
2790 #if 0
2791 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2793 DiffSelectedFile();
2794 return TRUE;
2796 #endif
2798 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2800 // select all entries
2801 for (int i=0; i<GetItemCount(); ++i)
2802 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2803 return TRUE;
2806 #if 0
2807 if (m_hAccel && !bSkipAccelerator)
2809 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2810 if (ret)
2811 return TRUE;
2814 #endif
2815 //m_tooltips.RelayEvent(pMsg);
2816 return __super::PreTranslateMessage(pMsg);
2819 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2821 // a double click on an entry in the revision list has happened
2822 *pResult = 0;
2824 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2825 DiffSelectedRevWithPrevious();
2828 void CGitLogListBase::FetchLogAsync(void* data)
2830 ReloadHashMap();
2831 m_ProcData=data;
2832 StartLoadingThread();
2835 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2837 return static_cast<CGitLogListBase*>(pVoid)->LogThread();
2840 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2842 //CTime time;
2843 oldest=CTime::GetCurrentTime();
2844 latest=CTime(1971,1,2,0,0,0);
2845 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2847 if(m_logEntries[i].IsEmpty())
2848 continue;
2850 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2851 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2853 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2854 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2858 if(latest<oldest)
2859 latest=oldest;
2862 UINT CGitLogListBase::LogThread()
2864 ::PostMessage(this->GetParent()->m_hWnd, MSG_LOAD_PERCENTAGE, GITLOG_START, 0);
2866 ULONGLONG t1,t2;
2868 if(BeginFetchLog())
2870 InterlockedExchange(&s_bThreadRunning, FALSE);
2871 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2873 return 1;
2876 // create a copy we can safely work on in this thread
2877 auto shared_filter(m_LogFilter);
2878 const auto& filter = *shared_filter;
2880 TRACE(L"\n===Begin===\n");
2881 //Update work copy item;
2883 if (!m_logEntries.empty())
2885 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2887 m_arShownList.SafeAdd(pRev);
2891 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2893 // store commit number of the last selected commit/line before the refresh or -1
2894 int lastSelectedHashNItem = -1;
2895 if (m_lastSelectedHash.IsEmpty())
2896 lastSelectedHashNItem = 0;
2898 int ret = 0;
2900 bool shouldWalk = true;
2901 CString range;
2903 Locker lock(m_critSec);
2904 range = m_sRange;
2906 if (!g_Git.CanParseRev(range))
2908 // walk revisions if show all branches and there exists any ref
2909 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2910 shouldWalk = false;
2911 else
2913 STRING_VECTOR list;
2914 if (g_Git.GetRefList(list))
2915 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2916 if (list.empty())
2917 shouldWalk = false;
2921 if (shouldWalk)
2923 g_Git.m_critGitDllSec.Lock();
2924 if (!m_DllGitLog)
2926 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2927 g_Git.m_critGitDllSec.Unlock();
2928 InterlockedExchange(&s_bThreadRunning, FALSE);
2929 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2930 return 1;
2932 int total = 0;
2935 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2936 total = git_get_log_estimate_commit_count(m_DllGitLog);
2938 catch (char* msg)
2940 CString err(msg);
2941 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2942 ret = -1;
2944 g_Git.m_critGitDllSec.Unlock();
2946 if (CGitMailmap::ShouldLoadMailmap())
2947 GitRevLoglist::s_Mailmap = std::make_shared<CGitMailmap>();
2948 else if (GitRevLoglist::s_Mailmap)
2949 GitRevLoglist::s_Mailmap = nullptr;
2950 auto mailmap = GitRevLoglist::s_Mailmap;
2952 auto hashMapSharedPtr = m_HashMap;
2953 const auto& hashMap = *hashMapSharedPtr;
2955 GIT_COMMIT commit;
2956 t2 = t1 = GetTickCount64();
2957 int oldprecentage = 0;
2958 size_t oldsize = m_logEntries.size();
2959 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2960 while (ret== 0 && !m_bExitThread)
2962 g_Git.m_critGitDllSec.Lock();
2965 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2967 catch (char* msg)
2969 g_Git.m_critGitDllSec.Unlock();
2970 CString err(msg);
2971 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2972 break;
2975 if(ret)
2977 g_Git.m_critGitDllSec.Unlock();
2978 if (ret != -2) // other than end of revision walking
2979 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2980 break;
2983 if (commit.m_ignore == 1)
2985 git_free_commit(&commit);
2986 g_Git.m_critGitDllSec.Unlock();
2987 continue;
2990 //printf("%s\r\n",commit.GetSubject());
2991 if(m_bExitThread)
2993 git_free_commit(&commit);
2994 g_Git.m_critGitDllSec.Unlock();
2995 break;
2998 CGitHash hash = CGitHash::FromRaw(commit.m_hash);
3000 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3001 pRev->Parse(&commit, mailmap.get()); // better parse here than on GITLOG_END in LogDlg::OnLogListLoading for updating the DateSelectors
3003 char* note = nullptr;
3006 git_get_notes(commit.m_hash, &note);
3008 catch (char* msg)
3010 g_Git.m_critGitDllSec.Unlock();
3011 CString err(msg);
3012 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3013 break;
3016 if(note)
3018 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3019 free(note);
3020 note = nullptr;
3022 git_free_commit(&commit);
3023 g_Git.m_critGitDllSec.Unlock();
3025 if(!pRev->m_IsDiffFiles)
3027 pRev->m_CallDiffAsync = DiffAsync;
3030 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3032 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3034 const CGitHash &parentHash = pRev->m_ParentHash[i];
3035 auto it = commitChildren.find(parentHash);
3036 if (it == commitChildren.end())
3037 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3038 it->second.insert(pRev->m_CommitHash);
3042 #ifdef DEBUG
3043 //pRev->DbgPrint();
3044 #endif
3046 bool visible = filter(pRev, this, hashMap);
3047 if (visible && !ShouldShowFilter(pRev, commitChildren, hashMap))
3048 visible = false;
3049 this->m_critSec.Lock();
3050 m_logEntries.append(hash, visible);
3051 if (visible)
3052 m_arShownList.push_back(pRev); // push_back is ok here, because we use the very same lock, otherwise use SafeAdd
3053 this->m_critSec.Unlock();
3055 if (!visible)
3056 continue;
3058 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3059 lastSelectedHashNItem = static_cast<int>(m_arShownList.size()) - 1;
3061 t2 = GetTickCount64();
3063 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3065 //update UI
3066 int percent = static_cast<int>(m_logEntries.size() * 100 / (total + 1));
3067 if(percent > 99)
3068 percent =99;
3069 if (percent <= GITLOG_START)
3070 percent = GITLOG_START +1;
3072 oldsize = m_logEntries.size();
3073 PostMessage(LVM_SETITEMCOUNT, this->m_logEntries.size(), LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3075 if (percent > oldprecentage)
3077 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE, percent, 0);
3078 oldprecentage = percent;
3081 if (lastSelectedHashNItem >= 0)
3082 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3084 t1 = t2;
3087 g_Git.m_critGitDllSec.Lock();
3088 git_close_log(m_DllGitLog);
3089 g_Git.m_critGitDllSec.Unlock();
3092 if (m_bExitThread)
3094 InterlockedExchange(&s_bThreadRunning, FALSE);
3095 return 0;
3098 //Update UI;
3099 PostMessage(LVM_SETITEMCOUNT, this->m_logEntries.size(), LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3101 if (lastSelectedHashNItem >= 0)
3102 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3104 if (this->m_hWnd)
3105 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE, GITLOG_END, 0);
3107 InterlockedExchange(&s_bThreadRunning, FALSE);
3109 return 0;
3112 void CGitLogListBase::FetchRemoteList()
3114 STRING_VECTOR remoteList;
3115 m_SingleRemote.Empty();
3116 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3117 m_SingleRemote = remoteList[0];
3120 void CGitLogListBase::FetchTrackingBranchList()
3122 m_TrackingMap.clear();
3123 auto hashMap = m_HashMap;
3124 for (auto it = hashMap->cbegin(); it != hashMap->cend(); ++it)
3126 for (const auto& ref : it->second)
3128 CString branchName;
3129 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3131 CString pullRemote, pullBranch;
3132 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3133 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3134 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3140 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3142 SafeTerminateThread();
3144 this->SetItemCountEx(0);
3145 this->Clear();
3147 ResetWcRev();
3149 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3151 //Update branch and Tag info
3152 ReloadHashMap();
3153 if (m_pFindDialog)
3154 m_pFindDialog->RefreshList();
3155 //Assume Thread have exited
3156 //if(!s_bThreadRunning)
3158 m_logEntries.clear();
3160 if (IsCleanFilter)
3161 m_LogFilter = std::make_shared<CLogDlgFilter>();
3163 SafeTerminateAsyncDiffThread();
3164 m_AsynDiffListLock.Lock();
3165 m_AsynDiffList.clear();
3166 m_AsynDiffListLock.Unlock();
3167 StartAsyncDiffThread();
3169 StartLoadingThread();
3173 void CGitLogListBase::StartAsyncDiffThread()
3175 if (m_AsyncThreadExit)
3176 return;
3177 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3178 return;
3179 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL, 0, CREATE_SUSPENDED);
3180 if (!m_DiffingThread)
3182 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3183 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3184 return;
3186 m_DiffingThread->m_bAutoDelete = FALSE;
3187 m_DiffingThread->ResumeThread();
3190 void CGitLogListBase::StartLoadingThread()
3192 if (InterlockedExchange(&s_bThreadRunning, TRUE) != FALSE)
3193 return;
3194 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3195 InterlockedExchange(&m_bExitThread, FALSE);
3196 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST, 0, CREATE_SUSPENDED);
3197 if (!m_LoadingThread)
3199 InterlockedExchange(&s_bThreadRunning, FALSE);
3200 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3201 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3202 return;
3204 m_LoadingThread->m_bAutoDelete = FALSE;
3205 m_LoadingThread->ResumeThread();
3208 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren, const MAP_HASH_NAME& hashMap)
3210 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3211 return true;
3213 if ((m_ShowFilter & FILTERSHOW_REFS) && hashMap.find(pRev->m_CommitHash) != hashMap.cend())
3215 // Keep all refs.
3216 const auto& refList = hashMap.find(pRev->m_CommitHash)->second;
3217 for (size_t i = 0; i < refList.size(); ++i)
3219 const CString &str = refList[i];
3220 if (CStringUtils::StartsWith(str, L"refs/heads/"))
3222 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3223 return true;
3225 else if (CStringUtils::StartsWith(str, L"refs/remotes/"))
3227 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3228 return true;
3230 else if (CStringUtils::StartsWith(str, L"refs/tags/"))
3232 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3233 return true;
3235 else if (CStringUtils::StartsWith(str, L"refs/stash"))
3237 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3238 return true;
3240 else if (CStringUtils::StartsWith(str, L"refs/bisect/"))
3242 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3243 return true;
3246 // Keep the head too.
3247 if (pRev->m_CommitHash == m_HeadHash)
3248 return true;
3251 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3253 if (pRev->ParentsCount() > 1)
3254 return true;
3255 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3256 if (childrenIt != commitChildren.end())
3258 const std::unordered_set<CGitHash> &children = childrenIt->second;
3259 if (children.size() > 1)
3260 return true;
3263 return false;
3266 void CGitLogListBase::ShowGraphColumn(bool bShow)
3268 // HACK to hide graph column
3269 if (bShow)
3270 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3271 else
3272 SetColumnWidth(0, 0);
3275 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry) const
3277 auto hashMap = m_HashMap;
3278 auto refs = hashMap->find(pLogEntry->m_CommitHash);
3279 if (refs == hashMap->end())
3280 return L"";
3282 return GetTagInfo(refs->second);
3285 CString CGitLogListBase::GetTagInfo(const STRING_VECTOR& refs) const
3287 CString tagInfo;
3288 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3290 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3291 continue;
3292 if (!CStringUtils::EndsWith((*it), L"^{}"))
3293 continue;
3295 CString cmd;
3296 cmd.Format(L"git.exe cat-file tag %s", static_cast<LPCTSTR>((*it).Left((*it).GetLength() - static_cast<int>(wcslen(L"^{}")))));
3297 CString output;
3298 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3299 continue;
3301 // parse tag date
3304 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3305 int pos1 = output.Find(L'>');
3306 if (pos1 < 0)
3307 break;
3308 ++pos1;
3309 if (output[pos1] == L' ')
3310 ++pos1;
3311 int pos2 = output.Find(L'\n', pos1);
3312 if (pos2 < 0)
3313 break;
3315 CString str = output.Mid(pos1, pos2 - pos1);
3316 wchar_t* pEnd = nullptr;
3317 errno = 0;
3318 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3319 if (str.GetBuffer() == pEnd)
3320 break;
3321 if (errno == ERANGE)
3322 break;
3324 output.Delete(pos1, pos2 - pos1);
3325 output.Insert(pos1, static_cast<LPCWSTR>(CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes)));
3326 } while (0);
3327 output.Trim().AppendChar(L'\n');
3328 tagInfo += output;
3330 return tagInfo;
3333 void CGitLogListBase::Clear()
3335 m_arShownList.SafeRemoveAll();
3336 DeleteAllItems();
3338 m_logEntries.ClearAll();
3341 void CGitLogListBase::OnDestroy()
3343 SafeTerminateThread();
3344 SafeTerminateAsyncDiffThread();
3346 int retry = 0;
3347 while(m_LogCache.SaveCache())
3349 if(retry > 5)
3350 break;
3351 Sleep(1000);
3353 ++retry;
3355 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3356 // MB_YESNO) == IDNO)
3357 // break;
3360 __super::OnDestroy();
3363 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3365 CRect rect;
3366 int i = static_cast<int>(wParam);
3367 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3368 this->InvalidateRect(rect);
3370 return 0;
3374 * Save column widths to the registry
3376 void CGitLogListBase::SaveColumnWidths()
3378 // HACK that graph column is always shown
3379 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3381 __super::SaveColumnWidths();
3384 int CGitLogListBase::GetHeadIndex()
3386 if(m_HeadHash.IsEmpty())
3387 return -1;
3389 for (size_t i = 0; i < m_arShownList.size(); ++i)
3391 GitRev* pRev = m_arShownList.SafeGetAt(i);
3392 if(pRev)
3394 if (pRev->m_CommitHash == m_HeadHash)
3395 return static_cast<int>(i);
3398 return -1;
3400 void CGitLogListBase::OnFind()
3402 if (!m_pFindDialog)
3404 m_pFindDialog = new CFindDlg(this);
3405 m_pFindDialog->Create(this);
3409 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3411 if (GetSelectedCount() != 0)
3412 return 0;
3414 CGitHash theSelectedHash = m_lastSelectedHash;
3415 SetItemState(static_cast<int>(itemToSelect), LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3416 m_lastSelectedHash = theSelectedHash;
3418 int countPerPage = GetCountPerPage();
3419 EnsureVisible(max(0, static_cast<int>(itemToSelect) - countPerPage / 2), FALSE);
3420 EnsureVisible(min(GetItemCount(), static_cast<int>(itemToSelect) + countPerPage / 2), FALSE);
3421 EnsureVisible(static_cast<int>(itemToSelect), FALSE);
3422 return 0;
3425 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3427 CString* ref = reinterpret_cast<CString*>(wParam);
3428 if (!ref || ref->IsEmpty())
3429 return 1;
3431 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3433 CGitHash hash;
3434 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3435 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3437 if (hash.IsEmpty())
3438 return 1;
3440 bool bFound = false;
3441 int cnt = static_cast<int>(m_arShownList.size());
3442 int i;
3443 for (i = 0; i < cnt; ++i)
3445 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3446 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3448 bFound = true;
3449 break;
3452 if (!bFound)
3453 return 1;
3455 EnsureVisible(i, FALSE);
3456 if (!bShift)
3458 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3459 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3460 SetSelectionMark(i);
3462 else
3464 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3465 if (pLogEntry)
3466 m_highlight = pLogEntry->m_CommitHash;
3468 Invalidate();
3469 UpdateData(FALSE);
3471 return 0;
3474 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
3476 ASSERT(m_pFindDialog);
3477 bool bFound = false;
3478 int i=0;
3480 if (m_pFindDialog->IsTerminating())
3482 // invalidate the handle identifying the dialog box.
3483 m_pFindDialog = nullptr;
3484 return 0;
3487 int cnt = static_cast<int>(m_arShownList.size());
3488 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3490 if(m_pFindDialog->IsRef())
3492 CString str;
3493 str=m_pFindDialog->GetFindString();
3495 CGitHash hash;
3497 if(!str.IsEmpty())
3499 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3500 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3503 if(!hash.IsEmpty())
3505 for (i = 0; i < cnt; ++i)
3507 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3508 if(pLogEntry && pLogEntry->m_CommitHash == hash)
3510 bFound = true;
3511 break;
3515 if (!bFound)
3517 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3518 return 0;
3522 if (m_pFindDialog->FindNext() && !bFound)
3524 //read data from dialog
3525 CLogDlgFilter filter { m_pFindDialog->GetFindString(), m_pFindDialog->Regex(), LOGFILTER_ALL, m_pFindDialog->MatchCase() == TRUE };
3527 auto hashMapSharedPtr = m_HashMap;
3528 auto& hashMap = *hashMapSharedPtr;
3530 for (i = m_nSearchIndex + 1; ; ++i)
3532 if (i >= cnt)
3534 i = 0;
3535 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3537 if (m_nSearchIndex >= 0)
3539 if (i == m_nSearchIndex)
3541 ::MessageBeep(0xFFFFFFFF);
3542 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
3543 break;
3547 if (filter(m_arShownList.SafeGetAt(i), this, hashMap))
3549 bFound = true;
3550 break;
3553 } // if(m_pFindDialog->FindNext())
3555 if (bFound)
3557 m_nSearchIndex = i;
3558 EnsureVisible(i, FALSE);
3559 if (!bShift)
3561 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3562 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3563 SetSelectionMark(i);
3565 else
3567 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3568 if (pLogEntry)
3569 m_highlight = pLogEntry->m_CommitHash;
3571 Invalidate();
3572 //FillLogMessageCtrl();
3573 UpdateData(FALSE);
3576 return 0;
3579 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
3581 LVHITTESTINFO lvhitTestInfo;
3583 lvhitTestInfo.pt = point;
3585 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
3586 int nSubItem = lvhitTestInfo.iSubItem;
3588 UINT nFlags = lvhitTestInfo.flags;
3590 // nFlags is 0 if the SubItemHitTest fails
3591 // Therefore, 0 & <anything> will equal false
3592 if (nFlags & LVHT_ONITEM)
3594 // Get the client area occupied by this control
3595 RECT rcClient;
3596 GetClientRect(&rcClient);
3598 // Fill in the TOOLINFO structure
3599 pTI->hwnd = m_hWnd;
3600 pTI->uId = static_cast<UINT>((nItem << 10) + (nSubItem & 0x3ff) + 1);
3601 pTI->lpszText = LPSTR_TEXTCALLBACK;
3602 pTI->rect = rcClient;
3604 return pTI->uId; // By returning a unique value per listItem,
3605 // we ensure that when the mouse moves over another list item,
3606 // the tooltip will change
3608 else
3610 // Otherwise, we aren't interested, so let the message propagate
3611 return -1;
3615 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
3617 auto pTTTA = reinterpret_cast<TOOLTIPTEXTA*>(pNMHDR);
3618 auto pTTTW = reinterpret_cast<TOOLTIPTEXTW*>(pNMHDR);
3620 *pResult = 0;
3622 // Ignore messages from the built in tooltip, we are processing them internally
3623 if ((pNMHDR->idFrom == reinterpret_cast<UINT_PTR>(m_hWnd)) &&
3624 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
3625 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
3626 return FALSE;
3628 // Get the mouse position
3629 const MSG* pMessage = GetCurrentMessage();
3631 CPoint pt;
3632 pt = pMessage->pt;
3633 ScreenToClient(&pt);
3635 // Check if the point falls onto a list item
3636 LVHITTESTINFO lvhitTestInfo;
3637 lvhitTestInfo.pt = pt;
3639 int nItem = SubItemHitTest(&lvhitTestInfo);
3641 if (lvhitTestInfo.flags & LVHT_ONITEM)
3643 // Get branch description first
3644 CString strTipText;
3645 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
3647 CString branch;
3648 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
3649 auto hashMap = m_HashMap;
3650 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, *hashMap.get(), &branch))
3652 MAP_STRING_STRING descriptions;
3653 g_Git.GetBranchDescriptions(descriptions);
3654 if (descriptions.find(branch) != descriptions.cend())
3656 strTipText.LoadString(IDS_DESCRIPTION);
3657 strTipText += L":\n";
3658 strTipText += descriptions[branch];
3663 bool followMousePos = false;
3664 if (!strTipText.IsEmpty())
3665 followMousePos = true;
3666 else
3667 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
3668 if (strTipText.IsEmpty())
3669 return FALSE;
3671 // we want multiline tooltips
3672 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
3674 if (strTipText.GetLength() >= _countof(m_wszTip))
3676 strTipText.Truncate(_countof(m_wszTip) - 1 - 3);
3677 strTipText += L"...";
3679 wcsncpy_s(m_wszTip, strTipText, _TRUNCATE);
3680 // handle Unicode as well as non-Unicode requests
3681 if (pNMHDR->code == TTN_NEEDTEXTA)
3683 pTTTA->hinst = nullptr;
3684 pTTTA->lpszText = m_szTip;
3685 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
3687 else
3689 pTTTW->hinst = nullptr;
3690 pTTTW->lpszText = m_wszTip;
3693 CRect rect;
3694 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
3695 if (followMousePos)
3696 rect.MoveToXY(pt.x, pt.y + CDPIAware::Instance().ScaleY(18)); // 18: to act like a normal tooltip
3697 ClientToScreen(rect);
3698 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
3700 return TRUE; // We found a tool tip,
3701 // tell the framework this message has been handled
3704 return FALSE; // We didn't handle the message,
3705 // let the framework continue propagating the message
3708 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
3710 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
3712 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3713 if (pLogEntry == nullptr)
3714 return CString();
3715 auto hashMap = m_HashMap;
3716 if (hashMap->find(pLogEntry->m_CommitHash) == hashMap->cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
3717 return CString();
3718 return pLogEntry->GetSubject();
3720 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
3722 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3723 if (pLogEntry == nullptr)
3724 return CString();
3725 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
3727 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
3729 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3730 if (pLogEntry == nullptr)
3731 return CString();
3732 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
3734 else if (nSubItem == LOGLIST_ACTION)
3736 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3737 if (pLogEntry == nullptr)
3738 return CString();
3740 int actions = pLogEntry->GetAction(this);
3741 if (!pLogEntry->m_IsDiffFiles)
3742 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
3744 CString actionText;
3745 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
3746 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
3748 if (actions & CTGitPath::LOGACTIONS_ADDED)
3750 if (!actionText.IsEmpty())
3751 actionText += L"\r\n";
3752 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
3755 if (actions & CTGitPath::LOGACTIONS_DELETED)
3757 if (!actionText.IsEmpty())
3758 actionText += L"\r\n";
3759 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
3762 if (actions & CTGitPath::LOGACTIONS_REPLACED)
3764 if (!actionText.IsEmpty())
3765 actionText += L"\r\n";
3766 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
3769 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
3771 if (!actionText.IsEmpty())
3772 actionText += L"\r\n";
3773 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
3776 if (!actionText.IsEmpty())
3778 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
3779 return sTitle + L":\r\n" + actionText;
3782 return CString();
3785 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, const MAP_HASH_NAME& hashMap, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3787 POINT pt = point;
3788 ScreenToClient(&pt);
3789 return IsMouseOnRefLabel(pLogEntry, pt, type, hashMap, pShortname, pIndex);
3792 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, const MAP_HASH_NAME& hashMap, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3794 if (!pLogEntry)
3795 return false;
3797 auto refList = hashMap.find(pLogEntry->m_CommitHash);
3798 if (refList == hashMap.cend())
3799 return false;
3801 for (size_t i = 0; i < refList->second.size(); ++i)
3803 const auto labelpos = m_RefLabelPosMap.find(refList->second[i]);
3804 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
3805 continue;
3807 CGit::REF_TYPE foundType;
3808 if (pShortname)
3809 *pShortname = CGit::GetShortName(refList->second[i], &foundType);
3810 else
3811 CGit::GetShortName(refList->second[i], &foundType);
3812 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
3813 return false;
3815 type = foundType;
3816 if (pIndex)
3817 *pIndex = i;
3818 return true;
3820 return false;
3823 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
3825 *pResult = 0;
3827 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
3828 return;
3830 m_bDragging = TRUE;
3831 m_nDropIndex = -1;
3832 m_nDropMarkerLast = -1;
3833 m_nDropMarkerLastHot = GetHotItem();
3834 SetCapture();
3837 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
3839 __super::OnMouseMove(nFlags, point);
3841 if (!m_bDragging)
3842 return;
3844 CPoint dropPoint = point;
3845 ClientToScreen(&dropPoint);
3847 if (WindowFromPoint(dropPoint) != this)
3849 SetCursor(LoadCursor(nullptr, IDC_NO));
3850 m_nDropIndex = -1;
3851 DrawDropInsertMarker(m_nDropIndex);
3852 return;
3855 SetCursor(LoadCursor(nullptr, IDC_ARROW));
3856 ScreenToClient(&dropPoint);
3858 dropPoint.y += 10;
3859 m_nDropIndex = HitTest(dropPoint);
3861 if (m_nDropIndex == -1) // might be last item, allow to move past last item
3863 dropPoint.y -= 10;
3864 m_nDropIndex = HitTest(dropPoint);
3865 if (m_nDropIndex != -1)
3866 m_nDropIndex = GetItemCount();
3869 POSITION pos = GetFirstSelectedItemPosition();
3870 int first = GetNextSelectedItem(pos);
3871 int last = first;
3872 while (pos)
3873 last = GetNextSelectedItem(pos);
3874 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
3876 SetCursor(LoadCursor(nullptr, IDC_NO));
3877 m_nDropIndex = -1;
3880 // handle auto scrolling
3881 int hotItem = GetHotItem();
3882 int topindex = GetTopIndex();
3883 if (hotItem == topindex && hotItem != 0)
3884 EnsureVisible(hotItem - 1, FALSE);
3885 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
3886 EnsureVisible(hotItem + 1, FALSE);
3888 DrawDropInsertMarker(m_nDropIndex);
3891 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
3893 if (m_bDragging)
3895 ::ReleaseCapture();
3896 SetCursor(LoadCursor(nullptr, IDC_HAND));
3897 m_bDragging = FALSE;
3899 CRect rect;
3900 GetItemRect(m_nDropMarkerLast, &rect, 0);
3901 rect.bottom = rect.top + 2;
3902 rect.top -= 2;
3903 InvalidateRect(&rect, 0);
3905 CPoint pt(point);
3906 ClientToScreen(&pt);
3907 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
3908 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
3911 __super::OnLButtonUp(nFlags, point);
3914 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
3916 if (m_nDropMarkerLast != nIndex)
3918 CRect rect;
3919 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
3921 rect.bottom = rect.top + 2;
3922 rect.top -= 2;
3923 InvalidateRect(&rect, 0);
3925 else if (m_nDropMarkerLast == GetItemCount())
3926 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
3927 m_nDropMarkerLast = nIndex;
3929 if (nIndex < 0)
3930 return;
3932 DrawDropInsertMarkerLine(m_nDropMarkerLast);
3934 else if (m_nDropMarkerLastHot != GetHotItem())
3936 m_nDropMarkerLastHot = GetHotItem();
3937 m_nDropMarkerLast = -1;
3941 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
3943 CBrush* pBrush = CDC::GetHalftoneBrush();
3944 CDC* pDC = GetDC();
3946 CRect rect;
3947 if (nIndex < GetItemCount())
3949 GetItemRect(nIndex, &rect, 0);
3950 rect.bottom = rect.top + 2;
3951 rect.top -= 2;
3953 else
3955 GetItemRect(nIndex - 1, &rect, 0);
3956 rect.top = rect.bottom - 2;
3957 rect.bottom += 2;
3960 CBrush* pBrushOld = pDC->SelectObject(pBrush);
3961 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
3962 pDC->SelectObject(pBrushOld);
3964 ReleaseDC(pDC);
3967 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
3969 return 0;
3972 void CGitLogListBase::DrawListItemWithMatchesRect(NMLVCUSTOMDRAW* pLVCD, const std::vector<CHARRANGE>& ranges, CRect rect, const CString& text, CColors& colors, HTHEME hTheme /*= nullptr*/, int txtState /*= 0*/)
3974 int drawPos = 0;
3975 COLORREF textColor = pLVCD->clrText;
3976 RECT rc = rect;
3977 if (!hTheme)
3979 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
3980 SetBkMode(pLVCD->nmcd.hdc, TRANSPARENT);
3982 DTTOPTS opts = { 0 };
3983 opts.dwSize = sizeof(opts);
3984 opts.crText = textColor;
3985 opts.dwFlags = DTT_TEXTCOLOR;
3987 for (auto it = ranges.cbegin(); it != ranges.cend(); ++it)
3989 rc = rect;
3990 if (it->cpMin - drawPos)
3992 if (!hTheme)
3994 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3995 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3997 else
3999 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), it->cpMin - drawPos, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rc, &opts);
4000 GetThemeTextExtent(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), it->cpMin - drawPos, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rect, &rc);
4002 rect.left = rc.right;
4004 rc = rect;
4005 drawPos = it->cpMin;
4006 if (it->cpMax - drawPos)
4008 if (!hTheme)
4010 ::SetTextColor(pLVCD->nmcd.hdc, CTheme::Instance().GetThemeColor(colors.GetColor(CColors::FilterMatch), true));
4011 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4012 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4013 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
4015 else
4017 opts.crText = CTheme::Instance().GetThemeColor(colors.GetColor(CColors::FilterMatch), true);
4018 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), it->cpMax - drawPos, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rc, &opts);
4019 GetThemeTextExtent(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), it->cpMax - drawPos, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rect, &rc);
4020 opts.crText = textColor;
4022 rect.left = rc.right;
4024 rc = rect;
4025 drawPos = it->cpMax;
4027 if (!hTheme)
4028 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), -1, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4029 else
4030 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), -1, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rc, &opts);
4033 bool CGitLogListBase::DrawListItemWithMatchesIfEnabled(std::shared_ptr<CLogDlgFilter> filter, DWORD selectedFilter, NMLVCUSTOMDRAW* pLVCD, LRESULT* pResult)
4035 if ((filter->GetSelectedFilters() & selectedFilter) && filter->IsFilterActive())
4037 CRect rect;
4038 GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_BOUNDS, rect);
4040 int index = static_cast<int>(pLVCD->nmcd.dwItemSpec);
4041 int state = GetItemState(index, LVIS_SELECTED);
4042 int txtState = LISS_NORMAL;
4043 if (IsAppThemed() && GetHotItem() == static_cast<int>(index))
4045 if (state & LVIS_SELECTED)
4046 txtState = LISS_HOTSELECTED;
4047 else
4048 txtState = LISS_HOT;
4050 else if (state & LVIS_SELECTED)
4052 if (::GetFocus() == m_hWnd)
4053 txtState = LISS_SELECTED;
4054 else
4055 txtState = LISS_SELECTEDNOTFOCUS;
4058 CAutoThemeData hTheme;
4059 if (IsAppThemed())
4061 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
4063 // make sure the column separator/border is not overpainted
4064 int borderWidth = 0;
4065 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
4066 InflateRect(&rect, -(2 * borderWidth), 0);
4069 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
4070 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
4071 else
4073 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
4074 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
4075 ::DeleteObject(brush);
4077 if (hTheme && txtState != LISS_NORMAL)
4079 CRect rt;
4080 // get rect of whole line
4081 GetItemRect(index, rt, LVIR_BOUNDS);
4082 CRect rect2 = rect;
4084 // calculate background for rect of whole line, but limit redrawing to SubItem rect
4085 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
4087 hTheme.CloseHandle();
4088 // END: extended redraw
4090 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec, rect);
4093 *pResult = DrawListItemWithMatches(filter.get(), *this, pLVCD, m_Colors);
4094 return true;
4096 return false;
4099 LRESULT CGitLogListBase::DrawListItemWithMatches(CFilterHelper* filter, CListCtrl& listCtrl, NMLVCUSTOMDRAW* pLVCD, CColors& colors)
4101 CString text = static_cast<LPCTSTR>(listCtrl.GetItemText(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem));
4102 if (text.IsEmpty())
4103 return CDRF_DODEFAULT;
4105 std::vector<CHARRANGE> ranges;
4106 filter->GetMatchRanges(ranges, text, 0);
4107 if (ranges.empty())
4108 return CDRF_DODEFAULT;
4110 // even though we initialize the 'rect' here with nmcd.rc,
4111 // we must not use it but use the rects from GetItemRect()
4112 // and GetSubItemRect(). Because on XP, the nmcd.rc has
4113 // bogus data in it.
4114 CRect rect = pLVCD->nmcd.rc;
4116 // find the margin where the text label starts
4117 CRect labelRC, boundsRC, iconRC;
4118 listCtrl.GetItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), &labelRC, LVIR_LABEL);
4119 listCtrl.GetItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), &iconRC, LVIR_ICON);
4120 listCtrl.GetItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), &boundsRC, LVIR_BOUNDS);
4122 int leftmargin = labelRC.left - boundsRC.left;
4123 if (pLVCD->iSubItem)
4124 leftmargin -= iconRC.Width();
4126 if (pLVCD->iSubItem != 0)
4127 listCtrl.GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_BOUNDS, rect);
4129 int borderWidth = 0;
4130 CAutoThemeData hTheme;
4131 if (IsAppThemed())
4133 hTheme = OpenThemeData(listCtrl.m_hWnd, L"Explorer::ListView;ListView");
4134 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
4136 else
4137 borderWidth = GetSystemMetrics(SM_CXBORDER);
4139 if (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES)
4141 // I'm not very happy about this fixed margin here
4142 // but I haven't found a way to ask the system what
4143 // the margin really is.
4144 // At least it works on XP/Vista/win7/win8, and even with
4145 // increased font sizes
4146 leftmargin = 4;
4149 LVITEM item = { 0 };
4150 item.iItem = static_cast<int>(pLVCD->nmcd.dwItemSpec);
4151 item.iSubItem = 0;
4152 item.mask = LVIF_IMAGE | LVIF_STATE;
4153 item.stateMask = static_cast<UINT>(-1);
4154 listCtrl.GetItem(&item);
4156 // fill background
4157 int txtState = LISS_NORMAL;
4158 if (!hTheme)
4160 HBRUSH brush = nullptr;
4161 if (item.state & LVIS_SELECTED)
4163 if (::GetFocus() == listCtrl.GetSafeHwnd())
4165 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
4166 pLVCD->clrText = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
4168 else
4170 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
4171 pLVCD->clrText = CTheme::Instance().IsDarkTheme() ? CTheme::darkTextColor : GetSysColor(COLOR_WINDOWTEXT);
4175 else
4176 brush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4177 CRect my;
4178 listCtrl.GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_LABEL, my);
4179 ::FillRect(pLVCD->nmcd.hdc, my, brush);
4180 ::DeleteObject(brush);
4182 else
4184 if (listCtrl.GetHotItem() == static_cast<int>(pLVCD->nmcd.dwItemSpec))
4186 if (item.state & LVIS_SELECTED)
4187 txtState = LISS_HOTSELECTED;
4188 else
4189 txtState = LISS_HOT;
4191 else if (item.state & LVIS_SELECTED)
4193 if (::GetFocus() == listCtrl.GetSafeHwnd())
4194 txtState = LISS_SELECTED;
4195 else
4196 txtState = LISS_SELECTEDNOTFOCUS;
4199 if (IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
4200 DrawThemeParentBackground(listCtrl.m_hWnd, pLVCD->nmcd.hdc, &rect);
4201 else
4203 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
4204 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
4205 ::DeleteObject(brush);
4207 if (txtState != LISS_NORMAL)
4209 CRect my;
4210 listCtrl.GetSubItemRect(static_cast<int>(pLVCD->nmcd.dwItemSpec), pLVCD->iSubItem, LVIR_LABEL, my);
4211 if (pLVCD->iSubItem == 0)
4213 // also fill the icon part of the line
4214 my.top = 0;
4215 my.left = 0;
4218 // calculate background for rect of whole line, but limit redrawing to SubItem rect
4219 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, boundsRC, my);
4223 // draw the icon for the first column
4224 if (pLVCD->iSubItem == 0)
4226 rect = boundsRC;
4227 rect.right = rect.left + listCtrl.GetColumnWidth(0);
4228 rect.left = iconRC.left;
4230 if (item.iImage >= 0)
4232 POINT pt;
4233 pt.x = rect.left;
4234 pt.y = rect.top;
4235 CDC dc;
4236 dc.Attach(pLVCD->nmcd.hdc);
4237 int style = ILD_TRANSPARENT;
4238 if (!hTheme)
4240 auto whitebrush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4241 ::FillRect(dc, iconRC, whitebrush);
4242 ::DeleteObject(whitebrush);
4243 if (item.state & LVIS_SELECTED)
4245 if (::GetFocus() == listCtrl.GetSafeHwnd())
4246 style = ILD_SELECTED;
4247 else
4248 style = ILD_FOCUS;
4251 listCtrl.GetImageList(LVSIL_SMALL)->Draw(&dc, item.iImage, pt, style);
4252 dc.Detach();
4253 leftmargin -= iconRC.left;
4255 else
4257 RECT irc = boundsRC;
4258 irc.left += borderWidth;
4259 irc.right = iconRC.left;
4261 int state = 0;
4262 if (item.state & LVIS_SELECTED)
4264 if (listCtrl.GetHotItem() == item.iItem)
4265 state = CBS_CHECKEDHOT;
4266 else
4267 state = CBS_CHECKEDNORMAL;
4269 else
4271 if (listCtrl.GetHotItem() == item.iItem)
4272 state = CBS_UNCHECKEDHOT;
4274 if ((state) && (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES))
4276 CAutoThemeData hTheme2 = OpenThemeData(listCtrl.m_hWnd, L"BUTTON");
4277 DrawThemeBackground(hTheme2, pLVCD->nmcd.hdc, BP_CHECKBOX, state, &irc, NULL);
4281 InflateRect(&rect, -(2 * borderWidth), 0);
4283 rect.left += leftmargin;
4284 RECT rc = rect;
4286 // is the column left- or right-aligned? (we don't handle centered (yet))
4287 LVCOLUMN Column;
4288 Column.mask = LVCF_FMT;
4289 listCtrl.GetColumn(pLVCD->iSubItem, &Column);
4290 if (Column.fmt & LVCFMT_RIGHT)
4292 DrawText(pLVCD->nmcd.hdc, text, -1, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4293 rect.left = rect.right - (rc.right - rc.left);
4294 if (!hTheme)
4296 rect.left += 2 * borderWidth;
4297 rect.right += 2 * borderWidth;
4301 DrawListItemWithMatchesRect(pLVCD, ranges, rect, text, colors, hTheme, txtState);
4303 return CDRF_SKIPDEFAULT;