Fix action icons in the log dialog being clipped on High-DPI displays
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blob8d1384e3ae95de923835e7d2e086febf0d820baf
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - 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 "GitProgressDlg.h"
27 #include "ProgressDlg.h"
28 #include "MessageBox.h"
29 #include "LoglistUtils.h"
30 #include "StringUtils.h"
31 #include "UnicodeUtils.h"
32 #include "IconMenu.h"
33 #include "..\TortoiseShell\Resource.h"
35 template < typename Cont, typename Pred>
36 void for_each(Cont& c, Pred p)
38 std::for_each(cbegin(c), cend(c), p);
41 template<typename T>
42 using const_iterator = typename T::const_iterator;
44 template <typename Cont, typename Pred>
45 const_iterator<Cont> find_if(Cont& c, Pred p)
47 return std::find_if(cbegin(c), cend(c), p);
50 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
51 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
52 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
53 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
55 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
57 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
58 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
59 ,m_nSearchIndex(0)
60 ,m_bNoDispUpdates(FALSE)
61 , m_bThreadRunning(FALSE)
62 , m_bStrictStopped(false)
63 , m_SelectedFilters(LOGFILTER_ALL)
64 , m_ShowFilter(FILTERSHOW_ALL)
65 , m_bShowWC(false)
66 , m_logEntries(&m_LogCache)
67 , m_pFindDialog(nullptr)
68 , m_dwDefaultColumns(0)
69 , m_arShownList(&m_critSec)
70 , m_hasWC(true)
71 , m_bNoHightlightHead(FALSE)
72 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
73 , m_bFullCommitMessageOnLogLine(false)
74 , m_OldTopIndex(-1)
75 , m_AsyncThreadRunning(FALSE)
76 , m_AsyncThreadExit(FALSE)
77 , m_bIsCherryPick(false)
78 , m_pMailmap(nullptr)
79 , m_bShowBugtraqColumn(false)
80 , m_IsIDReplaceAction(FALSE)
81 , m_ShowMask(0)
82 , m_LoadingThread(nullptr)
83 , m_bExitThread(FALSE)
84 , m_IsOldFirst(FALSE)
85 , m_IsRebaseReplaceGraph(FALSE)
86 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
87 , m_bDragndropEnabled(false)
88 , m_bDragging(FALSE)
89 , m_nDropIndex(-1)
90 , m_nDropMarkerLast(-1)
91 , m_nDropMarkerLastHot(-1)
93 // use the default GUI font, create a copy of it and
94 // change the copy to BOLD (leave the rest of the font
95 // the same)
96 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
97 LOGFONT lf = {0};
98 GetObject(hFont, sizeof(LOGFONT), &lf);
99 lf.lfWeight = FW_BOLD;
100 m_boldFont.CreateFontIndirect(&lf);
101 lf.lfWeight = FW_DONTCARE;
102 lf.lfItalic = TRUE;
103 m_FontItalics.CreateFontIndirect(&lf);
104 lf.lfWeight = FW_BOLD;
105 m_boldItalicsFont.CreateFontIndirect(&lf);
107 this->m_critSec.Init();
108 ResetWcRev(false);
110 int cx = GetSystemMetrics(SM_CXSMICON);
111 int cy = GetSystemMetrics(SM_CYSMICON);
112 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, cx, cy, 0);
113 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, cx, cy, 0);
114 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, cx, cy, 0);
115 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, cx, cy, 0);
116 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, cx, cy, 0);
117 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, cx, cy, 0);
119 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
120 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
122 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
123 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
125 CString key;
126 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
127 key.Replace(L':', L'_');
128 CString lastSelFromDate = CRegString(key);
129 if (lastSelFromDate.GetLength() == 10)
131 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
132 m_Filter.m_From = (DWORD)time.GetTime();
135 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
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);
155 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
156 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
157 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
158 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
159 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
160 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
161 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
163 m_ColumnRegKey = L"log";
165 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
166 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
167 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
168 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
170 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
171 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
173 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
174 git_read_mailmap(&m_pMailmap);
176 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
177 m_AsynDiffListLock.Init();
178 StartAsyncDiffThread();
181 int CGitLogListBase::AsyncDiffThread()
183 while(!m_AsyncThreadExit)
185 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
187 GitRevLoglist* pRev = nullptr;
188 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
190 m_AsynDiffListLock.Lock();
191 pRev = m_AsynDiffList.back();
192 m_AsynDiffList.pop_back();
193 m_AsynDiffListLock.Unlock();
195 if( pRev->m_CommitHash.IsEmpty() )
197 if(pRev->m_IsDiffFiles)
198 continue;
200 CTGitPathList& files = pRev->GetFiles(this);
201 files.Clear();
202 pRev->m_ParentHash.clear();
203 pRev->m_ParentHash.push_back(m_HeadHash);
204 g_Git.RefreshGitIndex();
205 g_Git.GetWorkingTreeChanges(files);
206 int& action = pRev->GetAction(this);
207 action = 0;
208 for (int j = 0; j < files.GetCount(); ++j)
209 action |= files[j].m_Action;
211 CString err;
212 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
214 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
215 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
216 return -1;
219 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
220 InterlockedExchange(&pRev->m_IsFull, TRUE);
222 CString body = L"\n";
223 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
224 pRev->GetBody() = body;
225 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
226 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
229 if (!pRev->CheckAndDiff())
230 { // fetch change file list
231 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
233 if (i < (int)m_arShownList.size())
235 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
236 if(data->m_CommitHash == pRev->m_CommitHash)
238 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
239 break;
244 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
246 POSITION pos = GetFirstSelectedItemPosition();
247 int nItem = GetNextSelectedItem(pos);
249 if(nItem>=0)
251 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
252 if(data)
253 if(data->m_CommitHash == pRev->m_CommitHash)
254 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
260 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
261 return 0;
263 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
265 if (exclusivelyShow)
266 m_ContextMenuMask &= hideMask;
267 else
268 m_ContextMenuMask &= ~hideMask;
271 CGitLogListBase::~CGitLogListBase()
273 InterlockedExchange(&m_bNoDispUpdates, TRUE);
274 this->m_arShownList.SafeRemoveAll();
276 DestroyIcon(m_hModifiedIcon);
277 DestroyIcon(m_hReplacedIcon);
278 DestroyIcon(m_hConflictedIcon);
279 DestroyIcon(m_hAddedIcon);
280 DestroyIcon(m_hDeletedIcon);
281 m_logEntries.ClearAll();
283 git_free_mailmap(m_pMailmap);
285 SafeTerminateThread();
286 SafeTerminateAsyncDiffThread();
288 if(m_AsyncDiffEvent)
289 CloseHandle(m_AsyncDiffEvent);
293 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
294 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
295 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
296 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
297 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
298 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
299 ON_WM_CONTEXTMENU()
300 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
301 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
302 ON_WM_CREATE()
303 ON_WM_DESTROY()
304 ON_MESSAGE(MSG_LOADED,OnLoad)
305 ON_WM_MEASUREITEM()
306 ON_WM_MEASUREITEM_REFLECT()
307 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
308 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
309 ON_WM_MOUSEMOVE()
310 ON_WM_LBUTTONUP()
311 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
312 END_MESSAGE_MAP()
314 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
316 //if (m_nRowHeight>0)
317 lpMeasureItemStruct->itemHeight = 50;
320 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
322 PreSubclassWindow();
323 return __super::OnCreate(lpCreateStruct);
326 void CGitLogListBase::SetStyle()
328 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
331 void CGitLogListBase::PreSubclassWindow()
333 SetStyle();
334 // load the icons for the action columns
335 // m_Theme.Open(m_hWnd, L"ListView");
336 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
337 __super::PreSubclassWindow();
340 CString CGitLogListBase::GetRebaseActionName(int action)
342 if (action & LOGACTIONS_REBASE_EDIT)
343 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
344 if (action & LOGACTIONS_REBASE_SQUASH)
345 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
346 if (action & LOGACTIONS_REBASE_PICK)
347 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
348 if (action & LOGACTIONS_REBASE_SKIP)
349 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
351 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
354 void CGitLogListBase::InsertGitColumn()
356 CString temp;
358 Init();
360 // only load properties if we have a repository
361 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
362 UpdateProjectProperties();
364 static UINT normal[] =
366 IDS_LOG_GRAPH,
367 IDS_LOG_REBASE,
368 IDS_LOG_ID,
369 IDS_LOG_HASH,
370 IDS_LOG_ACTIONS,
371 IDS_LOG_MESSAGE,
372 IDS_LOG_AUTHOR,
373 IDS_LOG_DATE,
374 IDS_LOG_EMAIL,
375 IDS_LOG_COMMIT_NAME,
376 IDS_LOG_COMMIT_EMAIL,
377 IDS_LOG_COMMIT_DATE,
378 IDS_LOG_BUGIDS,
379 IDS_LOG_SVNREV,
382 static int with[] =
384 ICONITEMBORDER+16*4,
385 ICONITEMBORDER+16*4,
386 ICONITEMBORDER+16*4,
387 ICONITEMBORDER+16*4,
388 2 * ICONITEMBORDER + GetSystemMetrics(SM_CXSMICON) * 5,
389 LOGLIST_MESSAGE_MIN,
390 ICONITEMBORDER+16*4,
391 ICONITEMBORDER+16*4,
392 ICONITEMBORDER+16*4,
393 ICONITEMBORDER+16*4,
394 ICONITEMBORDER+16*4,
395 ICONITEMBORDER+16*4,
396 ICONITEMBORDER+16*4,
397 ICONITEMBORDER+16*4,
399 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
401 DWORD hideColumns = 0;
402 if(this->m_IsRebaseReplaceGraph)
404 hideColumns |= GIT_LOG_GRAPH;
405 m_dwDefaultColumns |= GIT_LOG_REBASE;
407 else
408 hideColumns |= GIT_LOG_REBASE;
410 if(this->m_IsIDReplaceAction)
412 hideColumns |= GIT_LOG_ACTIONS;
413 m_dwDefaultColumns |= GIT_LOG_ID;
414 m_dwDefaultColumns |= GIT_LOG_HASH;
416 else
417 hideColumns |= GIT_LOG_ID;
418 if(this->m_bShowBugtraqColumn)
419 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
420 else
421 hideColumns |= GIT_LOGLIST_BUG;
422 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
423 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
424 else
425 hideColumns |= GIT_LOGLIST_SVNREV;
426 SetRedraw(false);
428 m_ColumnManager.SetNames(normal, _countof(normal));
429 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
430 m_ColumnManager.SetRightAlign(LOGLIST_ID);
432 if (!(hideColumns & GIT_LOG_ACTIONS))
434 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
435 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
436 // display's font height may be less than small icon height.
437 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
438 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
439 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
442 SetRedraw(true);
445 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
447 LVITEM rItem = { 0 };
448 rItem.mask = LVIF_STATE;
449 rItem.iItem = (int)Index;
450 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
451 GetItem(&rItem);
453 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
454 HBRUSH brush = nullptr;
456 if (!(rItem.state & LVIS_SELECTED))
458 int action = pLogEntry->GetRebaseAction();
459 if (action & LOGACTIONS_REBASE_SQUASH)
460 brush = ::CreateSolidBrush(RGB(156,156,156));
461 else if (action & LOGACTIONS_REBASE_EDIT)
462 brush = ::CreateSolidBrush(RGB(200,200,128));
464 else if (!IsAppThemed())
466 if (rItem.state & LVIS_SELECTED)
468 if (::GetFocus() == m_hWnd)
469 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
470 else
471 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
474 if (brush)
476 ::FillRect(hdc, &rect, brush);
477 ::DeleteObject(brush);
481 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
483 POINT point = { 4, 4 };
484 CRect rt2 = rect;
485 rt2.DeflateRect(1, 1);
486 rt2.OffsetRect(2, 2);
488 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
489 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
490 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
491 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
492 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
494 ::SelectObject(hdc, brush);
495 rt2.OffsetRect(-2, -2);
496 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
497 ::SelectObject(hdc, oldbrush);
498 ::SelectObject(hdc, oldpen);
499 ::DeleteObject(nullPen);
500 ::DeleteObject(darkBrush);
503 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
505 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
506 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
507 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
508 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
509 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
510 ::LineTo(hdc, rect.left, rect.top + 4);
511 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
512 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
513 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
514 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
515 ::SelectObject(hdc, oldpen);
516 ::DeleteObject(pen);
519 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
521 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
522 CRect rt=rect;
523 LVITEM rItem = { 0 };
524 rItem.mask = LVIF_STATE;
525 rItem.iItem = (int)index;
526 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
527 GetItem(&rItem);
529 CDC W_Dc;
530 W_Dc.Attach(hdc);
532 HTHEME hTheme = nullptr;
533 if (IsAppThemed())
534 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
536 SIZE oneSpaceSize;
537 if (m_bTagsBranchesOnRightSide)
539 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
540 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
541 SelectObject(hdc, oldFont);
542 rt.left += oneSpaceSize.cx * 2;
544 else
546 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
547 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
548 rt.left += oneSpaceSize.cx;
551 CString msg = MessageDisplayStr(data);
552 int action = data->GetRebaseAction();
553 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
554 if (IsAppThemed())
556 int txtState = LISS_NORMAL;
557 if (rItem.state & LVIS_SELECTED)
558 txtState = LISS_SELECTED;
560 DTTOPTS opts = { 0 };
561 opts.dwSize = sizeof(opts);
562 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
563 opts.dwFlags = DTT_TEXTCOLOR;
564 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
566 else
568 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
570 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
571 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
572 ::SetTextColor(hdc, clrOld);
574 else
576 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
577 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
578 ::SetTextColor(hdc, clrOld);
582 if (m_bTagsBranchesOnRightSide)
584 SIZE size;
585 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
587 rt.left += oneSpaceSize.cx + size.cx;
589 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
592 if (hTheme)
593 CloseThemeData(hTheme);
595 W_Dc.Detach();
598 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
600 for (unsigned int i = 0; i < refList.size(); ++i)
602 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
603 HBRUSH brush = 0;
604 COLORREF colRef = refList[i].color;
605 bool singleRemote = refList[i].singleRemote;
606 bool hasTracking = refList[i].hasTracking;
607 CGit::REF_TYPE refType = refList[i].refType;
609 //When row selected, ajust label color
610 if (!IsAppThemed())
612 if (rItem.state & LVIS_SELECTED)
613 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
616 brush = ::CreateSolidBrush(colRef);
618 if (!shortname.IsEmpty() && (rt.left < rect.right))
620 SIZE size = { 0 };
621 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
623 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
624 rt.right += 8;
626 int textpos = DT_CENTER;
628 if (rt.right > rect.right)
630 rt.right = rect.right;
631 textpos = 0;
634 CRect textRect = rt;
636 if (singleRemote)
638 rt.right += 5;
639 textRect.OffsetRect(5, 0);
642 if (hasTracking)
643 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
644 else
646 //Fill interior of ref label
647 ::FillRect(hdc, &rt, brush);
650 //Draw edge of label
651 CRect rectEdge = rt;
653 if (!hasTracking)
655 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
656 rectEdge.DeflateRect(1, 1);
657 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
660 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
662 rt.right += 8;
663 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
664 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
665 ::FillRgn(hdc, hrgn, brush);
666 ::DeleteObject(hrgn);
667 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
668 HPEN pen;
669 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
670 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
671 ::DeleteObject(pen);
672 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
673 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
674 ::DeleteObject(pen);
675 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
676 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
677 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
678 ::DeleteObject(pen);
679 SelectObject(hdc, oldpen);
682 //Draw text inside label
683 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
684 if (!customColor && IsAppThemed())
686 int txtState = LISS_NORMAL;
687 if (rItem.state & LVIS_SELECTED)
688 txtState = LISS_SELECTED;
690 DTTOPTS opts = { 0 };
691 opts.dwSize = sizeof(opts);
692 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
693 opts.dwFlags = DTT_TEXTCOLOR;
694 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
696 else
698 W_Dc.SetBkMode(TRANSPARENT);
699 if (customColor || (rItem.state & LVIS_SELECTED))
701 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
702 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
703 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
704 ::SetTextColor(hdc,clrOld);
706 else
708 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
709 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
710 ::SetTextColor(hdc, clrOld);
714 if (singleRemote)
716 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
717 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
718 CRect newRect;
719 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
720 DrawUpstream(hdc, newRect, color, bold);
723 if (!refList[i].fullName.IsEmpty())
724 m_RefLabelPosMap[refList[i].fullName] = rt;
726 rt.left = rt.right + 1;
728 if (brush)
729 ::DeleteObject(brush);
731 rt.right = rect.right;
734 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
735 // Returns ((256 - amount)*col1 + amount*col2) / 256;
736 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
737 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
738 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
741 Gdiplus::Color GetGdiColor(COLORREF col)
743 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
745 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
746 const COLORREF& col,const COLORREF& activeColor, int top
749 int h = laneHeight / 2;
750 int m = (x1 + x2) / 2;
751 int r = (x2 - x1) * m_NodeSize / 30;
752 int d = 2 * r;
754 #define P_CENTER m , h+top
755 #define P_0 x2, h+top
756 #define P_90 m , 0+top-1
757 #define P_180 x1, h+top
758 #define P_270 m , 2 * h+top +1
759 #define R_CENTER m - r, h - r+top, d, d
762 #define DELTA_UR_B 2*(x1 - m), 2*h +top
763 #define DELTA_UR_E 0*16, 90*16 +top // -,
765 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
766 #define DELTA_DR_E 270*16, 90*16 +top // -'
768 #define DELTA_UL_B 2*(x2 - m), 2*h +top
769 #define DELTA_UL_E 90*16, 90*16 +top // ,-
771 #define DELTA_DL_B 2*(x2 - m),2*-h +top
772 #define DELTA_DL_E 180*16, 90*16 // '-
774 #define CENTER_UR x1, 2*h, 225
775 #define CENTER_DR x1, 0 , 135
776 #define CENTER_UL x2, 2*h, 315
777 #define CENTER_DL x2, 0 , 45
780 Gdiplus::Graphics graphics( hdc );
782 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
784 // arc
785 switch (type) {
786 case Lanes::JOIN:
787 case Lanes::JOIN_R:
788 case Lanes::HEAD:
789 case Lanes::HEAD_R:
791 Gdiplus::LinearGradientBrush gradient(
792 Gdiplus::Point(x1-2, h+top-2),
793 Gdiplus::Point(P_270),
794 GetGdiColor(activeColor),GetGdiColor(col));
797 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
798 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
800 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
801 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
802 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
804 break;
806 case Lanes::JOIN_L:
808 Gdiplus::LinearGradientBrush gradient(
809 Gdiplus::Point(P_270),
810 Gdiplus::Point(x2+1, h+top-1),
811 GetGdiColor(col),GetGdiColor(activeColor));
814 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
815 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
817 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
818 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
819 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
822 break;
824 case Lanes::TAIL:
825 case Lanes::TAIL_R:
827 Gdiplus::LinearGradientBrush gradient(
828 Gdiplus::Point(x1-2, h+top-2),
829 Gdiplus::Point(P_90),
830 GetGdiColor(activeColor),GetGdiColor(col));
832 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
834 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
836 #if 0
837 QConicalGradient gradient(CENTER_DR);
838 gradient.setColorAt(0.375, activeCol);
839 gradient.setColorAt(0.625, col);
840 myPen.setBrush(gradient);
841 p->setPen(myPen);
842 p->drawArc(P_CENTER, DELTA_DR);
843 #endif
844 break;
846 default:
847 break;
851 //static QPen myPen(Qt::black, 2); // fast path here
852 CPen pen;
853 pen.CreatePen(PS_SOLID,2,col);
854 //myPen.setColor(col);
855 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
857 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
859 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
861 //p->setPen(myPen);
863 // vertical line
864 switch (type) {
865 case Lanes::ACTIVE:
866 case Lanes::NOT_ACTIVE:
867 case Lanes::MERGE_FORK:
868 case Lanes::MERGE_FORK_R:
869 case Lanes::MERGE_FORK_L:
870 case Lanes::JOIN:
871 case Lanes::JOIN_R:
872 case Lanes::JOIN_L:
873 case Lanes::CROSS:
874 //DrawLine(hdc,P_90,P_270);
875 graphics.DrawLine(&myPen,P_90,P_270);
876 //p->drawLine(P_90, P_270);
877 break;
878 case Lanes::HEAD_L:
879 case Lanes::BRANCH:
880 //DrawLine(hdc,P_CENTER,P_270);
881 graphics.DrawLine(&myPen,P_CENTER,P_270);
882 //p->drawLine(P_CENTER, P_270);
883 break;
884 case Lanes::TAIL_L:
885 case Lanes::INITIAL:
886 case Lanes::BOUNDARY:
887 case Lanes::BOUNDARY_C:
888 case Lanes::BOUNDARY_R:
889 case Lanes::BOUNDARY_L:
890 //DrawLine(hdc,P_90, P_CENTER);
891 graphics.DrawLine(&myPen,P_90,P_CENTER);
892 //p->drawLine(P_90, P_CENTER);
893 break;
894 default:
895 break;
898 myPen.SetColor(GetGdiColor(activeColor));
900 // horizontal line
901 switch (type) {
902 case Lanes::MERGE_FORK:
903 case Lanes::JOIN:
904 case Lanes::HEAD:
905 case Lanes::TAIL:
906 case Lanes::CROSS:
907 case Lanes::CROSS_EMPTY:
908 case Lanes::BOUNDARY_C:
909 //DrawLine(hdc,P_180,P_0);
910 graphics.DrawLine(&myPen,P_180,P_0);
911 //p->drawLine(P_180, P_0);
912 break;
913 case Lanes::MERGE_FORK_R:
914 case Lanes::BOUNDARY_R:
915 //DrawLine(hdc,P_180,P_CENTER);
916 graphics.DrawLine(&myPen,P_180,P_CENTER);
917 //p->drawLine(P_180, P_CENTER);
918 break;
919 case Lanes::MERGE_FORK_L:
920 case Lanes::HEAD_L:
921 case Lanes::TAIL_L:
922 case Lanes::BOUNDARY_L:
923 //DrawLine(hdc,P_CENTER,P_0);
924 graphics.DrawLine(&myPen,P_CENTER,P_0);
925 //p->drawLine(P_CENTER, P_0);
926 break;
927 default:
928 break;
931 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
933 CBrush brush;
934 brush.CreateSolidBrush(col);
935 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
937 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
938 // center symbol, e.g. rect or ellipse
939 switch (type) {
940 case Lanes::ACTIVE:
941 case Lanes::INITIAL:
942 case Lanes::BRANCH:
944 //p->setPen(Qt::NoPen);
945 //p->setBrush(col);
946 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
947 graphics.FillEllipse(&myBrush, R_CENTER);
948 //p->drawEllipse(R_CENTER);
949 break;
950 case Lanes::MERGE_FORK:
951 case Lanes::MERGE_FORK_R:
952 case Lanes::MERGE_FORK_L:
953 //p->setPen(Qt::NoPen);
954 //p->setBrush(col);
955 //p->drawRect(R_CENTER);
956 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
957 graphics.FillRectangle(&myBrush, R_CENTER);
958 break;
959 case Lanes::UNAPPLIED:
960 // Red minus sign
961 //p->setPen(Qt::NoPen);
962 //p->setBrush(Qt::red);
963 //p->drawRect(m - r, h - 1, d, 2);
964 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
965 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
966 break;
967 case Lanes::APPLIED:
968 // Green plus sign
969 //p->setPen(Qt::NoPen);
970 //p->setBrush(DARK_GREEN);
971 //p->drawRect(m - r, h - 1, d, 2);
972 //p->drawRect(m - 1, h - r, 2, d);
973 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
974 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
975 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
976 break;
977 case Lanes::BOUNDARY:
978 //p->setBrush(back);
979 //p->drawEllipse(R_CENTER);
980 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
981 graphics.DrawEllipse(&myPen, R_CENTER);
982 break;
983 case Lanes::BOUNDARY_C:
984 case Lanes::BOUNDARY_R:
985 case Lanes::BOUNDARY_L:
986 //p->setBrush(back);
987 //p->drawRect(R_CENTER);
988 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
989 graphics.FillRectangle(&myBrush,R_CENTER);
990 break;
991 default:
992 break;
995 ::SelectObject(hdc,oldpen);
996 ::SelectObject(hdc,oldbrush);
997 #undef P_CENTER
998 #undef P_0
999 #undef P_90
1000 #undef P_180
1001 #undef P_270
1002 #undef R_CENTER
1005 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
1007 // TODO: unfinished
1008 // return;
1009 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1010 if(data->m_CommitHash.IsEmpty())
1011 return;
1013 CRect rt=rect;
1014 LVITEM rItem = { 0 };
1015 rItem.mask = LVIF_STATE;
1016 rItem.iItem = (int)index;
1017 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1018 GetItem(&rItem);
1020 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1022 if (data->m_Lanes.empty())
1023 m_logEntries.setLane(data->m_CommitHash);
1025 std::vector<int>& lanes=data->m_Lanes;
1026 size_t laneNum = lanes.size();
1027 UINT activeLane = 0;
1028 for (UINT i = 0; i < laneNum; ++i)
1029 if (Lanes::isMerge(lanes[i])) {
1030 activeLane = i;
1031 break;
1034 int x2 = 0;
1035 int maxWidth = rect.Width();
1036 int lw = 3 * rect.Height() / 4; //laneWidth()
1038 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1039 //if (opt.state & QStyle::State_Selected)
1040 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1042 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1044 int x1 = x2;
1045 x2 += lw;
1047 int ln = lanes[i];
1048 if (ln == Lanes::EMPTY)
1049 continue;
1051 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1052 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1055 #if 0
1056 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1057 int x1 = x2;
1058 x2 += lw;
1060 int ln = lanes[i];
1061 if (ln == Lanes::EMPTY)
1062 continue;
1064 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1065 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1067 if (ln == Lanes::CROSS)
1069 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1070 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1072 else
1073 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1075 #endif
1078 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1080 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1081 // Take the default processing unless we set this to something else below.
1082 *pResult = CDRF_DODEFAULT;
1084 if (m_bNoDispUpdates)
1085 return;
1087 switch (pLVCD->nmcd.dwDrawStage)
1089 case CDDS_PREPAINT:
1091 *pResult = CDRF_NOTIFYITEMDRAW;
1092 return;
1094 break;
1095 case CDDS_ITEMPREPAINT:
1097 // This is the prepaint stage for an item. Here's where we set the
1098 // item's text color.
1100 // Tell Windows to send draw notifications for each subitem.
1101 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1103 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1105 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1107 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1108 if (data)
1110 HGDIOBJ hGdiObj = nullptr;
1111 int action = data->GetRebaseAction();
1112 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1113 crText = RGB(128,128,128);
1115 if (action & LOGACTIONS_REBASE_SQUASH)
1116 pLVCD->clrTextBk = RGB(156,156,156);
1117 else if (action & LOGACTIONS_REBASE_EDIT)
1118 pLVCD->clrTextBk = RGB(200,200,128);
1119 else
1120 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1122 if (action & LOGACTIONS_REBASE_CURRENT)
1123 hGdiObj = m_boldFont.GetSafeHandle();
1125 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1126 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1127 if (isHeadHash && isHighlight)
1128 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1129 else if (isHeadHash)
1130 hGdiObj = m_boldFont.GetSafeHandle();
1131 else if (isHighlight)
1132 hGdiObj = m_FontItalics.GetSafeHandle();
1134 if (hGdiObj)
1136 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1137 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1140 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1141 // crText = GetSysColor(COLOR_GRAYTEXT);
1143 if (data->m_CommitHash.IsEmpty())
1145 //crText = GetSysColor(RGB(200,200,0));
1146 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1147 // We changed the font, so we're returning CDRF_NEWFONT. This
1148 // tells the control to recalculate the extent of the text.
1149 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1153 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1155 if (m_bStrictStopped)
1156 crText = GetSysColor(COLOR_GRAYTEXT);
1158 // Store the color back in the NMLVCUSTOMDRAW struct.
1159 pLVCD->clrText = crText;
1160 return;
1162 break;
1163 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1165 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1167 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1170 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1172 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1174 CRect rect;
1175 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1177 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1178 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1180 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1181 if( !data ->m_CommitHash.IsEmpty())
1182 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1184 *pResult = CDRF_SKIPDEFAULT;
1185 return;
1189 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1191 // If the top index of list is changed, the position map of reference label is outdated.
1192 if (m_OldTopIndex != GetTopIndex())
1194 m_OldTopIndex = GetTopIndex();
1195 m_RefLabelPosMap.clear();
1198 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1200 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1202 if ((!m_HashMap[data->m_CommitHash].empty() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1204 CRect rect;
1205 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1207 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1208 // not in FillBackGround method, because this only affected the message subitem
1209 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1210 return;
1212 int index = (int)pLVCD->nmcd.dwItemSpec;
1213 int state = GetItemState(index, LVIS_SELECTED);
1214 int txtState = LISS_NORMAL;
1215 if (IsAppThemed() && GetHotItem() == (int)index)
1217 if (state & LVIS_SELECTED)
1218 txtState = LISS_HOTSELECTED;
1219 else
1220 txtState = LISS_HOT;
1222 else if (state & LVIS_SELECTED)
1224 if (::GetFocus() == m_hWnd)
1225 txtState = LISS_SELECTED;
1226 else
1227 txtState = LISS_SELECTEDNOTFOCUS;
1230 HTHEME hTheme = nullptr;
1231 if (IsAppThemed())
1232 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1234 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1235 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1236 else
1238 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1239 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1240 ::DeleteObject(brush);
1242 if (hTheme && txtState != LISS_NORMAL)
1244 CRect rt;
1245 // get rect of whole line
1246 GetItemRect(index, rt, LVIR_BOUNDS);
1247 CRect rect2 = rect;
1249 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1250 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1252 CloseThemeData(hTheme);
1254 // END: extended redraw
1256 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1258 std::vector<REFLABEL> refsToShow;
1259 STRING_VECTOR remoteTrackingList;
1260 STRING_VECTOR refList = m_HashMap[data->m_CommitHash];
1261 for (unsigned int i = 0; i < refList.size(); ++i)
1263 CString str = refList[i];
1265 REFLABEL refLabel;
1266 refLabel.color = RGB(255, 255, 255);
1267 refLabel.singleRemote = false;
1268 refLabel.hasTracking = false;
1269 refLabel.sameName = false;
1270 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1271 refLabel.fullName = str;
1273 switch (refLabel.refType)
1275 case CGit::REF_TYPE::LOCAL_BRANCH:
1277 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1278 continue;
1279 if (refLabel.name == m_CurrentBranch)
1280 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1281 else
1282 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1284 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1285 CString pullRemote = trackingEntry.first;
1286 CString pullBranch = trackingEntry.second;
1287 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1289 CString defaultUpstream;
1290 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1291 refLabel.hasTracking = true;
1292 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1294 bool found = false;
1295 for (size_t j = i + 1; j < refList.size(); ++j)
1297 if (refList[j] == defaultUpstream)
1299 found = true;
1300 break;
1304 if (found)
1306 bool sameName = pullBranch == refLabel.name;
1307 refsToShow.push_back(refLabel);
1308 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1309 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1310 if (m_bSymbolizeRefNames)
1312 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1314 refLabel.simplifiedName = L'/';
1315 if (sameName)
1316 refLabel.simplifiedName += L'≡';
1317 else
1318 refLabel.simplifiedName += 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((int)wcslen(L"refs/heads/")) + L'"';
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
2180 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2181 bAddSeparator = true;
2185 if (selectedCount == 2)
2187 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2189 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2190 bAddSeparator = true;
2193 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2195 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2196 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2197 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2198 CString menu;
2199 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2200 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2201 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2202 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2203 bAddSeparator = true;
2207 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2209 bAddSeparator = true;
2210 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2213 if (bAddSeparator)
2215 popup.AppendMenu(MF_SEPARATOR, NULL);
2216 bAddSeparator = false;
2219 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2220 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2222 if (bAddSeparator)
2223 popup.AppendMenu(MF_SEPARATOR, NULL);
2226 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2228 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2229 popup.AppendMenu(MF_SEPARATOR, NULL);
2232 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2234 bool bAddSeparator = false;
2235 if (selectedCount >= 2 && IsSelectionContinuous())
2237 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2239 CString head;
2240 int headindex;
2241 headindex = this->GetHeadIndex();
2242 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2244 head.Format(L"HEAD~%d", FirstSelect - headindex);
2245 CGitHash hashFirst;
2246 int ret = g_Git.GetHash(hashFirst, head);
2247 head.Format(L"HEAD~%d",LastSelect-headindex);
2248 CGitHash hash;
2249 ret = ret || g_Git.GetHash(hash, head);
2250 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2251 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2252 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2254 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2255 bAddSeparator = true;
2260 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2261 if (selectedCount >= 2)
2262 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2263 else
2264 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2265 bAddSeparator = true;
2268 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2269 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2270 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2271 bAddSeparator = true;
2274 if (bAddSeparator)
2275 popup.AppendMenu(MF_SEPARATOR, NULL);
2278 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2280 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2281 popup.AppendMenu(MF_SEPARATOR, NULL);
2284 if (selectedCount == 1)
2286 bool bAddSeparator = false;
2287 if (m_ContextMenuMask&GetContextMenuBit(ID_PUSH) && ((!isStash && !m_HashMap[pSelLogEntry->m_CommitHash].empty()) || showExtendedMenu))
2289 // show the push-option only if the log entry has an associated local branch
2290 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();
2291 if (isLocal || showExtendedMenu)
2293 CString str;
2294 str.LoadString(IDS_LOG_PUSH);
2296 CString branch;
2297 size_t index = (size_t)-1;
2298 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
2299 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2300 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2302 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2304 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2305 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2307 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2308 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2310 bAddSeparator = true;
2313 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2315 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2316 bAddSeparator = true;
2320 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2322 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2324 std::vector<const CString*> branchs;
2325 auto addCheck = [&](const CString& ref)
2327 if (ref == currentBranch)
2328 return;
2329 branchs.push_back(&ref);
2331 size_t index = (size_t)-1;
2332 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2333 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2334 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2335 else
2336 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2338 CString str;
2339 if (branchs.size() == 1)
2341 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2342 str += L' ';
2343 str += *branchs[0];
2344 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2345 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2346 bAddSeparator = true;
2348 else if (branchs.size() > 1)
2350 str.LoadString(IDS_DELETE_BRANCHTAG);
2351 submenu.CreatePopupMenu();
2352 for (size_t i = 0; i < branchs.size(); ++i)
2354 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2355 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2357 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2358 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2360 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2361 bAddSeparator = true;
2364 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2365 if (bAddSeparator)
2366 popup.AppendMenu(MF_SEPARATOR, NULL);
2367 } // selectedCount == 1
2369 CIconMenu clipSubMenu;
2370 if (!clipSubMenu.CreatePopupMenu())
2371 return;
2372 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2374 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2375 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2376 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2377 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2378 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2379 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2380 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2381 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2383 CString temp;
2384 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2385 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2388 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2389 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2391 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2392 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2394 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2395 // DialogEnableWindow(IDOK, FALSE);
2396 // SetPromptApp(&theApp);
2398 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2400 // EnableOKButton();
2401 } // if (popup.CreatePopupMenu())
2404 bool CGitLogListBase::IsSelectionContinuous()
2406 if ( GetSelectedCount()==1 )
2408 // if only one revision is selected, the selection is of course
2409 // continuous
2410 return true;
2413 POSITION pos = GetFirstSelectedItemPosition();
2414 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2415 if (bContinuous)
2417 int itemindex = GetNextSelectedItem(pos);
2418 while (pos)
2420 int nextindex = GetNextSelectedItem(pos);
2421 if (nextindex - itemindex > 1)
2423 bContinuous = false;
2424 break;
2426 itemindex = nextindex;
2429 return bContinuous;
2432 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2434 CString sClipdata;
2435 POSITION pos = GetFirstSelectedItemPosition();
2436 if (pos)
2438 CString sRev;
2439 sRev.LoadString(IDS_LOG_REVISION);
2440 CString sAuthor;
2441 sAuthor.LoadString(IDS_LOG_AUTHOR);
2442 CString sDate;
2443 sDate.LoadString(IDS_LOG_DATE);
2444 CString sMessage;
2445 sMessage.LoadString(IDS_LOG_MESSAGE);
2446 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2447 bool first = true;
2448 while (pos)
2450 CString sLogCopyText;
2451 CString sPaths;
2452 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2454 if (toCopy == ID_COPYCLIPBOARDFULL)
2456 sPaths = L"----\r\n";
2457 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2459 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2460 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2462 sPaths += L' ';
2463 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2465 sPaths += L"\r\n";
2467 sPaths.Trim();
2468 sPaths += L"\r\n";
2471 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2473 CString sNotesTags;
2474 if (!pLogEntry->m_Notes.IsEmpty())
2476 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2477 sNotesTags += L":\n";
2478 sNotesTags += pLogEntry->m_Notes;
2479 sNotesTags.Replace(L"\n", L"\r\n");
2481 CString tagInfo = GetTagInfo(pLogEntry);
2482 if (!tagInfo.IsEmpty())
2484 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2485 tagInfo.Replace(L"\n", L"\r\n");
2486 sNotesTags += tagInfo;
2489 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s%s\r\n",
2490 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2491 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2492 (LPCTSTR)sDate,
2493 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2494 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2495 (LPCTSTR)sNotesTags,
2496 (LPCTSTR)sPaths);
2497 sClipdata += sLogCopyText;
2499 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2501 if (!first)
2502 sClipdata += L"\r\n";
2503 sClipdata += pLogEntry->GetAuthorName();
2504 sClipdata += L" <";
2505 sClipdata += pLogEntry->GetAuthorEmail();
2506 sClipdata += L">";
2508 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2510 if (!first)
2511 sClipdata += L"\r\n";
2512 sClipdata += pLogEntry->GetAuthorName();
2514 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2516 if (!first)
2517 sClipdata += L"\r\n";
2518 sClipdata += pLogEntry->GetAuthorEmail();
2521 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2523 sClipdata += L"* ";
2524 sClipdata += pLogEntry->GetSubjectBody(true);
2525 sClipdata += L"\r\n\r\n";
2527 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2529 sClipdata += L"* ";
2530 sClipdata += pLogEntry->GetSubject().Trim();
2531 sClipdata += L"\r\n\r\n";
2533 else
2535 if (!first)
2536 sClipdata += L"\r\n";
2537 sClipdata += pLogEntry->m_CommitHash;
2540 first = false;
2542 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2546 void CGitLogListBase::DiffSelectedRevWithPrevious()
2548 if (m_bThreadRunning)
2549 return;
2551 int FirstSelect=-1, LastSelect=-1;
2552 POSITION pos = GetFirstSelectedItemPosition();
2553 FirstSelect = GetNextSelectedItem(pos);
2554 while(pos)
2555 LastSelect = GetNextSelectedItem(pos);
2557 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2560 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2562 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2563 *pResult = -1;
2565 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2566 return;
2567 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2568 return;
2569 if (!pFindInfo->lvfi.psz)
2570 return;
2571 #if 0
2572 CString sCmp = pFindInfo->lvfi.psz;
2573 CString sRev;
2574 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2576 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2577 sRev.Format(L"%ld", pLogEntry->Rev);
2578 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2580 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2582 *pResult = i;
2583 return;
2586 else
2588 if (sCmp.Compare(sRev)==0)
2590 *pResult = i;
2591 return;
2595 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2597 for (int i=0; i<pFindInfo->iStart; ++i)
2599 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2600 sRev.Format(L"%ld", pLogEntry->Rev);
2601 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2603 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2605 *pResult = i;
2606 return;
2609 else
2611 if (sCmp.Compare(sRev)==0)
2613 *pResult = i;
2614 return;
2619 #endif
2620 *pResult = -1;
2623 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2625 ClearText();
2627 this->m_arShownList.SafeRemoveAll();
2629 this->m_logEntries.ClearAll();
2630 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2631 return -1;
2633 SetItemCountEx((int)m_logEntries.size());
2635 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2637 if(m_IsOldFirst)
2639 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2640 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2642 else
2644 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2645 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2649 ReloadHashMap();
2651 if(path)
2652 m_Path=*path;
2653 return 0;
2656 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2658 ClearText();
2660 m_arShownList.SafeRemoveAll();
2662 m_logEntries.ClearAll();
2663 if (m_logEntries.Fill(hashes))
2664 return -1;
2666 SetItemCountEx((int)m_logEntries.size());
2668 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2670 if (m_IsOldFirst)
2672 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2673 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2675 else
2677 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2678 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2682 ReloadHashMap();
2684 return 0;
2687 int CGitLogListBase::BeginFetchLog()
2689 ClearText();
2691 this->m_arShownList.SafeRemoveAll();
2693 this->m_logEntries.ClearAll();
2695 this->m_LogCache.ClearAllParent();
2697 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2699 CTGitPath *path;
2700 if(this->m_Path.IsEmpty())
2701 path = nullptr;
2702 else
2703 path=&this->m_Path;
2705 int mask;
2706 mask = CGit::LOG_INFO_ONLY_HASH;
2707 if (m_bIncludeBoundaryCommits)
2708 mask |= CGit::LOG_INFO_BOUNDARY;
2709 // if(this->m_bAllBranch)
2710 mask |= m_ShowMask ;
2712 if(m_bShowWC)
2714 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2715 ResetWcRev();
2716 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2719 if (m_sRange.IsEmpty())
2720 m_sRange = L"HEAD";
2722 #if 0 /* use tortoiegit filter */
2723 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2724 data.m_Author = this->m_sFilterText;
2726 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2727 data.m_MessageFilter = this->m_sFilterText;
2729 data.m_IsRegex = m_bFilterWithRegex;
2730 #endif
2732 // follow does not work for directories
2733 if (!path || path->IsDirectory())
2734 mask &= ~CGit::LOG_INFO_FOLLOW;
2735 // follow does not work with all branches 8at least in TGit)
2736 if (mask & CGit::LOG_INFO_FOLLOW)
2737 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2739 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2741 //this->m_logEntries.ParserFromLog();
2742 if(IsInWorkingThread())
2744 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2746 else
2748 SetItemCountEx((int)m_logEntries.size());
2753 [] { git_init(); } ();
2755 catch (char* msg)
2757 CString err(msg);
2758 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2759 return -1;
2762 if (!g_Git.CanParseRev(m_sRange))
2764 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2765 return 0;
2767 // if show all branches, pick any ref as dummy entry ref
2768 STRING_VECTOR list;
2769 if (g_Git.GetRefList(list))
2770 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2771 if (list.empty())
2772 return 0;
2774 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2777 g_Git.m_critGitDllSec.Lock();
2778 try {
2779 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2781 g_Git.m_critGitDllSec.Unlock();
2782 return -1;
2785 catch (char* msg)
2787 g_Git.m_critGitDllSec.Unlock();
2788 CString err(msg);
2789 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2790 return -1;
2792 g_Git.m_critGitDllSec.Unlock();
2794 return 0;
2797 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2799 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2801 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2803 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2805 DiffSelectedRevWithPrevious();
2806 return TRUE;
2809 #if 0
2810 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2812 DiffSelectedFile();
2813 return TRUE;
2815 #endif
2817 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2819 // select all entries
2820 for (int i=0; i<GetItemCount(); ++i)
2821 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2822 return TRUE;
2825 #if 0
2826 if (m_hAccel && !bSkipAccelerator)
2828 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2829 if (ret)
2830 return TRUE;
2833 #endif
2834 //m_tooltips.RelayEvent(pMsg);
2835 return __super::PreTranslateMessage(pMsg);
2838 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2840 // a double click on an entry in the revision list has happened
2841 *pResult = 0;
2843 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2844 DiffSelectedRevWithPrevious();
2847 void CGitLogListBase::FetchLogAsync(void* data)
2849 ReloadHashMap();
2850 m_ProcData=data;
2851 StartLoadingThread();
2854 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2856 return ((CGitLogListBase*)pVoid)->LogThread();
2859 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2861 //CTime time;
2862 oldest=CTime::GetCurrentTime();
2863 latest=CTime(1971,1,2,0,0,0);
2864 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2866 if(m_logEntries[i].IsEmpty())
2867 continue;
2869 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2870 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2872 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2873 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2877 if(latest<oldest)
2878 latest=oldest;
2881 UINT CGitLogListBase::LogThread()
2883 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2885 ULONGLONG t1,t2;
2887 if(BeginFetchLog())
2889 InterlockedExchange(&m_bThreadRunning, FALSE);
2890 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2892 return 1;
2895 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
2896 bool bRegex = false;
2897 if (m_bFilterWithRegex)
2898 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2900 TRACE(L"\n===Begin===\n");
2901 //Update work copy item;
2903 if (!m_logEntries.empty())
2905 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2907 m_arShownList.SafeAdd(pRev);
2911 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2913 // store commit number of the last selected commit/line before the refresh or -1
2914 int lastSelectedHashNItem = -1;
2915 if (m_lastSelectedHash.IsEmpty())
2916 lastSelectedHashNItem = 0;
2918 int ret = 0;
2920 bool shouldWalk = true;
2921 if (!g_Git.CanParseRev(m_sRange))
2923 // walk revisions if show all branches and there exists any ref
2924 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2925 shouldWalk = false;
2926 else
2928 STRING_VECTOR list;
2929 if (g_Git.GetRefList(list))
2930 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2931 if (list.empty())
2932 shouldWalk = false;
2936 if (shouldWalk)
2938 g_Git.m_critGitDllSec.Lock();
2939 int total = 0;
2942 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2943 total = git_get_log_estimate_commit_count(m_DllGitLog);
2945 catch (char* msg)
2947 CString err(msg);
2948 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2949 ret = -1;
2951 g_Git.m_critGitDllSec.Unlock();
2953 GIT_COMMIT commit;
2954 t2 = t1 = GetTickCount64();
2955 int oldprecentage = 0;
2956 size_t oldsize = m_logEntries.size();
2957 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2958 while (ret== 0 && !m_bExitThread)
2960 g_Git.m_critGitDllSec.Lock();
2963 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2965 catch (char* msg)
2967 g_Git.m_critGitDllSec.Unlock();
2968 CString err(msg);
2969 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2970 break;
2972 g_Git.m_critGitDllSec.Unlock();
2974 if(ret)
2976 if (ret != -2) // other than end of revision walking
2977 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2978 break;
2981 if (commit.m_ignore == 1)
2983 git_free_commit(&commit);
2984 continue;
2987 //printf("%s\r\n",commit.GetSubject());
2988 if(m_bExitThread)
2989 break;
2991 CGitHash hash(commit.m_hash);
2993 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
2994 pRev->m_GitCommit = commit;
2995 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
2997 char* note = nullptr;
2998 g_Git.m_critGitDllSec.Lock();
3001 git_get_notes(commit.m_hash, &note);
3003 catch (char* msg)
3005 g_Git.m_critGitDllSec.Unlock();
3006 CString err(msg);
3007 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3008 break;
3010 g_Git.m_critGitDllSec.Unlock();
3012 if(note)
3014 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3015 free(note);
3016 note = nullptr;
3019 if(!pRev->m_IsDiffFiles)
3021 pRev->m_CallDiffAsync = DiffAsync;
3024 pRev->ParserParentFromCommit(&commit);
3025 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3027 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3029 const CGitHash &parentHash = pRev->m_ParentHash[i];
3030 auto it = commitChildren.find(parentHash);
3031 if (it == commitChildren.end())
3032 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3033 it->second.insert(pRev->m_CommitHash);
3037 #ifdef DEBUG
3038 pRev->DbgPrint();
3039 TRACE(L"\n");
3040 #endif
3042 bool visible = true;
3043 if (HasFilterText())
3045 if(!IsMatchFilter(bRegex,pRev,pat))
3046 visible = false;
3048 if (visible && !ShouldShowFilter(pRev, commitChildren))
3049 visible = false;
3050 this->m_critSec.Lock();
3051 m_logEntries.append(hash, visible);
3052 if (visible)
3053 m_arShownList.SafeAdd(pRev);
3054 this->m_critSec.Unlock();
3056 if (!visible)
3057 continue;
3059 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3060 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3062 t2 = GetTickCount64();
3064 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3066 //update UI
3067 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3068 if(percent > 99)
3069 percent =99;
3070 if(percent < GITLOG_START)
3071 percent = GITLOG_START +1;
3073 oldsize = m_logEntries.size();
3074 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3076 //if( percent > oldprecentage )
3078 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3079 oldprecentage = percent;
3082 if (lastSelectedHashNItem >= 0)
3083 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3085 t1 = t2;
3088 g_Git.m_critGitDllSec.Lock();
3089 git_close_log(m_DllGitLog);
3090 g_Git.m_critGitDllSec.Unlock();
3094 if (m_bExitThread)
3096 InterlockedExchange(&m_bThreadRunning, FALSE);
3097 return 0;
3100 //Update UI;
3101 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3103 if (lastSelectedHashNItem >= 0)
3104 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3106 if (this->m_hWnd)
3107 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3109 InterlockedExchange(&m_bThreadRunning, FALSE);
3111 return 0;
3114 void CGitLogListBase::FetchRemoteList()
3116 STRING_VECTOR remoteList;
3117 m_SingleRemote.Empty();
3118 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3119 m_SingleRemote = remoteList[0];
3122 void CGitLogListBase::FetchTrackingBranchList()
3124 m_TrackingMap.clear();
3125 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3127 for (const auto& ref : it->second)
3129 CString branchName;
3130 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3132 CString pullRemote, pullBranch;
3133 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3134 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3135 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3141 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3143 SafeTerminateThread();
3145 this->SetItemCountEx(0);
3146 this->Clear();
3148 ResetWcRev();
3150 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3152 if (m_pMailmap)
3154 git_free_mailmap(m_pMailmap);
3155 git_read_mailmap(&m_pMailmap);
3158 //Update branch and Tag info
3159 ReloadHashMap();
3160 if (m_pFindDialog)
3161 m_pFindDialog->RefreshList();
3162 //Assume Thread have exited
3163 //if(!m_bThreadRunning)
3165 m_logEntries.clear();
3167 if(IsCleanFilter)
3169 m_sFilterText.Empty();
3172 SafeTerminateAsyncDiffThread();
3173 m_AsynDiffListLock.Lock();
3174 m_AsynDiffList.clear();
3175 m_AsynDiffListLock.Unlock();
3176 StartAsyncDiffThread();
3178 StartLoadingThread();
3182 void CGitLogListBase::StartAsyncDiffThread()
3184 if (m_AsyncThreadExit)
3185 return;
3186 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3187 return;
3188 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3189 if (!m_DiffingThread)
3191 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3192 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3196 void CGitLogListBase::StartLoadingThread()
3198 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3199 return;
3200 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3201 InterlockedExchange(&m_bExitThread, FALSE);
3202 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3203 if (!m_LoadingThread)
3205 InterlockedExchange(&m_bThreadRunning, FALSE);
3206 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3207 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3211 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::tr1::wregex& pat, bool bMatchCase /* = false */)
3215 std::tr1::regex_constants::syntax_option_type type = std::tr1::regex_constants::ECMAScript;
3216 if (!bMatchCase)
3217 type |= std::tr1::regex_constants::icase;
3218 pat = std::tr1::wregex(regexp_str, type);
3219 return true;
3221 catch (std::exception&) {}
3222 return false;
3224 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::tr1::wregex& pat)
3226 BOOL result = TRUE;
3227 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3228 CString sRev;
3230 if ((bRegex)&&(m_bFilterWithRegex))
3232 if (m_SelectedFilters & LOGFILTER_BUGID)
3234 if(this->m_bShowBugtraqColumn)
3236 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3238 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3239 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3240 return TRUE;
3244 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3246 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3247 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3248 return TRUE;
3251 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3253 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3254 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3255 return TRUE;
3258 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3260 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3261 return TRUE;
3263 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3264 return TRUE;
3267 if (m_SelectedFilters & LOGFILTER_EMAILS)
3269 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3270 return TRUE;
3272 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3273 return TRUE;
3276 if (m_SelectedFilters & LOGFILTER_REVS)
3278 sRev = pRev->m_CommitHash.ToString();
3279 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3281 return TRUE;
3285 if (m_SelectedFilters & LOGFILTER_NOTES)
3287 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3288 return TRUE;
3291 if (m_SelectedFilters & LOGFILTER_REFNAME)
3293 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3294 for (const auto& ref : refs)
3296 if (std::regex_search(std::wstring(ref), pat, flags))
3297 return TRUE;
3301 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3303 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3304 return TRUE;
3307 if (m_SelectedFilters & LOGFILTER_PATHS)
3309 CTGitPathList* pathList = nullptr;
3310 if( pRev->m_IsDiffFiles)
3311 pathList = &pRev->GetFiles(this);
3312 else
3314 if(!pRev->m_IsSimpleListReady)
3315 pRev->SafeGetSimpleList(&g_Git);
3318 if(pathList)
3319 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3321 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3322 return true;
3323 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3324 return true;
3327 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3329 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3330 return true;
3334 else
3336 CString find = m_sFilterText;
3337 if (!m_bFilterCaseSensitively)
3338 find.MakeLower();
3339 result = find[0] == '!' ? FALSE : TRUE;
3340 if (!result)
3341 find = find.Mid(1);
3343 if (m_SelectedFilters & LOGFILTER_BUGID)
3345 if(this->m_bShowBugtraqColumn)
3347 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3349 if (!m_bFilterCaseSensitively)
3350 sBugIds.MakeLower();
3351 if ((sBugIds.Find(find) >= 0))
3352 return result;
3356 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3358 CString msg = pRev->GetSubject();
3360 if (!m_bFilterCaseSensitively)
3361 msg = msg.MakeLower();
3362 if ((msg.Find(find) >= 0))
3363 return result;
3366 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3368 CString msg = pRev->GetBody();
3370 if (!m_bFilterCaseSensitively)
3371 msg = msg.MakeLower();
3372 if ((msg.Find(find) >= 0))
3373 return result;
3376 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3378 CString msg = pRev->GetAuthorName();
3379 if (!m_bFilterCaseSensitively)
3380 msg = msg.MakeLower();
3381 if ((msg.Find(find) >= 0))
3382 return result;
3385 if (m_SelectedFilters & LOGFILTER_EMAILS)
3387 CString msg = pRev->GetAuthorEmail();
3388 if (!m_bFilterCaseSensitively)
3389 msg = msg.MakeLower();
3390 if ((msg.Find(find) >= 0))
3391 return result;
3394 if (m_SelectedFilters & LOGFILTER_NOTES)
3396 CString msg = pRev->m_Notes;
3397 if (!m_bFilterCaseSensitively)
3398 msg = msg.MakeLower();
3399 if ((msg.Find(find) >= 0))
3400 return result;
3403 if (m_SelectedFilters & LOGFILTER_REVS)
3405 sRev = pRev->m_CommitHash.ToString();
3406 if ((sRev.Find(find) >= 0))
3407 return result;
3410 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3412 CString msg = GetTagInfo(pRev);
3413 if (!m_bFilterCaseSensitively)
3414 msg = msg.MakeLower();
3415 if ((msg.Find(find) >= 0))
3416 return result;
3419 if (m_SelectedFilters & LOGFILTER_REFNAME)
3421 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3422 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3424 if (it->Find(find) >= 0)
3425 return result;
3429 if (m_SelectedFilters & LOGFILTER_PATHS)
3431 CTGitPathList* pathList = nullptr;
3432 if( pRev->m_IsDiffFiles)
3433 pathList = &pRev->GetFiles(this);
3434 else
3436 if(!pRev->m_IsSimpleListReady)
3437 pRev->SafeGetSimpleList(&g_Git);
3439 if(pathList)
3440 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3442 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3443 CString path = cpath->GetGitOldPathString();
3444 if (!m_bFilterCaseSensitively)
3445 path.MakeLower();
3446 if ((path.Find(find)>=0))
3447 return result;
3448 path = cpath->GetGitPathString();
3449 if (!m_bFilterCaseSensitively)
3450 path.MakeLower();
3451 if ((path.Find(find)>=0))
3452 return result;
3455 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3457 CString path = pRev->m_SimpleFileList[i];
3458 if (!m_bFilterCaseSensitively)
3459 path.MakeLower();
3460 if ((path.Find(find)>=0))
3461 return result;
3464 } // else (from if (bRegex))
3465 return !result;
3468 static bool CStringStartsWith(const CString &str, const CString &prefix)
3470 return str.Left(prefix.GetLength()) == prefix;
3472 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3474 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3475 return true;
3477 if (m_ShowFilter & FILTERSHOW_REFS)
3479 // Keep all refs.
3480 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3481 for (size_t i = 0; i < refList.size(); ++i)
3483 const CString &str = refList[i];
3484 if (CStringStartsWith(str, L"refs/heads/"))
3486 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3487 return true;
3489 else if (CStringStartsWith(str, L"refs/remotes/"))
3491 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3492 return true;
3494 else if (CStringStartsWith(str, L"refs/tags/"))
3496 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3497 return true;
3499 else if (CStringStartsWith(str, L"refs/stash"))
3501 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3502 return true;
3504 else if (CStringStartsWith(str, L"refs/bisect/"))
3506 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3507 return true;
3510 // Keep the head too.
3511 if (pRev->m_CommitHash == m_HeadHash)
3512 return true;
3515 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3517 if (pRev->ParentsCount() > 1)
3518 return true;
3519 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3520 if (childrenIt != commitChildren.end())
3522 const std::unordered_set<CGitHash> &children = childrenIt->second;
3523 if (children.size() > 1)
3524 return true;
3527 return false;
3530 void CGitLogListBase::ShowGraphColumn(bool bShow)
3532 // HACK to hide graph column
3533 if (bShow)
3534 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3535 else
3536 SetColumnWidth(0, 0);
3539 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3541 CString cmd;
3542 CString output;
3544 if (m_HashMap.find(pLogEntry->m_CommitHash) != m_HashMap.end())
3546 STRING_VECTOR &vector = m_HashMap[pLogEntry->m_CommitHash];
3547 for (size_t i = 0; i < vector.size(); ++i)
3549 if (CStringUtils::StartsWith(vector[i], L"refs/tags/"))
3551 CString tag = vector[i];
3552 int start = vector[i].Find(L"^{}");
3553 if (start > 0)
3554 tag = tag.Left(start);
3555 else
3556 continue;
3558 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)tag);
3559 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) == 0)
3560 output.Trim().AppendChar(L'\n');
3565 return output;
3568 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3570 pShownlist->SafeRemoveAll();
3572 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
3573 bool bRegex = false;
3574 if (m_bFilterWithRegex)
3575 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3577 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3578 CString sRev;
3579 for (DWORD i=0; i<m_logEntries.size(); ++i)
3581 if ((bRegex)&&(m_bFilterWithRegex))
3583 #if 0
3584 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3586 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3587 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3589 pShownlist->SafeAdd(m_logEntries[i]);
3590 continue;
3593 #endif
3594 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3596 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3597 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3599 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3600 continue;
3603 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3605 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3606 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3608 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3609 continue;
3612 if (m_SelectedFilters & LOGFILTER_PATHS)
3614 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3616 bool bGoing = true;
3617 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3619 CTGitPath cpath = pathList[cpPathIndex];
3620 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3622 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3623 bGoing = false;
3624 continue;
3626 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3628 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3629 bGoing = false;
3630 continue;
3632 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3634 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3635 bGoing = false;
3636 continue;
3640 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3642 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3644 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3645 continue;
3648 if (m_SelectedFilters & LOGFILTER_EMAILS)
3650 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3652 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3653 continue;
3656 if (m_SelectedFilters & LOGFILTER_REVS)
3658 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3659 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3661 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3662 continue;
3665 if (m_SelectedFilters & LOGFILTER_REFNAME)
3667 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3668 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3670 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3672 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3673 continue;
3677 } // if (bRegex)
3678 else
3680 CString find = m_sFilterText;
3681 if (!m_bFilterCaseSensitively)
3682 find.MakeLower();
3683 #if 0
3684 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3686 CString sBugIDs = m_logEntries[i]->sBugIDs;
3688 if (!m_bFilterCaseSensitively)
3689 sBugIDs = sBugIDs.MakeLower();
3690 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3692 pShownlist->SafeAdd(m_logEntries[i]);
3693 continue;
3696 #endif
3697 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3699 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3701 if (!m_bFilterCaseSensitively)
3702 msg = msg.MakeLower();
3703 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3705 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3706 continue;
3709 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3711 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3713 if (!m_bFilterCaseSensitively)
3714 msg = msg.MakeLower();
3715 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3717 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3718 continue;
3721 if (m_SelectedFilters & LOGFILTER_PATHS)
3723 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3725 bool bGoing = true;
3726 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3728 CTGitPath cpath = pathList[cpPathIndex];
3729 CString path = cpath.GetGitOldPathString();
3730 if (!m_bFilterCaseSensitively)
3731 path.MakeLower();
3732 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3734 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3735 bGoing = false;
3736 continue;
3738 path = cpath.GetGitPathString();
3739 if (!m_bFilterCaseSensitively)
3740 path.MakeLower();
3741 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3743 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3744 bGoing = false;
3745 continue;
3747 path = cpath.GetActionName();
3748 if (!m_bFilterCaseSensitively)
3749 path.MakeLower();
3750 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3752 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3753 bGoing = false;
3754 continue;
3758 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3760 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3761 if (!m_bFilterCaseSensitively)
3762 msg = msg.MakeLower();
3763 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3765 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3766 continue;
3769 if (m_SelectedFilters & LOGFILTER_EMAILS)
3771 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3772 if (!m_bFilterCaseSensitively)
3773 msg = msg.MakeLower();
3774 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3776 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3777 continue;
3780 if (m_SelectedFilters & LOGFILTER_REVS)
3782 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3783 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3785 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3786 continue;
3789 if (m_SelectedFilters & LOGFILTER_REFNAME)
3791 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3792 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3794 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3796 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3797 continue;
3801 } // else (from if (bRegex))
3802 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3805 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3808 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3810 if(m_From == -1)
3811 if(m_To == -1)
3812 return true;
3813 else
3814 return time <= m_To;
3815 else
3816 if(m_To == -1)
3817 return time >= m_From;
3818 else
3819 return ((time >= m_From)&&(time <= m_To));
3821 return TRUE; /* git dll will filter time range */
3823 // return TRUE;
3826 void CGitLogListBase::StartFilter()
3828 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3829 RecalculateShownList(&m_arShownList);
3830 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3833 DeleteAllItems();
3834 SetItemCountEx(ShownCountWithStopped());
3835 RedrawItems(0, ShownCountWithStopped());
3836 Invalidate();
3839 void CGitLogListBase::RemoveFilter()
3841 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3843 m_arShownList.SafeRemoveAll();
3845 // reset the time filter too
3846 #if 0
3847 m_timFrom = (__time64_t(m_tFrom));
3848 m_timTo = (__time64_t(m_tTo));
3849 m_DateFrom.SetTime(&m_timFrom);
3850 m_DateTo.SetTime(&m_timTo);
3851 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3852 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3853 #endif
3855 for (DWORD i=0; i<m_logEntries.size(); ++i)
3857 if(this->m_IsOldFirst)
3858 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3859 else
3860 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3862 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3863 DeleteAllItems();
3864 SetItemCountEx(ShownCountWithStopped());
3865 RedrawItems(0, ShownCountWithStopped());
3867 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3870 void CGitLogListBase::Clear()
3872 m_arShownList.SafeRemoveAll();
3873 DeleteAllItems();
3875 m_logEntries.ClearAll();
3878 void CGitLogListBase::OnDestroy()
3880 SafeTerminateThread();
3881 SafeTerminateAsyncDiffThread();
3883 int retry = 0;
3884 while(m_LogCache.SaveCache())
3886 if(retry > 5)
3887 break;
3888 Sleep(1000);
3890 ++retry;
3892 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3893 // MB_YESNO) == IDNO)
3894 // break;
3897 __super::OnDestroy();
3900 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3902 CRect rect;
3903 int i=(int)wParam;
3904 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3905 this->InvalidateRect(rect);
3907 return 0;
3911 * Save column widths to the registry
3913 void CGitLogListBase::SaveColumnWidths()
3915 // HACK that graph column is always shown
3916 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3918 __super::SaveColumnWidths();
3921 int CGitLogListBase::GetHeadIndex()
3923 if(m_HeadHash.IsEmpty())
3924 return -1;
3926 for (size_t i = 0; i < m_arShownList.size(); ++i)
3928 GitRev* pRev = m_arShownList.SafeGetAt(i);
3929 if(pRev)
3931 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3932 return (int)i;
3935 return -1;
3937 void CGitLogListBase::OnFind()
3939 if (!m_pFindDialog)
3941 m_pFindDialog = new CFindDlg(this);
3942 m_pFindDialog->Create(this);
3946 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3948 if (GetSelectedCount() != 0)
3949 return 0;
3951 CGitHash theSelectedHash = m_lastSelectedHash;
3952 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3953 m_lastSelectedHash = theSelectedHash;
3955 int countPerPage = GetCountPerPage();
3956 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3957 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3958 EnsureVisible((int)itemToSelect, FALSE);
3959 return 0;
3962 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3964 CString* ref = reinterpret_cast<CString*>(wParam);
3965 if (!ref || ref->IsEmpty())
3966 return 1;
3968 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3970 CGitHash hash;
3971 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3972 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3974 if (hash.IsEmpty())
3975 return 1;
3977 bool bFound = false;
3978 int cnt = (int)m_arShownList.size();
3979 int i;
3980 for (i = 0; i < cnt; ++i)
3982 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3983 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3985 bFound = true;
3986 break;
3989 if (!bFound)
3990 return 1;
3992 EnsureVisible(i, FALSE);
3993 if (!bShift)
3995 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3996 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3997 SetSelectionMark(i);
3999 else
4001 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4002 if (pLogEntry)
4003 m_highlight = pLogEntry->m_CommitHash;
4005 Invalidate();
4006 UpdateData(FALSE);
4008 return 0;
4011 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4013 ASSERT(m_pFindDialog);
4014 bool bFound = false;
4015 int i=0;
4017 if (m_pFindDialog->IsTerminating())
4019 // invalidate the handle identifying the dialog box.
4020 m_pFindDialog = nullptr;
4021 return 0;
4024 int cnt = (int)m_arShownList.size();
4025 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4027 if(m_pFindDialog->IsRef())
4029 CString str;
4030 str=m_pFindDialog->GetFindString();
4032 CGitHash hash;
4034 if(!str.IsEmpty())
4036 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4037 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4040 if(!hash.IsEmpty())
4042 for (i = 0; i < cnt; ++i)
4044 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4045 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4047 bFound = true;
4048 break;
4052 if (!bFound)
4054 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4055 return 0;
4059 if (m_pFindDialog->FindNext() && !bFound)
4061 //read data from dialog
4062 CString findText = m_pFindDialog->GetFindString();
4063 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4065 std::tr1::wregex pat;
4066 bool bRegex = false;
4067 if (m_pFindDialog->Regex())
4068 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4070 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_not_null;
4072 for (i = m_nSearchIndex + 1; ; ++i)
4074 if (i >= cnt)
4076 i = 0;
4077 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4079 if (m_nSearchIndex >= 0)
4081 if (i == m_nSearchIndex)
4083 ::MessageBeep(0xFFFFFFFF);
4084 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4085 break;
4089 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4091 CString str;
4092 str+=pLogEntry->m_CommitHash.ToString();
4093 str += L'\n';
4095 for (size_t j = 0; j < this->m_HashMap[pLogEntry->m_CommitHash].size(); ++j)
4097 str+=m_HashMap[pLogEntry->m_CommitHash][j];
4098 str += L'\n';
4101 str+=pLogEntry->GetAuthorEmail();
4102 str += L'\n';
4103 str+=pLogEntry->GetAuthorName();
4104 str += L'\n';
4105 str+=pLogEntry->GetBody();
4106 str += L'\n';
4107 str+=pLogEntry->GetCommitterEmail();
4108 str += L'\n';
4109 str+=pLogEntry->GetCommitterName();
4110 str += L'\n';
4111 str+=pLogEntry->GetSubject();
4112 str += L'\n';
4113 str+=pLogEntry->m_Notes;
4114 str += L'\n';
4115 str+=GetTagInfo(pLogEntry);
4116 str += L'\n';
4119 /*Because changed files list is loaded on demand when gui show,
4120 files will empty when files have not fetched.
4122 we can add it back by using one-way diff(with outnumber changed and rename detect.
4123 here just need changed filename list. one-way is much quicker.
4125 if(pLogEntry->m_IsFull)
4127 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4129 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4130 str += L'\n';
4131 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4132 str += L'\n';
4135 else
4137 if(!pLogEntry->m_IsSimpleListReady)
4138 pLogEntry->SafeGetSimpleList(&g_Git);
4140 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4142 str += pLogEntry->m_SimpleFileList[j];
4143 str += L'\n';
4147 if (bRegex)
4149 if (std::regex_search(std::wstring(str), pat, flags))
4151 bFound = true;
4152 break;
4155 else
4157 if (bMatchCase)
4159 if (str.Find(findText) >= 0)
4161 bFound = true;
4162 break;
4165 else
4167 CString msg = str;
4168 msg = msg.MakeLower();
4169 CString find = findText.MakeLower();
4170 if (msg.Find(find) >= 0)
4172 bFound = TRUE;
4173 break;
4177 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4179 } // if(m_pFindDialog->FindNext())
4180 //UpdateLogInfoLabel();
4182 if (bFound)
4184 m_nSearchIndex = i;
4185 EnsureVisible(i, FALSE);
4186 if (!bShift)
4188 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4189 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4190 SetSelectionMark(i);
4192 else
4194 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4195 if (pLogEntry)
4196 m_highlight = pLogEntry->m_CommitHash;
4198 Invalidate();
4199 //FillLogMessageCtrl();
4200 UpdateData(FALSE);
4203 return 0;
4206 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4208 LVHITTESTINFO lvhitTestInfo;
4210 lvhitTestInfo.pt = point;
4212 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4213 int nSubItem = lvhitTestInfo.iSubItem;
4215 UINT nFlags = lvhitTestInfo.flags;
4217 // nFlags is 0 if the SubItemHitTest fails
4218 // Therefore, 0 & <anything> will equal false
4219 if (nFlags & LVHT_ONITEM)
4221 // Get the client area occupied by this control
4222 RECT rcClient;
4223 GetClientRect(&rcClient);
4225 // Fill in the TOOLINFO structure
4226 pTI->hwnd = m_hWnd;
4227 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4228 pTI->lpszText = LPSTR_TEXTCALLBACK;
4229 pTI->rect = rcClient;
4231 return pTI->uId; // By returning a unique value per listItem,
4232 // we ensure that when the mouse moves over another list item,
4233 // the tooltip will change
4235 else
4237 // Otherwise, we aren't interested, so let the message propagate
4238 return -1;
4242 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4244 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4245 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4247 *pResult = 0;
4249 // Ignore messages from the built in tooltip, we are processing them internally
4250 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4251 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4252 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4253 return FALSE;
4255 // Get the mouse position
4256 const MSG* pMessage = GetCurrentMessage();
4258 CPoint pt;
4259 pt = pMessage->pt;
4260 ScreenToClient(&pt);
4262 // Check if the point falls onto a list item
4263 LVHITTESTINFO lvhitTestInfo;
4264 lvhitTestInfo.pt = pt;
4266 int nItem = SubItemHitTest(&lvhitTestInfo);
4268 if (lvhitTestInfo.flags & LVHT_ONITEM)
4270 // Get branch description first
4271 CString strTipText;
4272 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4274 CString branch;
4275 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4276 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4278 MAP_STRING_STRING descriptions;
4279 g_Git.GetBranchDescriptions(descriptions);
4280 if (descriptions.find(branch) != descriptions.cend())
4282 strTipText.LoadString(IDS_DESCRIPTION);
4283 strTipText += L":\n";
4284 strTipText += descriptions[branch];
4289 bool followMousePos = false;
4290 if (!strTipText.IsEmpty())
4291 followMousePos = true;
4292 else
4293 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4294 if (strTipText.IsEmpty())
4295 return FALSE;
4297 // we want multiline tooltips
4298 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, INT_MAX);
4300 wcscpy_s(m_wszTip, strTipText);
4301 // handle Unicode as well as non-Unicode requests
4302 if (pNMHDR->code == TTN_NEEDTEXTA)
4304 pTTTA->hinst = nullptr;
4305 pTTTA->lpszText = m_szTip;
4306 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4308 else
4310 pTTTW->hinst = nullptr;
4311 pTTTW->lpszText = m_wszTip;
4314 CRect rect;
4315 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4316 if (followMousePos)
4317 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4318 ClientToScreen(rect);
4319 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4321 return TRUE; // We found a tool tip,
4322 // tell the framework this message has been handled
4325 return FALSE; // We didn't handle the message,
4326 // let the framework continue propagating the message
4329 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4331 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4333 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4334 if (pLogEntry == nullptr)
4335 return CString();
4336 if (m_HashMap[pLogEntry->m_CommitHash].empty() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4337 return CString();
4338 return pLogEntry->GetSubject();
4340 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4342 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4343 if (pLogEntry == nullptr)
4344 return CString();
4345 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4347 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4349 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4350 if (pLogEntry == nullptr)
4351 return CString();
4352 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4354 else if (nSubItem == LOGLIST_ACTION)
4356 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4357 if (pLogEntry == nullptr)
4358 return CString();
4360 if (!pLogEntry->m_IsDiffFiles)
4361 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4363 int actions = pLogEntry->GetAction(this);
4364 CString sToolTipText;
4366 CString actionText;
4367 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4368 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4370 if (actions & CTGitPath::LOGACTIONS_ADDED)
4372 if (!actionText.IsEmpty())
4373 actionText += L"\r\n";
4374 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4377 if (actions & CTGitPath::LOGACTIONS_DELETED)
4379 if (!actionText.IsEmpty())
4380 actionText += L"\r\n";
4381 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4384 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4386 if (!actionText.IsEmpty())
4387 actionText += L"\r\n";
4388 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4391 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4393 if (!actionText.IsEmpty())
4394 actionText += L"\r\n";
4395 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4398 if (!actionText.IsEmpty())
4400 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4401 sToolTipText = sTitle + L":\r\n" + actionText;
4403 return sToolTipText;
4405 return CString();
4408 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4410 POINT pt = point;
4411 ScreenToClient(&pt);
4412 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4415 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4417 if (!pLogEntry)
4418 return false;
4420 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4422 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4423 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4424 continue;
4426 CGit::REF_TYPE foundType;
4427 if (pShortname)
4428 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4429 else
4430 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4431 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4432 return false;
4434 type = foundType;
4435 if (pIndex)
4436 *pIndex = i;
4437 return true;
4439 return false;
4442 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4444 *pResult = 0;
4446 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4447 return;
4449 m_bDragging = TRUE;
4450 m_nDropIndex = -1;
4451 m_nDropMarkerLast = -1;
4452 m_nDropMarkerLastHot = GetHotItem();
4453 SetCapture();
4456 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4458 __super::OnMouseMove(nFlags, point);
4460 if (!m_bDragging)
4461 return;
4463 CPoint dropPoint = point;
4464 ClientToScreen(&dropPoint);
4466 if (WindowFromPoint(dropPoint) != this)
4468 SetCursor(LoadCursor(nullptr, IDC_NO));
4469 m_nDropIndex = -1;
4470 DrawDropInsertMarker(m_nDropIndex);
4471 return;
4474 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4475 ScreenToClient(&dropPoint);
4477 dropPoint.y += 10;
4478 m_nDropIndex = HitTest(dropPoint);
4480 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4482 dropPoint.y -= 10;
4483 m_nDropIndex = HitTest(dropPoint);
4484 if (m_nDropIndex != -1)
4485 m_nDropIndex = GetItemCount();
4488 POSITION pos = GetFirstSelectedItemPosition();
4489 int first = GetNextSelectedItem(pos);
4490 int last = first;
4491 while (pos)
4492 last = GetNextSelectedItem(pos);
4493 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4495 SetCursor(LoadCursor(nullptr, IDC_NO));
4496 m_nDropIndex = -1;
4499 // handle auto scrolling
4500 int hotItem = GetHotItem();
4501 int topindex = GetTopIndex();
4502 if (hotItem == topindex && hotItem != 0)
4503 EnsureVisible(hotItem - 1, FALSE);
4504 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4505 EnsureVisible(hotItem + 1, FALSE);
4507 DrawDropInsertMarker(m_nDropIndex);
4510 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4512 if (m_bDragging)
4514 ::ReleaseCapture();
4515 SetCursor(LoadCursor(nullptr, IDC_HAND));
4516 m_bDragging = FALSE;
4518 CRect rect;
4519 GetItemRect(m_nDropMarkerLast, &rect, 0);
4520 rect.bottom = rect.top + 2;
4521 rect.top -= 2;
4522 InvalidateRect(&rect, 0);
4524 CPoint pt(point);
4525 ClientToScreen(&pt);
4526 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4527 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4530 __super::OnLButtonUp(nFlags, point);
4533 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4535 if (m_nDropMarkerLast != nIndex)
4537 CRect rect;
4538 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4540 rect.bottom = rect.top + 2;
4541 rect.top -= 2;
4542 InvalidateRect(&rect, 0);
4544 else if (m_nDropMarkerLast == GetItemCount())
4545 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4546 m_nDropMarkerLast = nIndex;
4548 if (nIndex < 0)
4549 return;
4551 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4553 else if (m_nDropMarkerLastHot != GetHotItem())
4555 m_nDropMarkerLastHot = GetHotItem();
4556 m_nDropMarkerLast = -1;
4560 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4562 CBrush* pBrush = CDC::GetHalftoneBrush();
4563 CDC* pDC = GetDC();
4565 CRect rect;
4566 if (nIndex < GetItemCount())
4568 GetItemRect(nIndex, &rect, 0);
4569 rect.bottom = rect.top + 2;
4570 rect.top -= 2;
4572 else
4574 GetItemRect(nIndex - 1, &rect, 0);
4575 rect.top = rect.bottom - 2;
4576 rect.bottom += 2;
4579 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4580 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4581 pDC->SelectObject(pBrushOld);
4583 ReleaseDC(pDC);