Use [] operator instead of at() method in order to speed things up
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blob9817ac50648320cf9fdd0eeb08151ad1aa385356
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - 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 "resource.h"
24 #include "GitLogListBase.h"
25 #include "IconMenu.h"
26 #include "cursor.h"
27 #include "GitProgressDlg.h"
28 #include "ProgressDlg.h"
29 #include "MessageBox.h"
30 #include "registry.h"
31 #include "LoglistUtils.h"
32 #include "StringUtils.h"
33 #include "UnicodeUtils.h"
34 #include "IconMenu.h"
35 #include "GitStatus.h"
36 #include "..\TortoiseShell\Resource.h"
37 #include "FindDlg.h"
39 template < typename Cont, typename Pred>
40 void for_each(Cont& c, Pred p)
42 std::for_each(cbegin(c), cend(c), p);
45 template<typename T>
46 using const_iterator = typename T::const_iterator;
48 template <typename Cont, typename Pred>
49 const_iterator<Cont> find_if(Cont& c, Pred p)
51 return std::find_if(cbegin(c), cend(c), p);
54 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
55 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
56 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
57 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
59 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
61 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
62 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
63 ,m_nSearchIndex(0)
64 ,m_bNoDispUpdates(FALSE)
65 , m_bThreadRunning(FALSE)
66 , m_bStrictStopped(false)
67 , m_SelectedFilters(LOGFILTER_ALL)
68 , m_ShowFilter(FILTERSHOW_ALL)
69 , m_bShowWC(false)
70 , m_logEntries(&m_LogCache)
71 , m_pFindDialog(nullptr)
72 , m_dwDefaultColumns(0)
73 , m_arShownList(&m_critSec)
74 , m_hasWC(true)
75 , m_bNoHightlightHead(FALSE)
76 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
77 , m_bFullCommitMessageOnLogLine(false)
78 , m_OldTopIndex(-1)
79 , m_AsyncThreadRunning(FALSE)
80 , m_AsyncThreadExit(FALSE)
81 , m_bIsCherryPick(false)
82 , m_pMailmap(nullptr)
84 // use the default GUI font, create a copy of it and
85 // change the copy to BOLD (leave the rest of the font
86 // the same)
87 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
88 LOGFONT lf = {0};
89 GetObject(hFont, sizeof(LOGFONT), &lf);
90 lf.lfWeight = FW_BOLD;
91 m_boldFont.CreateFontIndirect(&lf);
92 lf.lfWeight = FW_DONTCARE;
93 lf.lfItalic = TRUE;
94 m_FontItalics.CreateFontIndirect(&lf);
95 lf.lfWeight = FW_BOLD;
96 m_boldItalicsFont.CreateFontIndirect(&lf);
98 m_bShowBugtraqColumn=false;
100 m_IsIDReplaceAction=FALSE;
102 this->m_critSec.Init();
103 ResetWcRev(false);
105 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
106 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
107 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
108 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
109 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
110 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
112 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
113 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
115 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
116 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
118 CString key;
119 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
120 key.Replace(L':', L'_');
121 CString lastSelFromDate = CRegString(key);
122 if (lastSelFromDate.GetLength() == 10)
124 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
125 m_Filter.m_From = (DWORD)time.GetTime();
128 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
130 m_ShowMask = 0;
131 m_LoadingThread = nullptr;
133 InterlockedExchange(&m_bExitThread,FALSE);
134 m_IsOldFirst = FALSE;
135 m_IsRebaseReplaceGraph = FALSE;
137 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
139 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
141 // get short/long datetime setting from registry
142 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
143 if ( RegUseShortDateFormat )
145 m_DateFormat = DATE_SHORTDATE;
147 else
149 m_DateFormat = DATE_LONGDATE;
151 // get relative time display setting from registry
152 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
153 m_bRelativeTimes = (regRelativeTimes != 0);
154 m_ContextMenuMask = 0xFFFFFFFFFFFFFFFF;
156 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
157 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
158 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
159 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
160 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
161 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
162 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
164 m_ColumnRegKey = L"log";
166 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
167 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
168 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
169 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
171 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
172 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
174 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
175 git_read_mailmap(&m_pMailmap);
177 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
178 m_AsynDiffListLock.Init();
179 StartAsyncDiffThread();
182 int CGitLogListBase::AsyncDiffThread()
184 while(!m_AsyncThreadExit)
186 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
188 GitRevLoglist* pRev = nullptr;
189 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
191 m_AsynDiffListLock.Lock();
192 pRev = m_AsynDiffList.back();
193 m_AsynDiffList.pop_back();
194 m_AsynDiffListLock.Unlock();
196 if( pRev->m_CommitHash.IsEmpty() )
198 if(pRev->m_IsDiffFiles)
199 continue;
201 CTGitPathList& files = pRev->GetFiles(this);
202 files.Clear();
203 pRev->m_ParentHash.clear();
204 pRev->m_ParentHash.push_back(m_HeadHash);
205 g_Git.RefreshGitIndex();
206 g_Git.GetWorkingTreeChanges(files);
207 int& action = pRev->GetAction(this);
208 action = 0;
209 for (int j = 0; j < files.GetCount(); ++j)
210 action |= files[j].m_Action;
212 CString err;
213 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
215 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
216 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
217 return -1;
220 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
221 InterlockedExchange(&pRev->m_IsFull, TRUE);
223 CString body = L"\n";
224 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
225 pRev->GetBody() = body;
226 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
227 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
230 if (!pRev->CheckAndDiff())
231 { // fetch change file list
232 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
234 if (i < (int)m_arShownList.size())
236 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
237 if(data->m_CommitHash == pRev->m_CommitHash)
239 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
240 break;
245 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
247 POSITION pos = GetFirstSelectedItemPosition();
248 int nItem = GetNextSelectedItem(pos);
250 if(nItem>=0)
252 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
253 if(data)
254 if(data->m_CommitHash == pRev->m_CommitHash)
255 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
261 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
262 return 0;
264 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
266 if (exclusivelyShow)
267 m_ContextMenuMask &= hideMask;
268 else
269 m_ContextMenuMask &= ~hideMask;
272 CGitLogListBase::~CGitLogListBase()
274 InterlockedExchange(&m_bNoDispUpdates, TRUE);
275 this->m_arShownList.SafeRemoveAll();
277 DestroyIcon(m_hModifiedIcon);
278 DestroyIcon(m_hReplacedIcon);
279 DestroyIcon(m_hConflictedIcon);
280 DestroyIcon(m_hAddedIcon);
281 DestroyIcon(m_hDeletedIcon);
282 m_logEntries.ClearAll();
284 git_free_mailmap(m_pMailmap);
286 SafeTerminateThread();
287 SafeTerminateAsyncDiffThread();
289 if(m_AsyncDiffEvent)
290 CloseHandle(m_AsyncDiffEvent);
294 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
295 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
296 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
297 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
298 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
299 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
300 ON_WM_CONTEXTMENU()
301 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
302 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
303 ON_WM_CREATE()
304 ON_WM_DESTROY()
305 ON_MESSAGE(MSG_LOADED,OnLoad)
306 ON_WM_MEASUREITEM()
307 ON_WM_MEASUREITEM_REFLECT()
308 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
309 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
310 END_MESSAGE_MAP()
312 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
314 //if (m_nRowHeight>0)
315 lpMeasureItemStruct->itemHeight = 50;
318 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
320 PreSubclassWindow();
321 return __super::OnCreate(lpCreateStruct);
324 void CGitLogListBase::PreSubclassWindow()
326 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
327 // load the icons for the action columns
328 // m_Theme.Open(m_hWnd, L"ListView");
329 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
330 __super::PreSubclassWindow();
333 CString CGitLogListBase::GetRebaseActionName(int action)
335 if (action & LOGACTIONS_REBASE_EDIT)
336 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
337 if (action & LOGACTIONS_REBASE_SQUASH)
338 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
339 if (action & LOGACTIONS_REBASE_PICK)
340 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
341 if (action & LOGACTIONS_REBASE_SKIP)
342 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
344 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
347 void CGitLogListBase::InsertGitColumn()
349 CString temp;
351 Init();
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 static int with[] =
377 ICONITEMBORDER+16*4,
378 ICONITEMBORDER+16*4,
379 ICONITEMBORDER+16*4,
380 ICONITEMBORDER+16*4,
381 2*ICONITEMBORDER+16*5,
382 LOGLIST_MESSAGE_MIN,
383 ICONITEMBORDER+16*4,
384 ICONITEMBORDER+16*4,
385 ICONITEMBORDER+16*4,
386 ICONITEMBORDER+16*4,
387 ICONITEMBORDER+16*4,
388 ICONITEMBORDER+16*4,
389 ICONITEMBORDER+16*4,
390 ICONITEMBORDER+16*4,
392 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
394 DWORD hideColumns = 0;
395 if(this->m_IsRebaseReplaceGraph)
397 hideColumns |= GIT_LOG_GRAPH;
398 m_dwDefaultColumns |= GIT_LOG_REBASE;
400 else
401 hideColumns |= GIT_LOG_REBASE;
403 if(this->m_IsIDReplaceAction)
405 hideColumns |= GIT_LOG_ACTIONS;
406 m_dwDefaultColumns |= GIT_LOG_ID;
407 m_dwDefaultColumns |= GIT_LOG_HASH;
409 else
410 hideColumns |= GIT_LOG_ID;
411 if(this->m_bShowBugtraqColumn)
412 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
413 else
414 hideColumns |= GIT_LOGLIST_BUG;
415 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
416 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
417 else
418 hideColumns |= GIT_LOGLIST_SVNREV;
419 SetRedraw(false);
421 m_ColumnManager.SetNames(normal, _countof(normal));
422 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
423 m_ColumnManager.SetRightAlign(LOGLIST_ID);
425 SetRedraw(true);
428 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
430 LVITEM rItem = { 0 };
431 rItem.mask = LVIF_STATE;
432 rItem.iItem = (int)Index;
433 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
434 GetItem(&rItem);
436 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
437 HBRUSH brush = nullptr;
439 if (!(rItem.state & LVIS_SELECTED))
441 int action = pLogEntry->GetRebaseAction();
442 if (action & LOGACTIONS_REBASE_SQUASH)
443 brush = ::CreateSolidBrush(RGB(156,156,156));
444 else if (action & LOGACTIONS_REBASE_EDIT)
445 brush = ::CreateSolidBrush(RGB(200,200,128));
447 else if (!IsAppThemed())
449 if (rItem.state & LVIS_SELECTED)
451 if (::GetFocus() == m_hWnd)
452 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
453 else
454 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
457 if (brush)
459 ::FillRect(hdc, &rect, brush);
460 ::DeleteObject(brush);
464 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
466 POINT point = { 4, 4 };
467 CRect rt2 = rect;
468 rt2.DeflateRect(1, 1);
469 rt2.OffsetRect(2, 2);
471 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
472 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
473 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
474 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
475 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
477 ::SelectObject(hdc, brush);
478 rt2.OffsetRect(-2, -2);
479 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
480 ::SelectObject(hdc, oldbrush);
481 ::SelectObject(hdc, oldpen);
482 ::DeleteObject(nullPen);
483 ::DeleteObject(darkBrush);
486 void DrawLightning(HDC hdc, CRect rect, COLORREF color, int bold)
488 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
489 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
490 ::MoveToEx(hdc, rect.left + 7, rect.top, nullptr);
491 ::LineTo(hdc, rect.left + 1, (rect.top + rect.bottom) / 2);
492 ::LineTo(hdc, rect.left + 6, (rect.top + rect.bottom) / 2);
493 ::LineTo(hdc, rect.left, rect.bottom);
494 ::SelectObject(hdc, oldpen);
495 ::DeleteObject(pen);
498 void DrawUpTriangle(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 + rect.right) / 2, rect.top, nullptr);
503 ::LineTo(hdc, rect.left, rect.bottom);
504 ::LineTo(hdc, rect.right, rect.bottom);
505 ::LineTo(hdc, (rect.left + rect.right) / 2, rect.top);
506 ::SelectObject(hdc, oldpen);
507 ::DeleteObject(pen);
510 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
512 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
513 CRect rt=rect;
514 LVITEM rItem = { 0 };
515 rItem.mask = LVIF_STATE;
516 rItem.iItem = (int)index;
517 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
518 GetItem(&rItem);
520 CDC W_Dc;
521 W_Dc.Attach(hdc);
523 HTHEME hTheme = nullptr;
524 if (IsAppThemed())
525 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
527 SIZE oneSpaceSize;
528 if (m_bTagsBranchesOnRightSide)
530 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
531 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
532 SelectObject(hdc, oldFont);
533 rt.left += oneSpaceSize.cx * 2;
535 else
537 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
538 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
539 rt.left += oneSpaceSize.cx;
542 CString msg = MessageDisplayStr(data);
543 int action = data->GetRebaseAction();
544 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
545 if (IsAppThemed())
547 int txtState = LISS_NORMAL;
548 if (rItem.state & LVIS_SELECTED)
549 txtState = LISS_SELECTED;
551 DTTOPTS opts = { 0 };
552 opts.dwSize = sizeof(opts);
553 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
554 opts.dwFlags = DTT_TEXTCOLOR;
555 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
557 else
559 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
561 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
562 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
563 ::SetTextColor(hdc, clrOld);
565 else
567 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
568 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
569 ::SetTextColor(hdc, clrOld);
573 if (m_bTagsBranchesOnRightSide)
575 SIZE size;
576 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
578 rt.left += oneSpaceSize.cx + size.cx;
580 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
583 if (hTheme)
584 CloseThemeData(hTheme);
586 W_Dc.Detach();
589 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
591 for (unsigned int i = 0; i < refList.size(); ++i)
593 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
594 HBRUSH brush = 0;
595 COLORREF colRef = refList[i].color;
596 bool singleRemote = refList[i].singleRemote;
597 bool hasTracking = refList[i].hasTracking;
598 bool sameName = refList[i].sameName;
599 CGit::REF_TYPE refType = refList[i].refType;
601 //When row selected, ajust label color
602 if (!IsAppThemed())
604 if (rItem.state & LVIS_SELECTED)
605 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
608 brush = ::CreateSolidBrush(colRef);
610 if (!shortname.IsEmpty() && (rt.left < rect.right))
612 SIZE size = { 0 };
613 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
615 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
616 rt.right += 8;
618 int textpos = DT_CENTER;
620 if (rt.right > rect.right)
622 rt.right = rect.right;
623 textpos = 0;
626 CRect textRect = rt;
628 if (singleRemote)
630 rt.right += 8;
631 textRect.OffsetRect(8, 0);
634 if (sameName)
635 rt.right += 8;
637 if (hasTracking)
638 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
639 else
641 //Fill interior of ref label
642 ::FillRect(hdc, &rt, brush);
645 //Draw edge of label
646 CRect rectEdge = rt;
648 if (!hasTracking)
650 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
651 rectEdge.DeflateRect(1, 1);
652 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
655 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
657 rt.right += 8;
658 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
659 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
660 ::FillRgn(hdc, hrgn, brush);
661 ::DeleteObject(hrgn);
662 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
663 HPEN pen;
664 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
665 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
666 ::DeleteObject(pen);
667 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
668 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
669 ::DeleteObject(pen);
670 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
671 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
672 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
673 ::DeleteObject(pen);
674 SelectObject(hdc, oldpen);
677 //Draw text inside label
678 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
679 if (!customColor && IsAppThemed())
681 int txtState = LISS_NORMAL;
682 if (rItem.state & LVIS_SELECTED)
683 txtState = LISS_SELECTED;
685 DTTOPTS opts = { 0 };
686 opts.dwSize = sizeof(opts);
687 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
688 opts.dwFlags = DTT_TEXTCOLOR;
689 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
691 else
693 W_Dc.SetBkMode(TRANSPARENT);
694 if (customColor || (rItem.state & LVIS_SELECTED))
696 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
697 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
698 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
699 ::SetTextColor(hdc,clrOld);
701 else
703 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
704 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
705 ::SetTextColor(hdc, clrOld);
709 if (singleRemote)
711 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
712 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
713 CRect newRect;
714 newRect.SetRect(rt.left + 4, rt.top + 4, rt.left + 8, rt.bottom - 4);
715 DrawLightning(hdc, newRect, color, bold);
718 if (sameName)
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.right - 12, rt.top + 4, rt.right - 4, rt.bottom - 4);
724 DrawUpTriangle(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 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
739 // Returns ((256 - amount)*col1 + amount*col2) / 256;
740 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
741 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
742 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
745 Gdiplus::Color GetGdiColor(COLORREF col)
747 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
749 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
750 const COLORREF& col,const COLORREF& activeColor, int top
753 int h = laneHeight / 2;
754 int m = (x1 + x2) / 2;
755 int r = (x2 - x1) * m_NodeSize / 30;
756 int d = 2 * r;
758 #define P_CENTER m , h+top
759 #define P_0 x2, h+top
760 #define P_90 m , 0+top-1
761 #define P_180 x1, h+top
762 #define P_270 m , 2 * h+top +1
763 #define R_CENTER m - r, h - r+top, d, d
766 #define DELTA_UR_B 2*(x1 - m), 2*h +top
767 #define DELTA_UR_E 0*16, 90*16 +top // -,
769 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
770 #define DELTA_DR_E 270*16, 90*16 +top // -'
772 #define DELTA_UL_B 2*(x2 - m), 2*h +top
773 #define DELTA_UL_E 90*16, 90*16 +top // ,-
775 #define DELTA_DL_B 2*(x2 - m),2*-h +top
776 #define DELTA_DL_E 180*16, 90*16 // '-
778 #define CENTER_UR x1, 2*h, 225
779 #define CENTER_DR x1, 0 , 135
780 #define CENTER_UL x2, 2*h, 315
781 #define CENTER_DL x2, 0 , 45
784 Gdiplus::Graphics graphics( hdc );
786 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
788 // arc
789 switch (type) {
790 case Lanes::JOIN:
791 case Lanes::JOIN_R:
792 case Lanes::HEAD:
793 case Lanes::HEAD_R:
795 Gdiplus::LinearGradientBrush gradient(
796 Gdiplus::Point(x1-2, h+top-2),
797 Gdiplus::Point(P_270),
798 GetGdiColor(activeColor),GetGdiColor(col));
801 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
802 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
804 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
805 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
806 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
808 break;
810 case Lanes::JOIN_L:
812 Gdiplus::LinearGradientBrush gradient(
813 Gdiplus::Point(P_270),
814 Gdiplus::Point(x2+1, h+top-1),
815 GetGdiColor(col),GetGdiColor(activeColor));
818 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
819 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
821 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
822 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
823 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
826 break;
828 case Lanes::TAIL:
829 case Lanes::TAIL_R:
831 Gdiplus::LinearGradientBrush gradient(
832 Gdiplus::Point(x1-2, h+top-2),
833 Gdiplus::Point(P_90),
834 GetGdiColor(activeColor),GetGdiColor(col));
836 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
838 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
840 #if 0
841 QConicalGradient gradient(CENTER_DR);
842 gradient.setColorAt(0.375, activeCol);
843 gradient.setColorAt(0.625, col);
844 myPen.setBrush(gradient);
845 p->setPen(myPen);
846 p->drawArc(P_CENTER, DELTA_DR);
847 #endif
848 break;
850 default:
851 break;
855 //static QPen myPen(Qt::black, 2); // fast path here
856 CPen pen;
857 pen.CreatePen(PS_SOLID,2,col);
858 //myPen.setColor(col);
859 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
861 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
863 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
865 //p->setPen(myPen);
867 // vertical line
868 switch (type) {
869 case Lanes::ACTIVE:
870 case Lanes::NOT_ACTIVE:
871 case Lanes::MERGE_FORK:
872 case Lanes::MERGE_FORK_R:
873 case Lanes::MERGE_FORK_L:
874 case Lanes::JOIN:
875 case Lanes::JOIN_R:
876 case Lanes::JOIN_L:
877 case Lanes::CROSS:
878 //DrawLine(hdc,P_90,P_270);
879 graphics.DrawLine(&myPen,P_90,P_270);
880 //p->drawLine(P_90, P_270);
881 break;
882 case Lanes::HEAD_L:
883 case Lanes::BRANCH:
884 //DrawLine(hdc,P_CENTER,P_270);
885 graphics.DrawLine(&myPen,P_CENTER,P_270);
886 //p->drawLine(P_CENTER, P_270);
887 break;
888 case Lanes::TAIL_L:
889 case Lanes::INITIAL:
890 case Lanes::BOUNDARY:
891 case Lanes::BOUNDARY_C:
892 case Lanes::BOUNDARY_R:
893 case Lanes::BOUNDARY_L:
894 //DrawLine(hdc,P_90, P_CENTER);
895 graphics.DrawLine(&myPen,P_90,P_CENTER);
896 //p->drawLine(P_90, P_CENTER);
897 break;
898 default:
899 break;
902 myPen.SetColor(GetGdiColor(activeColor));
904 // horizontal line
905 switch (type) {
906 case Lanes::MERGE_FORK:
907 case Lanes::JOIN:
908 case Lanes::HEAD:
909 case Lanes::TAIL:
910 case Lanes::CROSS:
911 case Lanes::CROSS_EMPTY:
912 case Lanes::BOUNDARY_C:
913 //DrawLine(hdc,P_180,P_0);
914 graphics.DrawLine(&myPen,P_180,P_0);
915 //p->drawLine(P_180, P_0);
916 break;
917 case Lanes::MERGE_FORK_R:
918 case Lanes::BOUNDARY_R:
919 //DrawLine(hdc,P_180,P_CENTER);
920 graphics.DrawLine(&myPen,P_180,P_CENTER);
921 //p->drawLine(P_180, P_CENTER);
922 break;
923 case Lanes::MERGE_FORK_L:
924 case Lanes::HEAD_L:
925 case Lanes::TAIL_L:
926 case Lanes::BOUNDARY_L:
927 //DrawLine(hdc,P_CENTER,P_0);
928 graphics.DrawLine(&myPen,P_CENTER,P_0);
929 //p->drawLine(P_CENTER, P_0);
930 break;
931 default:
932 break;
935 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
937 CBrush brush;
938 brush.CreateSolidBrush(col);
939 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
941 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
942 // center symbol, e.g. rect or ellipse
943 switch (type) {
944 case Lanes::ACTIVE:
945 case Lanes::INITIAL:
946 case Lanes::BRANCH:
948 //p->setPen(Qt::NoPen);
949 //p->setBrush(col);
950 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
951 graphics.FillEllipse(&myBrush, R_CENTER);
952 //p->drawEllipse(R_CENTER);
953 break;
954 case Lanes::MERGE_FORK:
955 case Lanes::MERGE_FORK_R:
956 case Lanes::MERGE_FORK_L:
957 //p->setPen(Qt::NoPen);
958 //p->setBrush(col);
959 //p->drawRect(R_CENTER);
960 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
961 graphics.FillRectangle(&myBrush, R_CENTER);
962 break;
963 case Lanes::UNAPPLIED:
964 // Red minus sign
965 //p->setPen(Qt::NoPen);
966 //p->setBrush(Qt::red);
967 //p->drawRect(m - r, h - 1, d, 2);
968 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
969 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
970 break;
971 case Lanes::APPLIED:
972 // Green plus sign
973 //p->setPen(Qt::NoPen);
974 //p->setBrush(DARK_GREEN);
975 //p->drawRect(m - r, h - 1, d, 2);
976 //p->drawRect(m - 1, h - r, 2, d);
977 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
978 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
979 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
980 break;
981 case Lanes::BOUNDARY:
982 //p->setBrush(back);
983 //p->drawEllipse(R_CENTER);
984 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
985 graphics.DrawEllipse(&myPen, R_CENTER);
986 break;
987 case Lanes::BOUNDARY_C:
988 case Lanes::BOUNDARY_R:
989 case Lanes::BOUNDARY_L:
990 //p->setBrush(back);
991 //p->drawRect(R_CENTER);
992 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
993 graphics.FillRectangle(&myBrush,R_CENTER);
994 break;
995 default:
996 break;
999 ::SelectObject(hdc,oldpen);
1000 ::SelectObject(hdc,oldbrush);
1001 #undef P_CENTER
1002 #undef P_0
1003 #undef P_90
1004 #undef P_180
1005 #undef P_270
1006 #undef R_CENTER
1009 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
1011 // TODO: unfinished
1012 // return;
1013 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1014 if(data->m_CommitHash.IsEmpty())
1015 return;
1017 CRect rt=rect;
1018 LVITEM rItem = { 0 };
1019 rItem.mask = LVIF_STATE;
1020 rItem.iItem = (int)index;
1021 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1022 GetItem(&rItem);
1024 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1026 if (data->m_Lanes.empty())
1027 m_logEntries.setLane(data->m_CommitHash);
1029 std::vector<int>& lanes=data->m_Lanes;
1030 size_t laneNum = lanes.size();
1031 UINT activeLane = 0;
1032 for (UINT i = 0; i < laneNum; ++i)
1033 if (Lanes::isMerge(lanes[i])) {
1034 activeLane = i;
1035 break;
1038 int x2 = 0;
1039 int maxWidth = rect.Width();
1040 int lw = 3 * rect.Height() / 4; //laneWidth()
1042 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1043 //if (opt.state & QStyle::State_Selected)
1044 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1046 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1048 int x1 = x2;
1049 x2 += lw;
1051 int ln = lanes[i];
1052 if (ln == Lanes::EMPTY)
1053 continue;
1055 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1056 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1059 #if 0
1060 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1061 int x1 = x2;
1062 x2 += lw;
1064 int ln = lanes[i];
1065 if (ln == Lanes::EMPTY)
1066 continue;
1068 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1069 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1071 if (ln == Lanes::CROSS)
1073 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1074 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1076 else
1077 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1079 #endif
1082 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1084 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1085 // Take the default processing unless we set this to something else below.
1086 *pResult = CDRF_DODEFAULT;
1088 if (m_bNoDispUpdates)
1089 return;
1091 switch (pLVCD->nmcd.dwDrawStage)
1093 case CDDS_PREPAINT:
1095 *pResult = CDRF_NOTIFYITEMDRAW;
1096 return;
1098 break;
1099 case CDDS_ITEMPREPAINT:
1101 // This is the prepaint stage for an item. Here's where we set the
1102 // item's text color.
1104 // Tell Windows to send draw notifications for each subitem.
1105 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1107 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1109 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1111 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1112 if (data)
1114 HGDIOBJ hGdiObj = nullptr;
1115 int action = data->GetRebaseAction();
1116 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1117 crText = RGB(128,128,128);
1119 if (action & LOGACTIONS_REBASE_SQUASH)
1120 pLVCD->clrTextBk = RGB(156,156,156);
1121 else if (action & LOGACTIONS_REBASE_EDIT)
1122 pLVCD->clrTextBk = RGB(200,200,128);
1123 else
1124 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1126 if (action & LOGACTIONS_REBASE_CURRENT)
1127 hGdiObj = m_boldFont.GetSafeHandle();
1129 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1130 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1131 if (isHeadHash && isHighlight)
1132 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1133 else if (isHeadHash)
1134 hGdiObj = m_boldFont.GetSafeHandle();
1135 else if (isHighlight)
1136 hGdiObj = m_FontItalics.GetSafeHandle();
1138 if (hGdiObj)
1140 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1141 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1144 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1145 // crText = GetSysColor(COLOR_GRAYTEXT);
1147 if (data->m_CommitHash.IsEmpty())
1149 //crText = GetSysColor(RGB(200,200,0));
1150 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1151 // We changed the font, so we're returning CDRF_NEWFONT. This
1152 // tells the control to recalculate the extent of the text.
1153 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1157 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1159 if (m_bStrictStopped)
1160 crText = GetSysColor(COLOR_GRAYTEXT);
1162 // Store the color back in the NMLVCUSTOMDRAW struct.
1163 pLVCD->clrText = crText;
1164 return;
1166 break;
1167 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1169 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1171 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1174 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1176 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1178 CRect rect;
1179 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1181 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1182 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1184 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1185 if( !data ->m_CommitHash.IsEmpty())
1186 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1188 *pResult = CDRF_SKIPDEFAULT;
1189 return;
1193 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1195 // If the top index of list is changed, the position map of reference label is outdated.
1196 if (m_OldTopIndex != GetTopIndex())
1198 m_OldTopIndex = GetTopIndex();
1199 m_RefLabelPosMap.clear();
1202 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1204 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1206 if ((!m_HashMap[data->m_CommitHash].empty() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1208 CRect rect;
1209 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1211 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1212 // not in FillBackGround method, because this only affected the message subitem
1213 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1214 return;
1216 int index = (int)pLVCD->nmcd.dwItemSpec;
1217 int state = GetItemState(index, LVIS_SELECTED);
1218 int txtState = LISS_NORMAL;
1219 if (IsAppThemed() && GetHotItem() == (int)index)
1221 if (state & LVIS_SELECTED)
1222 txtState = LISS_HOTSELECTED;
1223 else
1224 txtState = LISS_HOT;
1226 else if (state & LVIS_SELECTED)
1228 if (::GetFocus() == m_hWnd)
1229 txtState = LISS_SELECTED;
1230 else
1231 txtState = LISS_SELECTEDNOTFOCUS;
1234 HTHEME hTheme = nullptr;
1235 if (IsAppThemed())
1236 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1238 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1239 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1240 else
1242 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1243 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1244 ::DeleteObject(brush);
1246 if (hTheme && txtState != LISS_NORMAL)
1248 CRect rt;
1249 // get rect of whole line
1250 GetItemRect(index, rt, LVIR_BOUNDS);
1251 CRect rect2 = rect;
1253 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1254 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1256 CloseThemeData(hTheme);
1258 // END: extended redraw
1260 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1262 std::vector<REFLABEL> refsToShow;
1263 STRING_VECTOR remoteTrackingList;
1264 STRING_VECTOR refList = m_HashMap[data->m_CommitHash];
1265 for (unsigned int i = 0; i < refList.size(); ++i)
1267 CString str = refList[i];
1269 REFLABEL refLabel;
1270 refLabel.color = RGB(255, 255, 255);
1271 refLabel.singleRemote = false;
1272 refLabel.hasTracking = false;
1273 refLabel.sameName = false;
1274 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1275 refLabel.fullName = str;
1277 switch (refLabel.refType)
1279 case CGit::REF_TYPE::LOCAL_BRANCH:
1281 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1282 continue;
1283 if (refLabel.name == m_CurrentBranch)
1284 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1285 else
1286 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1288 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1289 CString pullRemote = trackingEntry.first;
1290 CString pullBranch = trackingEntry.second;
1291 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1293 CString defaultUpstream;
1294 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1295 refLabel.hasTracking = true;
1296 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1298 bool found = false;
1299 for (size_t j = i + 1; j < refList.size(); ++j)
1301 if (refList[j] == defaultUpstream)
1303 found = true;
1304 break;
1308 if (found)
1310 bool sameName = pullBranch == refLabel.name;
1311 refsToShow.push_back(refLabel);
1312 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1313 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1314 if (m_bSymbolizeRefNames)
1316 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1318 refLabel.simplifiedName = L'/' + (sameName ? CString() : pullBranch);
1319 refLabel.singleRemote = true;
1321 else if (sameName)
1322 refLabel.simplifiedName = pullRemote + L'/';
1323 refLabel.sameName = sameName;
1325 refLabel.fullName = defaultUpstream;
1326 refsToShow.push_back(refLabel);
1327 remoteTrackingList.push_back(defaultUpstream);
1328 continue;
1332 break;
1334 case CGit::REF_TYPE::REMOTE_BRANCH:
1336 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1337 continue;
1338 bool found = false;
1339 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1341 if (remoteTrackingList[j] == str)
1343 found = true;
1344 break;
1347 if (found)
1348 continue;
1350 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1351 if (m_bSymbolizeRefNames)
1353 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1355 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1356 refLabel.singleRemote = true;
1359 break;
1361 case CGit::REF_TYPE::ANNOTATED_TAG:
1362 case CGit::REF_TYPE::TAG:
1363 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1364 continue;
1365 refLabel.color = m_Colors.GetColor(CColors::Tag);
1366 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;
1372 case CGit::REF_TYPE::BISECT_GOOD:
1373 case CGit::REF_TYPE::BISECT_BAD:
1374 case CGit::REF_TYPE::BISECT_SKIP:
1375 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1376 continue;
1377 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));
1378 break;
1379 default:
1380 continue;
1382 refsToShow.push_back(refLabel);
1384 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1386 REFLABEL refLabel;
1387 refLabel.color = RGB(246, 153, 253);
1388 refLabel.singleRemote = false;
1389 refLabel.hasTracking = false;
1390 refLabel.sameName = false;
1391 refLabel.name = L"super-project-pointer";
1392 refLabel.fullName = "";
1393 refsToShow.push_back(refLabel);
1396 if (refsToShow.empty())
1398 *pResult = CDRF_DODEFAULT;
1399 return;
1402 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1404 *pResult = CDRF_SKIPDEFAULT;
1405 return;
1412 if (pLVCD->iSubItem == LOGLIST_ACTION)
1414 if(this->m_IsIDReplaceAction)
1416 *pResult = CDRF_DODEFAULT;
1417 return;
1419 *pResult = CDRF_DODEFAULT;
1421 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1422 return;
1424 int nIcons = 0;
1425 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1426 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1428 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1429 CRect rect;
1430 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1431 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1432 // Get the selected state of the
1433 // item being drawn.
1435 // Fill the background if necessary
1436 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec, rect);
1438 // Draw the icon(s) into the compatible DC
1439 int action = pLogEntry->GetAction(this);
1440 if (!pLogEntry->m_IsDiffFiles)
1442 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1443 *pResult = CDRF_SKIPDEFAULT;
1444 return;
1447 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1448 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1449 ++nIcons;
1451 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1452 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1453 ++nIcons;
1455 if (action & CTGitPath::LOGACTIONS_DELETED)
1456 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 if (action & CTGitPath::LOGACTIONS_REPLACED)
1460 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1461 ++nIcons;
1463 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1464 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1465 ++nIcons;
1467 *pResult = CDRF_SKIPDEFAULT;
1468 return;
1471 break;
1473 *pResult = CDRF_DODEFAULT;
1476 CString FindSVNRev(const CString& msg)
1480 const std::tr1::wsregex_iterator end;
1481 std::wstring s = msg;
1482 std::tr1::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1483 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1485 const std::tr1::wsmatch match = *it;
1486 if (match.size() == 4)
1488 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1489 return std::wstring(match[2]).c_str();
1492 std::tr1::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1493 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1495 const std::tr1::wsmatch match = *it;
1496 if (match.size() == 3)
1498 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1499 return std::wstring(match[1]).c_str();
1503 catch (std::exception&) {}
1505 return L"";
1508 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1510 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1511 return pLogEntry->GetSubject();
1513 CString txt(pLogEntry->GetSubject());
1514 txt += L' ';
1515 txt += pLogEntry->GetBody();
1517 // Deal with CRLF
1518 txt.Replace(L'\n', L' ');
1519 txt.Replace(L'\r', L' ');
1521 return txt;
1524 // CGitLogListBase message handlers
1526 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1528 struct payload_struct { const CString* name; const char* authorName; };
1529 payload_struct payload = { &name, nullptr };
1530 const char* author1 = nullptr;
1531 const char* email1 = nullptr;
1532 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1533 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1534 free((void *)payload.authorName);
1535 if (returnEmail)
1536 return email1;
1537 return author1;
1540 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1542 if (mailmap)
1544 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1545 if (translated)
1547 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1548 return;
1551 if (returnEmail)
1552 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1553 else
1554 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1557 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1559 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1561 // Create a pointer to the item
1562 LV_ITEM* pItem = &(pDispInfo)->item;
1564 // Do the list need text information?
1565 if (!(pItem->mask & LVIF_TEXT))
1566 return;
1568 // By default, clear text buffer.
1569 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1571 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1573 *pResult = 0;
1574 if (m_bNoDispUpdates || bOutOfRange)
1575 return;
1577 // Which item number?
1578 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1580 CString temp;
1581 if(m_IsOldFirst)
1582 temp.Format(L"%d", pItem->iItem + 1);
1583 else
1584 temp.Format(L"%d", m_arShownList.size() - pItem->iItem);
1586 if (!pLogEntry)
1587 return;
1589 // Which column?
1590 switch (pItem->iSubItem)
1592 case LOGLIST_GRAPH: //Graphic
1593 break;
1594 case LOGLIST_REBASE:
1595 if (m_IsRebaseReplaceGraph)
1596 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1597 break;
1598 case LOGLIST_ACTION: //action -- no text in the column
1599 break;
1600 case LOGLIST_HASH:
1601 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1602 break;
1603 case LOGLIST_ID:
1604 if (this->m_IsIDReplaceAction)
1605 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1606 break;
1607 case LOGLIST_MESSAGE: //Message
1608 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1609 break;
1610 case LOGLIST_AUTHOR: //Author
1611 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1612 break;
1613 case LOGLIST_DATE: //Date
1614 if (!pLogEntry->m_CommitHash.IsEmpty())
1615 lstrcpyn(pItem->pszText,
1616 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1617 pItem->cchTextMax - 1);
1618 break;
1620 case LOGLIST_EMAIL:
1621 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1622 break;
1624 case LOGLIST_COMMIT_NAME: //Commit
1625 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1626 break;
1628 case LOGLIST_COMMIT_EMAIL: //Commit Email
1629 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1630 break;
1632 case LOGLIST_COMMIT_DATE: //Commit Date
1633 if (!pLogEntry->m_CommitHash.IsEmpty())
1634 lstrcpyn(pItem->pszText,
1635 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1636 pItem->cchTextMax - 1);
1637 break;
1638 case LOGLIST_BUG: //Bug ID
1639 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1640 break;
1641 case LOGLIST_SVNREV: //SVN revision
1642 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1643 break;
1645 default:
1646 ASSERT(false);
1650 bool CGitLogListBase::IsOnStash(int index)
1652 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1653 if (IsStash(rev))
1654 return true;
1655 if (index > 0)
1657 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1658 if (IsStash(preRev))
1659 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1661 return false;
1664 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1666 for (size_t i = 0; i < m_HashMap[pSelLogEntry->m_CommitHash].size(); ++i)
1668 if (m_HashMap[pSelLogEntry->m_CommitHash][i] == L"refs/stash")
1669 return true;
1671 return false;
1674 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1676 for (size_t i = 0; i < m_HashMap[pSelLogEntry->m_CommitHash].size(); ++i)
1678 if (CStringUtils::StartsWith(m_HashMap[pSelLogEntry->m_CommitHash][i], L"refs/bisect/"))
1679 return true;
1681 return false;
1684 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1686 if (pRev->m_ParentHash.empty())
1688 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1689 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1691 parentHash = pRev->m_ParentHash;
1694 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1696 __super::OnContextMenu(pWnd, point);
1698 if (pWnd != this)
1699 return;
1701 int selIndex = GetSelectionMark();
1702 if (selIndex < 0)
1703 return; // nothing selected, nothing to do with a context menu
1705 // if the user selected the info text telling about not all revisions shown due to
1706 // the "stop on copy/rename" option, we also don't show the context menu
1707 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1708 return;
1710 // if the context menu is invoked through the keyboard, we have to use
1711 // a calculated position on where to anchor the menu on
1712 if ((point.x == -1) && (point.y == -1))
1714 CRect rect;
1715 GetItemRect(selIndex, &rect, LVIR_LABEL);
1716 ClientToScreen(&rect);
1717 point = rect.CenterPoint();
1719 m_nSearchIndex = selIndex;
1720 m_bCancelled = FALSE;
1722 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1724 POSITION pos = GetFirstSelectedItemPosition();
1725 int FirstSelect = GetNextSelectedItem(pos);
1726 if (FirstSelect < 0)
1727 return;
1729 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1730 if (pSelLogEntry == nullptr)
1731 return;
1733 int LastSelect = -1;
1734 UINT selectedCount = 1;
1735 while (pos)
1737 LastSelect = GetNextSelectedItem(pos);
1738 ++selectedCount;
1741 ASSERT(GetSelectedCount() == selectedCount);
1743 #if 0
1744 GitRev revSelected = pSelLogEntry->Rev;
1745 GitRev revPrevious = git_revnum_t(revSelected)-1;
1746 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1748 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1750 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1751 if (changedpath->lCopyFromRev)
1752 revPrevious = changedpath->lCopyFromRev;
1755 GitRev revSelected2;
1756 if (pos)
1758 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1759 revSelected2 = pLogEntry->Rev;
1761 bool bAllFromTheSameAuthor = true;
1762 CString firstAuthor;
1763 CLogDataVector selEntries;
1764 GitRev revLowest, revHighest;
1765 GitRevRangeArray revisionRanges;
1767 POSITION pos = GetFirstSelectedItemPosition();
1768 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1769 revisionRanges.AddRevision(pLogEntry->Rev);
1770 selEntries.push_back(pLogEntry);
1771 firstAuthor = pLogEntry->sAuthor;
1772 revLowest = pLogEntry->Rev;
1773 revHighest = pLogEntry->Rev;
1774 while (pos)
1776 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1777 revisionRanges.AddRevision(pLogEntry->Rev);
1778 selEntries.push_back(pLogEntry);
1779 if (firstAuthor.Compare(pLogEntry->sAuthor))
1780 bAllFromTheSameAuthor = false;
1781 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1782 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1786 #endif
1788 //entry is selected, now show the popup menu
1789 CIconMenu popup;
1790 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1792 if (popup.CreatePopupMenu())
1794 bool isHeadCommit = (pSelLogEntry->m_CommitHash == m_HeadHash);
1795 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1796 CTGitPath workingTree(g_Git.m_CurrentDir);
1797 bool isMergeActive = workingTree.IsMergeActive();
1798 bool isBisectActive = workingTree.IsBisectActive();
1799 bool isStash = IsOnStash(FirstSelect);
1800 GIT_REV_LIST parentHash;
1801 GetParentHashes(pSelLogEntry, parentHash);
1803 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1804 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1806 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))
1807 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1809 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1810 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1812 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1813 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1815 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)))
1816 popup.AppendMenu(MF_SEPARATOR, NULL);
1818 if (selectedCount == 1)
1821 bool requiresSeparator = false;
1822 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1824 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1826 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1827 requiresSeparator = true;
1830 else
1832 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1834 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1835 requiresSeparator = true;
1837 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1839 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1840 requiresSeparator = true;
1844 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1846 if (parentHash.size() == 1)
1848 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1849 requiresSeparator = true;
1851 else if (parentHash.size() > 1)
1853 blamemenu.CreatePopupMenu();
1854 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1855 for (size_t i = 0; i < parentHash.size(); ++i)
1857 CString str;
1858 str.Format(IDS_PARENT, i + 1);
1859 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1861 requiresSeparator = true;
1865 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1867 if (parentHash.size() == 1)
1869 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1870 requiresSeparator = true;
1872 else if (parentHash.size() > 1)
1874 gnudiffmenu.CreatePopupMenu();
1875 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1877 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1878 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1879 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1881 for (size_t i = 0; i < parentHash.size(); ++i)
1883 CString str;
1884 str.Format(IDS_PARENT, i + 1);
1885 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1887 requiresSeparator = true;
1891 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1893 if (parentHash.size() == 1)
1895 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1896 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1897 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1898 requiresSeparator = true;
1900 else if (parentHash.size() > 1)
1902 diffmenu.CreatePopupMenu();
1903 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1904 for (size_t i = 0; i < parentHash.size(); ++i)
1906 CString str;
1907 str.Format(IDS_PARENT, i + 1);
1908 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1909 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1911 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1912 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1915 requiresSeparator = true;
1919 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1921 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1922 requiresSeparator = true;
1925 if (requiresSeparator)
1927 popup.AppendMenu(MF_SEPARATOR, NULL);
1928 requiresSeparator = false;
1931 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1933 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1935 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1936 requiresSeparator = true;
1940 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1942 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1944 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1945 requiresSeparator = true;
1948 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1950 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1951 requiresSeparator = true;
1955 if (requiresSeparator)
1957 popup.AppendMenu(MF_SEPARATOR, NULL);
1958 requiresSeparator = false;
1961 if (isBisectActive)
1963 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1964 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1966 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1967 requiresSeparator = true;
1970 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1972 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1973 requiresSeparator = true;
1975 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1977 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1978 requiresSeparator = true;
1982 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1984 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1986 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1987 requiresSeparator = true;
1991 if (requiresSeparator)
1993 popup.AppendMenu(MF_SEPARATOR, NULL);
1994 requiresSeparator = false;
1997 if (pSelLogEntry->m_CommitHash.IsEmpty())
1999 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
2000 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2002 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
2003 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
2005 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2006 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2008 popup.AppendMenu(MF_SEPARATOR, NULL);
2010 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2011 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2013 popup.AppendMenu(MF_SEPARATOR, NULL);
2017 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2018 // {
2019 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2020 // }
2021 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2022 // {
2023 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2024 // }
2025 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2026 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2027 // {
2028 // popup.AppendMenu(MF_SEPARATOR, NULL);
2029 // }
2031 CString str;
2032 //if (m_hasWC)
2033 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2035 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2037 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2038 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2040 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2041 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2043 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2045 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2047 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2049 size_t index = (size_t)-1;
2050 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2051 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2052 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2055 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2057 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2058 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2061 // Add Switch Branch express Menu
2062 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2063 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2066 std::vector<const CString*> branchs;
2067 auto addCheck = [&](const CString& ref)
2069 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2070 return;
2071 branchs.push_back(&ref);
2073 size_t index = (size_t)-1;
2074 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2075 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2076 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2077 else
2078 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2080 CString str2;
2081 str2.LoadString(IDS_SWITCH_BRANCH);
2083 if(branchs.size() == 1)
2085 str2 += L' ';
2086 str2 += L'"' + branchs[0]->Mid(11) + L'"'; // 11 = len("refs/heads/")
2087 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2089 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2092 else if(branchs.size() > 1)
2094 subbranchmenu.CreatePopupMenu();
2095 for (size_t i = 0 ; i < branchs.size(); ++i)
2097 if (*branchs[i] != currentBranch)
2099 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2100 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2104 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2108 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2110 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2111 size_t index = (size_t)-1;
2112 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2113 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2114 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2117 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2119 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2121 size_t index = (size_t)-1;
2122 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2123 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2124 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2127 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2128 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2130 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2132 if (pSelLogEntry->m_CommitHash != m_HeadHash && m_hasWC && !isMergeActive && !isStash)
2133 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2134 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2136 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2137 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2139 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2141 if (parentHash.size() == 1)
2142 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2143 else if (parentHash.size() > 1)
2145 revertmenu.CreatePopupMenu();
2146 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2148 for (size_t i = 0; i < parentHash.size(); ++i)
2150 CString str2;
2151 str2.Format(IDS_PARENT, i + 1);
2152 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2157 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2158 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2160 popup.AppendMenu(MF_SEPARATOR, NULL);
2164 if(!pSelLogEntry->m_Ref.IsEmpty())
2166 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2167 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2168 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2169 if (selectedCount <= 2)
2170 popup.AppendMenu(MF_SEPARATOR, NULL);
2173 if (selectedCount >= 2)
2175 bool bAddSeparator = false;
2176 if ((selectedCount == 2) || IsSelectionContinuous())
2178 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2179 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2182 if (selectedCount == 2)
2184 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2185 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2187 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2189 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2190 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2191 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2192 CString menu;
2193 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2194 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2195 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2196 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2199 bAddSeparator = true;
2202 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2204 bAddSeparator = true;
2205 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2208 if (m_hasWC)
2209 bAddSeparator = true;
2211 if (bAddSeparator)
2213 popup.AppendMenu(MF_SEPARATOR, NULL);
2214 bAddSeparator = false;
2217 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2218 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2220 if (bAddSeparator)
2221 popup.AppendMenu(MF_SEPARATOR, NULL);
2224 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2226 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2227 popup.AppendMenu(MF_SEPARATOR, NULL);
2230 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2232 bool bAddSeparator = false;
2233 if (selectedCount >= 2 && IsSelectionContinuous())
2235 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2237 CString head;
2238 int headindex;
2239 headindex = this->GetHeadIndex();
2240 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2242 head.Format(L"HEAD~%d", FirstSelect - headindex);
2243 CGitHash hashFirst;
2244 int ret = g_Git.GetHash(hashFirst, head);
2245 head.Format(L"HEAD~%d",LastSelect-headindex);
2246 CGitHash hash;
2247 ret = ret || g_Git.GetHash(hash, head);
2248 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2249 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2250 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2252 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2253 bAddSeparator = true;
2258 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2259 if (selectedCount >= 2)
2260 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2261 else
2262 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2263 bAddSeparator = true;
2266 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2267 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2268 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2269 bAddSeparator = true;
2272 if (bAddSeparator)
2273 popup.AppendMenu(MF_SEPARATOR, NULL);
2276 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2278 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2279 popup.AppendMenu(MF_SEPARATOR, NULL);
2282 if (selectedCount == 1)
2284 bool bAddSeparator = false;
2285 if (m_ContextMenuMask&GetContextMenuBit(ID_PUSH) && ((!isStash && !m_HashMap[pSelLogEntry->m_CommitHash].empty()) || showExtendedMenu))
2287 // show the push-option only if the log entry has an associated local branch
2288 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2289 if (isLocal || showExtendedMenu)
2291 CString str;
2292 str.LoadString(IDS_LOG_PUSH);
2294 CString branch;
2295 size_t index = (size_t)-1;
2296 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
2297 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2298 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2300 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2302 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2303 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2305 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2306 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2308 bAddSeparator = true;
2311 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2313 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2314 bAddSeparator = true;
2318 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2320 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2322 std::vector<const CString*> branchs;
2323 auto addCheck = [&](const CString& ref)
2325 if (ref == currentBranch)
2326 return;
2327 branchs.push_back(&ref);
2329 size_t index = (size_t)-1;
2330 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2331 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2332 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2333 else
2334 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2336 CString str;
2337 if (branchs.size() == 1)
2339 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2340 str += L' ';
2341 str += *branchs[0];
2342 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2343 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2344 bAddSeparator = true;
2346 else if (branchs.size() > 1)
2348 str.LoadString(IDS_DELETE_BRANCHTAG);
2349 submenu.CreatePopupMenu();
2350 for (size_t i = 0; i < branchs.size(); ++i)
2352 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2353 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2355 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2356 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2358 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2359 bAddSeparator = true;
2362 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2363 if (bAddSeparator)
2364 popup.AppendMenu(MF_SEPARATOR, NULL);
2365 } // selectedCount == 1
2367 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYHASH))
2368 popup.AppendMenuIcon(ID_COPYHASH, IDS_COPY_COMMIT_HASH, IDI_COPYCLIP);
2369 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2370 popup.AppendMenuIcon(ID_COPYCLIPBOARD, IDS_LOG_POPUP_COPYTOCLIPBOARD, IDI_COPYCLIP);
2371 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARDMESSAGES))
2372 popup.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_COPYTOCLIPBOARDMESSAGES, IDI_COPYCLIP);
2374 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2375 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2377 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2378 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2380 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2381 // DialogEnableWindow(IDOK, FALSE);
2382 // SetPromptApp(&theApp);
2384 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2386 // EnableOKButton();
2387 } // if (popup.CreatePopupMenu())
2390 bool CGitLogListBase::IsSelectionContinuous()
2392 if ( GetSelectedCount()==1 )
2394 // if only one revision is selected, the selection is of course
2395 // continuous
2396 return true;
2399 POSITION pos = GetFirstSelectedItemPosition();
2400 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2401 if (bContinuous)
2403 int itemindex = GetNextSelectedItem(pos);
2404 while (pos)
2406 int nextindex = GetNextSelectedItem(pos);
2407 if (nextindex - itemindex > 1)
2409 bContinuous = false;
2410 break;
2412 itemindex = nextindex;
2415 return bContinuous;
2418 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2420 CString sClipdata;
2421 POSITION pos = GetFirstSelectedItemPosition();
2422 if (pos)
2424 CString sRev;
2425 sRev.LoadString(IDS_LOG_REVISION);
2426 CString sAuthor;
2427 sAuthor.LoadString(IDS_LOG_AUTHOR);
2428 CString sDate;
2429 sDate.LoadString(IDS_LOG_DATE);
2430 CString sMessage;
2431 sMessage.LoadString(IDS_LOG_MESSAGE);
2432 bool first = true;
2433 while (pos)
2435 CString sLogCopyText;
2436 CString sPaths;
2437 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2439 if (toCopy == ID_COPY_ALL)
2441 //pLogEntry->GetFiles(this)
2442 //LogChangedPathArray * cpatharray = pLogEntry->pArChangedPaths;
2444 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2445 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2447 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2448 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2450 sPaths += L' ';
2451 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2453 sPaths += L"\r\n";
2455 sPaths.Trim();
2457 CString sNotesTags;
2458 if (!pLogEntry->m_Notes.IsEmpty())
2460 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2461 sNotesTags += L":\n";
2462 sNotesTags += pLogEntry->m_Notes;
2463 sNotesTags.Replace(L"\n", L"\r\n");
2465 CString tagInfo = GetTagInfo(pLogEntry);
2466 if (!tagInfo.IsEmpty())
2468 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2469 tagInfo.Replace(L"\n", L"\r\n");
2470 sNotesTags += tagInfo;
2473 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s----\r\n%s\r\n\r\n",
2474 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2475 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2476 (LPCTSTR)sDate,
2477 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2478 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2479 (LPCTSTR)sNotesTags,
2480 (LPCTSTR)sPaths);
2481 sClipdata += sLogCopyText;
2483 else if (toCopy == ID_COPY_MESSAGE)
2485 sClipdata += L"* ";
2486 sClipdata += pLogEntry->GetSubjectBody(true);
2487 sClipdata += L"\r\n\r\n";
2489 else if (toCopy == ID_COPY_SUBJECT)
2491 sClipdata += L"* ";
2492 sClipdata += pLogEntry->GetSubject().Trim();
2493 sClipdata += L"\r\n\r\n";
2495 else
2497 if (!first)
2498 sClipdata += L"\r\n";
2499 sClipdata += pLogEntry->m_CommitHash;
2502 first = false;
2504 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2508 void CGitLogListBase::DiffSelectedRevWithPrevious()
2510 if (m_bThreadRunning)
2511 return;
2513 int FirstSelect=-1, LastSelect=-1;
2514 POSITION pos = GetFirstSelectedItemPosition();
2515 FirstSelect = GetNextSelectedItem(pos);
2516 while(pos)
2517 LastSelect = GetNextSelectedItem(pos);
2519 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2522 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2524 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2525 *pResult = -1;
2527 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2528 return;
2529 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2530 return;
2531 if (!pFindInfo->lvfi.psz)
2532 return;
2533 #if 0
2534 CString sCmp = pFindInfo->lvfi.psz;
2535 CString sRev;
2536 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2538 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2539 sRev.Format(L"%ld", pLogEntry->Rev);
2540 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2542 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2544 *pResult = i;
2545 return;
2548 else
2550 if (sCmp.Compare(sRev)==0)
2552 *pResult = i;
2553 return;
2557 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2559 for (int i=0; i<pFindInfo->iStart; ++i)
2561 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2562 sRev.Format(L"%ld", pLogEntry->Rev);
2563 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2565 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2567 *pResult = i;
2568 return;
2571 else
2573 if (sCmp.Compare(sRev)==0)
2575 *pResult = i;
2576 return;
2581 #endif
2582 *pResult = -1;
2585 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2587 ClearText();
2589 this->m_arShownList.SafeRemoveAll();
2591 this->m_logEntries.ClearAll();
2592 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2593 return -1;
2595 SetItemCountEx((int)m_logEntries.size());
2597 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2599 if(m_IsOldFirst)
2601 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2602 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2604 else
2606 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2607 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2611 ReloadHashMap();
2613 if(path)
2614 m_Path=*path;
2615 return 0;
2618 int CGitLogListBase::FillGitLog(std::set<CGitHash>& hashes)
2620 ClearText();
2622 m_arShownList.SafeRemoveAll();
2624 m_logEntries.ClearAll();
2625 if (m_logEntries.Fill(hashes))
2626 return -1;
2628 SetItemCountEx((int)m_logEntries.size());
2630 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2632 if (m_IsOldFirst)
2634 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2635 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2637 else
2639 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2640 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2644 ReloadHashMap();
2646 return 0;
2649 int CGitLogListBase::BeginFetchLog()
2651 ClearText();
2653 this->m_arShownList.SafeRemoveAll();
2655 this->m_logEntries.ClearAll();
2657 this->m_LogCache.ClearAllParent();
2659 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2661 CTGitPath *path;
2662 if(this->m_Path.IsEmpty())
2663 path = nullptr;
2664 else
2665 path=&this->m_Path;
2667 int mask;
2668 mask = CGit::LOG_INFO_ONLY_HASH;
2669 if (m_bIncludeBoundaryCommits)
2670 mask |= CGit::LOG_INFO_BOUNDARY;
2671 // if(this->m_bAllBranch)
2672 mask |= m_ShowMask ;
2674 if(m_bShowWC)
2676 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2677 ResetWcRev();
2678 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2681 if (m_sRange.IsEmpty())
2682 m_sRange = L"HEAD";
2684 #if 0 /* use tortoiegit filter */
2685 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2686 data.m_Author = this->m_sFilterText;
2688 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2689 data.m_MessageFilter = this->m_sFilterText;
2691 data.m_IsRegex = m_bFilterWithRegex;
2692 #endif
2694 // follow does not work for directories
2695 if (!path || path->IsDirectory())
2696 mask &= ~CGit::LOG_INFO_FOLLOW;
2697 // follow does not work with all branches 8at least in TGit)
2698 if (mask & CGit::LOG_INFO_FOLLOW)
2699 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2701 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2703 //this->m_logEntries.ParserFromLog();
2704 if(IsInWorkingThread())
2706 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2708 else
2710 SetItemCountEx((int)m_logEntries.size());
2715 [] { git_init(); } ();
2717 catch (char* msg)
2719 CString err(msg);
2720 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2721 return -1;
2724 if (!g_Git.CanParseRev(m_sRange))
2726 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2727 return 0;
2729 // if show all branches, pick any ref as dummy entry ref
2730 STRING_VECTOR list;
2731 if (g_Git.GetRefList(list))
2732 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2733 if (list.empty())
2734 return 0;
2736 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2739 g_Git.m_critGitDllSec.Lock();
2740 try {
2741 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2743 g_Git.m_critGitDllSec.Unlock();
2744 return -1;
2747 catch (char* msg)
2749 g_Git.m_critGitDllSec.Unlock();
2750 CString err(msg);
2751 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2752 return -1;
2754 g_Git.m_critGitDllSec.Unlock();
2756 return 0;
2759 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2761 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2763 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2765 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2767 DiffSelectedRevWithPrevious();
2768 return TRUE;
2771 #if 0
2772 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2774 DiffSelectedFile();
2775 return TRUE;
2777 #endif
2779 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2781 // select all entries
2782 for (int i=0; i<GetItemCount(); ++i)
2783 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2784 return TRUE;
2787 #if 0
2788 if (m_hAccel && !bSkipAccelerator)
2790 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2791 if (ret)
2792 return TRUE;
2795 #endif
2796 //m_tooltips.RelayEvent(pMsg);
2797 return __super::PreTranslateMessage(pMsg);
2800 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2802 // a double click on an entry in the revision list has happened
2803 *pResult = 0;
2805 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2806 DiffSelectedRevWithPrevious();
2809 void CGitLogListBase::FetchLogAsync(void* data)
2811 ReloadHashMap();
2812 m_ProcData=data;
2813 StartLoadingThread();
2816 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2818 return ((CGitLogListBase*)pVoid)->LogThread();
2821 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2823 //CTime time;
2824 oldest=CTime::GetCurrentTime();
2825 latest=CTime(1971,1,2,0,0,0);
2826 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2828 if(m_logEntries[i].IsEmpty())
2829 continue;
2831 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2832 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2834 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2835 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2839 if(latest<oldest)
2840 latest=oldest;
2843 UINT CGitLogListBase::LogThread()
2845 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2847 ULONGLONG t1,t2;
2849 if(BeginFetchLog())
2851 InterlockedExchange(&m_bThreadRunning, FALSE);
2852 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2854 return 1;
2857 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
2858 bool bRegex = false;
2859 if (m_bFilterWithRegex)
2860 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2862 TRACE(L"\n===Begin===\n");
2863 //Update work copy item;
2865 if (!m_logEntries.empty())
2867 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2869 m_arShownList.SafeAdd(pRev);
2873 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2875 // store commit number of the last selected commit/line before the refresh or -1
2876 int lastSelectedHashNItem = -1;
2877 if (m_lastSelectedHash.IsEmpty())
2878 lastSelectedHashNItem = 0;
2880 int ret = 0;
2882 bool shouldWalk = true;
2883 if (!g_Git.CanParseRev(m_sRange))
2885 // walk revisions if show all branches and there exists any ref
2886 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2887 shouldWalk = false;
2888 else
2890 STRING_VECTOR list;
2891 if (g_Git.GetRefList(list))
2892 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2893 if (list.empty())
2894 shouldWalk = false;
2898 if (shouldWalk)
2900 g_Git.m_critGitDllSec.Lock();
2901 int total = 0;
2904 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2905 total = git_get_log_estimate_commit_count(m_DllGitLog);
2907 catch (char* msg)
2909 CString err(msg);
2910 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2911 ret = -1;
2913 g_Git.m_critGitDllSec.Unlock();
2915 GIT_COMMIT commit;
2916 t2 = t1 = GetTickCount64();
2917 int oldprecentage = 0;
2918 size_t oldsize = m_logEntries.size();
2919 std::map<CGitHash, std::set<CGitHash>> commitChildren;
2920 while (ret== 0 && !m_bExitThread)
2922 g_Git.m_critGitDllSec.Lock();
2925 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2927 catch (char* msg)
2929 g_Git.m_critGitDllSec.Unlock();
2930 CString err(msg);
2931 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2932 break;
2934 g_Git.m_critGitDllSec.Unlock();
2936 if(ret)
2938 if (ret != -2) // other than end of revision walking
2939 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2940 break;
2943 if (commit.m_ignore == 1)
2945 git_free_commit(&commit);
2946 continue;
2949 //printf("%s\r\n",commit.GetSubject());
2950 if(m_bExitThread)
2951 break;
2953 CGitHash hash(commit.m_hash);
2955 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
2956 pRev->m_GitCommit = commit;
2957 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
2959 char* note = nullptr;
2960 g_Git.m_critGitDllSec.Lock();
2963 git_get_notes(commit.m_hash, &note);
2965 catch (char* msg)
2967 g_Git.m_critGitDllSec.Unlock();
2968 CString err(msg);
2969 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2970 break;
2972 g_Git.m_critGitDllSec.Unlock();
2974 if(note)
2976 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
2977 free(note);
2978 note = nullptr;
2981 if(!pRev->m_IsDiffFiles)
2983 pRev->m_CallDiffAsync = DiffAsync;
2986 pRev->ParserParentFromCommit(&commit);
2987 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
2989 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
2991 const CGitHash &parentHash = pRev->m_ParentHash[i];
2992 auto it = commitChildren.find(parentHash);
2993 if (it == commitChildren.end())
2994 it = commitChildren.insert(make_pair(parentHash, std::set<CGitHash>())).first;
2995 it->second.insert(pRev->m_CommitHash);
2999 #ifdef DEBUG
3000 pRev->DbgPrint();
3001 TRACE(L"\n");
3002 #endif
3004 bool visible = true;
3005 if (HasFilterText())
3007 if(!IsMatchFilter(bRegex,pRev,pat))
3008 visible = false;
3010 if (visible && !ShouldShowFilter(pRev, commitChildren))
3011 visible = false;
3012 this->m_critSec.Lock();
3013 m_logEntries.append(hash, visible);
3014 if (visible)
3015 m_arShownList.SafeAdd(pRev);
3016 this->m_critSec.Unlock();
3018 if (!visible)
3019 continue;
3021 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3022 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3024 t2 = GetTickCount64();
3026 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3028 //update UI
3029 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3030 if(percent > 99)
3031 percent =99;
3032 if(percent < GITLOG_START)
3033 percent = GITLOG_START +1;
3035 oldsize = m_logEntries.size();
3036 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3038 //if( percent > oldprecentage )
3040 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3041 oldprecentage = percent;
3044 if (lastSelectedHashNItem >= 0)
3045 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3047 t1 = t2;
3050 g_Git.m_critGitDllSec.Lock();
3051 git_close_log(m_DllGitLog);
3052 g_Git.m_critGitDllSec.Unlock();
3056 if (m_bExitThread)
3058 InterlockedExchange(&m_bThreadRunning, FALSE);
3059 return 0;
3062 //Update UI;
3063 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3065 if (lastSelectedHashNItem >= 0)
3066 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3068 if (this->m_hWnd)
3069 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3071 InterlockedExchange(&m_bThreadRunning, FALSE);
3073 return 0;
3076 void CGitLogListBase::FetchRemoteList()
3078 STRING_VECTOR remoteList;
3079 m_SingleRemote.Empty();
3080 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3081 m_SingleRemote = remoteList[0];
3084 void CGitLogListBase::FetchTrackingBranchList()
3086 m_TrackingMap.clear();
3087 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3089 for (const auto& ref : it->second)
3091 CString branchName;
3092 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3094 CString pullRemote, pullBranch;
3095 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3096 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3097 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3103 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3105 SafeTerminateThread();
3107 this->SetItemCountEx(0);
3108 this->Clear();
3110 ResetWcRev();
3112 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3114 if (m_pMailmap)
3116 git_free_mailmap(m_pMailmap);
3117 git_read_mailmap(&m_pMailmap);
3120 //Update branch and Tag info
3121 ReloadHashMap();
3122 if (m_pFindDialog)
3123 m_pFindDialog->RefreshList();
3124 //Assume Thread have exited
3125 //if(!m_bThreadRunning)
3127 m_logEntries.clear();
3129 if(IsCleanFilter)
3131 m_sFilterText.Empty();
3134 SafeTerminateAsyncDiffThread();
3135 m_AsynDiffListLock.Lock();
3136 m_AsynDiffList.clear();
3137 m_AsynDiffListLock.Unlock();
3138 StartAsyncDiffThread();
3140 StartLoadingThread();
3144 void CGitLogListBase::StartAsyncDiffThread()
3146 if (m_AsyncThreadExit)
3147 return;
3148 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3149 return;
3150 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3151 if (!m_DiffingThread)
3153 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3154 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3158 void CGitLogListBase::StartLoadingThread()
3160 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3161 return;
3162 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3163 InterlockedExchange(&m_bExitThread, FALSE);
3164 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3165 if (!m_LoadingThread)
3167 InterlockedExchange(&m_bThreadRunning, FALSE);
3168 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3169 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3173 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::tr1::wregex& pat, bool bMatchCase /* = false */)
3177 std::tr1::regex_constants::syntax_option_type type = std::tr1::regex_constants::ECMAScript;
3178 if (!bMatchCase)
3179 type |= std::tr1::regex_constants::icase;
3180 pat = std::tr1::wregex(regexp_str, type);
3181 return true;
3183 catch (std::exception&) {}
3184 return false;
3186 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::tr1::wregex& pat)
3188 BOOL result = TRUE;
3189 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3190 CString sRev;
3192 if ((bRegex)&&(m_bFilterWithRegex))
3194 if (m_SelectedFilters & LOGFILTER_BUGID)
3196 if(this->m_bShowBugtraqColumn)
3198 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3200 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3201 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3202 return TRUE;
3206 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3208 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3209 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3210 return TRUE;
3213 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3215 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3216 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3217 return TRUE;
3220 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3222 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3223 return TRUE;
3225 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3226 return TRUE;
3229 if (m_SelectedFilters & LOGFILTER_EMAILS)
3231 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3232 return TRUE;
3234 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3235 return TRUE;
3238 if (m_SelectedFilters & LOGFILTER_REVS)
3240 sRev = pRev->m_CommitHash.ToString();
3241 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3243 return TRUE;
3247 if (m_SelectedFilters & LOGFILTER_NOTES)
3249 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3250 return TRUE;
3253 if (m_SelectedFilters & LOGFILTER_REFNAME)
3255 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3256 for (const auto& ref : refs)
3258 if (std::regex_search(std::wstring(ref), pat, flags))
3259 return TRUE;
3263 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3265 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3266 return TRUE;
3269 if (m_SelectedFilters & LOGFILTER_PATHS)
3271 CTGitPathList* pathList = nullptr;
3272 if( pRev->m_IsDiffFiles)
3273 pathList = &pRev->GetFiles(this);
3274 else
3276 if(!pRev->m_IsSimpleListReady)
3277 pRev->SafeGetSimpleList(&g_Git);
3280 if(pathList)
3281 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3283 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3284 return true;
3285 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3286 return true;
3289 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3291 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3292 return true;
3296 else
3298 CString find = m_sFilterText;
3299 if (!m_bFilterCaseSensitively)
3300 find.MakeLower();
3301 result = find[0] == '!' ? FALSE : TRUE;
3302 if (!result)
3303 find = find.Mid(1);
3305 if (m_SelectedFilters & LOGFILTER_BUGID)
3307 if(this->m_bShowBugtraqColumn)
3309 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3311 if (!m_bFilterCaseSensitively)
3312 sBugIds.MakeLower();
3313 if ((sBugIds.Find(find) >= 0))
3314 return result;
3318 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3320 CString msg = pRev->GetSubject();
3322 if (!m_bFilterCaseSensitively)
3323 msg = msg.MakeLower();
3324 if ((msg.Find(find) >= 0))
3325 return result;
3328 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3330 CString msg = pRev->GetBody();
3332 if (!m_bFilterCaseSensitively)
3333 msg = msg.MakeLower();
3334 if ((msg.Find(find) >= 0))
3335 return result;
3338 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3340 CString msg = pRev->GetAuthorName();
3341 if (!m_bFilterCaseSensitively)
3342 msg = msg.MakeLower();
3343 if ((msg.Find(find) >= 0))
3344 return result;
3347 if (m_SelectedFilters & LOGFILTER_EMAILS)
3349 CString msg = pRev->GetAuthorEmail();
3350 if (!m_bFilterCaseSensitively)
3351 msg = msg.MakeLower();
3352 if ((msg.Find(find) >= 0))
3353 return result;
3356 if (m_SelectedFilters & LOGFILTER_NOTES)
3358 CString msg = pRev->m_Notes;
3359 if (!m_bFilterCaseSensitively)
3360 msg = msg.MakeLower();
3361 if ((msg.Find(find) >= 0))
3362 return result;
3365 if (m_SelectedFilters & LOGFILTER_REVS)
3367 sRev = pRev->m_CommitHash.ToString();
3368 if ((sRev.Find(find) >= 0))
3369 return result;
3372 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3374 CString msg = GetTagInfo(pRev);
3375 if (!m_bFilterCaseSensitively)
3376 msg = msg.MakeLower();
3377 if ((msg.Find(find) >= 0))
3378 return result;
3381 if (m_SelectedFilters & LOGFILTER_REFNAME)
3383 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3384 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3386 if (it->Find(find) >= 0)
3387 return result;
3391 if (m_SelectedFilters & LOGFILTER_PATHS)
3393 CTGitPathList* pathList = nullptr;
3394 if( pRev->m_IsDiffFiles)
3395 pathList = &pRev->GetFiles(this);
3396 else
3398 if(!pRev->m_IsSimpleListReady)
3399 pRev->SafeGetSimpleList(&g_Git);
3401 if(pathList)
3402 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3404 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3405 CString path = cpath->GetGitOldPathString();
3406 if (!m_bFilterCaseSensitively)
3407 path.MakeLower();
3408 if ((path.Find(find)>=0))
3409 return result;
3410 path = cpath->GetGitPathString();
3411 if (!m_bFilterCaseSensitively)
3412 path.MakeLower();
3413 if ((path.Find(find)>=0))
3414 return result;
3417 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3419 CString path = pRev->m_SimpleFileList[i];
3420 if (!m_bFilterCaseSensitively)
3421 path.MakeLower();
3422 if ((path.Find(find)>=0))
3423 return result;
3426 } // else (from if (bRegex))
3427 return !result;
3430 static bool CStringStartsWith(const CString &str, const CString &prefix)
3432 return str.Left(prefix.GetLength()) == prefix;
3434 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::map<CGitHash, std::set<CGitHash>>& commitChildren)
3436 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3437 return true;
3439 if (m_ShowFilter & FILTERSHOW_REFS)
3441 // Keep all refs.
3442 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3443 for (size_t i = 0; i < refList.size(); ++i)
3445 const CString &str = refList[i];
3446 if (CStringStartsWith(str, L"refs/heads/"))
3448 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3449 return true;
3451 else if (CStringStartsWith(str, L"refs/remotes/"))
3453 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3454 return true;
3456 else if (CStringStartsWith(str, L"refs/tags/"))
3458 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3459 return true;
3461 else if (CStringStartsWith(str, L"refs/stash"))
3463 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3464 return true;
3466 else if (CStringStartsWith(str, L"refs/bisect/"))
3468 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3469 return true;
3472 // Keep the head too.
3473 if (pRev->m_CommitHash == m_HeadHash)
3474 return true;
3477 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3479 if (pRev->ParentsCount() > 1)
3480 return true;
3481 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3482 if (childrenIt != commitChildren.end())
3484 const std::set<CGitHash> &children = childrenIt->second;
3485 if (children.size() > 1)
3486 return true;
3489 return false;
3492 void CGitLogListBase::ShowGraphColumn(bool bShow)
3494 // HACK to hide graph column
3495 if (bShow)
3496 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3497 else
3498 SetColumnWidth(0, 0);
3501 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3503 CString cmd;
3504 CString output;
3506 if (m_HashMap.find(pLogEntry->m_CommitHash) != m_HashMap.end())
3508 STRING_VECTOR &vector = m_HashMap[pLogEntry->m_CommitHash];
3509 for (size_t i = 0; i < vector.size(); ++i)
3511 if (CStringUtils::StartsWith(vector[i], L"refs/tags/"))
3513 CString tag = vector[i];
3514 int start = vector[i].Find(L"^{}");
3515 if (start > 0)
3516 tag = tag.Left(start);
3517 else
3518 continue;
3520 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)tag);
3521 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) == 0)
3522 output.Trim().AppendChar(L'\n');
3527 return output;
3530 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3532 pShownlist->SafeRemoveAll();
3534 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
3535 bool bRegex = false;
3536 if (m_bFilterWithRegex)
3537 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3539 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3540 CString sRev;
3541 for (DWORD i=0; i<m_logEntries.size(); ++i)
3543 if ((bRegex)&&(m_bFilterWithRegex))
3545 #if 0
3546 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3548 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3549 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3551 pShownlist->SafeAdd(m_logEntries[i]);
3552 continue;
3555 #endif
3556 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3558 ATLTRACE(L"messge = \"%s\"\n", m_logEntries.GetGitRevAt(i).GetSubject());
3559 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3561 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3562 continue;
3565 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3567 ATLTRACE("messge = \"%s\"\n", m_logEntries.GetGitRevAt(i).GetBody());
3568 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3570 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3571 continue;
3574 if (m_SelectedFilters & LOGFILTER_PATHS)
3576 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3578 bool bGoing = true;
3579 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3581 CTGitPath cpath = pathList[cpPathIndex];
3582 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3584 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3585 bGoing = false;
3586 continue;
3588 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3590 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3591 bGoing = false;
3592 continue;
3594 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3596 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3597 bGoing = false;
3598 continue;
3602 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3604 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3606 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3607 continue;
3610 if (m_SelectedFilters & LOGFILTER_EMAILS)
3612 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3614 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3615 continue;
3618 if (m_SelectedFilters & LOGFILTER_REVS)
3620 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3621 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3623 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3624 continue;
3627 if (m_SelectedFilters & LOGFILTER_REFNAME)
3629 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3630 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3632 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3634 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3635 continue;
3639 } // if (bRegex)
3640 else
3642 CString find = m_sFilterText;
3643 if (!m_bFilterCaseSensitively)
3644 find.MakeLower();
3645 #if 0
3646 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3648 CString sBugIDs = m_logEntries[i]->sBugIDs;
3650 if (!m_bFilterCaseSensitively)
3651 sBugIDs = sBugIDs.MakeLower();
3652 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3654 pShownlist->SafeAdd(m_logEntries[i]);
3655 continue;
3658 #endif
3659 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3661 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3663 if (!m_bFilterCaseSensitively)
3664 msg = msg.MakeLower();
3665 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3667 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3668 continue;
3671 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3673 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3675 if (!m_bFilterCaseSensitively)
3676 msg = msg.MakeLower();
3677 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3679 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3680 continue;
3683 if (m_SelectedFilters & LOGFILTER_PATHS)
3685 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3687 bool bGoing = true;
3688 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3690 CTGitPath cpath = pathList[cpPathIndex];
3691 CString path = cpath.GetGitOldPathString();
3692 if (!m_bFilterCaseSensitively)
3693 path.MakeLower();
3694 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3696 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3697 bGoing = false;
3698 continue;
3700 path = cpath.GetGitPathString();
3701 if (!m_bFilterCaseSensitively)
3702 path.MakeLower();
3703 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3705 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3706 bGoing = false;
3707 continue;
3709 path = cpath.GetActionName();
3710 if (!m_bFilterCaseSensitively)
3711 path.MakeLower();
3712 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3714 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3715 bGoing = false;
3716 continue;
3720 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3722 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3723 if (!m_bFilterCaseSensitively)
3724 msg = msg.MakeLower();
3725 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3727 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3728 continue;
3731 if (m_SelectedFilters & LOGFILTER_EMAILS)
3733 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3734 if (!m_bFilterCaseSensitively)
3735 msg = msg.MakeLower();
3736 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3738 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3739 continue;
3742 if (m_SelectedFilters & LOGFILTER_REVS)
3744 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3745 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3747 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3748 continue;
3751 if (m_SelectedFilters & LOGFILTER_REFNAME)
3753 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3754 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3756 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3758 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3759 continue;
3763 } // else (from if (bRegex))
3764 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3767 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3770 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3772 if(m_From == -1)
3773 if(m_To == -1)
3774 return true;
3775 else
3776 return time <= m_To;
3777 else
3778 if(m_To == -1)
3779 return time >= m_From;
3780 else
3781 return ((time >= m_From)&&(time <= m_To));
3783 return TRUE; /* git dll will filter time range */
3785 // return TRUE;
3788 void CGitLogListBase::StartFilter()
3790 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3791 RecalculateShownList(&m_arShownList);
3792 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3795 DeleteAllItems();
3796 SetItemCountEx(ShownCountWithStopped());
3797 RedrawItems(0, ShownCountWithStopped());
3798 Invalidate();
3801 void CGitLogListBase::RemoveFilter()
3803 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3805 m_arShownList.SafeRemoveAll();
3807 // reset the time filter too
3808 #if 0
3809 m_timFrom = (__time64_t(m_tFrom));
3810 m_timTo = (__time64_t(m_tTo));
3811 m_DateFrom.SetTime(&m_timFrom);
3812 m_DateTo.SetTime(&m_timTo);
3813 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3814 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3815 #endif
3817 for (DWORD i=0; i<m_logEntries.size(); ++i)
3819 if(this->m_IsOldFirst)
3820 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3821 else
3822 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3824 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3825 DeleteAllItems();
3826 SetItemCountEx(ShownCountWithStopped());
3827 RedrawItems(0, ShownCountWithStopped());
3829 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3832 void CGitLogListBase::Clear()
3834 m_arShownList.SafeRemoveAll();
3835 DeleteAllItems();
3837 m_logEntries.ClearAll();
3840 void CGitLogListBase::OnDestroy()
3842 SafeTerminateThread();
3843 SafeTerminateAsyncDiffThread();
3845 int retry = 0;
3846 while(m_LogCache.SaveCache())
3848 if(retry > 5)
3849 break;
3850 Sleep(1000);
3852 ++retry;
3854 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3855 // MB_YESNO) == IDNO)
3856 // break;
3859 __super::OnDestroy();
3862 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3864 CRect rect;
3865 int i=(int)wParam;
3866 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3867 this->InvalidateRect(rect);
3869 return 0;
3873 * Save column widths to the registry
3875 void CGitLogListBase::SaveColumnWidths()
3877 // HACK that graph column is always shown
3878 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3880 __super::SaveColumnWidths();
3883 int CGitLogListBase::GetHeadIndex()
3885 if(m_HeadHash.IsEmpty())
3886 return -1;
3888 for (size_t i = 0; i < m_arShownList.size(); ++i)
3890 GitRev* pRev = m_arShownList.SafeGetAt(i);
3891 if(pRev)
3893 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3894 return (int)i;
3897 return -1;
3899 void CGitLogListBase::OnFind()
3901 if (!m_pFindDialog)
3903 m_pFindDialog = new CFindDlg(this);
3904 m_pFindDialog->Create(this);
3908 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3910 if (GetSelectedCount() != 0)
3911 return 0;
3913 CGitHash theSelectedHash = m_lastSelectedHash;
3914 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3915 m_lastSelectedHash = theSelectedHash;
3917 int countPerPage = GetCountPerPage();
3918 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3919 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3920 EnsureVisible((int)itemToSelect, FALSE);
3921 return 0;
3924 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3926 CString* ref = reinterpret_cast<CString*>(wParam);
3927 if (!ref || ref->IsEmpty())
3928 return 1;
3930 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3932 CGitHash hash;
3933 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3934 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3936 if (hash.IsEmpty())
3937 return 1;
3939 bool bFound = false;
3940 int cnt = (int)m_arShownList.size();
3941 int i;
3942 for (i = 0; i < cnt; ++i)
3944 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3945 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3947 bFound = true;
3948 break;
3951 if (!bFound)
3952 return 1;
3954 EnsureVisible(i, FALSE);
3955 if (!bShift)
3957 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3958 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3959 SetSelectionMark(i);
3961 else
3963 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3964 if (pLogEntry)
3965 m_highlight = pLogEntry->m_CommitHash;
3967 Invalidate();
3968 UpdateData(FALSE);
3970 return 0;
3973 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
3975 ASSERT(m_pFindDialog);
3976 bool bFound = false;
3977 int i=0;
3979 if (m_pFindDialog->IsTerminating())
3981 // invalidate the handle identifying the dialog box.
3982 m_pFindDialog = nullptr;
3983 return 0;
3986 int cnt = (int)m_arShownList.size();
3987 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3989 if(m_pFindDialog->IsRef())
3991 CString str;
3992 str=m_pFindDialog->GetFindString();
3994 CGitHash hash;
3996 if(!str.IsEmpty())
3998 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3999 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4002 if(!hash.IsEmpty())
4004 for (i = 0; i < cnt; ++i)
4006 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4007 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4009 bFound = true;
4010 break;
4014 if (!bFound)
4016 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4017 return 0;
4021 if (m_pFindDialog->FindNext() && !bFound)
4023 //read data from dialog
4024 CString findText = m_pFindDialog->GetFindString();
4025 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4027 std::tr1::wregex pat;
4028 bool bRegex = false;
4029 if (m_pFindDialog->Regex())
4030 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4032 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_not_null;
4034 for (i = m_nSearchIndex + 1; ; ++i)
4036 if (i >= cnt)
4038 i = 0;
4039 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4041 if (m_nSearchIndex >= 0)
4043 if (i == m_nSearchIndex)
4045 ::MessageBeep(0xFFFFFFFF);
4046 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4047 break;
4051 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4053 CString str;
4054 str+=pLogEntry->m_CommitHash.ToString();
4055 str += L'\n';
4057 for (size_t j = 0; j < this->m_HashMap[pLogEntry->m_CommitHash].size(); ++j)
4059 str+=m_HashMap[pLogEntry->m_CommitHash][j];
4060 str += L'\n';
4063 str+=pLogEntry->GetAuthorEmail();
4064 str += L'\n';
4065 str+=pLogEntry->GetAuthorName();
4066 str += L'\n';
4067 str+=pLogEntry->GetBody();
4068 str += L'\n';
4069 str+=pLogEntry->GetCommitterEmail();
4070 str += L'\n';
4071 str+=pLogEntry->GetCommitterName();
4072 str += L'\n';
4073 str+=pLogEntry->GetSubject();
4074 str += L'\n';
4075 str+=pLogEntry->m_Notes;
4076 str += L'\n';
4077 str+=GetTagInfo(pLogEntry);
4078 str += L'\n';
4081 /*Because changed files list is loaded on demand when gui show,
4082 files will empty when files have not fetched.
4084 we can add it back by using one-way diff(with outnumber changed and rename detect.
4085 here just need changed filename list. one-way is much quicker.
4087 if(pLogEntry->m_IsFull)
4089 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4091 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4092 str += L'\n';
4093 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4094 str += L'\n';
4097 else
4099 if(!pLogEntry->m_IsSimpleListReady)
4100 pLogEntry->SafeGetSimpleList(&g_Git);
4102 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4104 str += pLogEntry->m_SimpleFileList[j];
4105 str += L'\n';
4109 if (bRegex)
4111 if (std::regex_search(std::wstring(str), pat, flags))
4113 bFound = true;
4114 break;
4117 else
4119 if (bMatchCase)
4121 if (str.Find(findText) >= 0)
4123 bFound = true;
4124 break;
4127 else
4129 CString msg = str;
4130 msg = msg.MakeLower();
4131 CString find = findText.MakeLower();
4132 if (msg.Find(find) >= 0)
4134 bFound = TRUE;
4135 break;
4139 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4141 } // if(m_pFindDialog->FindNext())
4142 //UpdateLogInfoLabel();
4144 if (bFound)
4146 m_nSearchIndex = i;
4147 EnsureVisible(i, FALSE);
4148 if (!bShift)
4150 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4151 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4152 SetSelectionMark(i);
4154 else
4156 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4157 if (pLogEntry)
4158 m_highlight = pLogEntry->m_CommitHash;
4160 Invalidate();
4161 //FillLogMessageCtrl();
4162 UpdateData(FALSE);
4165 return 0;
4168 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4170 LVHITTESTINFO lvhitTestInfo;
4172 lvhitTestInfo.pt = point;
4174 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4175 int nSubItem = lvhitTestInfo.iSubItem;
4177 UINT nFlags = lvhitTestInfo.flags;
4179 // nFlags is 0 if the SubItemHitTest fails
4180 // Therefore, 0 & <anything> will equal false
4181 if (nFlags & LVHT_ONITEM)
4183 // Get the client area occupied by this control
4184 RECT rcClient;
4185 GetClientRect(&rcClient);
4187 // Fill in the TOOLINFO structure
4188 pTI->hwnd = m_hWnd;
4189 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4190 pTI->lpszText = LPSTR_TEXTCALLBACK;
4191 pTI->rect = rcClient;
4193 return pTI->uId; // By returning a unique value per listItem,
4194 // we ensure that when the mouse moves over another list item,
4195 // the tooltip will change
4197 else
4199 // Otherwise, we aren't interested, so let the message propagate
4200 return -1;
4204 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4206 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4207 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4209 *pResult = 0;
4211 // Ignore messages from the built in tooltip, we are processing them internally
4212 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4213 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4214 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4215 return FALSE;
4217 // Get the mouse position
4218 const MSG* pMessage = GetCurrentMessage();
4220 CPoint pt;
4221 pt = pMessage->pt;
4222 ScreenToClient(&pt);
4224 // Check if the point falls onto a list item
4225 LVHITTESTINFO lvhitTestInfo;
4226 lvhitTestInfo.pt = pt;
4228 int nItem = SubItemHitTest(&lvhitTestInfo);
4230 if (lvhitTestInfo.flags & LVHT_ONITEM)
4232 // Get branch description first
4233 CString strTipText;
4234 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4236 CString branch;
4237 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4238 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4240 MAP_STRING_STRING descriptions;
4241 g_Git.GetBranchDescriptions(descriptions);
4242 if (descriptions.find(branch) != descriptions.cend())
4244 strTipText.LoadString(IDS_DESCRIPTION);
4245 strTipText += L":\n";
4246 strTipText += descriptions[branch];
4251 bool followMousePos = false;
4252 if (!strTipText.IsEmpty())
4253 followMousePos = true;
4254 else
4255 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4256 if (strTipText.IsEmpty())
4257 return FALSE;
4259 // we want multiline tooltips
4260 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, INT_MAX);
4262 wcscpy_s(m_wszTip, strTipText);
4263 // handle Unicode as well as non-Unicode requests
4264 if (pNMHDR->code == TTN_NEEDTEXTA)
4266 pTTTA->hinst = nullptr;
4267 pTTTA->lpszText = m_szTip;
4268 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4270 else
4272 pTTTW->hinst = nullptr;
4273 pTTTW->lpszText = m_wszTip;
4276 CRect rect;
4277 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4278 if (followMousePos)
4279 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4280 ClientToScreen(rect);
4281 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4283 return TRUE; // We found a tool tip,
4284 // tell the framework this message has been handled
4287 return FALSE; // We didn't handle the message,
4288 // let the framework continue propagating the message
4291 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4293 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4295 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4296 if (pLogEntry == nullptr)
4297 return CString();
4298 if (m_HashMap[pLogEntry->m_CommitHash].empty() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4299 return CString();
4300 return pLogEntry->GetSubject();
4302 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4304 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4305 if (pLogEntry == nullptr)
4306 return CString();
4307 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4309 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4311 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4312 if (pLogEntry == nullptr)
4313 return CString();
4314 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4316 else if (nSubItem == LOGLIST_ACTION)
4318 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4319 if (pLogEntry == nullptr)
4320 return CString();
4322 if (!pLogEntry->m_IsDiffFiles)
4323 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4325 int actions = pLogEntry->GetAction(this);
4326 CString sToolTipText;
4328 CString actionText;
4329 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4330 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4332 if (actions & CTGitPath::LOGACTIONS_ADDED)
4334 if (!actionText.IsEmpty())
4335 actionText += L"\r\n";
4336 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4339 if (actions & CTGitPath::LOGACTIONS_DELETED)
4341 if (!actionText.IsEmpty())
4342 actionText += L"\r\n";
4343 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4346 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4348 if (!actionText.IsEmpty())
4349 actionText += L"\r\n";
4350 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4353 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4355 if (!actionText.IsEmpty())
4356 actionText += L"\r\n";
4357 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4360 if (!actionText.IsEmpty())
4362 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4363 sToolTipText = sTitle + L":\r\n" + actionText;
4365 return sToolTipText;
4367 return CString();
4370 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4372 POINT pt = point;
4373 ScreenToClient(&pt);
4374 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4377 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4379 if (!pLogEntry)
4380 return false;
4382 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4384 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4385 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4386 continue;
4388 CGit::REF_TYPE foundType;
4389 if (pShortname)
4390 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4391 else
4392 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4393 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4394 return false;
4396 type = foundType;
4397 if (pIndex)
4398 *pIndex = i;
4399 return true;
4401 return false;