Drop unused code
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blob50edfd7dc265ef7ed53f608bed9c3cef1d1e089a
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, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
143 m_NodeSize = max(1, 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))
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))
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)
2041 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2043 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2044 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2046 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2048 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2050 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2052 size_t index = (size_t)-1;
2053 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2054 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2055 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2058 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2060 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2061 popup.AppendMenuIcon(ID_RESET, str, IDI_RESET);
2064 // Add Switch Branch express Menu
2065 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2066 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2069 std::vector<const CString*> branchs;
2070 auto addCheck = [&](const CString& ref)
2072 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2073 return;
2074 branchs.push_back(&ref);
2076 size_t index = (size_t)-1;
2077 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2078 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2079 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2080 else
2081 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2083 CString str2;
2084 str2.LoadString(IDS_SWITCH_BRANCH);
2086 if(branchs.size() == 1)
2088 str2 += L' ';
2089 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2090 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2092 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2095 else if(branchs.size() > 1)
2097 subbranchmenu.CreatePopupMenu();
2098 for (size_t i = 0 ; i < branchs.size(); ++i)
2100 if (*branchs[i] != currentBranch)
2102 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH + (i << 16), branchs[i]->Mid((int)wcslen(L"refs/heads/")));
2103 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2107 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2111 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2113 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2114 size_t index = (size_t)-1;
2115 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2116 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2117 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2120 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2122 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2124 size_t index = (size_t)-1;
2125 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2126 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2127 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2130 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2131 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2133 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2135 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2136 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2137 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2139 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2140 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2142 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2144 if (parentHash.size() == 1)
2145 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2146 else if (parentHash.size() > 1)
2148 revertmenu.CreatePopupMenu();
2149 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2151 for (size_t i = 0; i < parentInfo.size(); ++i)
2153 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), parentInfo[i]);
2158 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2159 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2161 popup.AppendMenu(MF_SEPARATOR, NULL);
2165 if(!pSelLogEntry->m_Ref.IsEmpty())
2167 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2168 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2169 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_UNSHELVE);
2170 if (selectedCount <= 2)
2171 popup.AppendMenu(MF_SEPARATOR, NULL);
2174 if (selectedCount >= 2)
2176 bool bAddSeparator = false;
2177 if ((selectedCount == 2) || IsSelectionContinuous())
2179 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2181 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2182 bAddSeparator = true;
2186 if (selectedCount == 2)
2188 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2190 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2191 bAddSeparator = true;
2194 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2196 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2197 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2198 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2199 CString menu;
2200 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2201 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2202 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2203 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2204 bAddSeparator = true;
2208 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2210 bAddSeparator = true;
2211 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2214 if (bAddSeparator)
2216 popup.AppendMenu(MF_SEPARATOR, NULL);
2217 bAddSeparator = false;
2220 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2221 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2223 if (bAddSeparator)
2224 popup.AppendMenu(MF_SEPARATOR, NULL);
2227 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2229 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2230 popup.AppendMenu(MF_SEPARATOR, NULL);
2233 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2235 bool bAddSeparator = false;
2236 if (selectedCount >= 2 && IsSelectionContinuous())
2238 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2240 CString head;
2241 int headindex;
2242 headindex = this->GetHeadIndex();
2243 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2245 head.Format(L"HEAD~%d", FirstSelect - headindex);
2246 CGitHash hashFirst;
2247 int ret = g_Git.GetHash(hashFirst, head);
2248 head.Format(L"HEAD~%d",LastSelect-headindex);
2249 CGitHash hash;
2250 ret = ret || g_Git.GetHash(hash, head);
2251 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2252 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2253 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2255 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2256 bAddSeparator = true;
2261 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2262 if (selectedCount >= 2)
2263 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_PICK);
2264 else
2265 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_PICK);
2266 bAddSeparator = true;
2269 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2270 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2271 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2272 bAddSeparator = true;
2275 if (bAddSeparator)
2276 popup.AppendMenu(MF_SEPARATOR, NULL);
2279 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2281 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2282 popup.AppendMenu(MF_SEPARATOR, NULL);
2285 if (selectedCount == 1)
2287 bool bAddSeparator = false;
2288 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2290 // show the push-option only if the log entry has an associated local branch
2291 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();
2292 if (isLocal || showExtendedMenu)
2294 CString str;
2295 str.LoadString(IDS_MENUPUSH);
2297 CString branch;
2298 size_t index = (size_t)-1;
2299 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2300 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2301 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2302 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2304 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2306 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2307 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2309 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2310 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2312 bAddSeparator = true;
2315 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2317 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2318 bAddSeparator = true;
2322 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2324 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2326 std::vector<const CString*> branchs;
2327 auto addCheck = [&](const CString& ref)
2329 if (ref == currentBranch)
2330 return;
2331 branchs.push_back(&ref);
2333 size_t index = (size_t)-1;
2334 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2335 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2336 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2337 else
2338 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2340 CString str;
2341 if (branchs.size() == 1)
2343 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2344 str += L' ';
2345 str += *branchs[0];
2346 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2347 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2348 bAddSeparator = true;
2350 else if (branchs.size() > 1)
2352 str.LoadString(IDS_DELETE_BRANCHTAG);
2353 submenu.CreatePopupMenu();
2354 for (size_t i = 0; i < branchs.size(); ++i)
2356 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2357 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2359 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2360 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2362 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2363 bAddSeparator = true;
2366 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2367 if (bAddSeparator)
2368 popup.AppendMenu(MF_SEPARATOR, NULL);
2369 } // selectedCount == 1
2371 CIconMenu clipSubMenu;
2372 if (!clipSubMenu.CreatePopupMenu())
2373 return;
2374 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2376 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2377 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2378 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2379 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2380 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2381 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2382 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2383 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2384 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2386 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2387 size_t index = (size_t)-1;
2388 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2389 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2390 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2393 CString temp;
2394 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2395 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2398 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2399 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2401 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2402 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2404 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2405 // DialogEnableWindow(IDOK, FALSE);
2406 // SetPromptApp(&theApp);
2408 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2410 // EnableOKButton();
2411 } // if (popup.CreatePopupMenu())
2414 bool CGitLogListBase::IsSelectionContinuous()
2416 if ( GetSelectedCount()==1 )
2418 // if only one revision is selected, the selection is of course
2419 // continuous
2420 return true;
2423 POSITION pos = GetFirstSelectedItemPosition();
2424 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2425 if (bContinuous)
2427 int itemindex = GetNextSelectedItem(pos);
2428 while (pos)
2430 int nextindex = GetNextSelectedItem(pos);
2431 if (nextindex - itemindex > 1)
2433 bContinuous = false;
2434 break;
2436 itemindex = nextindex;
2439 return bContinuous;
2442 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2444 CString sClipdata;
2445 POSITION pos = GetFirstSelectedItemPosition();
2446 if (pos)
2448 CString sRev;
2449 sRev.LoadString(IDS_LOG_REVISION);
2450 CString sAuthor;
2451 sAuthor.LoadString(IDS_LOG_AUTHOR);
2452 CString sDate;
2453 sDate.LoadString(IDS_LOG_DATE);
2454 CString sMessage;
2455 sMessage.LoadString(IDS_LOG_MESSAGE);
2456 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2457 bool first = true;
2458 while (pos)
2460 CString sLogCopyText;
2461 CString sPaths;
2462 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2464 if (toCopy == ID_COPYCLIPBOARDFULL)
2466 sPaths = L"----\r\n";
2467 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2469 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2470 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2472 sPaths += L' ';
2473 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2475 sPaths += L"\r\n";
2477 sPaths.Trim();
2478 sPaths += L"\r\n";
2481 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2483 CString sNotesTags;
2484 if (!pLogEntry->m_Notes.IsEmpty())
2486 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2487 sNotesTags += L":\n";
2488 sNotesTags += pLogEntry->m_Notes;
2489 sNotesTags.Replace(L"\n", L"\r\n");
2491 CString tagInfo = GetTagInfo(pLogEntry);
2492 if (!tagInfo.IsEmpty())
2494 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2495 tagInfo.Replace(L"\n", L"\r\n");
2496 sNotesTags += tagInfo;
2499 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",
2500 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2501 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2502 (LPCTSTR)sDate,
2503 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2504 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2505 (LPCTSTR)sNotesTags,
2506 (LPCTSTR)sPaths);
2507 sClipdata += sLogCopyText;
2509 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2511 if (!first)
2512 sClipdata += L"\r\n";
2513 sClipdata += pLogEntry->GetAuthorName();
2514 sClipdata += L" <";
2515 sClipdata += pLogEntry->GetAuthorEmail();
2516 sClipdata += L">";
2518 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2520 if (!first)
2521 sClipdata += L"\r\n";
2522 sClipdata += pLogEntry->GetAuthorName();
2524 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2526 if (!first)
2527 sClipdata += L"\r\n";
2528 sClipdata += pLogEntry->GetAuthorEmail();
2531 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2533 sClipdata += L"* ";
2534 sClipdata += pLogEntry->GetSubjectBody(true);
2535 sClipdata += L"\r\n\r\n";
2537 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2539 sClipdata += L"* ";
2540 sClipdata += pLogEntry->GetSubject().Trim();
2541 sClipdata += L"\r\n\r\n";
2543 else
2545 if (!first)
2546 sClipdata += L"\r\n";
2547 sClipdata += pLogEntry->m_CommitHash.ToString();
2550 first = false;
2552 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2556 void CGitLogListBase::DiffSelectedRevWithPrevious()
2558 if (m_bThreadRunning)
2559 return;
2561 int FirstSelect=-1, LastSelect=-1;
2562 POSITION pos = GetFirstSelectedItemPosition();
2563 FirstSelect = GetNextSelectedItem(pos);
2564 while(pos)
2565 LastSelect = GetNextSelectedItem(pos);
2567 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2570 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2572 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2573 *pResult = -1;
2575 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2576 return;
2577 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2578 return;
2579 if (!pFindInfo->lvfi.psz)
2580 return;
2581 #if 0
2582 CString sCmp = pFindInfo->lvfi.psz;
2583 CString sRev;
2584 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2586 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2587 sRev.Format(L"%ld", pLogEntry->Rev);
2588 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2590 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2592 *pResult = i;
2593 return;
2596 else
2598 if (sCmp.Compare(sRev)==0)
2600 *pResult = i;
2601 return;
2605 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2607 for (int i=0; i<pFindInfo->iStart; ++i)
2609 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2610 sRev.Format(L"%ld", pLogEntry->Rev);
2611 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2613 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2615 *pResult = i;
2616 return;
2619 else
2621 if (sCmp.Compare(sRev)==0)
2623 *pResult = i;
2624 return;
2629 #endif
2630 *pResult = -1;
2633 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2635 ClearText();
2637 this->m_arShownList.SafeRemoveAll();
2639 this->m_logEntries.ClearAll();
2640 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2641 return -1;
2643 SetItemCountEx((int)m_logEntries.size());
2645 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2647 if(m_IsOldFirst)
2649 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2650 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2652 else
2654 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2655 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2659 ReloadHashMap();
2661 if(path)
2662 m_Path=*path;
2663 return 0;
2666 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2668 ClearText();
2670 m_arShownList.SafeRemoveAll();
2672 m_logEntries.ClearAll();
2673 if (m_logEntries.Fill(hashes))
2674 return -1;
2676 SetItemCountEx((int)m_logEntries.size());
2678 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2680 if (m_IsOldFirst)
2682 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2683 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2685 else
2687 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2688 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2692 ReloadHashMap();
2694 return 0;
2697 int CGitLogListBase::BeginFetchLog()
2699 ClearText();
2701 this->m_arShownList.SafeRemoveAll();
2703 this->m_logEntries.ClearAll();
2705 this->m_LogCache.ClearAllParent();
2707 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2709 CTGitPath *path;
2710 if(this->m_Path.IsEmpty())
2711 path = nullptr;
2712 else
2713 path=&this->m_Path;
2715 int mask;
2716 mask = CGit::LOG_INFO_ONLY_HASH;
2717 if (m_bIncludeBoundaryCommits)
2718 mask |= CGit::LOG_INFO_BOUNDARY;
2719 // if(this->m_bAllBranch)
2720 mask |= m_ShowMask ;
2722 if(m_bShowWC)
2724 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2725 ResetWcRev();
2726 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2729 if (m_sRange.IsEmpty())
2730 m_sRange = L"HEAD";
2732 // follow does not work for directories
2733 if (!path || path->IsDirectory())
2734 mask &= ~CGit::LOG_INFO_FOLLOW;
2735 // follow does not work with all branches 8at least in TGit)
2736 if (mask & CGit::LOG_INFO_FOLLOW)
2737 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2739 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2741 //this->m_logEntries.ParserFromLog();
2742 if(IsInWorkingThread())
2744 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2746 else
2748 SetItemCountEx((int)m_logEntries.size());
2753 g_Git.CheckAndInitDll();
2755 catch (char* msg)
2757 CString err(msg);
2758 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2759 return -1;
2762 if (!g_Git.CanParseRev(m_sRange))
2764 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2765 return 0;
2767 // if show all branches, pick any ref as dummy entry ref
2768 STRING_VECTOR list;
2769 if (g_Git.GetRefList(list))
2770 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2771 if (list.empty())
2772 return 0;
2774 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2777 g_Git.m_critGitDllSec.Lock();
2778 try {
2779 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8)))
2781 g_Git.m_critGitDllSec.Unlock();
2782 return -1;
2785 catch (char* msg)
2787 g_Git.m_critGitDllSec.Unlock();
2788 CString err(msg);
2789 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2790 return -1;
2792 g_Git.m_critGitDllSec.Unlock();
2794 return 0;
2797 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2799 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2801 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2803 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2805 DiffSelectedRevWithPrevious();
2806 return TRUE;
2809 #if 0
2810 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2812 DiffSelectedFile();
2813 return TRUE;
2815 #endif
2817 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2819 // select all entries
2820 for (int i=0; i<GetItemCount(); ++i)
2821 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2822 return TRUE;
2825 #if 0
2826 if (m_hAccel && !bSkipAccelerator)
2828 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2829 if (ret)
2830 return TRUE;
2833 #endif
2834 //m_tooltips.RelayEvent(pMsg);
2835 return __super::PreTranslateMessage(pMsg);
2838 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2840 // a double click on an entry in the revision list has happened
2841 *pResult = 0;
2843 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2844 DiffSelectedRevWithPrevious();
2847 void CGitLogListBase::FetchLogAsync(void* data)
2849 ReloadHashMap();
2850 m_ProcData=data;
2851 StartLoadingThread();
2854 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2856 return ((CGitLogListBase*)pVoid)->LogThread();
2859 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2861 //CTime time;
2862 oldest=CTime::GetCurrentTime();
2863 latest=CTime(1971,1,2,0,0,0);
2864 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2866 if(m_logEntries[i].IsEmpty())
2867 continue;
2869 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2870 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2872 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2873 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2877 if(latest<oldest)
2878 latest=oldest;
2881 UINT CGitLogListBase::LogThread()
2883 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2885 ULONGLONG t1,t2;
2887 if(BeginFetchLog())
2889 InterlockedExchange(&m_bThreadRunning, FALSE);
2890 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2892 return 1;
2895 // create a copy we can safely work on in this thread
2896 auto shared_filter(m_LogFilter);
2897 auto& filter = *shared_filter;
2899 TRACE(L"\n===Begin===\n");
2900 //Update work copy item;
2902 if (!m_logEntries.empty())
2904 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2906 m_arShownList.SafeAdd(pRev);
2910 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2912 // store commit number of the last selected commit/line before the refresh or -1
2913 int lastSelectedHashNItem = -1;
2914 if (m_lastSelectedHash.IsEmpty())
2915 lastSelectedHashNItem = 0;
2917 int ret = 0;
2919 bool shouldWalk = true;
2920 if (!g_Git.CanParseRev(m_sRange))
2922 // walk revisions if show all branches and there exists any ref
2923 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2924 shouldWalk = false;
2925 else
2927 STRING_VECTOR list;
2928 if (g_Git.GetRefList(list))
2929 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2930 if (list.empty())
2931 shouldWalk = false;
2935 if (shouldWalk)
2937 g_Git.m_critGitDllSec.Lock();
2938 if (!m_DllGitLog)
2940 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2941 g_Git.m_critGitDllSec.Unlock();
2942 InterlockedExchange(&m_bThreadRunning, FALSE);
2943 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2944 return 1;
2946 int total = 0;
2949 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2950 total = git_get_log_estimate_commit_count(m_DllGitLog);
2952 catch (char* msg)
2954 CString err(msg);
2955 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2956 ret = -1;
2958 g_Git.m_critGitDllSec.Unlock();
2960 GIT_COMMIT commit;
2961 t2 = t1 = GetTickCount64();
2962 int oldprecentage = 0;
2963 size_t oldsize = m_logEntries.size();
2964 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2965 while (ret== 0 && !m_bExitThread)
2967 g_Git.m_critGitDllSec.Lock();
2970 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2972 catch (char* msg)
2974 g_Git.m_critGitDllSec.Unlock();
2975 CString err(msg);
2976 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2977 break;
2979 g_Git.m_critGitDllSec.Unlock();
2981 if(ret)
2983 if (ret != -2) // other than end of revision walking
2984 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2985 break;
2988 if (commit.m_ignore == 1)
2990 git_free_commit(&commit);
2991 continue;
2994 //printf("%s\r\n",commit.GetSubject());
2995 if(m_bExitThread)
2996 break;
2998 CGitHash hash(commit.m_hash);
3000 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3001 pRev->m_GitCommit = commit;
3002 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3004 char* note = nullptr;
3005 g_Git.m_critGitDllSec.Lock();
3008 git_get_notes(commit.m_hash, &note);
3010 catch (char* msg)
3012 g_Git.m_critGitDllSec.Unlock();
3013 CString err(msg);
3014 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3015 break;
3017 g_Git.m_critGitDllSec.Unlock();
3019 if(note)
3021 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3022 free(note);
3023 note = nullptr;
3026 if(!pRev->m_IsDiffFiles)
3028 pRev->m_CallDiffAsync = DiffAsync;
3031 pRev->ParserParentFromCommit(&commit);
3032 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3034 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3036 const CGitHash &parentHash = pRev->m_ParentHash[i];
3037 auto it = commitChildren.find(parentHash);
3038 if (it == commitChildren.end())
3039 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3040 it->second.insert(pRev->m_CommitHash);
3044 #ifdef DEBUG
3045 pRev->DbgPrint();
3046 TRACE(L"\n");
3047 #endif
3049 bool visible = filter(pRev, this);
3050 if (visible && !ShouldShowFilter(pRev, commitChildren))
3051 visible = false;
3052 this->m_critSec.Lock();
3053 m_logEntries.append(hash, visible);
3054 if (visible)
3055 m_arShownList.SafeAdd(pRev);
3056 this->m_critSec.Unlock();
3058 if (!visible)
3059 continue;
3061 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3062 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3064 t2 = GetTickCount64();
3066 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3068 //update UI
3069 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3070 if(percent > 99)
3071 percent =99;
3072 if(percent < GITLOG_START)
3073 percent = GITLOG_START +1;
3075 oldsize = m_logEntries.size();
3076 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3078 //if( percent > oldprecentage )
3080 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3081 oldprecentage = percent;
3084 if (lastSelectedHashNItem >= 0)
3085 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3087 t1 = t2;
3090 g_Git.m_critGitDllSec.Lock();
3091 git_close_log(m_DllGitLog);
3092 g_Git.m_critGitDllSec.Unlock();
3096 if (m_bExitThread)
3098 InterlockedExchange(&m_bThreadRunning, FALSE);
3099 return 0;
3102 //Update UI;
3103 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3105 if (lastSelectedHashNItem >= 0)
3106 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3108 if (this->m_hWnd)
3109 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3111 InterlockedExchange(&m_bThreadRunning, FALSE);
3113 return 0;
3116 void CGitLogListBase::FetchRemoteList()
3118 STRING_VECTOR remoteList;
3119 m_SingleRemote.Empty();
3120 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3121 m_SingleRemote = remoteList[0];
3124 void CGitLogListBase::FetchTrackingBranchList()
3126 m_TrackingMap.clear();
3127 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3129 for (const auto& ref : it->second)
3131 CString branchName;
3132 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3134 CString pullRemote, pullBranch;
3135 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3136 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3137 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3143 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3145 SafeTerminateThread();
3147 this->SetItemCountEx(0);
3148 this->Clear();
3150 ResetWcRev();
3152 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3154 if (m_pMailmap)
3156 git_free_mailmap(m_pMailmap);
3157 git_read_mailmap(&m_pMailmap);
3160 //Update branch and Tag info
3161 ReloadHashMap();
3162 if (m_pFindDialog)
3163 m_pFindDialog->RefreshList();
3164 //Assume Thread have exited
3165 //if(!m_bThreadRunning)
3167 m_logEntries.clear();
3169 if (IsCleanFilter)
3170 m_LogFilter = std::make_shared<CLogDlgFilter>();
3172 SafeTerminateAsyncDiffThread();
3173 m_AsynDiffListLock.Lock();
3174 m_AsynDiffList.clear();
3175 m_AsynDiffListLock.Unlock();
3176 StartAsyncDiffThread();
3178 StartLoadingThread();
3182 void CGitLogListBase::StartAsyncDiffThread()
3184 if (m_AsyncThreadExit)
3185 return;
3186 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3187 return;
3188 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3189 if (!m_DiffingThread)
3191 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3192 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3196 void CGitLogListBase::StartLoadingThread()
3198 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3199 return;
3200 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3201 InterlockedExchange(&m_bExitThread, FALSE);
3202 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3203 if (!m_LoadingThread)
3205 InterlockedExchange(&m_bThreadRunning, FALSE);
3206 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3207 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3211 static bool CStringStartsWith(const CString &str, const CString &prefix)
3213 return str.Left(prefix.GetLength()) == prefix;
3215 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3217 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3218 return true;
3220 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3222 // Keep all refs.
3223 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3224 for (size_t i = 0; i < refList.size(); ++i)
3226 const CString &str = refList[i];
3227 if (CStringStartsWith(str, L"refs/heads/"))
3229 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3230 return true;
3232 else if (CStringStartsWith(str, L"refs/remotes/"))
3234 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3235 return true;
3237 else if (CStringStartsWith(str, L"refs/tags/"))
3239 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3240 return true;
3242 else if (CStringStartsWith(str, L"refs/stash"))
3244 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3245 return true;
3247 else if (CStringStartsWith(str, L"refs/bisect/"))
3249 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3250 return true;
3253 // Keep the head too.
3254 if (pRev->m_CommitHash == m_HeadHash)
3255 return true;
3258 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3260 if (pRev->ParentsCount() > 1)
3261 return true;
3262 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3263 if (childrenIt != commitChildren.end())
3265 const std::unordered_set<CGitHash> &children = childrenIt->second;
3266 if (children.size() > 1)
3267 return true;
3270 return false;
3273 void CGitLogListBase::ShowGraphColumn(bool bShow)
3275 // HACK to hide graph column
3276 if (bShow)
3277 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3278 else
3279 SetColumnWidth(0, 0);
3282 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3284 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3285 return L"";
3287 CString tagInfo;
3288 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3289 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3291 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3292 continue;
3293 if (!CStringUtils::EndsWith((*it), L"^{}"))
3294 continue;
3296 CString cmd;
3297 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3298 CString output;
3299 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3300 continue;
3302 // parse tag date
3305 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3306 int pos1 = output.Find(L'>');
3307 if (pos1 < 0)
3308 break;
3309 ++pos1;
3310 if (output[pos1] == L' ')
3311 ++pos1;
3312 int pos2 = output.Find(L'\n', pos1);
3313 if (pos2 < 0)
3314 break;
3316 CString str = output.Mid(pos1, pos2 - pos1);
3317 wchar_t* pEnd = nullptr;
3318 errno = 0;
3319 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3320 if (str.GetBuffer() == pEnd)
3321 break;
3322 if (errno == ERANGE)
3323 break;
3325 output.Delete(pos1, pos2 - pos1);
3326 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3327 } while (0);
3328 output.Trim().AppendChar(L'\n');
3329 tagInfo += output;
3331 return tagInfo;
3334 void CGitLogListBase::Clear()
3336 m_arShownList.SafeRemoveAll();
3337 DeleteAllItems();
3339 m_logEntries.ClearAll();
3342 void CGitLogListBase::OnDestroy()
3344 SafeTerminateThread();
3345 SafeTerminateAsyncDiffThread();
3347 int retry = 0;
3348 while(m_LogCache.SaveCache())
3350 if(retry > 5)
3351 break;
3352 Sleep(1000);
3354 ++retry;
3356 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3357 // MB_YESNO) == IDNO)
3358 // break;
3361 __super::OnDestroy();
3364 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3366 CRect rect;
3367 int i=(int)wParam;
3368 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3369 this->InvalidateRect(rect);
3371 return 0;
3375 * Save column widths to the registry
3377 void CGitLogListBase::SaveColumnWidths()
3379 // HACK that graph column is always shown
3380 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3382 __super::SaveColumnWidths();
3385 int CGitLogListBase::GetHeadIndex()
3387 if(m_HeadHash.IsEmpty())
3388 return -1;
3390 for (size_t i = 0; i < m_arShownList.size(); ++i)
3392 GitRev* pRev = m_arShownList.SafeGetAt(i);
3393 if(pRev)
3395 if (pRev->m_CommitHash == m_HeadHash)
3396 return (int)i;
3399 return -1;
3401 void CGitLogListBase::OnFind()
3403 if (!m_pFindDialog)
3405 m_pFindDialog = new CFindDlg(this);
3406 m_pFindDialog->Create(this);
3410 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3412 if (GetSelectedCount() != 0)
3413 return 0;
3415 CGitHash theSelectedHash = m_lastSelectedHash;
3416 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3417 m_lastSelectedHash = theSelectedHash;
3419 int countPerPage = GetCountPerPage();
3420 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3421 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3422 EnsureVisible((int)itemToSelect, FALSE);
3423 return 0;
3426 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3428 CString* ref = reinterpret_cast<CString*>(wParam);
3429 if (!ref || ref->IsEmpty())
3430 return 1;
3432 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3434 CGitHash hash;
3435 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3436 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3438 if (hash.IsEmpty())
3439 return 1;
3441 bool bFound = false;
3442 int cnt = (int)m_arShownList.size();
3443 int i;
3444 for (i = 0; i < cnt; ++i)
3446 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3447 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3449 bFound = true;
3450 break;
3453 if (!bFound)
3454 return 1;
3456 EnsureVisible(i, FALSE);
3457 if (!bShift)
3459 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3460 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3461 SetSelectionMark(i);
3463 else
3465 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3466 if (pLogEntry)
3467 m_highlight = pLogEntry->m_CommitHash;
3469 Invalidate();
3470 UpdateData(FALSE);
3472 return 0;
3475 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
3477 ASSERT(m_pFindDialog);
3478 bool bFound = false;
3479 int i=0;
3481 if (m_pFindDialog->IsTerminating())
3483 // invalidate the handle identifying the dialog box.
3484 m_pFindDialog = nullptr;
3485 return 0;
3488 int cnt = (int)m_arShownList.size();
3489 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3491 if(m_pFindDialog->IsRef())
3493 CString str;
3494 str=m_pFindDialog->GetFindString();
3496 CGitHash hash;
3498 if(!str.IsEmpty())
3500 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3501 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3504 if(!hash.IsEmpty())
3506 for (i = 0; i < cnt; ++i)
3508 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3509 if(pLogEntry && pLogEntry->m_CommitHash == hash)
3511 bFound = true;
3512 break;
3516 if (!bFound)
3518 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3519 return 0;
3523 if (m_pFindDialog->FindNext() && !bFound)
3525 //read data from dialog
3526 CLogDlgFilter filter { m_pFindDialog->GetFindString(), m_pFindDialog->Regex(), LOGFILTER_ALL, m_pFindDialog->MatchCase() == TRUE };
3528 for (i = m_nSearchIndex + 1; ; ++i)
3530 if (i >= cnt)
3532 i = 0;
3533 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
3535 if (m_nSearchIndex >= 0)
3537 if (i == m_nSearchIndex)
3539 ::MessageBeep(0xFFFFFFFF);
3540 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
3541 break;
3545 if (filter(m_arShownList.SafeGetAt(i), this))
3547 bFound = true;
3548 break;
3551 } // if(m_pFindDialog->FindNext())
3553 if (bFound)
3555 m_nSearchIndex = i;
3556 EnsureVisible(i, FALSE);
3557 if (!bShift)
3559 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3560 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3561 SetSelectionMark(i);
3563 else
3565 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3566 if (pLogEntry)
3567 m_highlight = pLogEntry->m_CommitHash;
3569 Invalidate();
3570 //FillLogMessageCtrl();
3571 UpdateData(FALSE);
3574 return 0;
3577 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
3579 LVHITTESTINFO lvhitTestInfo;
3581 lvhitTestInfo.pt = point;
3583 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
3584 int nSubItem = lvhitTestInfo.iSubItem;
3586 UINT nFlags = lvhitTestInfo.flags;
3588 // nFlags is 0 if the SubItemHitTest fails
3589 // Therefore, 0 & <anything> will equal false
3590 if (nFlags & LVHT_ONITEM)
3592 // Get the client area occupied by this control
3593 RECT rcClient;
3594 GetClientRect(&rcClient);
3596 // Fill in the TOOLINFO structure
3597 pTI->hwnd = m_hWnd;
3598 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
3599 pTI->lpszText = LPSTR_TEXTCALLBACK;
3600 pTI->rect = rcClient;
3602 return pTI->uId; // By returning a unique value per listItem,
3603 // we ensure that when the mouse moves over another list item,
3604 // the tooltip will change
3606 else
3608 // Otherwise, we aren't interested, so let the message propagate
3609 return -1;
3613 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
3615 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
3616 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
3618 *pResult = 0;
3620 // Ignore messages from the built in tooltip, we are processing them internally
3621 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
3622 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
3623 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
3624 return FALSE;
3626 // Get the mouse position
3627 const MSG* pMessage = GetCurrentMessage();
3629 CPoint pt;
3630 pt = pMessage->pt;
3631 ScreenToClient(&pt);
3633 // Check if the point falls onto a list item
3634 LVHITTESTINFO lvhitTestInfo;
3635 lvhitTestInfo.pt = pt;
3637 int nItem = SubItemHitTest(&lvhitTestInfo);
3639 if (lvhitTestInfo.flags & LVHT_ONITEM)
3641 // Get branch description first
3642 CString strTipText;
3643 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
3645 CString branch;
3646 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
3647 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
3649 MAP_STRING_STRING descriptions;
3650 g_Git.GetBranchDescriptions(descriptions);
3651 if (descriptions.find(branch) != descriptions.cend())
3653 strTipText.LoadString(IDS_DESCRIPTION);
3654 strTipText += L":\n";
3655 strTipText += descriptions[branch];
3660 bool followMousePos = false;
3661 if (!strTipText.IsEmpty())
3662 followMousePos = true;
3663 else
3664 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
3665 if (strTipText.IsEmpty())
3666 return FALSE;
3668 // we want multiline tooltips
3669 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
3671 wcscpy_s(m_wszTip, strTipText);
3672 // handle Unicode as well as non-Unicode requests
3673 if (pNMHDR->code == TTN_NEEDTEXTA)
3675 pTTTA->hinst = nullptr;
3676 pTTTA->lpszText = m_szTip;
3677 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
3679 else
3681 pTTTW->hinst = nullptr;
3682 pTTTW->lpszText = m_wszTip;
3685 CRect rect;
3686 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
3687 if (followMousePos)
3688 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
3689 ClientToScreen(rect);
3690 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
3692 return TRUE; // We found a tool tip,
3693 // tell the framework this message has been handled
3696 return FALSE; // We didn't handle the message,
3697 // let the framework continue propagating the message
3700 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
3702 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
3704 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3705 if (pLogEntry == nullptr)
3706 return CString();
3707 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
3708 return CString();
3709 return pLogEntry->GetSubject();
3711 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
3713 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3714 if (pLogEntry == nullptr)
3715 return CString();
3716 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
3718 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
3720 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3721 if (pLogEntry == nullptr)
3722 return CString();
3723 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
3725 else if (nSubItem == LOGLIST_ACTION)
3727 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
3728 if (pLogEntry == nullptr)
3729 return CString();
3731 if (!pLogEntry->m_IsDiffFiles)
3732 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
3734 int actions = pLogEntry->GetAction(this);
3735 CString sToolTipText;
3737 CString actionText;
3738 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
3739 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
3741 if (actions & CTGitPath::LOGACTIONS_ADDED)
3743 if (!actionText.IsEmpty())
3744 actionText += L"\r\n";
3745 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
3748 if (actions & CTGitPath::LOGACTIONS_DELETED)
3750 if (!actionText.IsEmpty())
3751 actionText += L"\r\n";
3752 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
3755 if (actions & CTGitPath::LOGACTIONS_REPLACED)
3757 if (!actionText.IsEmpty())
3758 actionText += L"\r\n";
3759 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
3762 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
3764 if (!actionText.IsEmpty())
3765 actionText += L"\r\n";
3766 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
3769 if (!actionText.IsEmpty())
3771 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
3772 sToolTipText = sTitle + L":\r\n" + actionText;
3774 return sToolTipText;
3776 return CString();
3779 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3781 POINT pt = point;
3782 ScreenToClient(&pt);
3783 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
3786 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
3788 if (!pLogEntry)
3789 return false;
3791 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
3792 if (refList == m_HashMap.cend())
3793 return false;
3795 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
3797 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
3798 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
3799 continue;
3801 CGit::REF_TYPE foundType;
3802 if (pShortname)
3803 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
3804 else
3805 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
3806 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
3807 return false;
3809 type = foundType;
3810 if (pIndex)
3811 *pIndex = i;
3812 return true;
3814 return false;
3817 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
3819 *pResult = 0;
3821 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
3822 return;
3824 m_bDragging = TRUE;
3825 m_nDropIndex = -1;
3826 m_nDropMarkerLast = -1;
3827 m_nDropMarkerLastHot = GetHotItem();
3828 SetCapture();
3831 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
3833 __super::OnMouseMove(nFlags, point);
3835 if (!m_bDragging)
3836 return;
3838 CPoint dropPoint = point;
3839 ClientToScreen(&dropPoint);
3841 if (WindowFromPoint(dropPoint) != this)
3843 SetCursor(LoadCursor(nullptr, IDC_NO));
3844 m_nDropIndex = -1;
3845 DrawDropInsertMarker(m_nDropIndex);
3846 return;
3849 SetCursor(LoadCursor(nullptr, IDC_ARROW));
3850 ScreenToClient(&dropPoint);
3852 dropPoint.y += 10;
3853 m_nDropIndex = HitTest(dropPoint);
3855 if (m_nDropIndex == -1) // might be last item, allow to move past last item
3857 dropPoint.y -= 10;
3858 m_nDropIndex = HitTest(dropPoint);
3859 if (m_nDropIndex != -1)
3860 m_nDropIndex = GetItemCount();
3863 POSITION pos = GetFirstSelectedItemPosition();
3864 int first = GetNextSelectedItem(pos);
3865 int last = first;
3866 while (pos)
3867 last = GetNextSelectedItem(pos);
3868 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
3870 SetCursor(LoadCursor(nullptr, IDC_NO));
3871 m_nDropIndex = -1;
3874 // handle auto scrolling
3875 int hotItem = GetHotItem();
3876 int topindex = GetTopIndex();
3877 if (hotItem == topindex && hotItem != 0)
3878 EnsureVisible(hotItem - 1, FALSE);
3879 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
3880 EnsureVisible(hotItem + 1, FALSE);
3882 DrawDropInsertMarker(m_nDropIndex);
3885 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
3887 if (m_bDragging)
3889 ::ReleaseCapture();
3890 SetCursor(LoadCursor(nullptr, IDC_HAND));
3891 m_bDragging = FALSE;
3893 CRect rect;
3894 GetItemRect(m_nDropMarkerLast, &rect, 0);
3895 rect.bottom = rect.top + 2;
3896 rect.top -= 2;
3897 InvalidateRect(&rect, 0);
3899 CPoint pt(point);
3900 ClientToScreen(&pt);
3901 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
3902 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
3905 __super::OnLButtonUp(nFlags, point);
3908 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
3910 if (m_nDropMarkerLast != nIndex)
3912 CRect rect;
3913 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
3915 rect.bottom = rect.top + 2;
3916 rect.top -= 2;
3917 InvalidateRect(&rect, 0);
3919 else if (m_nDropMarkerLast == GetItemCount())
3920 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
3921 m_nDropMarkerLast = nIndex;
3923 if (nIndex < 0)
3924 return;
3926 DrawDropInsertMarkerLine(m_nDropMarkerLast);
3928 else if (m_nDropMarkerLastHot != GetHotItem())
3930 m_nDropMarkerLastHot = GetHotItem();
3931 m_nDropMarkerLast = -1;
3935 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
3937 CBrush* pBrush = CDC::GetHalftoneBrush();
3938 CDC* pDC = GetDC();
3940 CRect rect;
3941 if (nIndex < GetItemCount())
3943 GetItemRect(nIndex, &rect, 0);
3944 rect.bottom = rect.top + 2;
3945 rect.top -= 2;
3947 else
3949 GetItemRect(nIndex - 1, &rect, 0);
3950 rect.top = rect.bottom - 2;
3951 rect.bottom += 2;
3954 CBrush* pBrushOld = pDC->SelectObject(pBrush);
3955 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
3956 pDC->SelectObject(pBrushOld);
3958 ReleaseDC(pDC);
3961 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
3963 return 0;
3966 void CGitLogListBase::DrawListItemWithMatchesRect(NMLVCUSTOMDRAW* pLVCD, const std::vector<CHARRANGE>& ranges, CRect rect, const CString& text, HTHEME hTheme /*= nullptr*/, int txtState /*= 0*/)
3968 int drawPos = 0;
3969 COLORREF textColor = pLVCD->clrText;
3970 RECT rc = rect;
3971 if (!hTheme)
3973 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
3974 SetBkMode(pLVCD->nmcd.hdc, TRANSPARENT);
3976 DTTOPTS opts = { 0 };
3977 opts.dwSize = sizeof(opts);
3978 opts.crText = textColor;
3979 opts.dwFlags = DTT_TEXTCOLOR;
3981 for (auto it = ranges.cbegin(); it != ranges.cend(); ++it)
3983 rc = rect;
3984 if (it->cpMin - drawPos)
3986 if (!hTheme)
3988 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3989 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMin - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
3991 else
3993 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);
3994 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);
3996 rect.left = rc.right;
3998 rc = rect;
3999 drawPos = it->cpMin;
4000 if (it->cpMax - drawPos)
4002 if (!hTheme)
4004 ::SetTextColor(pLVCD->nmcd.hdc, m_Colors.GetColor(CColors::FilterMatch));
4005 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4006 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), it->cpMax - drawPos, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4007 ::SetTextColor(pLVCD->nmcd.hdc, textColor);
4009 else
4011 opts.crText = m_Colors.GetColor(CColors::FilterMatch);
4012 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);
4013 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);
4014 opts.crText = textColor;
4016 rect.left = rc.right;
4018 rc = rect;
4019 drawPos = it->cpMax;
4021 if (!hTheme)
4022 DrawText(pLVCD->nmcd.hdc, text.Mid(drawPos), -1, &rc, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4023 else
4024 DrawThemeTextEx(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, text.Mid(drawPos), -1, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS, &rc, &opts);
4027 bool CGitLogListBase::DrawListItemWithMatchesIfEnabled(std::shared_ptr<CLogDlgFilter> filter, DWORD selectedFilter, NMLVCUSTOMDRAW* pLVCD, LRESULT* pResult)
4029 if ((filter->GetSelectedFilters() & selectedFilter) && filter->IsFilterActive())
4031 *pResult = DrawListItemWithMatches(filter.get(), *this, pLVCD);
4032 return true;
4034 return false;
4037 LRESULT CGitLogListBase::DrawListItemWithMatches(CLogDlgFilter* filter, CListCtrl& listCtrl, NMLVCUSTOMDRAW* pLVCD)
4039 CString text;
4040 text = (LPCTSTR)listCtrl.GetItemText((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem);
4041 if (text.IsEmpty())
4042 return CDRF_DODEFAULT;
4044 std::vector<CHARRANGE> ranges;
4045 filter->GetMatchRanges(ranges, text, 0);
4046 if (ranges.empty())
4047 return CDRF_DODEFAULT;
4049 // even though we initialize the 'rect' here with nmcd.rc,
4050 // we must not use it but use the rects from GetItemRect()
4051 // and GetSubItemRect(). Because on XP, the nmcd.rc has
4052 // bogus data in it.
4053 CRect rect = pLVCD->nmcd.rc;
4055 // find the margin where the text label starts
4056 CRect labelRC, boundsRC, iconRC;
4057 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &labelRC, LVIR_LABEL);
4058 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &iconRC, LVIR_ICON);
4059 listCtrl.GetItemRect((int)pLVCD->nmcd.dwItemSpec, &boundsRC, LVIR_BOUNDS);
4061 int leftmargin = labelRC.left - boundsRC.left;
4062 if (pLVCD->iSubItem)
4063 leftmargin -= iconRC.Width();
4065 if (pLVCD->iSubItem != 0)
4066 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
4068 int borderWidth = 0;
4069 HTHEME hTheme = nullptr;
4070 if (IsAppThemed())
4072 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
4073 GetThemeMetric(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, LISS_NORMAL, TMT_BORDERSIZE, &borderWidth);
4075 else
4076 borderWidth = GetSystemMetrics(SM_CXBORDER);
4078 if (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES)
4080 // I'm not very happy about this fixed margin here
4081 // but I haven't found a way to ask the system what
4082 // the margin really is.
4083 // At least it works on XP/Vista/win7/win8, and even with
4084 // increased font sizes
4085 leftmargin = 4;
4088 LVITEM item = { 0 };
4089 item.iItem = (int)pLVCD->nmcd.dwItemSpec;
4090 item.iSubItem = 0;
4091 item.mask = LVIF_IMAGE | LVIF_STATE;
4092 item.stateMask = (UINT)-1;
4093 listCtrl.GetItem(&item);
4095 // fill background
4096 int txtState = LISS_NORMAL;
4097 if (!hTheme)
4099 HBRUSH brush = nullptr;
4100 if (item.state & LVIS_SELECTED)
4102 if (::GetFocus() == listCtrl.GetSafeHwnd())
4104 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
4105 pLVCD->clrText = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
4107 else
4109 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
4110 pLVCD->clrText = ::GetSysColor(COLOR_WINDOWTEXT);
4113 else
4114 brush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4115 CRect my;
4116 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, my);
4117 ::FillRect(pLVCD->nmcd.hdc, my, brush);
4118 ::DeleteObject(brush);
4120 else
4122 if (listCtrl.GetHotItem() == (int)pLVCD->nmcd.dwItemSpec)
4124 if (item.state & LVIS_SELECTED)
4125 txtState = LISS_HOTSELECTED;
4126 else
4127 txtState = LISS_HOT;
4129 else if (item.state & LVIS_SELECTED)
4131 if (::GetFocus() == listCtrl.GetSafeHwnd())
4132 txtState = LISS_SELECTED;
4133 else
4134 txtState = LISS_SELECTEDNOTFOCUS;
4137 if (IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
4138 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
4139 else
4141 HBRUSH brush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4142 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
4143 ::DeleteObject(brush);
4145 if (txtState != LISS_NORMAL)
4147 CRect my;
4148 listCtrl.GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, my);
4149 if (pLVCD->iSubItem == 0)
4151 // also fill the icon part of the line
4152 my.top = 0;
4153 my.left = 0;
4156 // calculate background for rect of whole line, but limit redrawing to SubItem rect
4157 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, boundsRC, my);
4161 // draw the icon for the first column
4162 if (pLVCD->iSubItem == 0)
4164 rect = boundsRC;
4165 rect.right = rect.left + listCtrl.GetColumnWidth(0);
4166 rect.left = iconRC.left;
4168 if (item.iImage >= 0)
4170 POINT pt;
4171 pt.x = rect.left;
4172 pt.y = rect.top;
4173 CDC dc;
4174 dc.Attach(pLVCD->nmcd.hdc);
4175 int style = ILD_TRANSPARENT;
4176 if (!hTheme)
4178 auto whitebrush = ::CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
4179 ::FillRect(dc, iconRC, whitebrush);
4180 ::DeleteObject(whitebrush);
4181 if (item.state & LVIS_SELECTED)
4183 if (::GetFocus() == listCtrl.GetSafeHwnd())
4184 style = ILD_SELECTED;
4185 else
4186 style = ILD_FOCUS;
4189 listCtrl.GetImageList(LVSIL_SMALL)->Draw(&dc, item.iImage, pt, style);
4190 dc.Detach();
4191 leftmargin -= iconRC.left;
4193 else
4195 RECT irc = boundsRC;
4196 irc.left += borderWidth;
4197 irc.right = iconRC.left;
4199 int state = 0;
4200 if (item.state & LVIS_SELECTED)
4202 if (listCtrl.GetHotItem() == item.iItem)
4203 state = CBS_CHECKEDHOT;
4204 else
4205 state = CBS_CHECKEDNORMAL;
4207 else
4209 if (listCtrl.GetHotItem() == item.iItem)
4210 state = CBS_UNCHECKEDHOT;
4212 if ((state) && (listCtrl.GetExtendedStyle() & LVS_EX_CHECKBOXES))
4214 HTHEME hTheme2 = OpenThemeData(m_hWnd, L"BUTTON");
4215 DrawThemeBackground(hTheme2, pLVCD->nmcd.hdc, BP_CHECKBOX, state, &irc, NULL);
4216 CloseThemeData(hTheme2);
4220 InflateRect(&rect, -(2 * borderWidth), 0);
4222 rect.left += leftmargin;
4223 RECT rc = rect;
4225 // is the column left- or right-aligned? (we don't handle centered (yet))
4226 LVCOLUMN Column;
4227 Column.mask = LVCF_FMT;
4228 listCtrl.GetColumn(pLVCD->iSubItem, &Column);
4229 if (Column.fmt & LVCFMT_RIGHT)
4231 DrawText(pLVCD->nmcd.hdc, text, -1, &rc, DT_CALCRECT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
4232 rect.left = rect.right - (rc.right - rc.left);
4233 if (!hTheme)
4235 rect.left += 2 * borderWidth;
4236 rect.right += 2 * borderWidth;
4240 DrawListItemWithMatchesRect(pLVCD, ranges, rect, text, hTheme, txtState);
4241 if (hTheme)
4242 CloseThemeData(hTheme);
4244 return CDRF_SKIPDEFAULT;