Fixed issue #3304: Double click on stash list item does nothing, show log instead
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blobe0be0c9e0808bf45df0fa8fd253db186cd87a9c8
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - TortoiseGit
4 // Copyright (C) 2005-2007 Marco Costalba
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // GitLogList.cpp : implementation file
22 #include "stdafx.h"
23 #include "GitLogListBase.h"
24 #include "IconMenu.h"
25 #include "GitProgressDlg.h"
26 #include "ProgressDlg.h"
27 #include "MessageBox.h"
28 #include "LoglistUtils.h"
29 #include "StringUtils.h"
30 #include "UnicodeUtils.h"
31 #include "../TortoiseShell/Resource.h"
32 #include "CommonAppUtils.h"
33 #include "DPIAware.h"
35 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
39 const UINT CGitLogListBase::LOGLIST_RESET_WCREV = RegisterWindowMessage(L"TORTOISEGIT_LOG_RESET_WCREV");
41 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
43 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
44 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
45 ,m_nSearchIndex(0)
46 ,m_bNoDispUpdates(FALSE)
47 , m_bThreadRunning(FALSE)
48 , m_ShowFilter(FILTERSHOW_ALL)
49 , m_bShowWC(false)
50 , m_logEntries(&m_LogCache)
51 , m_pFindDialog(nullptr)
52 , m_dwDefaultColumns(0)
53 , m_arShownList(&m_critSec)
54 , m_hasWC(true)
55 , m_bNoHightlightHead(FALSE)
56 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
57 , m_bFullCommitMessageOnLogLine(false)
58 , m_OldTopIndex(-1)
59 , m_AsyncThreadRunning(FALSE)
60 , m_AsyncThreadExit(FALSE)
61 , m_bIsCherryPick(false)
62 , m_pMailmap(nullptr)
63 , m_bShowBugtraqColumn(false)
64 , m_IsIDReplaceAction(FALSE)
65 , m_ShowMask(0)
66 , m_LoadingThread(nullptr)
67 , m_bExitThread(FALSE)
68 , m_IsOldFirst(FALSE)
69 , m_IsRebaseReplaceGraph(FALSE)
70 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
71 , m_bDragndropEnabled(false)
72 , m_bDragging(FALSE)
73 , m_nDropIndex(-1)
74 , m_nDropMarkerLast(-1)
75 , m_nDropMarkerLastHot(-1)
76 , m_LogFilter(std::make_shared<CLogDlgFilter>())
78 // use the default GUI font, create a copy of it and
79 // change the copy to BOLD (leave the rest of the font
80 // the same)
82 this->m_critSec.Init();
83 ResetWcRev(false);
85 int cx = GetSystemMetrics(SM_CXSMICON);
86 int cy = GetSystemMetrics(SM_CYSMICON);
87 m_hModifiedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONMODIFIED, cx, cy);
88 m_hReplacedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONREPLACED, cx, cy);
89 m_hConflictedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONCONFLICTED, cx, cy);
90 m_hAddedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONADDED, cx, cy);
91 m_hDeletedIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONDELETED, cx, cy);
92 m_hFetchIcon = CCommonAppUtils::LoadIconEx(IDI_ACTIONFETCHING, cx, cy);
94 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
95 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
97 CString key;
98 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
99 key.Replace(L':', L'_');
100 CString lastSelFromDate = CRegString(key);
101 if (lastSelFromDate.GetLength() == 10)
103 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Left(4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
104 m_Filter.m_From = (DWORD)time.GetTime();
107 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
109 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
111 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
113 // get short/long datetime setting from registry
114 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
115 if ( RegUseShortDateFormat )
117 m_DateFormat = DATE_SHORTDATE;
119 else
121 m_DateFormat = DATE_LONGDATE;
123 // get relative time display setting from registry
124 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
125 m_bRelativeTimes = (regRelativeTimes != 0);
127 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
128 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
129 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
130 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
131 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
132 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
133 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
135 m_ColumnRegKey = L"log";
137 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
138 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
139 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
140 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
142 m_LineWidth = max(1, (int)CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
143 m_NodeSize = max(1, (int)CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
145 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
146 git_read_mailmap(&m_pMailmap);
148 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
149 m_AsynDiffListLock.Init();
150 StartAsyncDiffThread();
153 HWND CGitLogListBase::GetParentHWND()
155 auto owner = GetSafeOwner();
156 if (!owner)
157 return GetSafeHwnd();
158 return owner->GetSafeHwnd();
161 int CGitLogListBase::AsyncDiffThread()
163 while(!m_AsyncThreadExit)
165 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
167 GitRevLoglist* pRev = nullptr;
168 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
170 m_AsynDiffListLock.Lock();
171 pRev = m_AsynDiffList.back();
172 m_AsynDiffList.pop_back();
173 m_AsynDiffListLock.Unlock();
175 if( pRev->m_CommitHash.IsEmpty() )
177 if(pRev->m_IsDiffFiles)
178 continue;
180 CTGitPathList& files = pRev->GetFiles(this);
181 files.Clear();
182 pRev->m_ParentHash.clear();
183 pRev->m_ParentHash.push_back(m_HeadHash);
184 g_Git.RefreshGitIndex();
185 g_Git.GetWorkingTreeChanges(files, false, nullptr, true); // filtering is done in LogDlg.cpp
186 auto& action = pRev->GetAction(this);
187 action = 0;
188 for (int j = 0; j < files.GetCount(); ++j)
189 action |= files[j].m_Action;
191 CString err;
192 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
194 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
195 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
196 return -1;
199 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
200 InterlockedExchange(&pRev->m_IsFull, TRUE);
202 CString body = L"\n";
203 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
204 pRev->GetBody() = body;
205 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
206 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
209 if (!pRev->CheckAndDiff())
210 { // fetch change file list
211 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
213 if (i < (int)m_arShownList.size())
215 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
216 if(data->m_CommitHash == pRev->m_CommitHash)
218 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
219 break;
224 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
226 POSITION pos = GetFirstSelectedItemPosition();
227 int nItem = GetNextSelectedItem(pos);
229 if(nItem>=0)
231 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
232 if(data)
233 if(data->m_CommitHash == pRev->m_CommitHash)
234 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
240 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
241 return 0;
243 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
245 if (exclusivelyShow)
246 m_ContextMenuMask &= hideMask;
247 else
248 m_ContextMenuMask &= ~hideMask;
251 CGitLogListBase::~CGitLogListBase()
253 InterlockedExchange(&m_bNoDispUpdates, TRUE);
254 this->m_arShownList.SafeRemoveAll();
256 DestroyIcon(m_hModifiedIcon);
257 DestroyIcon(m_hReplacedIcon);
258 DestroyIcon(m_hConflictedIcon);
259 DestroyIcon(m_hAddedIcon);
260 DestroyIcon(m_hDeletedIcon);
261 m_logEntries.ClearAll();
263 git_free_mailmap(m_pMailmap);
265 SafeTerminateThread();
266 SafeTerminateAsyncDiffThread();
268 if(m_AsyncDiffEvent)
269 CloseHandle(m_AsyncDiffEvent);
273 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
274 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
275 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
276 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
277 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
278 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
279 ON_WM_CONTEXTMENU()
280 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
281 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
282 ON_WM_CREATE()
283 ON_WM_DESTROY()
284 ON_MESSAGE(MSG_LOADED,OnLoad)
285 ON_WM_MEASUREITEM()
286 ON_WM_MEASUREITEM_REFLECT()
287 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
288 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
289 ON_WM_MOUSEMOVE()
290 ON_WM_LBUTTONUP()
291 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
292 END_MESSAGE_MAP()
294 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
296 //if (m_nRowHeight>0)
297 lpMeasureItemStruct->itemHeight = CDPIAware::Instance().ScaleY(50);
300 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
302 PreSubclassWindow();
303 return __super::OnCreate(lpCreateStruct);
306 void CGitLogListBase::SetStyle()
308 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
311 void CGitLogListBase::PreSubclassWindow()
313 SetStyle();
314 // load the icons for the action columns
315 // m_Theme.Open(m_hWnd, L"ListView");
316 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
317 __super::PreSubclassWindow();
320 CString CGitLogListBase::GetRebaseActionName(int action)
322 if (action & LOGACTIONS_REBASE_EDIT)
323 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
324 if (action & LOGACTIONS_REBASE_SQUASH)
325 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
326 if (action & LOGACTIONS_REBASE_PICK)
327 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
328 if (action & LOGACTIONS_REBASE_SKIP)
329 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
331 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
334 void CGitLogListBase::InsertGitColumn()
336 CString temp;
338 Init();
340 // use the default font, create a copy of it and
341 // change the copy to BOLD (leave the rest of the font
342 // the same)
343 LOGFONT lf = { 0 };
344 GetFont()->GetLogFont(&lf);
345 lf.lfWeight = FW_BOLD;
346 m_boldFont.CreateFontIndirect(&lf);
347 lf.lfWeight = FW_DONTCARE;
348 lf.lfItalic = TRUE;
349 m_FontItalics.CreateFontIndirect(&lf);
350 lf.lfWeight = FW_BOLD;
351 m_boldItalicsFont.CreateFontIndirect(&lf);
353 // only load properties if we have a repository
354 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
355 UpdateProjectProperties();
357 static UINT normal[] =
359 IDS_LOG_GRAPH,
360 IDS_LOG_REBASE,
361 IDS_LOG_ID,
362 IDS_LOG_HASH,
363 IDS_LOG_ACTIONS,
364 IDS_LOG_MESSAGE,
365 IDS_LOG_AUTHOR,
366 IDS_LOG_DATE,
367 IDS_LOG_EMAIL,
368 IDS_LOG_COMMIT_NAME,
369 IDS_LOG_COMMIT_EMAIL,
370 IDS_LOG_COMMIT_DATE,
371 IDS_LOG_BUGIDS,
372 IDS_LOG_SVNREV,
375 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
376 auto columnWidth = CDPIAware::Instance().ScaleX(ICONITEMBORDER + 16 * 4);
377 static int with[] =
379 columnWidth,
380 columnWidth,
381 columnWidth,
382 columnWidth,
383 2 * iconItemBorder + GetSystemMetrics(SM_CXSMICON) * 5,
384 CDPIAware::Instance().ScaleX(LOGLIST_MESSAGE_MIN),
385 columnWidth,
386 columnWidth,
387 columnWidth,
388 columnWidth,
389 columnWidth,
390 columnWidth,
391 columnWidth,
392 columnWidth,
394 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
396 DWORD hideColumns = 0;
397 if(this->m_IsRebaseReplaceGraph)
399 hideColumns |= GIT_LOG_GRAPH;
400 m_dwDefaultColumns |= GIT_LOG_REBASE;
402 else
403 hideColumns |= GIT_LOG_REBASE;
405 if(this->m_IsIDReplaceAction)
407 hideColumns |= GIT_LOG_ACTIONS;
408 m_dwDefaultColumns |= GIT_LOG_ID;
409 m_dwDefaultColumns |= GIT_LOG_HASH;
411 else
412 hideColumns |= GIT_LOG_ID;
413 if(this->m_bShowBugtraqColumn)
414 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
415 else
416 hideColumns |= GIT_LOGLIST_BUG;
417 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
418 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
419 else
420 hideColumns |= GIT_LOGLIST_SVNREV;
421 SetRedraw(false);
423 m_ColumnManager.SetNames(normal, _countof(normal));
424 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
425 m_ColumnManager.SetRightAlign(LOGLIST_ID);
427 if (!(hideColumns & GIT_LOG_ACTIONS))
429 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
430 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
431 // display's font height may be less than small icon height.
432 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
433 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
434 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
437 SetRedraw(true);
440 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
442 LVITEM rItem = { 0 };
443 rItem.mask = LVIF_STATE;
444 rItem.iItem = (int)Index;
445 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
446 GetItem(&rItem);
448 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
449 HBRUSH brush = nullptr;
451 if (!(rItem.state & LVIS_SELECTED))
453 int action = pLogEntry->GetRebaseAction();
454 if (action & LOGACTIONS_REBASE_SQUASH)
455 brush = ::CreateSolidBrush(RGB(156,156,156));
456 else if (action & LOGACTIONS_REBASE_EDIT)
457 brush = ::CreateSolidBrush(RGB(200,200,128));
459 else if (!IsAppThemed())
461 if (rItem.state & LVIS_SELECTED)
463 if (::GetFocus() == m_hWnd)
464 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
465 else
466 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
469 if (brush)
471 ::FillRect(hdc, &rect, brush);
472 ::DeleteObject(brush);
476 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
478 POINT point = { 4, 4 };
479 CRect rt2 = rect;
480 rt2.DeflateRect(1, 1);
481 rt2.OffsetRect(2, 2);
483 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
484 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
485 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
486 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
487 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
489 ::SelectObject(hdc, brush);
490 rt2.OffsetRect(-2, -2);
491 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
492 ::SelectObject(hdc, oldbrush);
493 ::SelectObject(hdc, oldpen);
494 ::DeleteObject(nullPen);
495 ::DeleteObject(darkBrush);
498 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
500 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
501 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
502 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
503 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
504 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
505 ::LineTo(hdc, rect.left, rect.top + 4);
506 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
507 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
508 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
509 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
510 ::SelectObject(hdc, oldpen);
511 ::DeleteObject(pen);
514 void CGitLogListBase::DrawTagBranchMessage(NMLVCUSTOMDRAW* pLVCD, CRect& rect, INT_PTR index, std::vector<REFLABEL>& refList)
516 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
517 CRect rt=rect;
518 LVITEM rItem = { 0 };
519 rItem.mask = LVIF_STATE;
520 rItem.iItem = (int)index;
521 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
522 GetItem(&rItem);
524 CDC W_Dc;
525 W_Dc.Attach(pLVCD->nmcd.hdc);
527 HTHEME hTheme = nullptr;
528 if (IsAppThemed())
529 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
531 SIZE oneSpaceSize;
532 if (m_bTagsBranchesOnRightSide)
534 HFONT oldFont = (HFONT)SelectObject(pLVCD->nmcd.hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
535 GetTextExtentPoint32(pLVCD->nmcd.hdc, L" ", 1, &oneSpaceSize);
536 SelectObject(pLVCD->nmcd.hdc, oldFont);
537 rt.left += oneSpaceSize.cx * 2;
539 else
541 GetTextExtentPoint32(pLVCD->nmcd.hdc, L" ", 1, &oneSpaceSize);
542 DrawTagBranch(pLVCD->nmcd.hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
543 rt.left += oneSpaceSize.cx;
546 CString msg = MessageDisplayStr(data);
547 int action = data->GetRebaseAction();
548 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
549 std::vector<CHARRANGE> ranges;
550 auto filter = m_LogFilter;
551 if ((filter->GetSelectedFilters() & (LOGFILTER_SUBJECT | (m_bFullCommitMessageOnLogLine ? LOGFILTER_MESSAGES : 0))) && filter->IsFilterActive())
552 filter->GetMatchRanges(ranges, msg, 0);
553 if (hTheme)
555 int txtState = LISS_NORMAL;
556 if (rItem.state & LVIS_SELECTED)
557 txtState = LISS_SELECTED;
559 if (!ranges.empty())
560 DrawListItemWithMatchesRect(pLVCD, ranges, rt, msg, hTheme, txtState);
561 else
563 DTTOPTS opts = { 0 };
564 opts.dwSize = sizeof(opts);
565 opts.crText = skip ? RGB(128, 128, 128) : ::GetSysColor(COLOR_WINDOWTEXT);
566 opts.dwFlags = DTT_TEXTCOLOR;
567 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
570 else
572 if ((rItem.state & LVIS_SELECTED) && ::GetFocus() == m_hWnd)
573 pLVCD->clrText = skip ? RGB(128, 128, 128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT);
574 else
575 pLVCD->clrText = skip ? RGB(128, 128, 128) : ::GetSysColor(COLOR_WINDOWTEXT);
576 if (!ranges.empty())
577 DrawListItemWithMatchesRect(pLVCD, ranges, rt, msg);
578 else
580 COLORREF clrOld = ::SetTextColor(pLVCD->nmcd.hdc, pLVCD->clrText);
581 ::DrawText(pLVCD->nmcd.hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
582 ::SetTextColor(pLVCD->nmcd.hdc, clrOld);
586 if (m_bTagsBranchesOnRightSide)
588 SIZE size;
589 GetTextExtentPoint32(pLVCD->nmcd.hdc, msg, msg.GetLength(), &size);
591 rt.left += oneSpaceSize.cx + size.cx;
593 DrawTagBranch(pLVCD->nmcd.hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
596 if (hTheme)
597 CloseThemeData(hTheme);
599 W_Dc.Detach();
602 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
604 for (unsigned int i = 0; i < refList.size(); ++i)
606 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
607 HBRUSH brush = 0;
608 COLORREF colRef = refList[i].color;
609 bool singleRemote = refList[i].singleRemote;
610 bool hasTracking = refList[i].hasTracking;
611 CGit::REF_TYPE refType = refList[i].refType;
613 //When row selected, ajust label color
614 if (!IsAppThemed())
616 if (rItem.state & LVIS_SELECTED)
617 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
620 brush = ::CreateSolidBrush(colRef);
622 if (!shortname.IsEmpty() && (rt.left < rect.right))
624 SIZE size = { 0 };
625 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
627 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
628 rt.right += 8;
630 int textpos = DT_CENTER;
632 if (rt.right > rect.right)
634 rt.right = rect.right;
635 textpos = 0;
638 CRect textRect = rt;
640 if (singleRemote)
642 rt.right += 5;
643 textRect.OffsetRect(5, 0);
646 if (hasTracking)
647 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
648 else
650 //Fill interior of ref label
651 ::FillRect(hdc, &rt, brush);
654 //Draw edge of label
655 CRect rectEdge = rt;
657 if (!hasTracking)
659 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
660 rectEdge.DeflateRect(1, 1);
661 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
664 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
666 rt.right += 8;
667 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
668 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
669 ::FillRgn(hdc, hrgn, brush);
670 ::DeleteObject(hrgn);
671 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
672 HPEN pen;
673 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
674 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
675 ::DeleteObject(pen);
676 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
677 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
678 ::DeleteObject(pen);
679 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
680 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
681 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
682 ::DeleteObject(pen);
683 SelectObject(hdc, oldpen);
686 //Draw text inside label
687 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
688 if (!customColor && IsAppThemed())
690 int txtState = LISS_NORMAL;
691 if (rItem.state & LVIS_SELECTED)
692 txtState = LISS_SELECTED;
694 DTTOPTS opts = { 0 };
695 opts.dwSize = sizeof(opts);
696 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
697 opts.dwFlags = DTT_TEXTCOLOR;
698 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
700 else
702 W_Dc.SetBkMode(TRANSPARENT);
703 if (customColor || (rItem.state & LVIS_SELECTED))
705 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
706 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
707 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
708 ::SetTextColor(hdc,clrOld);
710 else
712 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
713 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
714 ::SetTextColor(hdc, clrOld);
718 if (singleRemote)
720 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
721 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
722 CRect newRect;
723 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
724 DrawUpstream(hdc, newRect, color, bold);
727 if (!refList[i].fullName.IsEmpty())
728 m_RefLabelPosMap[refList[i].fullName] = rt;
730 rt.left = rt.right + 1;
732 if (brush)
733 ::DeleteObject(brush);
735 rt.right = rect.right;
738 Gdiplus::Color GetGdiColor(COLORREF col)
740 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
742 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
743 const COLORREF& col,const COLORREF& activeColor, int top
746 int h = laneHeight / 2;
747 int m = (x1 + x2) / 2;
748 int r = (x2 - x1) * m_NodeSize / 30;
749 int d = 2 * r;
751 #define P_CENTER m , h+top
752 #define P_0 x2, h+top
753 #define P_90 m , 0+top-1
754 #define P_180 x1, h+top
755 #define P_270 m , 2 * h+top +1
756 #define R_CENTER m - r, h - r+top, d, d
759 #define DELTA_UR_B 2*(x1 - m), 2*h +top
760 #define DELTA_UR_E 0*16, 90*16 +top // -,
762 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
763 #define DELTA_DR_E 270*16, 90*16 +top // -'
765 #define DELTA_UL_B 2*(x2 - m), 2*h +top
766 #define DELTA_UL_E 90*16, 90*16 +top // ,-
768 #define DELTA_DL_B 2*(x2 - m),2*-h +top
769 #define DELTA_DL_E 180*16, 90*16 // '-
771 #define CENTER_UR x1, 2*h, 225
772 #define CENTER_DR x1, 0 , 135
773 #define CENTER_UL x2, 2*h, 315
774 #define CENTER_DL x2, 0 , 45
777 Gdiplus::Graphics graphics( hdc );
779 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
781 // arc
782 switch (type) {
783 case Lanes::JOIN:
784 case Lanes::JOIN_R:
785 case Lanes::HEAD:
786 case Lanes::HEAD_R:
788 Gdiplus::LinearGradientBrush gradient(
789 Gdiplus::Point(x1-2, h+top-2),
790 Gdiplus::Point(P_270),
791 GetGdiColor(activeColor),GetGdiColor(col));
794 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
795 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
797 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
798 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
799 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
801 break;
803 case Lanes::JOIN_L:
805 Gdiplus::LinearGradientBrush gradient(
806 Gdiplus::Point(P_270),
807 Gdiplus::Point(x2+1, h+top-1),
808 GetGdiColor(col),GetGdiColor(activeColor));
811 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
812 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
814 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
815 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
816 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
819 break;
821 case Lanes::TAIL:
822 case Lanes::TAIL_R:
824 Gdiplus::LinearGradientBrush gradient(
825 Gdiplus::Point(x1-2, h+top-2),
826 Gdiplus::Point(P_90),
827 GetGdiColor(activeColor),GetGdiColor(col));
829 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
831 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
833 #if 0
834 QConicalGradient gradient(CENTER_DR);
835 gradient.setColorAt(0.375, activeCol);
836 gradient.setColorAt(0.625, col);
837 myPen.setBrush(gradient);
838 p->setPen(myPen);
839 p->drawArc(P_CENTER, DELTA_DR);
840 #endif
841 break;
843 default:
844 break;
848 //static QPen myPen(Qt::black, 2); // fast path here
849 CPen pen;
850 pen.CreatePen(PS_SOLID,2,col);
851 //myPen.setColor(col);
852 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
854 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
856 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
858 //p->setPen(myPen);
860 // vertical line
861 switch (type) {
862 case Lanes::ACTIVE:
863 case Lanes::NOT_ACTIVE:
864 case Lanes::MERGE_FORK:
865 case Lanes::MERGE_FORK_R:
866 case Lanes::MERGE_FORK_L:
867 case Lanes::JOIN:
868 case Lanes::JOIN_R:
869 case Lanes::JOIN_L:
870 case Lanes::CROSS:
871 //DrawLine(hdc,P_90,P_270);
872 graphics.DrawLine(&myPen,P_90,P_270);
873 //p->drawLine(P_90, P_270);
874 break;
875 case Lanes::HEAD_L:
876 case Lanes::BRANCH:
877 //DrawLine(hdc,P_CENTER,P_270);
878 graphics.DrawLine(&myPen,P_CENTER,P_270);
879 //p->drawLine(P_CENTER, P_270);
880 break;
881 case Lanes::TAIL_L:
882 case Lanes::INITIAL:
883 case Lanes::MERGE_FORK_L_INITIAL:
884 case Lanes::BOUNDARY:
885 case Lanes::BOUNDARY_C:
886 case Lanes::BOUNDARY_R:
887 case Lanes::BOUNDARY_L:
888 //DrawLine(hdc,P_90, P_CENTER);
889 graphics.DrawLine(&myPen,P_90,P_CENTER);
890 //p->drawLine(P_90, P_CENTER);
891 break;
892 default:
893 break;
896 myPen.SetColor(GetGdiColor(activeColor));
898 // horizontal line
899 switch (type) {
900 case Lanes::MERGE_FORK:
901 case Lanes::JOIN:
902 case Lanes::HEAD:
903 case Lanes::TAIL:
904 case Lanes::CROSS:
905 case Lanes::CROSS_EMPTY:
906 case Lanes::BOUNDARY_C:
907 //DrawLine(hdc,P_180,P_0);
908 graphics.DrawLine(&myPen,P_180,P_0);
909 //p->drawLine(P_180, P_0);
910 break;
911 case Lanes::MERGE_FORK_R:
912 case Lanes::BOUNDARY_R:
913 //DrawLine(hdc,P_180,P_CENTER);
914 graphics.DrawLine(&myPen,P_180,P_CENTER);
915 //p->drawLine(P_180, P_CENTER);
916 break;
917 case Lanes::MERGE_FORK_L:
918 case Lanes::MERGE_FORK_L_INITIAL:
919 case Lanes::HEAD_L:
920 case Lanes::TAIL_L:
921 case Lanes::BOUNDARY_L:
922 //DrawLine(hdc,P_CENTER,P_0);
923 graphics.DrawLine(&myPen,P_CENTER,P_0);
924 //p->drawLine(P_CENTER, P_0);
925 break;
926 default:
927 break;
930 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
932 CBrush brush;
933 brush.CreateSolidBrush(col);
934 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
936 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
937 // center symbol, e.g. rect or ellipse
938 switch (type) {
939 case Lanes::ACTIVE:
940 case Lanes::INITIAL:
941 case Lanes::BRANCH:
943 //p->setPen(Qt::NoPen);
944 //p->setBrush(col);
945 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
946 graphics.FillEllipse(&myBrush, R_CENTER);
947 //p->drawEllipse(R_CENTER);
948 break;
949 case Lanes::MERGE_FORK:
950 case Lanes::MERGE_FORK_R:
951 case Lanes::MERGE_FORK_L:
952 case Lanes::MERGE_FORK_L_INITIAL:
953 //p->setPen(Qt::NoPen);
954 //p->setBrush(col);
955 //p->drawRect(R_CENTER);
956 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
957 graphics.FillRectangle(&myBrush, R_CENTER);
958 break;
959 case Lanes::UNAPPLIED:
960 // Red minus sign
961 //p->setPen(Qt::NoPen);
962 //p->setBrush(Qt::red);
963 //p->drawRect(m - r, h - 1, d, 2);
964 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
965 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
966 break;
967 case Lanes::APPLIED:
968 // Green plus sign
969 //p->setPen(Qt::NoPen);
970 //p->setBrush(DARK_GREEN);
971 //p->drawRect(m - r, h - 1, d, 2);
972 //p->drawRect(m - 1, h - r, 2, d);
973 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
974 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
975 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
976 break;
977 case Lanes::BOUNDARY:
978 //p->setBrush(back);
979 //p->drawEllipse(R_CENTER);
980 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
981 graphics.DrawEllipse(&myPen, R_CENTER);
982 break;
983 case Lanes::BOUNDARY_C:
984 case Lanes::BOUNDARY_R:
985 case Lanes::BOUNDARY_L:
986 //p->setBrush(back);
987 //p->drawRect(R_CENTER);
988 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
989 graphics.FillRectangle(&myBrush,R_CENTER);
990 break;
991 default:
992 break;
995 ::SelectObject(hdc,oldpen);
996 ::SelectObject(hdc,oldbrush);
997 #undef P_CENTER
998 #undef P_0
999 #undef P_90
1000 #undef P_180
1001 #undef P_270
1002 #undef R_CENTER
1005 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
1007 // TODO: unfinished
1008 // return;
1009 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1010 if(data->m_CommitHash.IsEmpty())
1011 return;
1013 CRect rt=rect;
1014 LVITEM rItem = { 0 };
1015 rItem.mask = LVIF_STATE;
1016 rItem.iItem = (int)index;
1017 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1018 GetItem(&rItem);
1020 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1022 if (data->m_Lanes.empty())
1023 m_logEntries.setLane(data->m_CommitHash);
1025 std::vector<int>& lanes=data->m_Lanes;
1026 size_t laneNum = lanes.size();
1027 UINT activeLane = 0;
1028 for (UINT i = 0; i < laneNum; ++i)
1029 if (Lanes::isMerge(lanes[i])) {
1030 activeLane = i;
1031 break;
1034 int x2 = 0;
1035 int maxWidth = rect.Width();
1036 int lw = 3 * rect.Height() / 4; //laneWidth()
1038 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1040 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1042 int x1 = x2;
1043 x2 += lw;
1045 int ln = lanes[i];
1046 if (ln == Lanes::EMPTY)
1047 continue;
1049 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1050 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1053 #if 0
1054 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1055 int x1 = x2;
1056 x2 += lw;
1058 int ln = lanes[i];
1059 if (ln == Lanes::EMPTY)
1060 continue;
1062 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1063 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1065 if (ln == Lanes::CROSS)
1067 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1068 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1070 else
1071 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1073 #endif
1076 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1078 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1079 // Take the default processing unless we set this to something else below.
1080 *pResult = CDRF_DODEFAULT;
1082 if (m_bNoDispUpdates)
1083 return;
1085 switch (pLVCD->nmcd.dwDrawStage)
1087 case CDDS_PREPAINT:
1089 *pResult = CDRF_NOTIFYITEMDRAW;
1090 return;
1092 break;
1093 case CDDS_ITEMPREPAINT:
1095 // This is the prepaint stage for an item. Here's where we set the
1096 // item's text color.
1098 // Tell Windows to send draw notifications for each subitem.
1099 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1101 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1103 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1105 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1106 if (data)
1108 HGDIOBJ hGdiObj = nullptr;
1109 int action = data->GetRebaseAction();
1110 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1111 crText = RGB(128,128,128);
1113 if (action & LOGACTIONS_REBASE_SQUASH)
1114 pLVCD->clrTextBk = RGB(156,156,156);
1115 else if (action & LOGACTIONS_REBASE_EDIT)
1116 pLVCD->clrTextBk = RGB(200,200,128);
1117 else
1118 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1120 if (action & LOGACTIONS_REBASE_CURRENT)
1121 hGdiObj = m_boldFont.GetSafeHandle();
1123 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1124 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1125 if (isHeadHash && isHighlight)
1126 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1127 else if (isHeadHash)
1128 hGdiObj = m_boldFont.GetSafeHandle();
1129 else if (isHighlight)
1130 hGdiObj = m_FontItalics.GetSafeHandle();
1132 if (hGdiObj)
1134 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1135 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1138 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1139 // crText = GetSysColor(COLOR_GRAYTEXT);
1141 if (data->m_CommitHash.IsEmpty())
1143 //crText = GetSysColor(RGB(200,200,0));
1144 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1145 // We changed the font, so we're returning CDRF_NEWFONT. This
1146 // tells the control to recalculate the extent of the text.
1147 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1151 // Store the color back in the NMLVCUSTOMDRAW struct.
1152 pLVCD->clrText = crText;
1153 return;
1155 break;
1157 case CDDS_ITEMPREPAINT | CDDS_ITEM | CDDS_SUBITEM:
1159 switch (pLVCD->iSubItem)
1161 case LOGLIST_GRAPH:
1162 if ((m_ShowFilter & FILTERSHOW_MERGEPOINTS) && !m_LogFilter->IsFilterActive())
1164 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1166 CRect rect;
1167 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1169 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1170 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1172 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1173 if( !data ->m_CommitHash.IsEmpty())
1174 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1176 *pResult = CDRF_SKIPDEFAULT;
1177 return;
1180 break;
1182 case LOGLIST_MESSAGE:
1183 // If the top index of list is changed, the position map of reference label is outdated.
1184 if (m_OldTopIndex != GetTopIndex())
1186 m_OldTopIndex = GetTopIndex();
1187 m_RefLabelPosMap.clear();
1190 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1192 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1194 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1196 CRect rect;
1197 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1199 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1200 // not in FillBackGround method, because this only affected the message subitem
1201 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1202 return;
1204 int index = (int)pLVCD->nmcd.dwItemSpec;
1205 int state = GetItemState(index, LVIS_SELECTED);
1206 int txtState = LISS_NORMAL;
1207 if (IsAppThemed() && GetHotItem() == (int)index)
1209 if (state & LVIS_SELECTED)
1210 txtState = LISS_HOTSELECTED;
1211 else
1212 txtState = LISS_HOT;
1214 else if (state & LVIS_SELECTED)
1216 if (::GetFocus() == m_hWnd)
1217 txtState = LISS_SELECTED;
1218 else
1219 txtState = LISS_SELECTEDNOTFOCUS;
1222 HTHEME hTheme = nullptr;
1223 if (IsAppThemed())
1225 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1227 // make sure the column separator/border is not overpainted
1228 int borderWidth = 0;
1229 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
1230 InflateRect(&rect, -(2 * borderWidth), 0);
1233 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1234 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1235 else
1237 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1238 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1239 ::DeleteObject(brush);
1241 if (hTheme && txtState != LISS_NORMAL)
1243 CRect rt;
1244 // get rect of whole line
1245 GetItemRect(index, rt, LVIR_BOUNDS);
1246 CRect rect2 = rect;
1248 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1249 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1251 CloseThemeData(hTheme);
1253 // END: extended redraw
1255 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec, rect);
1257 std::vector<REFLABEL> refsToShow;
1258 STRING_VECTOR remoteTrackingList;
1259 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1260 for (unsigned int i = 0; i < refList.size(); ++i)
1262 CString str = refList[i];
1264 REFLABEL refLabel;
1265 refLabel.color = RGB(255, 255, 255);
1266 refLabel.singleRemote = false;
1267 refLabel.hasTracking = false;
1268 refLabel.sameName = false;
1269 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1270 refLabel.fullName = str;
1272 switch (refLabel.refType)
1274 case CGit::REF_TYPE::LOCAL_BRANCH:
1276 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1277 continue;
1278 if (refLabel.name == m_CurrentBranch)
1279 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1280 else
1281 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1283 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1284 CString pullRemote = trackingEntry.first;
1285 CString pullBranch = trackingEntry.second;
1286 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1288 CString defaultUpstream;
1289 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1290 refLabel.hasTracking = true;
1291 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1293 bool found = false;
1294 for (size_t j = i + 1; j < refList.size(); ++j)
1296 if (refList[j] == defaultUpstream)
1298 found = true;
1299 break;
1303 if (found)
1305 bool sameName = pullBranch == refLabel.name;
1306 refsToShow.push_back(refLabel);
1307 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1308 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1309 if (m_bSymbolizeRefNames)
1311 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1313 refLabel.simplifiedName = L'/';
1314 if (sameName)
1315 refLabel.simplifiedName += L'≡';
1316 else
1317 refLabel.simplifiedName += pullBranch;
1318 refLabel.singleRemote = true;
1320 else if (sameName)
1321 refLabel.simplifiedName = pullRemote + L"/≡";
1322 refLabel.sameName = sameName;
1324 refLabel.fullName = defaultUpstream;
1325 refsToShow.push_back(refLabel);
1326 remoteTrackingList.push_back(defaultUpstream);
1327 continue;
1331 break;
1333 case CGit::REF_TYPE::REMOTE_BRANCH:
1335 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1336 continue;
1337 bool found = false;
1338 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1340 if (remoteTrackingList[j] == str)
1342 found = true;
1343 break;
1346 if (found)
1347 continue;
1349 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1350 if (m_bSymbolizeRefNames)
1352 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1354 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1355 refLabel.singleRemote = true;
1358 break;
1360 case CGit::REF_TYPE::ANNOTATED_TAG: // fallthrough
1361 case CGit::REF_TYPE::TAG:
1362 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1363 continue;
1364 refLabel.color = m_Colors.GetColor(CColors::Tag);
1365 break;
1367 case CGit::REF_TYPE::STASH:
1368 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1369 continue;
1370 refLabel.color = m_Colors.GetColor(CColors::Stash);
1371 break;
1373 case CGit::REF_TYPE::BISECT_GOOD: // fallthrough
1374 case CGit::REF_TYPE::BISECT_BAD: // fallthrough
1375 case CGit::REF_TYPE::BISECT_SKIP:
1376 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1377 continue;
1378 refLabel.color = (refLabel.refType == CGit::REF_TYPE::BISECT_GOOD) ? m_Colors.GetColor(CColors::BisectGood) : ((refLabel.refType == CGit::REF_TYPE::BISECT_SKIP) ? m_Colors.GetColor(CColors::BisectSkip) : m_Colors.GetColor(CColors::BisectBad));
1379 break;
1381 case CGit::REF_TYPE::NOTES:
1382 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1383 continue;
1384 refLabel.color = m_Colors.GetColor(CColors::NoteNode);
1385 break;
1387 default:
1388 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1389 continue;
1390 refLabel.color = m_Colors.GetColor(CColors::OtherRef);
1391 break;
1393 refsToShow.push_back(refLabel);
1395 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1397 REFLABEL refLabel;
1398 refLabel.color = RGB(246, 153, 253);
1399 refLabel.singleRemote = false;
1400 refLabel.hasTracking = false;
1401 refLabel.sameName = false;
1402 refLabel.name = L"super-project-pointer";
1403 refLabel.fullName = "";
1404 refsToShow.push_back(refLabel);
1407 if (refsToShow.empty())
1409 *pResult = CDRF_DODEFAULT;
1410 return;
1413 DrawTagBranchMessage(pLVCD, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1415 *pResult = CDRF_SKIPDEFAULT;
1416 return;
1418 else if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_SUBJECT | LOGFILTER_MESSAGES, pLVCD, pResult))
1419 return;
1421 break;
1423 case LOGLIST_ACTION:
1425 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1427 *pResult = CDRF_DODEFAULT;
1428 return;
1430 *pResult = CDRF_DODEFAULT;
1432 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1433 return;
1435 int nIcons = 0;
1436 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1437 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1439 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1440 CRect rect;
1441 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1442 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1443 // Get the selected state of the
1444 // item being drawn.
1446 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1447 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1449 // Fill the background if necessary
1450 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1452 // Draw the icon(s) into the compatible DC
1453 int action = pLogEntry->GetAction(this);
1454 auto iconItemBorder = CDPIAware::Instance().ScaleX(ICONITEMBORDER);
1455 if (!pLogEntry->m_IsDiffFiles)
1457 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1458 *pResult = CDRF_SKIPDEFAULT;
1459 return;
1462 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1463 ::DrawIconEx(myDC.GetDC(), rect.left + iconItemBorder, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1464 ++nIcons;
1466 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1467 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1468 ++nIcons;
1470 if (action & CTGitPath::LOGACTIONS_DELETED)
1471 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1472 ++nIcons;
1474 if (action & CTGitPath::LOGACTIONS_REPLACED)
1475 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1476 ++nIcons;
1478 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1479 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + iconItemBorder, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1480 ++nIcons;
1482 *pResult = CDRF_SKIPDEFAULT;
1483 return;
1486 case LOGLIST_HASH:
1487 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_REVS, pLVCD, pResult))
1488 return;
1489 break;
1491 case LOGLIST_AUTHOR:
1492 case LOGLIST_COMMIT_NAME:
1493 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_AUTHORS, pLVCD, pResult))
1494 return;
1495 break;
1497 case LOGLIST_EMAIL:
1498 case LOGLIST_COMMIT_EMAIL:
1499 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_EMAILS, pLVCD, pResult))
1500 return;
1501 break;
1503 case LOGLIST_BUG:
1504 if (DrawListItemWithMatchesIfEnabled(m_LogFilter, LOGFILTER_BUGID, pLVCD, pResult))
1505 return;
1506 break;
1509 break;
1511 *pResult = CDRF_DODEFAULT;
1514 CString FindSVNRev(const CString& msg)
1518 const std::wsregex_iterator end;
1519 std::wstring s = msg;
1520 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1521 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1523 const std::wsmatch match = *it;
1524 if (match.size() == 4)
1526 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1527 return std::wstring(match[2]).c_str();
1530 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1531 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1533 const std::wsmatch match = *it;
1534 if (match.size() == 3)
1536 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1537 return std::wstring(match[1]).c_str();
1541 catch (std::exception&) {}
1543 return L"";
1546 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1548 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1549 return pLogEntry->GetSubject();
1551 CString txt(pLogEntry->GetSubject());
1552 txt += L' ';
1553 txt += pLogEntry->GetBody();
1555 // Deal with CRLF
1556 txt.Replace(L'\n', L' ');
1557 txt.Replace(L'\r', L' ');
1559 return txt;
1562 // CGitLogListBase message handlers
1564 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1566 struct payload_struct { const CString* name; const char* authorName; };
1567 payload_struct payload = { &name, nullptr };
1568 const char* author1 = nullptr;
1569 const char* email1 = nullptr;
1570 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1571 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1572 free((void *)payload.authorName);
1573 if (returnEmail)
1574 return email1;
1575 return author1;
1578 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1580 if (mailmap)
1582 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1583 if (translated)
1585 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1586 return;
1589 if (returnEmail)
1590 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1591 else
1592 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1595 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1597 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1599 // Create a pointer to the item
1600 LV_ITEM* pItem = &(pDispInfo)->item;
1602 // Do the list need text information?
1603 if (!(pItem->mask & LVIF_TEXT))
1604 return;
1606 // By default, clear text buffer.
1607 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1609 bool bOutOfRange = pItem->iItem >= (int)m_arShownList.size();
1611 *pResult = 0;
1612 if (m_bNoDispUpdates || bOutOfRange)
1613 return;
1615 // Which item number?
1616 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1618 CString temp;
1619 if(m_IsOldFirst)
1620 temp.Format(L"%d", pItem->iItem + 1);
1621 else
1622 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1624 if (!pLogEntry)
1625 return;
1627 // Which column?
1628 switch (pItem->iSubItem)
1630 case LOGLIST_GRAPH: //Graphic
1631 break;
1632 case LOGLIST_REBASE:
1633 if (m_IsRebaseReplaceGraph)
1634 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1635 break;
1636 case LOGLIST_ACTION: //action -- no text in the column
1637 break;
1638 case LOGLIST_HASH:
1639 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1640 break;
1641 case LOGLIST_ID:
1642 if (this->m_IsIDReplaceAction)
1643 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1644 break;
1645 case LOGLIST_MESSAGE: //Message
1646 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1647 break;
1648 case LOGLIST_AUTHOR: //Author
1649 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1650 break;
1651 case LOGLIST_DATE: //Date
1652 if (!pLogEntry->m_CommitHash.IsEmpty())
1653 lstrcpyn(pItem->pszText,
1654 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1655 pItem->cchTextMax - 1);
1656 break;
1658 case LOGLIST_EMAIL:
1659 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1660 break;
1662 case LOGLIST_COMMIT_NAME: //Commit
1663 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1664 break;
1666 case LOGLIST_COMMIT_EMAIL: //Commit Email
1667 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1668 break;
1670 case LOGLIST_COMMIT_DATE: //Commit Date
1671 if (!pLogEntry->m_CommitHash.IsEmpty())
1672 lstrcpyn(pItem->pszText,
1673 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1674 pItem->cchTextMax - 1);
1675 break;
1676 case LOGLIST_BUG: //Bug ID
1677 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1678 break;
1679 case LOGLIST_SVNREV: //SVN revision
1680 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1681 break;
1683 default:
1684 ASSERT(false);
1688 bool CGitLogListBase::IsOnStash(int index)
1690 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1691 if (IsStash(rev))
1692 return true;
1693 if (index > 0)
1695 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1696 if (IsStash(preRev))
1697 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1699 return false;
1702 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1704 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1705 if (refList == m_HashMap.cend())
1706 return false;
1707 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1710 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1712 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1713 if (refList == m_HashMap.cend())
1714 return false;
1715 return find_if((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1718 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1720 if (pRev->m_ParentHash.empty())
1722 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1723 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1725 parentHash = pRev->m_ParentHash;
1728 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1730 __super::OnContextMenu(pWnd, point);
1732 if (pWnd != this)
1733 return;
1735 int selIndex = GetSelectionMark();
1736 if (selIndex < 0)
1737 return; // nothing selected, nothing to do with a context menu
1739 // if the context menu is invoked through the keyboard, we have to use
1740 // a calculated position on where to anchor the menu on
1741 if ((point.x == -1) && (point.y == -1))
1743 CRect rect;
1744 GetItemRect(selIndex, &rect, LVIR_LABEL);
1745 ClientToScreen(&rect);
1746 point = rect.CenterPoint();
1748 m_nSearchIndex = selIndex;
1750 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1752 POSITION pos = GetFirstSelectedItemPosition();
1753 int FirstSelect = GetNextSelectedItem(pos);
1754 if (FirstSelect < 0)
1755 return;
1757 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1758 if (pSelLogEntry == nullptr)
1759 return;
1761 int LastSelect = -1;
1762 UINT selectedCount = 1;
1763 while (pos)
1765 LastSelect = GetNextSelectedItem(pos);
1766 ++selectedCount;
1769 ASSERT(GetSelectedCount() == selectedCount);
1771 //entry is selected, now show the popup menu
1772 CIconMenu popup;
1773 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1775 if (popup.CreatePopupMenu())
1777 CGitHash headHash;
1778 if (g_Git.GetHash(headHash, L"HEAD"))
1780 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1781 return;
1783 bool isHeadCommit = (pSelLogEntry->m_CommitHash == headHash);
1784 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1785 CTGitPath workingTree(g_Git.m_CurrentDir);
1786 bool isMergeActive = workingTree.IsMergeActive();
1787 bool isBisectActive = workingTree.IsBisectActive();
1788 bool isStash = IsOnStash(FirstSelect);
1789 GIT_REV_LIST parentHash;
1790 GetParentHashes(pSelLogEntry, parentHash);
1791 STRING_VECTOR parentInfo;
1792 for (size_t i = 0; i < parentHash.size(); ++i)
1794 CString str;
1795 str.Format(IDS_PARENT, i + 1);
1796 GitRev rev;
1797 if (rev.GetCommit(parentHash[i].ToString()) == 0)
1799 CString commitTitle = rev.GetSubject();
1800 if (commitTitle.GetLength() > 20)
1802 commitTitle.Truncate(20);
1803 commitTitle += L"...";
1805 str.AppendFormat(L": \"%s\" (%s)", (LPCTSTR)commitTitle, (LPCTSTR)parentHash[i].ToString().Left(g_Git.GetShortHASHLength()));
1807 else
1808 str.AppendFormat(L" (%s)", (LPCTSTR)parentHash[i].ToString().Left(g_Git.GetShortHASHLength()));
1809 parentInfo.push_back(str);
1812 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1813 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1815 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))
1816 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1818 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1819 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1821 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1822 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1824 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)))
1825 popup.AppendMenu(MF_SEPARATOR, NULL);
1827 if (selectedCount == 1)
1830 bool requiresSeparator = false;
1831 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1833 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1835 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1836 requiresSeparator = true;
1839 else
1841 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1843 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1844 requiresSeparator = true;
1846 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1848 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1849 requiresSeparator = true;
1853 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1855 if (parentHash.size() == 1)
1857 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1858 requiresSeparator = true;
1860 else if (parentHash.size() > 1)
1862 blamemenu.CreatePopupMenu();
1863 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1864 for (size_t i = 0; i < parentInfo.size(); ++i)
1866 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS + ((i + 1) << 16), parentInfo[i]);
1868 requiresSeparator = true;
1872 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1874 if (parentHash.size() == 1)
1876 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1877 requiresSeparator = true;
1879 else if (parentHash.size() > 1)
1881 gnudiffmenu.CreatePopupMenu();
1882 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1884 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1885 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1886 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1888 for (size_t i = 0; i < parentInfo.size(); ++i)
1890 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1 + ((i + 1) << 16), parentInfo[i]);
1892 requiresSeparator = true;
1896 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1898 if (parentHash.size() == 1)
1900 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1901 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE) && m_ColumnRegKey != L"reflog")
1902 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1903 requiresSeparator = true;
1905 else if (parentHash.size() > 1)
1907 diffmenu.CreatePopupMenu();
1908 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1909 for (size_t i = 0; i < parentInfo.size(); ++i)
1911 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16), parentInfo[i]);
1912 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE) && m_ColumnRegKey != L"reflog")
1914 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1915 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1918 requiresSeparator = true;
1922 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1924 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1925 requiresSeparator = true;
1928 if (requiresSeparator)
1930 popup.AppendMenu(MF_SEPARATOR, NULL);
1931 requiresSeparator = false;
1934 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1936 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1938 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_SHELVE);
1939 requiresSeparator = true;
1943 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1945 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1947 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_UNSHELVE);
1948 requiresSeparator = true;
1951 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1953 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1954 requiresSeparator = true;
1958 if (requiresSeparator)
1960 popup.AppendMenu(MF_SEPARATOR, NULL);
1961 requiresSeparator = false;
1964 if (isBisectActive)
1966 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1967 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1969 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1970 requiresSeparator = true;
1973 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1975 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1976 requiresSeparator = true;
1978 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1980 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1981 requiresSeparator = true;
1985 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1987 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1989 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1990 requiresSeparator = true;
1994 if (requiresSeparator)
1996 popup.AppendMenu(MF_SEPARATOR, NULL);
1997 requiresSeparator = false;
2000 if (pSelLogEntry->m_CommitHash.IsEmpty())
2002 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
2003 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2005 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
2006 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_UPDATE);
2008 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2009 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2011 popup.AppendMenu(MF_SEPARATOR, NULL);
2013 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2014 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2016 popup.AppendMenu(MF_SEPARATOR, NULL);
2020 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2021 // {
2022 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2023 // }
2024 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2025 // {
2026 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2027 // }
2028 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2029 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2030 // {
2031 // popup.AppendMenu(MF_SEPARATOR, NULL);
2032 // }
2034 CString str;
2035 //if (m_hasWC)
2036 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2038 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2040 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2042 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2043 if (m_ColumnRegKey == L"reflog")
2044 popup.SetDefaultItem(ID_LOG, FALSE);
2047 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2048 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2050 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2052 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2054 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2056 size_t index = (size_t)-1;
2057 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2058 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2059 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2062 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2064 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2065 popup.AppendMenuIcon(ID_RESET, str, IDI_RESET);
2068 // Add Switch Branch express Menu
2069 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2070 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2073 std::vector<const CString*> branchs;
2074 auto addCheck = [&](const CString& ref)
2076 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2077 return;
2078 branchs.push_back(&ref);
2080 size_t index = (size_t)-1;
2081 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2082 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2083 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2084 else
2085 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2087 CString str2;
2088 str2.LoadString(IDS_SWITCH_BRANCH);
2090 if(branchs.size() == 1)
2092 str2 += L' ';
2093 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2094 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2096 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2099 else if(branchs.size() > 1)
2101 subbranchmenu.CreatePopupMenu();
2102 for (size_t i = 0 ; i < branchs.size(); ++i)
2104 if (*branchs[i] != currentBranch)
2106 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH + (i << 16), branchs[i]->Mid((int)wcslen(L"refs/heads/")));
2107 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2111 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2115 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2117 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2118 size_t index = (size_t)-1;
2119 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2120 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2121 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2124 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2126 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2128 size_t index = (size_t)-1;
2129 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2130 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2131 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2134 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2135 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2137 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2139 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2140 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2141 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2143 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2144 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2146 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2148 if (parentHash.size() == 1)
2149 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2150 else if (parentHash.size() > 1)
2152 revertmenu.CreatePopupMenu();
2153 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2155 for (size_t i = 0; i < parentInfo.size(); ++i)
2157 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), parentInfo[i]);
2162 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2163 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2165 popup.AppendMenu(MF_SEPARATOR, NULL);
2169 if(!pSelLogEntry->m_Ref.IsEmpty())
2171 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2172 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2173 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_UNSHELVE);
2174 if (selectedCount <= 2)
2175 popup.AppendMenu(MF_SEPARATOR, NULL);
2178 if (selectedCount >= 2)
2180 bool bAddSeparator = false;
2181 if ((selectedCount == 2) || IsSelectionContinuous())
2183 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2185 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2186 bAddSeparator = true;
2190 if (selectedCount == 2)
2192 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2194 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2195 bAddSeparator = true;
2198 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2200 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2201 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2202 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2203 CString menu;
2204 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2205 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2206 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2207 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2208 bAddSeparator = true;
2212 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2214 bAddSeparator = true;
2215 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2218 if (bAddSeparator)
2220 popup.AppendMenu(MF_SEPARATOR, NULL);
2221 bAddSeparator = false;
2224 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2225 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2227 if (bAddSeparator)
2228 popup.AppendMenu(MF_SEPARATOR, NULL);
2231 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2233 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2234 popup.AppendMenu(MF_SEPARATOR, NULL);
2237 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2239 bool bAddSeparator = false;
2240 if (selectedCount >= 2 && IsSelectionContinuous())
2242 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2244 CString head;
2245 int headindex;
2246 headindex = this->GetHeadIndex();
2247 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2249 head.Format(L"HEAD~%d", FirstSelect - headindex);
2250 CGitHash hashFirst;
2251 int ret = g_Git.GetHash(hashFirst, head);
2252 head.Format(L"HEAD~%d",LastSelect-headindex);
2253 CGitHash hash;
2254 ret = ret || g_Git.GetHash(hash, head);
2255 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2256 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2257 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2259 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2260 bAddSeparator = true;
2265 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2266 if (selectedCount >= 2)
2267 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_PICK);
2268 else
2269 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_PICK);
2270 bAddSeparator = true;
2273 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2274 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2275 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2276 bAddSeparator = true;
2279 if (bAddSeparator)
2280 popup.AppendMenu(MF_SEPARATOR, NULL);
2283 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2285 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2286 popup.AppendMenu(MF_SEPARATOR, NULL);
2289 if (selectedCount == 1)
2291 bool bAddSeparator = false;
2292 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2294 // show the push-option only if the log entry has an associated local branch
2295 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2296 if (isLocal || showExtendedMenu)
2298 CString str;
2299 str.LoadString(IDS_MENUPUSH);
2301 CString branch;
2302 size_t index = (size_t)-1;
2303 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2304 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2305 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2306 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2308 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2310 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2311 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2313 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2314 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2316 bAddSeparator = true;
2319 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2321 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2322 bAddSeparator = true;
2326 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2328 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2330 std::vector<const CString*> branchs;
2331 auto addCheck = [&](const CString& ref)
2333 if (ref == currentBranch)
2334 return;
2335 branchs.push_back(&ref);
2337 size_t index = (size_t)-1;
2338 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2339 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2340 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2341 else
2342 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2344 CString str;
2345 if (branchs.size() == 1)
2347 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2348 str += L' ';
2349 str += *branchs[0];
2350 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2351 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2352 bAddSeparator = true;
2354 else if (branchs.size() > 1)
2356 str.LoadString(IDS_DELETE_BRANCHTAG);
2357 submenu.CreatePopupMenu();
2358 for (size_t i = 0; i < branchs.size(); ++i)
2360 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2361 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2363 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2364 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2366 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2367 bAddSeparator = true;
2370 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2371 if (bAddSeparator)
2372 popup.AppendMenu(MF_SEPARATOR, NULL);
2373 } // selectedCount == 1
2375 CIconMenu clipSubMenu;
2376 if (!clipSubMenu.CreatePopupMenu())
2377 return;
2378 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2380 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2381 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2382 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2383 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2384 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2385 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2386 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2387 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2388 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2390 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2391 size_t index = (size_t)-1;
2392 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2393 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2394 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2397 CString temp;
2398 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2399 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2402 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2403 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2405 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2406 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2408 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2409 // DialogEnableWindow(IDOK, FALSE);
2410 // SetPromptApp(&theApp);
2412 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2414 // EnableOKButton();
2415 } // if (popup.CreatePopupMenu())
2418 bool CGitLogListBase::IsSelectionContinuous()
2420 if ( GetSelectedCount()==1 )
2422 // if only one revision is selected, the selection is of course
2423 // continuous
2424 return true;
2427 POSITION pos = GetFirstSelectedItemPosition();
2428 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2429 if (bContinuous)
2431 int itemindex = GetNextSelectedItem(pos);
2432 while (pos)
2434 int nextindex = GetNextSelectedItem(pos);
2435 if (nextindex - itemindex > 1)
2437 bContinuous = false;
2438 break;
2440 itemindex = nextindex;
2443 return bContinuous;
2446 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2448 CString sClipdata;
2449 POSITION pos = GetFirstSelectedItemPosition();
2450 if (pos)
2452 CString sRev;
2453 sRev.LoadString(IDS_LOG_REVISION);
2454 CString sAuthor;
2455 sAuthor.LoadString(IDS_LOG_AUTHOR);
2456 CString sDate;
2457 sDate.LoadString(IDS_LOG_DATE);
2458 CString sMessage;
2459 sMessage.LoadString(IDS_LOG_MESSAGE);
2460 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2461 bool first = true;
2462 while (pos)
2464 CString sLogCopyText;
2465 CString sPaths;
2466 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2468 if (toCopy == ID_COPYCLIPBOARDFULL)
2470 sPaths = L"----\r\n";
2471 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2473 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2474 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2476 sPaths += L' ';
2477 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2479 sPaths += L"\r\n";
2481 sPaths.Trim();
2482 sPaths += L"\r\n";
2485 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2487 CString sNotesTags;
2488 if (!pLogEntry->m_Notes.IsEmpty())
2490 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2491 sNotesTags += L":\n";
2492 sNotesTags += pLogEntry->m_Notes;
2493 sNotesTags.Replace(L"\n", L"\r\n");
2495 CString tagInfo = GetTagInfo(pLogEntry);
2496 if (!tagInfo.IsEmpty())
2498 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2499 tagInfo.Replace(L"\n", L"\r\n");
2500 sNotesTags += tagInfo;
2503 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",
2504 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2505 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2506 (LPCTSTR)sDate,
2507 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2508 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2509 (LPCTSTR)sNotesTags,
2510 (LPCTSTR)sPaths);
2511 sClipdata += sLogCopyText;
2513 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2515 if (!first)
2516 sClipdata += L"\r\n";
2517 sClipdata += pLogEntry->GetAuthorName();
2518 sClipdata += L" <";
2519 sClipdata += pLogEntry->GetAuthorEmail();
2520 sClipdata += L">";
2522 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2524 if (!first)
2525 sClipdata += L"\r\n";
2526 sClipdata += pLogEntry->GetAuthorName();
2528 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2530 if (!first)
2531 sClipdata += L"\r\n";
2532 sClipdata += pLogEntry->GetAuthorEmail();
2535 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2537 sClipdata += L"* ";
2538 sClipdata += pLogEntry->GetSubjectBody(true);
2539 sClipdata += L"\r\n\r\n";
2541 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2543 sClipdata += L"* ";
2544 sClipdata += pLogEntry->GetSubject().Trim();
2545 sClipdata += L"\r\n\r\n";
2547 else
2549 if (!first)
2550 sClipdata += L"\r\n";
2551 sClipdata += pLogEntry->m_CommitHash.ToString();
2554 first = false;
2556 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2560 void CGitLogListBase::DiffSelectedRevWithPrevious()
2562 if (m_bThreadRunning)
2563 return;
2565 int FirstSelect=-1, LastSelect=-1;
2566 POSITION pos = GetFirstSelectedItemPosition();
2567 FirstSelect = GetNextSelectedItem(pos);
2568 while(pos)
2569 LastSelect = GetNextSelectedItem(pos);
2571 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2574 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2576 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2577 *pResult = -1;
2579 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2580 return;
2581 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2582 return;
2583 if (!pFindInfo->lvfi.psz)
2584 return;
2585 #if 0
2586 CString sCmp = pFindInfo->lvfi.psz;
2587 CString sRev;
2588 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2590 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2591 sRev.Format(L"%ld", pLogEntry->Rev);
2592 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2594 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2596 *pResult = i;
2597 return;
2600 else
2602 if (sCmp.Compare(sRev)==0)
2604 *pResult = i;
2605 return;
2609 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2611 for (int i=0; i<pFindInfo->iStart; ++i)
2613 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2614 sRev.Format(L"%ld", pLogEntry->Rev);
2615 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2617 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2619 *pResult = i;
2620 return;
2623 else
2625 if (sCmp.Compare(sRev)==0)
2627 *pResult = i;
2628 return;
2633 #endif
2634 *pResult = -1;
2637 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2639 ClearText();
2641 this->m_arShownList.SafeRemoveAll();
2643 this->m_logEntries.ClearAll();
2644 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2645 return -1;
2647 SetItemCountEx((int)m_logEntries.size());
2649 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2651 if(m_IsOldFirst)
2653 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2654 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2656 else
2658 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2659 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2663 ReloadHashMap();
2665 if(path)
2666 m_Path=*path;
2667 return 0;
2670 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2672 ClearText();
2674 m_arShownList.SafeRemoveAll();
2676 m_logEntries.ClearAll();
2677 if (m_logEntries.Fill(hashes))
2678 return -1;
2680 SetItemCountEx((int)m_logEntries.size());
2682 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2684 if (m_IsOldFirst)
2686 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2687 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2689 else
2691 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2692 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2696 ReloadHashMap();
2698 return 0;
2701 int CGitLogListBase::BeginFetchLog()
2703 ClearText();
2705 this->m_arShownList.SafeRemoveAll();
2707 this->m_logEntries.ClearAll();
2709 this->m_LogCache.ClearAllParent();
2711 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2713 CTGitPath *path;
2714 if(this->m_Path.IsEmpty())
2715 path = nullptr;
2716 else
2717 path=&this->m_Path;
2719 int mask;
2720 mask = CGit::LOG_INFO_ONLY_HASH;
2721 if (m_bIncludeBoundaryCommits)
2722 mask |= CGit::LOG_INFO_BOUNDARY;
2723 // if(this->m_bAllBranch)
2724 mask |= m_ShowMask ;
2726 if(m_bShowWC)
2728 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2729 ResetWcRev();
2730 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2733 if (m_sRange.IsEmpty())
2734 m_sRange = L"HEAD";
2736 // follow does not work for directories
2737 if (!path || path->IsDirectory())
2738 mask &= ~CGit::LOG_INFO_FOLLOW;
2739 // follow does not work with all branches 8at least in TGit)
2740 if (mask & CGit::LOG_INFO_FOLLOW)
2741 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2743 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2745 //this->m_logEntries.ParserFromLog();
2746 if(IsInWorkingThread())
2748 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2750 else
2752 SetItemCountEx((int)m_logEntries.size());
2757 g_Git.CheckAndInitDll();
2759 catch (char* msg)
2761 CString err(msg);
2762 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2763 return -1;
2766 if (!g_Git.CanParseRev(m_sRange))
2768 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2769 return 0;
2771 // if show all branches, pick any ref as dummy entry ref
2772 STRING_VECTOR list;
2773 if (g_Git.GetRefList(list))
2774 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2775 if (list.empty())
2776 return 0;
2778 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2781 g_Git.m_critGitDllSec.Lock();
2782 try {
2783 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8)))
2785 g_Git.m_critGitDllSec.Unlock();
2786 return -1;
2789 catch (char* msg)
2791 g_Git.m_critGitDllSec.Unlock();
2792 CString err(msg);
2793 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2794 return -1;
2796 g_Git.m_critGitDllSec.Unlock();
2798 return 0;
2801 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2803 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2805 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2807 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2809 DiffSelectedRevWithPrevious();
2810 return TRUE;
2813 #if 0
2814 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2816 DiffSelectedFile();
2817 return TRUE;
2819 #endif
2821 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2823 // select all entries
2824 for (int i=0; i<GetItemCount(); ++i)
2825 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2826 return TRUE;
2829 #if 0
2830 if (m_hAccel && !bSkipAccelerator)
2832 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2833 if (ret)
2834 return TRUE;
2837 #endif
2838 //m_tooltips.RelayEvent(pMsg);
2839 return __super::PreTranslateMessage(pMsg);
2842 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2844 // a double click on an entry in the revision list has happened
2845 *pResult = 0;
2847 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2848 DiffSelectedRevWithPrevious();
2851 void CGitLogListBase::FetchLogAsync(void* data)
2853 ReloadHashMap();
2854 m_ProcData=data;
2855 StartLoadingThread();
2858 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2860 return ((CGitLogListBase*)pVoid)->LogThread();
2863 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2865 //CTime time;
2866 oldest=CTime::GetCurrentTime();
2867 latest=CTime(1971,1,2,0,0,0);
2868 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2870 if(m_logEntries[i].IsEmpty())
2871 continue;
2873 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2874 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2876 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2877 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2881 if(latest<oldest)
2882 latest=oldest;
2885 UINT CGitLogListBase::LogThread()
2887 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2889 ULONGLONG t1,t2;
2891 if(BeginFetchLog())
2893 InterlockedExchange(&m_bThreadRunning, FALSE);
2894 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2896 return 1;
2899 // create a copy we can safely work on in this thread
2900 auto shared_filter(m_LogFilter);
2901 auto& filter = *shared_filter;
2903 TRACE(L"\n===Begin===\n");
2904 //Update work copy item;
2906 if (!m_logEntries.empty())
2908 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2910 m_arShownList.SafeAdd(pRev);
2914 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2916 // store commit number of the last selected commit/line before the refresh or -1
2917 int lastSelectedHashNItem = -1;
2918 if (m_lastSelectedHash.IsEmpty())
2919 lastSelectedHashNItem = 0;
2921 int ret = 0;
2923 bool shouldWalk = true;
2924 if (!g_Git.CanParseRev(m_sRange))
2926 // walk revisions if show all branches and there exists any ref
2927 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2928 shouldWalk = false;
2929 else
2931 STRING_VECTOR list;
2932 if (g_Git.GetRefList(list))
2933 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2934 if (list.empty())
2935 shouldWalk = false;
2939 if (shouldWalk)
2941 g_Git.m_critGitDllSec.Lock();
2942 if (!m_DllGitLog)
2944 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2945 g_Git.m_critGitDllSec.Unlock();
2946 InterlockedExchange(&m_bThreadRunning, FALSE);
2947 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2948 return 1;
2950 int total = 0;
2953 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2954 total = git_get_log_estimate_commit_count(m_DllGitLog);
2956 catch (char* msg)
2958 CString err(msg);
2959 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2960 ret = -1;
2962 g_Git.m_critGitDllSec.Unlock();
2964 GIT_COMMIT commit;
2965 t2 = t1 = GetTickCount64();
2966 int oldprecentage = 0;
2967 size_t oldsize = m_logEntries.size();
2968 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2969 while (ret== 0 && !m_bExitThread)
2971 g_Git.m_critGitDllSec.Lock();
2974 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2976 catch (char* msg)
2978 g_Git.m_critGitDllSec.Unlock();
2979 CString err(msg);
2980 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2981 break;
2983 g_Git.m_critGitDllSec.Unlock();
2985 if(ret)
2987 if (ret != -2) // other than end of revision walking
2988 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2989 break;
2992 if (commit.m_ignore == 1)
2994 git_free_commit(&commit);
2995 continue;
2998 //printf("%s\r\n",commit.GetSubject());
2999 if(m_bExitThread)
3000 break;
3002 CGitHash hash(commit.m_hash);
3004 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3005 pRev->m_GitCommit = commit;
3006 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3008 char* note = nullptr;
3009 g_Git.m_critGitDllSec.Lock();
3012 git_get_notes(commit.m_hash, &note);
3014 catch (char* msg)
3016 g_Git.m_critGitDllSec.Unlock();
3017 CString err(msg);
3018 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3019 break;
3021 g_Git.m_critGitDllSec.Unlock();
3023 if(note)
3025 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3026 free(note);
3027 note = nullptr;
3030 if(!pRev->m_IsDiffFiles)
3032 pRev->m_CallDiffAsync = DiffAsync;
3035 pRev->ParserParentFromCommit(&commit);
3036 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3038 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3040 const CGitHash &parentHash = pRev->m_ParentHash[i];
3041 auto it = commitChildren.find(parentHash);
3042 if (it == commitChildren.end())
3043 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3044 it->second.insert(pRev->m_CommitHash);
3048 #ifdef DEBUG
3049 pRev->DbgPrint();
3050 TRACE(L"\n");
3051 #endif
3053 bool visible = filter(pRev, this);
3054 if (visible && !ShouldShowFilter(pRev, commitChildren))
3055 visible = false;
3056 this->m_critSec.Lock();
3057 m_logEntries.append(hash, visible);
3058 if (visible)
3059 m_arShownList.SafeAdd(pRev);
3060 this->m_critSec.Unlock();
3062 if (!visible)
3063 continue;
3065 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3066 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3068 t2 = GetTickCount64();
3070 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3072 //update UI
3073 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3074 if(percent > 99)
3075 percent =99;
3076 if(percent < GITLOG_START)
3077 percent = GITLOG_START +1;
3079 oldsize = m_logEntries.size();
3080 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3082 //if( percent > oldprecentage )
3084 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3085 oldprecentage = percent;
3088 if (lastSelectedHashNItem >= 0)
3089 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3091 t1 = t2;
3094 g_Git.m_critGitDllSec.Lock();
3095 git_close_log(m_DllGitLog);
3096 g_Git.m_critGitDllSec.Unlock();
3100 if (m_bExitThread)
3102 InterlockedExchange(&m_bThreadRunning, FALSE);
3103 return 0;
3106 //Update UI;
3107 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3109 if (lastSelectedHashNItem >= 0)
3110 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3112 if (this->m_hWnd)
3113 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3115 InterlockedExchange(&m_bThreadRunning, FALSE);
3117 return 0;
3120 void CGitLogListBase::FetchRemoteList()
3122 STRING_VECTOR remoteList;
3123 m_SingleRemote.Empty();
3124 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3125 m_SingleRemote = remoteList[0];
3128 void CGitLogListBase::FetchTrackingBranchList()
3130 m_TrackingMap.clear();
3131 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3133 for (const auto& ref : it->second)
3135 CString branchName;
3136 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3138 CString pullRemote, pullBranch;
3139 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3140 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3141 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3147 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3149 SafeTerminateThread();
3151 this->SetItemCountEx(0);
3152 this->Clear();
3154 ResetWcRev();
3156 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3158 if (m_pMailmap)
3160 git_free_mailmap(m_pMailmap);
3161 git_read_mailmap(&m_pMailmap);
3164 //Update branch and Tag info
3165 ReloadHashMap();
3166 if (m_pFindDialog)
3167 m_pFindDialog->RefreshList();
3168 //Assume Thread have exited
3169 //if(!m_bThreadRunning)
3171 m_logEntries.clear();
3173 if (IsCleanFilter)
3174 m_LogFilter = std::make_shared<CLogDlgFilter>();
3176 SafeTerminateAsyncDiffThread();
3177 m_AsynDiffListLock.Lock();
3178 m_AsynDiffList.clear();
3179 m_AsynDiffListLock.Unlock();
3180 StartAsyncDiffThread();
3182 StartLoadingThread();
3186 void CGitLogListBase::StartAsyncDiffThread()
3188 if (m_AsyncThreadExit)
3189 return;
3190 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3191 return;
3192 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3193 if (!m_DiffingThread)
3195 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3196 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3200 void CGitLogListBase::StartLoadingThread()
3202 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3203 return;
3204 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3205 InterlockedExchange(&m_bExitThread, FALSE);
3206 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3207 if (!m_LoadingThread)
3209 InterlockedExchange(&m_bThreadRunning, FALSE);
3210 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3211 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3215 static bool CStringStartsWith(const CString &str, const CString &prefix)
3217 return str.Left(prefix.GetLength()) == prefix;
3219 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3221 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3222 return true;
3224 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3226 // Keep all refs.
3227 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3228 for (size_t i = 0; i < refList.size(); ++i)
3230 const CString &str = refList[i];
3231 if (CStringStartsWith(str, L"refs/heads/"))
3233 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3234 return true;
3236 else if (CStringStartsWith(str, L"refs/remotes/"))
3238 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3239 return true;
3241 else if (CStringStartsWith(str, L"refs/tags/"))
3243 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3244 return true;
3246 else if (CStringStartsWith(str, L"refs/stash"))
3248 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3249 return true;
3251 else if (CStringStartsWith(str, L"refs/bisect/"))
3253 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3254 return true;
3257 // Keep the head too.
3258 if (pRev->m_CommitHash == m_HeadHash)
3259 return true;
3262 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3264 if (pRev->ParentsCount() > 1)
3265 return true;
3266 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3267 if (childrenIt != commitChildren.end())
3269 const std::unordered_set<CGitHash> &children = childrenIt->second;
3270 if (children.size() > 1)
3271 return true;
3274 return false;
3277 void CGitLogListBase::ShowGraphColumn(bool bShow)
3279 // HACK to hide graph column
3280 if (bShow)
3281 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3282 else
3283 SetColumnWidth(0, 0);
3286 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3288 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3289 return L"";
3291 CString tagInfo;
3292 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3293 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3295 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3296 continue;
3297 if (!CStringUtils::EndsWith((*it), L"^{}"))
3298 continue;
3300 CString cmd;
3301 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3302 CString output;
3303 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3304 continue;
3306 // parse tag date
3309 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3310 int pos1 = output.Find(L'>');
3311 if (pos1 < 0)
3312 break;
3313 ++pos1;
3314 if (output[pos1] == L' ')
3315 ++pos1;
3316 int pos2 = output.Find(L'\n', pos1);
3317 if (pos2 < 0)
3318 break;
3320 CString str = output.Mid(pos1, pos2 - pos1);
3321 wchar_t* pEnd = nullptr;
3322 errno = 0;
3323 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3324 if (str.GetBuffer() == pEnd)
3325 break;
3326 if (errno == ERANGE)
3327 break;
3329 output.Delete(pos1, pos2 - pos1);
3330 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3331 } while (0);
3332 output.Trim().AppendChar(L'\n');
3333 tagInfo += output;
3335 return tagInfo;
3338 void CGitLogListBase::Clear()
3340 m_arShownList.SafeRemoveAll();
3341 DeleteAllItems();
3343 m_logEntries.ClearAll();
3346 void CGitLogListBase::OnDestroy()
3348 SafeTerminateThread();
3349 SafeTerminateAsyncDiffThread();
3351 int retry = 0;
3352 while(m_LogCache.SaveCache())
3354 if(retry > 5)
3355 break;
3356 Sleep(1000);
3358 ++retry;
3360 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3361 // MB_YESNO) == IDNO)
3362 // break;
3365 __super::OnDestroy();
3368 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3370 CRect rect;
3371 int i=(int)wParam;
3372 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3373 this->InvalidateRect(rect);
3375 return 0;
3379 * Save column widths to the registry
3381 void CGitLogListBase::SaveColumnWidths()
3383 // HACK that graph column is always shown
3384 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3386 __super::SaveColumnWidths();
3389 int CGitLogListBase::GetHeadIndex()
3391 if(m_HeadHash.IsEmpty())
3392 return -1;
3394 for (size_t i = 0; i < m_arShownList.size(); ++i)
3396 GitRev* pRev = m_arShownList.SafeGetAt(i);
3397 if(pRev)
3399 if (pRev->m_CommitHash == m_HeadHash)
3400 return (int)i;
3403 return -1;
3405 void CGitLogListBase::OnFind()
3407 if (!m_pFindDialog)
3409 m_pFindDialog = new CFindDlg(this);
3410 m_pFindDialog->Create(this);
3414 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3416 if (GetSelectedCount() != 0)
3417 return 0;
3419 CGitHash theSelectedHash = m_lastSelectedHash;
3420 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3421 m_lastSelectedHash = theSelectedHash;
3423 int countPerPage = GetCountPerPage();
3424 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3425 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3426 EnsureVisible((int)itemToSelect, FALSE);
3427 return 0;
3430 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3432 CString* ref = reinterpret_cast<CString*>(wParam);
3433 if (!ref || ref->IsEmpty())
3434 return 1;
3436 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3438 CGitHash hash;
3439 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3440 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3442 if (hash.IsEmpty())
3443 return 1;
3445 bool bFound = false;
3446 int cnt = (int)m_arShownList.size();
3447 int i;
3448 for (i = 0; i < cnt; ++i)
3450 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3451 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3453 bFound = true;
3454 break;
3457 if (!bFound)
3458 return 1;
3460 EnsureVisible(i, FALSE);
3461 if (!bShift)
3463 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3464 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3465 SetSelectionMark(i);
3467 else
3469 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3470 if (pLogEntry)
3471 m_highlight = pLogEntry->m_CommitHash;
3473 Invalidate();
3474 UpdateData(FALSE);
3476 return 0;
3479 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
3481 ASSERT(m_pFindDialog);
3482 bool bFound = false;
3483 int i=0;
3485 if (m_pFindDialog->IsTerminating())
3487 // invalidate the handle identifying the dialog box.
3488 m_pFindDialog = nullptr;
3489 return 0;
3492 int cnt = (int)m_arShownList.size();
3493 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3495 if(m_pFindDialog->IsRef())
3497 CString str;
3498 str=m_pFindDialog->GetFindString();
3500 CGitHash hash;
3502 if(!str.IsEmpty())
3504 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3505 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3508 if(!hash.IsEmpty())
3510 for (i = 0; i < cnt; ++i)
3512 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3513 if(pLogEntry && pLogEntry->m_CommitHash == hash)
3515 bFound = true;
3516 break;
3520 if (!bFound)
3522 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3523 return 0;
3527 if (m_pFindDialog->FindNext() && !bFound)
3529 //read data from dialog
3530 CLogDlgFilter filter { m_pFindDialog->GetFindString(), m_pFindDialog->Regex(), LOGFILTER_ALL, m_pFindDialog->MatchCase() == TRUE };
3532 for (i = m_nSearchIndex + 1; ; ++i)
3534 if (i >= cnt)
3536 i = 0;
3537 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3539 if (m_nSearchIndex >= 0)
3541 if (i == m_nSearchIndex)
3543 ::MessageBeep(0xFFFFFFFF);
3544 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
3545 break;
3549 if (filter(m_arShownList.SafeGetAt(i), this))
3551 bFound = true;
3552 break;
3555 } // if(m_pFindDialog->FindNext())
3557 if (bFound)
3559 m_nSearchIndex = i;
3560 EnsureVisible(i, FALSE);
3561 if (!bShift)
3563 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3564 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3565 SetSelectionMark(i);
3567 else
3569 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3570 if (pLogEntry)
3571 m_highlight = pLogEntry->m_CommitHash;
3573 Invalidate();
3574 //FillLogMessageCtrl();
3575 UpdateData(FALSE);
3578 return 0;
3581 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
3583 LVHITTESTINFO lvhitTestInfo;
3585 lvhitTestInfo.pt = point;
3587 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
3588 int nSubItem = lvhitTestInfo.iSubItem;
3590 UINT nFlags = lvhitTestInfo.flags;
3592 // nFlags is 0 if the SubItemHitTest fails
3593 // Therefore, 0 & <anything> will equal false
3594 if (nFlags & LVHT_ONITEM)
3596 // Get the client area occupied by this control
3597 RECT rcClient;
3598 GetClientRect(&rcClient);
3600 // Fill in the TOOLINFO structure
3601 pTI->hwnd = m_hWnd;
3602 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
3603 pTI->lpszText = LPSTR_TEXTCALLBACK;
3604 pTI->rect = rcClient;
3606 return pTI->uId; // By returning a unique value per listItem,
3607 // we ensure that when the mouse moves over another list item,
3608 // the tooltip will change
3610 else
3612 // Otherwise, we aren't interested, so let the message propagate
3613 return -1;
3617 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
3619 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
3620 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
3622 *pResult = 0;
3624 // Ignore messages from the built in tooltip, we are processing them internally
3625 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
3626 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
3627 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
3628 return FALSE;
3630 // Get the mouse position
3631 const MSG* pMessage = GetCurrentMessage();
3633 CPoint pt;
3634 pt = pMessage->pt;
3635 ScreenToClient(&pt);
3637 // Check if the point falls onto a list item
3638 LVHITTESTINFO lvhitTestInfo;
3639 lvhitTestInfo.pt = pt;
3641 int nItem = SubItemHitTest(&lvhitTestInfo);
3643 if (lvhitTestInfo.flags & LVHT_ONITEM)
3645 // Get branch description first
3646 CString strTipText;
3647 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
3649 CString branch;
3650 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
3651 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
3653 MAP_STRING_STRING descriptions;
3654 g_Git.GetBranchDescriptions(descriptions);
3655 if (descriptions.find(branch) != descriptions.cend())
3657 strTipText.LoadString(IDS_DESCRIPTION);
3658 strTipText += L":\n";
3659 strTipText += descriptions[branch];
3664 bool followMousePos = false;
3665 if (!strTipText.IsEmpty())
3666 followMousePos = true;
3667 else
3668 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
3669 if (strTipText.IsEmpty())
3670 return FALSE;
3672 // we want multiline tooltips
3673 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
3675 wcscpy_s(m_wszTip, strTipText);
3676 // handle Unicode as well as non-Unicode requests
3677 if (pNMHDR->code == TTN_NEEDTEXTA)
3679 pTTTA->hinst = nullptr;
3680 pTTTA->lpszText = m_szTip;
3681 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
3683 else
3685 pTTTW->hinst = nullptr;
3686 pTTTW->lpszText = m_wszTip;
3689 CRect rect;
3690 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
3691 if (followMousePos)
3692 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
3693 ClientToScreen(rect);
3694 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
3696 return TRUE; // We found a tool tip,
3697 // tell the framework this message has been handled
3700 return FALSE; // We didn't handle the message,
3701 // let the framework continue propagating the message
3704 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
3706 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
3708 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3709 if (pLogEntry == nullptr)
3710 return CString();
3711 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
3712 return CString();
3713 return pLogEntry->GetSubject();
3715 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
3717 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3718 if (pLogEntry == nullptr)
3719 return CString();
3720 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
3722 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
3724 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3725 if (pLogEntry == nullptr)
3726 return CString();
3727 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
3729 else if (nSubItem == LOGLIST_ACTION)
3731 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3732 if (pLogEntry == nullptr)
3733 return CString();
3735 if (!pLogEntry->m_IsDiffFiles)
3736 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
3738 int actions = pLogEntry->GetAction(this);
3739 CString sToolTipText;
3741 CString actionText;
3742 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
3743 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
3745 if (actions & CTGitPath::LOGACTIONS_ADDED)
3747 if (!actionText.IsEmpty())
3748 actionText += L"\r\n";
3749 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
3752 if (actions & CTGitPath::LOGACTIONS_DELETED)
3754 if (!actionText.IsEmpty())
3755 actionText += L"\r\n";
3756 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
3759 if (actions & CTGitPath::LOGACTIONS_REPLACED)
3761 if (!actionText.IsEmpty())
3762 actionText += L"\r\n";
3763 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
3766 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
3768 if (!actionText.IsEmpty())
3769 actionText += L"\r\n";
3770 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
3773 if (!actionText.IsEmpty())
3775 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
3776 sToolTipText = sTitle + L":\r\n" + actionText;
3778 return sToolTipText;
3780 return CString();
3783 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3785 POINT pt = point;
3786 ScreenToClient(&pt);
3787 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
3790 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3792 if (!pLogEntry)
3793 return false;
3795 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
3796 if (refList == m_HashMap.cend())
3797 return false;
3799 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
3801 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
3802 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
3803 continue;
3805 CGit::REF_TYPE foundType;
3806 if (pShortname)
3807 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
3808 else
3809 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
3810 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
3811 return false;
3813 type = foundType;
3814 if (pIndex)
3815 *pIndex = i;
3816 return true;
3818 return false;
3821 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
3823 *pResult = 0;
3825 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
3826 return;
3828 m_bDragging = TRUE;
3829 m_nDropIndex = -1;
3830 m_nDropMarkerLast = -1;
3831 m_nDropMarkerLastHot = GetHotItem();
3832 SetCapture();
3835 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
3837 __super::OnMouseMove(nFlags, point);
3839 if (!m_bDragging)
3840 return;
3842 CPoint dropPoint = point;
3843 ClientToScreen(&dropPoint);
3845 if (WindowFromPoint(dropPoint) != this)
3847 SetCursor(LoadCursor(nullptr, IDC_NO));
3848 m_nDropIndex = -1;
3849 DrawDropInsertMarker(m_nDropIndex);
3850 return;
3853 SetCursor(LoadCursor(nullptr, IDC_ARROW));
3854 ScreenToClient(&dropPoint);
3856 dropPoint.y += 10;
3857 m_nDropIndex = HitTest(dropPoint);
3859 if (m_nDropIndex == -1) // might be last item, allow to move past last item
3861 dropPoint.y -= 10;
3862 m_nDropIndex = HitTest(dropPoint);
3863 if (m_nDropIndex != -1)
3864 m_nDropIndex = GetItemCount();
3867 POSITION pos = GetFirstSelectedItemPosition();
3868 int first = GetNextSelectedItem(pos);
3869 int last = first;
3870 while (pos)
3871 last = GetNextSelectedItem(pos);
3872 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
3874 SetCursor(LoadCursor(nullptr, IDC_NO));
3875 m_nDropIndex = -1;
3878 // handle auto scrolling
3879 int hotItem = GetHotItem();
3880 int topindex = GetTopIndex();
3881 if (hotItem == topindex && hotItem != 0)
3882 EnsureVisible(hotItem - 1, FALSE);
3883 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
3884 EnsureVisible(hotItem + 1, FALSE);
3886 DrawDropInsertMarker(m_nDropIndex);
3889 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
3891 if (m_bDragging)
3893 ::ReleaseCapture();
3894 SetCursor(LoadCursor(nullptr, IDC_HAND));
3895 m_bDragging = FALSE;
3897 CRect rect;
3898 GetItemRect(m_nDropMarkerLast, &rect, 0);
3899 rect.bottom = rect.top + 2;
3900 rect.top -= 2;
3901 InvalidateRect(&rect, 0);
3903 CPoint pt(point);
3904 ClientToScreen(&pt);
3905 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
3906 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
3909 __super::OnLButtonUp(nFlags, point);
3912 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
3914 if (m_nDropMarkerLast != nIndex)
3916 CRect rect;
3917 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
3919 rect.bottom = rect.top + 2;
3920 rect.top -= 2;
3921 InvalidateRect(&rect, 0);
3923 else if (m_nDropMarkerLast == GetItemCount())
3924 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
3925 m_nDropMarkerLast = nIndex;
3927 if (nIndex < 0)
3928 return;
3930 DrawDropInsertMarkerLine(m_nDropMarkerLast);
3932 else if (m_nDropMarkerLastHot != GetHotItem())
3934 m_nDropMarkerLastHot = GetHotItem();
3935 m_nDropMarkerLast = -1;
3939 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
3941 CBrush* pBrush = CDC::GetHalftoneBrush();
3942 CDC* pDC = GetDC();
3944 CRect rect;
3945 if (nIndex < GetItemCount())
3947 GetItemRect(nIndex, &rect, 0);
3948 rect.bottom = rect.top + 2;
3949 rect.top -= 2;
3951 else
3953 GetItemRect(nIndex - 1, &rect, 0);
3954 rect.top = rect.bottom - 2;
3955 rect.bottom += 2;
3958 CBrush* pBrushOld = pDC->SelectObject(pBrush);
3959 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
3960 pDC->SelectObject(pBrushOld);
3962 ReleaseDC(pDC);
3965 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
3967 return 0;
3970 void CGitLogListBase::DrawListItemWithMatchesRect(NMLVCUSTOMDRAW* pLVCD, const std::vector<CHARRANGE>& ranges, CRect rect, const CString& text, HTHEME hTheme /*= nullptr*/, int txtState /*= 0*/)
3972 int drawPos = 0;
3973 COLORREF textColor = pLVCD->clrText;
3974 RECT rc = rect;
3975 if (!hTheme)
3977 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
3978 SetBkMode(pLVCD->nmcd.hdc, TRANSPARENT);
3980 DTTOPTS opts = { 0 };
3981 opts.dwSize = sizeof(opts);
3982 opts.crText = textColor;
3983 opts.dwFlags = DTT_TEXTCOLOR;
3985 for (auto it = ranges.cbegin(); it != ranges.cend(); ++it)
3987 rc = rect;
3988 if (it->cpMin - drawPos)
3990 if (!hTheme)
3992 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3993 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3995 else
3997 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);
3998 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);
4000 rect.left = rc.right;
4002 rc = rect;
4003 drawPos = it->cpMin;
4004 if (it->cpMax - drawPos)
4006 if (!hTheme)
4008 ::SetTextColor(pLVCD->nmcd.hdc, m_Colors.GetColor(CColors::FilterMatch));
4009 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4010 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4011 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
4013 else
4015 opts.crText = m_Colors.GetColor(CColors::FilterMatch);
4016 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);
4017 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);
4018 opts.crText = textColor;
4020 rect.left = rc.right;
4022 rc = rect;
4023 drawPos = it->cpMax;
4025 if (!hTheme)
4026 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), -1, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4027 else
4028 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), -1, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rc, &opts);
4031 bool CGitLogListBase::DrawListItemWithMatchesIfEnabled(std::shared_ptr<CLogDlgFilter> filter, DWORD selectedFilter, NMLVCUSTOMDRAW* pLVCD, LRESULT* pResult)
4033 if ((filter->GetSelectedFilters() & selectedFilter) && filter->IsFilterActive())
4035 *pResult = DrawListItemWithMatches(filter.get(), *this, pLVCD);
4036 return true;
4038 return false;
4041 LRESULT CGitLogListBase::DrawListItemWithMatches(CLogDlgFilter* filter, CListCtrl& listCtrl, NMLVCUSTOMDRAW* pLVCD)
4043 CString text;
4044 text = (LPCTSTR)listCtrl.GetItemText((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem);
4045 if (text.IsEmpty())
4046 return CDRF_DODEFAULT;
4048 std::vector<CHARRANGE> ranges;
4049 filter->GetMatchRanges(ranges, text, 0);
4050 if (ranges.empty())
4051 return CDRF_DODEFAULT;
4053 // even though we initialize the 'rect' here with nmcd.rc,
4054 // we must not use it but use the rects from GetItemRect()
4055 // and GetSubItemRect(). Because on XP, the nmcd.rc has
4056 // bogus data in it.
4057 CRect rect = pLVCD->nmcd.rc;
4059 // find the margin where the text label starts
4060 CRect labelRC, boundsRC, iconRC;
4061 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &labelRC, LVIR_LABEL);
4062 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &iconRC, LVIR_ICON);
4063 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &boundsRC, LVIR_BOUNDS);
4065 int leftmargin = labelRC.left - boundsRC.left;
4066 if (pLVCD->iSubItem)
4067 leftmargin -= iconRC.Width();
4069 if (pLVCD->iSubItem != 0)
4070 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
4072 int borderWidth = 0;
4073 HTHEME hTheme = nullptr;
4074 if (IsAppThemed())
4076 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
4077 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
4079 else
4080 borderWidth = GetSystemMetrics(SM_CXBORDER);
4082 if (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES)
4084 // I'm not very happy about this fixed margin here
4085 // but I haven't found a way to ask the system what
4086 // the margin really is.
4087 // At least it works on XP/Vista/win7/win8, and even with
4088 // increased font sizes
4089 leftmargin = 4;
4092 LVITEM item = { 0 };
4093 item.iItem = (int)pLVCD->nmcd.dwItemSpec;
4094 item.iSubItem = 0;
4095 item.mask = LVIF_IMAGE | LVIF_STATE;
4096 item.stateMask = (UINT)-1;
4097 listCtrl.GetItem(&item);
4099 // fill background
4100 int txtState = LISS_NORMAL;
4101 if (!hTheme)
4103 HBRUSH brush = nullptr;
4104 if (item.state & LVIS_SELECTED)
4106 if (::GetFocus() == listCtrl.GetSafeHwnd())
4108 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
4109 pLVCD->clrText = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
4111 else
4113 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
4114 pLVCD->clrText = ::GetSysColor(COLOR_WINDOWTEXT);
4117 else
4118 brush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4119 CRect my;
4120 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, my);
4121 ::FillRect(pLVCD->nmcd.hdc, my, brush);
4122 ::DeleteObject(brush);
4124 else
4126 if (listCtrl.GetHotItem() == (int)pLVCD->nmcd.dwItemSpec)
4128 if (item.state & LVIS_SELECTED)
4129 txtState = LISS_HOTSELECTED;
4130 else
4131 txtState = LISS_HOT;
4133 else if (item.state & LVIS_SELECTED)
4135 if (::GetFocus() == listCtrl.GetSafeHwnd())
4136 txtState = LISS_SELECTED;
4137 else
4138 txtState = LISS_SELECTEDNOTFOCUS;
4141 if (IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
4142 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
4143 else
4145 HBRUSH brush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4146 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
4147 ::DeleteObject(brush);
4149 if (txtState != LISS_NORMAL)
4151 CRect my;
4152 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, my);
4153 if (pLVCD->iSubItem == 0)
4155 // also fill the icon part of the line
4156 my.top = 0;
4157 my.left = 0;
4160 // calculate background for rect of whole line, but limit redrawing to SubItem rect
4161 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, boundsRC, my);
4165 // draw the icon for the first column
4166 if (pLVCD->iSubItem == 0)
4168 rect = boundsRC;
4169 rect.right = rect.left + listCtrl.GetColumnWidth(0);
4170 rect.left = iconRC.left;
4172 if (item.iImage >= 0)
4174 POINT pt;
4175 pt.x = rect.left;
4176 pt.y = rect.top;
4177 CDC dc;
4178 dc.Attach(pLVCD->nmcd.hdc);
4179 int style = ILD_TRANSPARENT;
4180 if (!hTheme)
4182 auto whitebrush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4183 ::FillRect(dc, iconRC, whitebrush);
4184 ::DeleteObject(whitebrush);
4185 if (item.state & LVIS_SELECTED)
4187 if (::GetFocus() == listCtrl.GetSafeHwnd())
4188 style = ILD_SELECTED;
4189 else
4190 style = ILD_FOCUS;
4193 listCtrl.GetImageList(LVSIL_SMALL)->Draw(&dc, item.iImage, pt, style);
4194 dc.Detach();
4195 leftmargin -= iconRC.left;
4197 else
4199 RECT irc = boundsRC;
4200 irc.left += borderWidth;
4201 irc.right = iconRC.left;
4203 int state = 0;
4204 if (item.state & LVIS_SELECTED)
4206 if (listCtrl.GetHotItem() == item.iItem)
4207 state = CBS_CHECKEDHOT;
4208 else
4209 state = CBS_CHECKEDNORMAL;
4211 else
4213 if (listCtrl.GetHotItem() == item.iItem)
4214 state = CBS_UNCHECKEDHOT;
4216 if ((state) && (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES))
4218 HTHEME hTheme2 = OpenThemeData(m_hWnd, L"BUTTON");
4219 DrawThemeBackground(hTheme2, pLVCD->nmcd.hdc, BP_CHECKBOX, state, &irc, NULL);
4220 CloseThemeData(hTheme2);
4224 InflateRect(&rect, -(2 * borderWidth), 0);
4226 rect.left += leftmargin;
4227 RECT rc = rect;
4229 // is the column left- or right-aligned? (we don't handle centered (yet))
4230 LVCOLUMN Column;
4231 Column.mask = LVCF_FMT;
4232 listCtrl.GetColumn(pLVCD->iSubItem, &Column);
4233 if (Column.fmt & LVCFMT_RIGHT)
4235 DrawText(pLVCD->nmcd.hdc, text, -1, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4236 rect.left = rect.right - (rc.right - rc.left);
4237 if (!hTheme)
4239 rect.left += 2 * borderWidth;
4240 rect.right += 2 * borderWidth;
4244 DrawListItemWithMatchesRect(pLVCD, ranges, rect, text, hTheme, txtState);
4245 if (hTheme)
4246 CloseThemeData(hTheme);
4248 return CDRF_SKIPDEFAULT;