Re-integrate the GPG signed commit into the unit tests
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blobc8eaff2510bfcc39518982ce814afc0a70af506f
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 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
40 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
42 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
43 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
44 ,m_nSearchIndex(0)
45 ,m_bNoDispUpdates(FALSE)
46 , m_bThreadRunning(FALSE)
47 , m_bStrictStopped(false)
48 , m_SelectedFilters(LOGFILTER_ALL)
49 , m_ShowFilter(FILTERSHOW_ALL)
50 , m_bShowWC(false)
51 , m_logEntries(&m_LogCache)
52 , m_pFindDialog(nullptr)
53 , m_dwDefaultColumns(0)
54 , m_arShownList(&m_critSec)
55 , m_hasWC(true)
56 , m_bNoHightlightHead(FALSE)
57 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
58 , m_bFullCommitMessageOnLogLine(false)
59 , m_OldTopIndex(-1)
60 , m_AsyncThreadRunning(FALSE)
61 , m_AsyncThreadExit(FALSE)
62 , m_bIsCherryPick(false)
63 , m_pMailmap(nullptr)
64 , m_bShowBugtraqColumn(false)
65 , m_IsIDReplaceAction(FALSE)
66 , m_ShowMask(0)
67 , m_LoadingThread(nullptr)
68 , m_bExitThread(FALSE)
69 , m_IsOldFirst(FALSE)
70 , m_IsRebaseReplaceGraph(FALSE)
71 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
72 , m_bDragndropEnabled(false)
73 , m_bDragging(FALSE)
74 , m_nDropIndex(-1)
75 , m_nDropMarkerLast(-1)
76 , m_nDropMarkerLastHot(-1)
78 // use the default GUI font, create a copy of it and
79 // change the copy to BOLD (leave the rest of the font
80 // the same)
81 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
82 LOGFONT lf = {0};
83 GetObject(hFont, sizeof(LOGFONT), &lf);
84 lf.lfWeight = FW_BOLD;
85 m_boldFont.CreateFontIndirect(&lf);
86 lf.lfWeight = FW_DONTCARE;
87 lf.lfItalic = TRUE;
88 m_FontItalics.CreateFontIndirect(&lf);
89 lf.lfWeight = FW_BOLD;
90 m_boldItalicsFont.CreateFontIndirect(&lf);
92 this->m_critSec.Init();
93 ResetWcRev(false);
95 int cx = GetSystemMetrics(SM_CXSMICON);
96 int cy = GetSystemMetrics(SM_CYSMICON);
97 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, cx, cy, 0);
98 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, cx, cy, 0);
99 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, cx, cy, 0);
100 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, cx, cy, 0);
101 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, cx, cy, 0);
102 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, cx, cy, 0);
104 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
105 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
107 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
108 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
110 CString key;
111 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
112 key.Replace(L':', L'_');
113 CString lastSelFromDate = CRegString(key);
114 if (lastSelFromDate.GetLength() == 10)
116 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
117 m_Filter.m_From = (DWORD)time.GetTime();
120 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
122 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
124 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
126 // get short/long datetime setting from registry
127 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
128 if ( RegUseShortDateFormat )
130 m_DateFormat = DATE_SHORTDATE;
132 else
134 m_DateFormat = DATE_LONGDATE;
136 // get relative time display setting from registry
137 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
138 m_bRelativeTimes = (regRelativeTimes != 0);
140 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
141 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
142 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
143 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
144 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
145 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
146 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
148 m_ColumnRegKey = L"log";
150 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
151 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
152 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
153 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
155 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
156 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
158 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
159 git_read_mailmap(&m_pMailmap);
161 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
162 m_AsynDiffListLock.Init();
163 StartAsyncDiffThread();
166 int CGitLogListBase::AsyncDiffThread()
168 while(!m_AsyncThreadExit)
170 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
172 GitRevLoglist* pRev = nullptr;
173 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
175 m_AsynDiffListLock.Lock();
176 pRev = m_AsynDiffList.back();
177 m_AsynDiffList.pop_back();
178 m_AsynDiffListLock.Unlock();
180 if( pRev->m_CommitHash.IsEmpty() )
182 if(pRev->m_IsDiffFiles)
183 continue;
185 CTGitPathList& files = pRev->GetFiles(this);
186 files.Clear();
187 pRev->m_ParentHash.clear();
188 pRev->m_ParentHash.push_back(m_HeadHash);
189 g_Git.RefreshGitIndex();
190 g_Git.GetWorkingTreeChanges(files);
191 int& action = pRev->GetAction(this);
192 action = 0;
193 for (int j = 0; j < files.GetCount(); ++j)
194 action |= files[j].m_Action;
196 CString err;
197 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
199 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
200 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
201 return -1;
204 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
205 InterlockedExchange(&pRev->m_IsFull, TRUE);
207 CString body = L"\n";
208 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
209 pRev->GetBody() = body;
210 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
211 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
214 if (!pRev->CheckAndDiff())
215 { // fetch change file list
216 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
218 if (i < (int)m_arShownList.size())
220 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
221 if(data->m_CommitHash == pRev->m_CommitHash)
223 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
224 break;
229 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
231 POSITION pos = GetFirstSelectedItemPosition();
232 int nItem = GetNextSelectedItem(pos);
234 if(nItem>=0)
236 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
237 if(data)
238 if(data->m_CommitHash == pRev->m_CommitHash)
239 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
245 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
246 return 0;
248 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
250 if (exclusivelyShow)
251 m_ContextMenuMask &= hideMask;
252 else
253 m_ContextMenuMask &= ~hideMask;
256 CGitLogListBase::~CGitLogListBase()
258 InterlockedExchange(&m_bNoDispUpdates, TRUE);
259 this->m_arShownList.SafeRemoveAll();
261 DestroyIcon(m_hModifiedIcon);
262 DestroyIcon(m_hReplacedIcon);
263 DestroyIcon(m_hConflictedIcon);
264 DestroyIcon(m_hAddedIcon);
265 DestroyIcon(m_hDeletedIcon);
266 m_logEntries.ClearAll();
268 git_free_mailmap(m_pMailmap);
270 SafeTerminateThread();
271 SafeTerminateAsyncDiffThread();
273 if(m_AsyncDiffEvent)
274 CloseHandle(m_AsyncDiffEvent);
278 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
279 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
280 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
281 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
282 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
283 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
284 ON_WM_CONTEXTMENU()
285 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
286 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
287 ON_WM_CREATE()
288 ON_WM_DESTROY()
289 ON_MESSAGE(MSG_LOADED,OnLoad)
290 ON_WM_MEASUREITEM()
291 ON_WM_MEASUREITEM_REFLECT()
292 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
293 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
294 ON_WM_MOUSEMOVE()
295 ON_WM_LBUTTONUP()
296 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
297 END_MESSAGE_MAP()
299 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
301 //if (m_nRowHeight>0)
302 lpMeasureItemStruct->itemHeight = 50;
305 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
307 PreSubclassWindow();
308 return __super::OnCreate(lpCreateStruct);
311 void CGitLogListBase::SetStyle()
313 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
316 void CGitLogListBase::PreSubclassWindow()
318 SetStyle();
319 // load the icons for the action columns
320 // m_Theme.Open(m_hWnd, L"ListView");
321 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
322 __super::PreSubclassWindow();
325 CString CGitLogListBase::GetRebaseActionName(int action)
327 if (action & LOGACTIONS_REBASE_EDIT)
328 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
329 if (action & LOGACTIONS_REBASE_SQUASH)
330 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
331 if (action & LOGACTIONS_REBASE_PICK)
332 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
333 if (action & LOGACTIONS_REBASE_SKIP)
334 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
336 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
339 void CGitLogListBase::InsertGitColumn()
341 CString temp;
343 Init();
345 // only load properties if we have a repository
346 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
347 UpdateProjectProperties();
349 static UINT normal[] =
351 IDS_LOG_GRAPH,
352 IDS_LOG_REBASE,
353 IDS_LOG_ID,
354 IDS_LOG_HASH,
355 IDS_LOG_ACTIONS,
356 IDS_LOG_MESSAGE,
357 IDS_LOG_AUTHOR,
358 IDS_LOG_DATE,
359 IDS_LOG_EMAIL,
360 IDS_LOG_COMMIT_NAME,
361 IDS_LOG_COMMIT_EMAIL,
362 IDS_LOG_COMMIT_DATE,
363 IDS_LOG_BUGIDS,
364 IDS_LOG_SVNREV,
367 static int with[] =
369 ICONITEMBORDER+16*4,
370 ICONITEMBORDER+16*4,
371 ICONITEMBORDER+16*4,
372 ICONITEMBORDER+16*4,
373 2 * ICONITEMBORDER + GetSystemMetrics(SM_CXSMICON) * 5,
374 LOGLIST_MESSAGE_MIN,
375 ICONITEMBORDER+16*4,
376 ICONITEMBORDER+16*4,
377 ICONITEMBORDER+16*4,
378 ICONITEMBORDER+16*4,
379 ICONITEMBORDER+16*4,
380 ICONITEMBORDER+16*4,
381 ICONITEMBORDER+16*4,
382 ICONITEMBORDER+16*4,
384 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
386 DWORD hideColumns = 0;
387 if(this->m_IsRebaseReplaceGraph)
389 hideColumns |= GIT_LOG_GRAPH;
390 m_dwDefaultColumns |= GIT_LOG_REBASE;
392 else
393 hideColumns |= GIT_LOG_REBASE;
395 if(this->m_IsIDReplaceAction)
397 hideColumns |= GIT_LOG_ACTIONS;
398 m_dwDefaultColumns |= GIT_LOG_ID;
399 m_dwDefaultColumns |= GIT_LOG_HASH;
401 else
402 hideColumns |= GIT_LOG_ID;
403 if(this->m_bShowBugtraqColumn)
404 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
405 else
406 hideColumns |= GIT_LOGLIST_BUG;
407 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
408 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
409 else
410 hideColumns |= GIT_LOGLIST_SVNREV;
411 SetRedraw(false);
413 m_ColumnManager.SetNames(normal, _countof(normal));
414 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
415 m_ColumnManager.SetRightAlign(LOGLIST_ID);
417 if (!(hideColumns & GIT_LOG_ACTIONS))
419 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
420 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
421 // display's font height may be less than small icon height.
422 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
423 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
424 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
427 SetRedraw(true);
430 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
432 LVITEM rItem = { 0 };
433 rItem.mask = LVIF_STATE;
434 rItem.iItem = (int)Index;
435 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
436 GetItem(&rItem);
438 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
439 HBRUSH brush = nullptr;
441 if (!(rItem.state & LVIS_SELECTED))
443 int action = pLogEntry->GetRebaseAction();
444 if (action & LOGACTIONS_REBASE_SQUASH)
445 brush = ::CreateSolidBrush(RGB(156,156,156));
446 else if (action & LOGACTIONS_REBASE_EDIT)
447 brush = ::CreateSolidBrush(RGB(200,200,128));
449 else if (!IsAppThemed())
451 if (rItem.state & LVIS_SELECTED)
453 if (::GetFocus() == m_hWnd)
454 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
455 else
456 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
459 if (brush)
461 ::FillRect(hdc, &rect, brush);
462 ::DeleteObject(brush);
466 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
468 POINT point = { 4, 4 };
469 CRect rt2 = rect;
470 rt2.DeflateRect(1, 1);
471 rt2.OffsetRect(2, 2);
473 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
474 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
475 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
476 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
477 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
479 ::SelectObject(hdc, brush);
480 rt2.OffsetRect(-2, -2);
481 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
482 ::SelectObject(hdc, oldbrush);
483 ::SelectObject(hdc, oldpen);
484 ::DeleteObject(nullPen);
485 ::DeleteObject(darkBrush);
488 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
490 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
491 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
492 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
493 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
494 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
495 ::LineTo(hdc, rect.left, rect.top + 4);
496 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
497 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
498 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
499 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
500 ::SelectObject(hdc, oldpen);
501 ::DeleteObject(pen);
504 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
506 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
507 CRect rt=rect;
508 LVITEM rItem = { 0 };
509 rItem.mask = LVIF_STATE;
510 rItem.iItem = (int)index;
511 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
512 GetItem(&rItem);
514 CDC W_Dc;
515 W_Dc.Attach(hdc);
517 HTHEME hTheme = nullptr;
518 if (IsAppThemed())
519 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
521 SIZE oneSpaceSize;
522 if (m_bTagsBranchesOnRightSide)
524 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
525 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
526 SelectObject(hdc, oldFont);
527 rt.left += oneSpaceSize.cx * 2;
529 else
531 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
532 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
533 rt.left += oneSpaceSize.cx;
536 CString msg = MessageDisplayStr(data);
537 int action = data->GetRebaseAction();
538 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
539 if (IsAppThemed())
541 int txtState = LISS_NORMAL;
542 if (rItem.state & LVIS_SELECTED)
543 txtState = LISS_SELECTED;
545 DTTOPTS opts = { 0 };
546 opts.dwSize = sizeof(opts);
547 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
548 opts.dwFlags = DTT_TEXTCOLOR;
549 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
551 else
553 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
555 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
556 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
557 ::SetTextColor(hdc, clrOld);
559 else
561 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
562 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
563 ::SetTextColor(hdc, clrOld);
567 if (m_bTagsBranchesOnRightSide)
569 SIZE size;
570 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
572 rt.left += oneSpaceSize.cx + size.cx;
574 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
577 if (hTheme)
578 CloseThemeData(hTheme);
580 W_Dc.Detach();
583 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
585 for (unsigned int i = 0; i < refList.size(); ++i)
587 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
588 HBRUSH brush = 0;
589 COLORREF colRef = refList[i].color;
590 bool singleRemote = refList[i].singleRemote;
591 bool hasTracking = refList[i].hasTracking;
592 CGit::REF_TYPE refType = refList[i].refType;
594 //When row selected, ajust label color
595 if (!IsAppThemed())
597 if (rItem.state & LVIS_SELECTED)
598 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
601 brush = ::CreateSolidBrush(colRef);
603 if (!shortname.IsEmpty() && (rt.left < rect.right))
605 SIZE size = { 0 };
606 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
608 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
609 rt.right += 8;
611 int textpos = DT_CENTER;
613 if (rt.right > rect.right)
615 rt.right = rect.right;
616 textpos = 0;
619 CRect textRect = rt;
621 if (singleRemote)
623 rt.right += 5;
624 textRect.OffsetRect(5, 0);
627 if (hasTracking)
628 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
629 else
631 //Fill interior of ref label
632 ::FillRect(hdc, &rt, brush);
635 //Draw edge of label
636 CRect rectEdge = rt;
638 if (!hasTracking)
640 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
641 rectEdge.DeflateRect(1, 1);
642 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
645 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
647 rt.right += 8;
648 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
649 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
650 ::FillRgn(hdc, hrgn, brush);
651 ::DeleteObject(hrgn);
652 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
653 HPEN pen;
654 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
655 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
656 ::DeleteObject(pen);
657 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
658 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
659 ::DeleteObject(pen);
660 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
661 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
662 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
663 ::DeleteObject(pen);
664 SelectObject(hdc, oldpen);
667 //Draw text inside label
668 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
669 if (!customColor && IsAppThemed())
671 int txtState = LISS_NORMAL;
672 if (rItem.state & LVIS_SELECTED)
673 txtState = LISS_SELECTED;
675 DTTOPTS opts = { 0 };
676 opts.dwSize = sizeof(opts);
677 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
678 opts.dwFlags = DTT_TEXTCOLOR;
679 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
681 else
683 W_Dc.SetBkMode(TRANSPARENT);
684 if (customColor || (rItem.state & LVIS_SELECTED))
686 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
687 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
688 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
689 ::SetTextColor(hdc,clrOld);
691 else
693 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
694 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
695 ::SetTextColor(hdc, clrOld);
699 if (singleRemote)
701 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
702 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
703 CRect newRect;
704 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
705 DrawUpstream(hdc, newRect, color, bold);
708 if (!refList[i].fullName.IsEmpty())
709 m_RefLabelPosMap[refList[i].fullName] = rt;
711 rt.left = rt.right + 1;
713 if (brush)
714 ::DeleteObject(brush);
716 rt.right = rect.right;
719 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
720 // Returns ((256 - amount)*col1 + amount*col2) / 256;
721 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
722 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
723 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
726 Gdiplus::Color GetGdiColor(COLORREF col)
728 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
730 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
731 const COLORREF& col,const COLORREF& activeColor, int top
734 int h = laneHeight / 2;
735 int m = (x1 + x2) / 2;
736 int r = (x2 - x1) * m_NodeSize / 30;
737 int d = 2 * r;
739 #define P_CENTER m , h+top
740 #define P_0 x2, h+top
741 #define P_90 m , 0+top-1
742 #define P_180 x1, h+top
743 #define P_270 m , 2 * h+top +1
744 #define R_CENTER m - r, h - r+top, d, d
747 #define DELTA_UR_B 2*(x1 - m), 2*h +top
748 #define DELTA_UR_E 0*16, 90*16 +top // -,
750 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
751 #define DELTA_DR_E 270*16, 90*16 +top // -'
753 #define DELTA_UL_B 2*(x2 - m), 2*h +top
754 #define DELTA_UL_E 90*16, 90*16 +top // ,-
756 #define DELTA_DL_B 2*(x2 - m),2*-h +top
757 #define DELTA_DL_E 180*16, 90*16 // '-
759 #define CENTER_UR x1, 2*h, 225
760 #define CENTER_DR x1, 0 , 135
761 #define CENTER_UL x2, 2*h, 315
762 #define CENTER_DL x2, 0 , 45
765 Gdiplus::Graphics graphics( hdc );
767 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
769 // arc
770 switch (type) {
771 case Lanes::JOIN:
772 case Lanes::JOIN_R:
773 case Lanes::HEAD:
774 case Lanes::HEAD_R:
776 Gdiplus::LinearGradientBrush gradient(
777 Gdiplus::Point(x1-2, h+top-2),
778 Gdiplus::Point(P_270),
779 GetGdiColor(activeColor),GetGdiColor(col));
782 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
783 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
785 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
786 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
787 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
789 break;
791 case Lanes::JOIN_L:
793 Gdiplus::LinearGradientBrush gradient(
794 Gdiplus::Point(P_270),
795 Gdiplus::Point(x2+1, h+top-1),
796 GetGdiColor(col),GetGdiColor(activeColor));
799 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
800 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
802 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
803 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
804 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
807 break;
809 case Lanes::TAIL:
810 case Lanes::TAIL_R:
812 Gdiplus::LinearGradientBrush gradient(
813 Gdiplus::Point(x1-2, h+top-2),
814 Gdiplus::Point(P_90),
815 GetGdiColor(activeColor),GetGdiColor(col));
817 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
819 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
821 #if 0
822 QConicalGradient gradient(CENTER_DR);
823 gradient.setColorAt(0.375, activeCol);
824 gradient.setColorAt(0.625, col);
825 myPen.setBrush(gradient);
826 p->setPen(myPen);
827 p->drawArc(P_CENTER, DELTA_DR);
828 #endif
829 break;
831 default:
832 break;
836 //static QPen myPen(Qt::black, 2); // fast path here
837 CPen pen;
838 pen.CreatePen(PS_SOLID,2,col);
839 //myPen.setColor(col);
840 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
842 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
844 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
846 //p->setPen(myPen);
848 // vertical line
849 switch (type) {
850 case Lanes::ACTIVE:
851 case Lanes::NOT_ACTIVE:
852 case Lanes::MERGE_FORK:
853 case Lanes::MERGE_FORK_R:
854 case Lanes::MERGE_FORK_L:
855 case Lanes::JOIN:
856 case Lanes::JOIN_R:
857 case Lanes::JOIN_L:
858 case Lanes::CROSS:
859 //DrawLine(hdc,P_90,P_270);
860 graphics.DrawLine(&myPen,P_90,P_270);
861 //p->drawLine(P_90, P_270);
862 break;
863 case Lanes::HEAD_L:
864 case Lanes::BRANCH:
865 //DrawLine(hdc,P_CENTER,P_270);
866 graphics.DrawLine(&myPen,P_CENTER,P_270);
867 //p->drawLine(P_CENTER, P_270);
868 break;
869 case Lanes::TAIL_L:
870 case Lanes::INITIAL:
871 case Lanes::MERGE_FORK_L_INITIAL:
872 case Lanes::BOUNDARY:
873 case Lanes::BOUNDARY_C:
874 case Lanes::BOUNDARY_R:
875 case Lanes::BOUNDARY_L:
876 //DrawLine(hdc,P_90, P_CENTER);
877 graphics.DrawLine(&myPen,P_90,P_CENTER);
878 //p->drawLine(P_90, P_CENTER);
879 break;
880 default:
881 break;
884 myPen.SetColor(GetGdiColor(activeColor));
886 // horizontal line
887 switch (type) {
888 case Lanes::MERGE_FORK:
889 case Lanes::JOIN:
890 case Lanes::HEAD:
891 case Lanes::TAIL:
892 case Lanes::CROSS:
893 case Lanes::CROSS_EMPTY:
894 case Lanes::BOUNDARY_C:
895 //DrawLine(hdc,P_180,P_0);
896 graphics.DrawLine(&myPen,P_180,P_0);
897 //p->drawLine(P_180, P_0);
898 break;
899 case Lanes::MERGE_FORK_R:
900 case Lanes::BOUNDARY_R:
901 //DrawLine(hdc,P_180,P_CENTER);
902 graphics.DrawLine(&myPen,P_180,P_CENTER);
903 //p->drawLine(P_180, P_CENTER);
904 break;
905 case Lanes::MERGE_FORK_L:
906 case Lanes::MERGE_FORK_L_INITIAL:
907 case Lanes::HEAD_L:
908 case Lanes::TAIL_L:
909 case Lanes::BOUNDARY_L:
910 //DrawLine(hdc,P_CENTER,P_0);
911 graphics.DrawLine(&myPen,P_CENTER,P_0);
912 //p->drawLine(P_CENTER, P_0);
913 break;
914 default:
915 break;
918 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
920 CBrush brush;
921 brush.CreateSolidBrush(col);
922 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
924 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
925 // center symbol, e.g. rect or ellipse
926 switch (type) {
927 case Lanes::ACTIVE:
928 case Lanes::INITIAL:
929 case Lanes::BRANCH:
931 //p->setPen(Qt::NoPen);
932 //p->setBrush(col);
933 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
934 graphics.FillEllipse(&myBrush, R_CENTER);
935 //p->drawEllipse(R_CENTER);
936 break;
937 case Lanes::MERGE_FORK:
938 case Lanes::MERGE_FORK_R:
939 case Lanes::MERGE_FORK_L:
940 case Lanes::MERGE_FORK_L_INITIAL:
941 //p->setPen(Qt::NoPen);
942 //p->setBrush(col);
943 //p->drawRect(R_CENTER);
944 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
945 graphics.FillRectangle(&myBrush, R_CENTER);
946 break;
947 case Lanes::UNAPPLIED:
948 // Red minus sign
949 //p->setPen(Qt::NoPen);
950 //p->setBrush(Qt::red);
951 //p->drawRect(m - r, h - 1, d, 2);
952 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
953 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
954 break;
955 case Lanes::APPLIED:
956 // Green plus sign
957 //p->setPen(Qt::NoPen);
958 //p->setBrush(DARK_GREEN);
959 //p->drawRect(m - r, h - 1, d, 2);
960 //p->drawRect(m - 1, h - r, 2, d);
961 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
962 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
963 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
964 break;
965 case Lanes::BOUNDARY:
966 //p->setBrush(back);
967 //p->drawEllipse(R_CENTER);
968 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
969 graphics.DrawEllipse(&myPen, R_CENTER);
970 break;
971 case Lanes::BOUNDARY_C:
972 case Lanes::BOUNDARY_R:
973 case Lanes::BOUNDARY_L:
974 //p->setBrush(back);
975 //p->drawRect(R_CENTER);
976 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
977 graphics.FillRectangle(&myBrush,R_CENTER);
978 break;
979 default:
980 break;
983 ::SelectObject(hdc,oldpen);
984 ::SelectObject(hdc,oldbrush);
985 #undef P_CENTER
986 #undef P_0
987 #undef P_90
988 #undef P_180
989 #undef P_270
990 #undef R_CENTER
993 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
995 // TODO: unfinished
996 // return;
997 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
998 if(data->m_CommitHash.IsEmpty())
999 return;
1001 CRect rt=rect;
1002 LVITEM rItem = { 0 };
1003 rItem.mask = LVIF_STATE;
1004 rItem.iItem = (int)index;
1005 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1006 GetItem(&rItem);
1008 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1010 if (data->m_Lanes.empty())
1011 m_logEntries.setLane(data->m_CommitHash);
1013 std::vector<int>& lanes=data->m_Lanes;
1014 size_t laneNum = lanes.size();
1015 UINT activeLane = 0;
1016 for (UINT i = 0; i < laneNum; ++i)
1017 if (Lanes::isMerge(lanes[i])) {
1018 activeLane = i;
1019 break;
1022 int x2 = 0;
1023 int maxWidth = rect.Width();
1024 int lw = 3 * rect.Height() / 4; //laneWidth()
1026 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1027 //if (opt.state & QStyle::State_Selected)
1028 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1030 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1032 int x1 = x2;
1033 x2 += lw;
1035 int ln = lanes[i];
1036 if (ln == Lanes::EMPTY)
1037 continue;
1039 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1040 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1043 #if 0
1044 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1045 int x1 = x2;
1046 x2 += lw;
1048 int ln = lanes[i];
1049 if (ln == Lanes::EMPTY)
1050 continue;
1052 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1053 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1055 if (ln == Lanes::CROSS)
1057 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1058 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1060 else
1061 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1063 #endif
1066 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1068 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1069 // Take the default processing unless we set this to something else below.
1070 *pResult = CDRF_DODEFAULT;
1072 if (m_bNoDispUpdates)
1073 return;
1075 switch (pLVCD->nmcd.dwDrawStage)
1077 case CDDS_PREPAINT:
1079 *pResult = CDRF_NOTIFYITEMDRAW;
1080 return;
1082 break;
1083 case CDDS_ITEMPREPAINT:
1085 // This is the prepaint stage for an item. Here's where we set the
1086 // item's text color.
1088 // Tell Windows to send draw notifications for each subitem.
1089 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1091 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1093 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1095 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1096 if (data)
1098 HGDIOBJ hGdiObj = nullptr;
1099 int action = data->GetRebaseAction();
1100 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1101 crText = RGB(128,128,128);
1103 if (action & LOGACTIONS_REBASE_SQUASH)
1104 pLVCD->clrTextBk = RGB(156,156,156);
1105 else if (action & LOGACTIONS_REBASE_EDIT)
1106 pLVCD->clrTextBk = RGB(200,200,128);
1107 else
1108 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1110 if (action & LOGACTIONS_REBASE_CURRENT)
1111 hGdiObj = m_boldFont.GetSafeHandle();
1113 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1114 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1115 if (isHeadHash && isHighlight)
1116 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1117 else if (isHeadHash)
1118 hGdiObj = m_boldFont.GetSafeHandle();
1119 else if (isHighlight)
1120 hGdiObj = m_FontItalics.GetSafeHandle();
1122 if (hGdiObj)
1124 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1125 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1128 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1129 // crText = GetSysColor(COLOR_GRAYTEXT);
1131 if (data->m_CommitHash.IsEmpty())
1133 //crText = GetSysColor(RGB(200,200,0));
1134 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1135 // We changed the font, so we're returning CDRF_NEWFONT. This
1136 // tells the control to recalculate the extent of the text.
1137 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1141 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1143 if (m_bStrictStopped)
1144 crText = GetSysColor(COLOR_GRAYTEXT);
1146 // Store the color back in the NMLVCUSTOMDRAW struct.
1147 pLVCD->clrText = crText;
1148 return;
1150 break;
1151 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1153 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1155 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1158 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1160 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1162 CRect rect;
1163 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1165 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1166 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1168 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1169 if( !data ->m_CommitHash.IsEmpty())
1170 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1172 *pResult = CDRF_SKIPDEFAULT;
1173 return;
1177 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1179 // If the top index of list is changed, the position map of reference label is outdated.
1180 if (m_OldTopIndex != GetTopIndex())
1182 m_OldTopIndex = GetTopIndex();
1183 m_RefLabelPosMap.clear();
1186 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1188 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1190 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1192 CRect rect;
1193 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1195 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1196 // not in FillBackGround method, because this only affected the message subitem
1197 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1198 return;
1200 int index = (int)pLVCD->nmcd.dwItemSpec;
1201 int state = GetItemState(index, LVIS_SELECTED);
1202 int txtState = LISS_NORMAL;
1203 if (IsAppThemed() && GetHotItem() == (int)index)
1205 if (state & LVIS_SELECTED)
1206 txtState = LISS_HOTSELECTED;
1207 else
1208 txtState = LISS_HOT;
1210 else if (state & LVIS_SELECTED)
1212 if (::GetFocus() == m_hWnd)
1213 txtState = LISS_SELECTED;
1214 else
1215 txtState = LISS_SELECTEDNOTFOCUS;
1218 HTHEME hTheme = nullptr;
1219 if (IsAppThemed())
1220 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1222 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1223 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1224 else
1226 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1227 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1228 ::DeleteObject(brush);
1230 if (hTheme && txtState != LISS_NORMAL)
1232 CRect rt;
1233 // get rect of whole line
1234 GetItemRect(index, rt, LVIR_BOUNDS);
1235 CRect rect2 = rect;
1237 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1238 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1240 CloseThemeData(hTheme);
1242 // END: extended redraw
1244 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1246 std::vector<REFLABEL> refsToShow;
1247 STRING_VECTOR remoteTrackingList;
1248 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1249 for (unsigned int i = 0; i < refList.size(); ++i)
1251 CString str = refList[i];
1253 REFLABEL refLabel;
1254 refLabel.color = RGB(255, 255, 255);
1255 refLabel.singleRemote = false;
1256 refLabel.hasTracking = false;
1257 refLabel.sameName = false;
1258 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1259 refLabel.fullName = str;
1261 switch (refLabel.refType)
1263 case CGit::REF_TYPE::LOCAL_BRANCH:
1265 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1266 continue;
1267 if (refLabel.name == m_CurrentBranch)
1268 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1269 else
1270 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1272 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1273 CString pullRemote = trackingEntry.first;
1274 CString pullBranch = trackingEntry.second;
1275 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1277 CString defaultUpstream;
1278 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1279 refLabel.hasTracking = true;
1280 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1282 bool found = false;
1283 for (size_t j = i + 1; j < refList.size(); ++j)
1285 if (refList[j] == defaultUpstream)
1287 found = true;
1288 break;
1292 if (found)
1294 bool sameName = pullBranch == refLabel.name;
1295 refsToShow.push_back(refLabel);
1296 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1297 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1298 if (m_bSymbolizeRefNames)
1300 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1302 refLabel.simplifiedName = L'/';
1303 if (sameName)
1304 refLabel.simplifiedName += L'≡';
1305 else
1306 refLabel.simplifiedName += pullBranch;
1307 refLabel.singleRemote = true;
1309 else if (sameName)
1310 refLabel.simplifiedName = pullRemote + L"/≡";
1311 refLabel.sameName = sameName;
1313 refLabel.fullName = defaultUpstream;
1314 refsToShow.push_back(refLabel);
1315 remoteTrackingList.push_back(defaultUpstream);
1316 continue;
1320 break;
1322 case CGit::REF_TYPE::REMOTE_BRANCH:
1324 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1325 continue;
1326 bool found = false;
1327 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1329 if (remoteTrackingList[j] == str)
1331 found = true;
1332 break;
1335 if (found)
1336 continue;
1338 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1339 if (m_bSymbolizeRefNames)
1341 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1343 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1344 refLabel.singleRemote = true;
1347 break;
1349 case CGit::REF_TYPE::ANNOTATED_TAG:
1350 case CGit::REF_TYPE::TAG:
1351 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1352 continue;
1353 refLabel.color = m_Colors.GetColor(CColors::Tag);
1354 break;
1355 case CGit::REF_TYPE::STASH:
1356 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1357 continue;
1358 refLabel.color = m_Colors.GetColor(CColors::Stash);
1359 break;
1360 case CGit::REF_TYPE::BISECT_GOOD:
1361 case CGit::REF_TYPE::BISECT_BAD:
1362 case CGit::REF_TYPE::BISECT_SKIP:
1363 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1364 continue;
1365 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));
1366 break;
1367 default:
1368 continue;
1370 refsToShow.push_back(refLabel);
1372 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1374 REFLABEL refLabel;
1375 refLabel.color = RGB(246, 153, 253);
1376 refLabel.singleRemote = false;
1377 refLabel.hasTracking = false;
1378 refLabel.sameName = false;
1379 refLabel.name = L"super-project-pointer";
1380 refLabel.fullName = "";
1381 refsToShow.push_back(refLabel);
1384 if (refsToShow.empty())
1386 *pResult = CDRF_DODEFAULT;
1387 return;
1390 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1392 *pResult = CDRF_SKIPDEFAULT;
1393 return;
1400 if (pLVCD->iSubItem == LOGLIST_ACTION)
1402 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1404 *pResult = CDRF_DODEFAULT;
1405 return;
1407 *pResult = CDRF_DODEFAULT;
1409 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1410 return;
1412 int nIcons = 0;
1413 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1414 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1416 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1417 CRect rect;
1418 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1419 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1420 // Get the selected state of the
1421 // item being drawn.
1423 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1424 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1426 // Fill the background if necessary
1427 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1429 // Draw the icon(s) into the compatible DC
1430 int action = pLogEntry->GetAction(this);
1431 if (!pLogEntry->m_IsDiffFiles)
1433 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1434 *pResult = CDRF_SKIPDEFAULT;
1435 return;
1438 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1439 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1440 ++nIcons;
1442 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1443 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1444 ++nIcons;
1446 if (action & CTGitPath::LOGACTIONS_DELETED)
1447 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1448 ++nIcons;
1450 if (action & CTGitPath::LOGACTIONS_REPLACED)
1451 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1452 ++nIcons;
1454 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1455 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1456 ++nIcons;
1458 *pResult = CDRF_SKIPDEFAULT;
1459 return;
1462 break;
1464 *pResult = CDRF_DODEFAULT;
1467 CString FindSVNRev(const CString& msg)
1471 const std::tr1::wsregex_iterator end;
1472 std::wstring s = msg;
1473 std::tr1::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1474 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1476 const std::tr1::wsmatch match = *it;
1477 if (match.size() == 4)
1479 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1480 return std::wstring(match[2]).c_str();
1483 std::tr1::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1484 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1486 const std::tr1::wsmatch match = *it;
1487 if (match.size() == 3)
1489 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1490 return std::wstring(match[1]).c_str();
1494 catch (std::exception&) {}
1496 return L"";
1499 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1501 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1502 return pLogEntry->GetSubject();
1504 CString txt(pLogEntry->GetSubject());
1505 txt += L' ';
1506 txt += pLogEntry->GetBody();
1508 // Deal with CRLF
1509 txt.Replace(L'\n', L' ');
1510 txt.Replace(L'\r', L' ');
1512 return txt;
1515 // CGitLogListBase message handlers
1517 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1519 struct payload_struct { const CString* name; const char* authorName; };
1520 payload_struct payload = { &name, nullptr };
1521 const char* author1 = nullptr;
1522 const char* email1 = nullptr;
1523 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1524 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1525 free((void *)payload.authorName);
1526 if (returnEmail)
1527 return email1;
1528 return author1;
1531 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1533 if (mailmap)
1535 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1536 if (translated)
1538 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1539 return;
1542 if (returnEmail)
1543 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1544 else
1545 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1548 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1550 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1552 // Create a pointer to the item
1553 LV_ITEM* pItem = &(pDispInfo)->item;
1555 // Do the list need text information?
1556 if (!(pItem->mask & LVIF_TEXT))
1557 return;
1559 // By default, clear text buffer.
1560 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1562 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1564 *pResult = 0;
1565 if (m_bNoDispUpdates || bOutOfRange)
1566 return;
1568 // Which item number?
1569 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1571 CString temp;
1572 if(m_IsOldFirst)
1573 temp.Format(L"%d", pItem->iItem + 1);
1574 else
1575 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1577 if (!pLogEntry)
1578 return;
1580 // Which column?
1581 switch (pItem->iSubItem)
1583 case LOGLIST_GRAPH: //Graphic
1584 break;
1585 case LOGLIST_REBASE:
1586 if (m_IsRebaseReplaceGraph)
1587 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1588 break;
1589 case LOGLIST_ACTION: //action -- no text in the column
1590 break;
1591 case LOGLIST_HASH:
1592 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1593 break;
1594 case LOGLIST_ID:
1595 if (this->m_IsIDReplaceAction)
1596 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1597 break;
1598 case LOGLIST_MESSAGE: //Message
1599 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1600 break;
1601 case LOGLIST_AUTHOR: //Author
1602 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1603 break;
1604 case LOGLIST_DATE: //Date
1605 if (!pLogEntry->m_CommitHash.IsEmpty())
1606 lstrcpyn(pItem->pszText,
1607 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1608 pItem->cchTextMax - 1);
1609 break;
1611 case LOGLIST_EMAIL:
1612 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1613 break;
1615 case LOGLIST_COMMIT_NAME: //Commit
1616 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1617 break;
1619 case LOGLIST_COMMIT_EMAIL: //Commit Email
1620 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1621 break;
1623 case LOGLIST_COMMIT_DATE: //Commit Date
1624 if (!pLogEntry->m_CommitHash.IsEmpty())
1625 lstrcpyn(pItem->pszText,
1626 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1627 pItem->cchTextMax - 1);
1628 break;
1629 case LOGLIST_BUG: //Bug ID
1630 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1631 break;
1632 case LOGLIST_SVNREV: //SVN revision
1633 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1634 break;
1636 default:
1637 ASSERT(false);
1641 bool CGitLogListBase::IsOnStash(int index)
1643 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1644 if (IsStash(rev))
1645 return true;
1646 if (index > 0)
1648 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1649 if (IsStash(preRev))
1650 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1652 return false;
1655 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1657 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1658 if (refList == m_HashMap.cend())
1659 return false;
1660 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1663 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1665 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1666 if (refList == m_HashMap.cend())
1667 return false;
1668 return find_if((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1671 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1673 if (pRev->m_ParentHash.empty())
1675 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1676 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1678 parentHash = pRev->m_ParentHash;
1681 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1683 __super::OnContextMenu(pWnd, point);
1685 if (pWnd != this)
1686 return;
1688 int selIndex = GetSelectionMark();
1689 if (selIndex < 0)
1690 return; // nothing selected, nothing to do with a context menu
1692 // if the user selected the info text telling about not all revisions shown due to
1693 // the "stop on copy/rename" option, we also don't show the context menu
1694 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1695 return;
1697 // if the context menu is invoked through the keyboard, we have to use
1698 // a calculated position on where to anchor the menu on
1699 if ((point.x == -1) && (point.y == -1))
1701 CRect rect;
1702 GetItemRect(selIndex, &rect, LVIR_LABEL);
1703 ClientToScreen(&rect);
1704 point = rect.CenterPoint();
1706 m_nSearchIndex = selIndex;
1707 m_bCancelled = FALSE;
1709 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1711 POSITION pos = GetFirstSelectedItemPosition();
1712 int FirstSelect = GetNextSelectedItem(pos);
1713 if (FirstSelect < 0)
1714 return;
1716 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1717 if (pSelLogEntry == nullptr)
1718 return;
1720 int LastSelect = -1;
1721 UINT selectedCount = 1;
1722 while (pos)
1724 LastSelect = GetNextSelectedItem(pos);
1725 ++selectedCount;
1728 ASSERT(GetSelectedCount() == selectedCount);
1730 #if 0
1731 GitRev revSelected = pSelLogEntry->Rev;
1732 GitRev revPrevious = git_revnum_t(revSelected)-1;
1733 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1735 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1737 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1738 if (changedpath->lCopyFromRev)
1739 revPrevious = changedpath->lCopyFromRev;
1742 GitRev revSelected2;
1743 if (pos)
1745 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1746 revSelected2 = pLogEntry->Rev;
1748 bool bAllFromTheSameAuthor = true;
1749 CString firstAuthor;
1750 CLogDataVector selEntries;
1751 GitRev revLowest, revHighest;
1752 GitRevRangeArray revisionRanges;
1754 POSITION pos = GetFirstSelectedItemPosition();
1755 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1756 revisionRanges.AddRevision(pLogEntry->Rev);
1757 selEntries.push_back(pLogEntry);
1758 firstAuthor = pLogEntry->sAuthor;
1759 revLowest = pLogEntry->Rev;
1760 revHighest = pLogEntry->Rev;
1761 while (pos)
1763 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1764 revisionRanges.AddRevision(pLogEntry->Rev);
1765 selEntries.push_back(pLogEntry);
1766 if (firstAuthor.Compare(pLogEntry->sAuthor))
1767 bAllFromTheSameAuthor = false;
1768 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1769 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1773 #endif
1775 //entry is selected, now show the popup menu
1776 CIconMenu popup;
1777 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1779 if (popup.CreatePopupMenu())
1781 bool isHeadCommit = (pSelLogEntry->m_CommitHash == m_HeadHash);
1782 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1783 CTGitPath workingTree(g_Git.m_CurrentDir);
1784 bool isMergeActive = workingTree.IsMergeActive();
1785 bool isBisectActive = workingTree.IsBisectActive();
1786 bool isStash = IsOnStash(FirstSelect);
1787 GIT_REV_LIST parentHash;
1788 GetParentHashes(pSelLogEntry, parentHash);
1790 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1791 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1793 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))
1794 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1796 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1797 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1799 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1800 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1802 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)))
1803 popup.AppendMenu(MF_SEPARATOR, NULL);
1805 if (selectedCount == 1)
1808 bool requiresSeparator = false;
1809 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1811 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1813 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1814 requiresSeparator = true;
1817 else
1819 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1821 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1822 requiresSeparator = true;
1824 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1826 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1827 requiresSeparator = true;
1831 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1833 if (parentHash.size() == 1)
1835 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1836 requiresSeparator = true;
1838 else if (parentHash.size() > 1)
1840 blamemenu.CreatePopupMenu();
1841 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1842 for (size_t i = 0; i < parentHash.size(); ++i)
1844 CString str;
1845 str.Format(IDS_PARENT, i + 1);
1846 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1848 requiresSeparator = true;
1852 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1854 if (parentHash.size() == 1)
1856 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1857 requiresSeparator = true;
1859 else if (parentHash.size() > 1)
1861 gnudiffmenu.CreatePopupMenu();
1862 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1864 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1865 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1866 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1868 for (size_t i = 0; i < parentHash.size(); ++i)
1870 CString str;
1871 str.Format(IDS_PARENT, i + 1);
1872 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1874 requiresSeparator = true;
1878 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1880 if (parentHash.size() == 1)
1882 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1883 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1884 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1885 requiresSeparator = true;
1887 else if (parentHash.size() > 1)
1889 diffmenu.CreatePopupMenu();
1890 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1891 for (size_t i = 0; i < parentHash.size(); ++i)
1893 CString str;
1894 str.Format(IDS_PARENT, i + 1);
1895 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1896 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1898 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1899 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1902 requiresSeparator = true;
1906 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1908 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1909 requiresSeparator = true;
1912 if (requiresSeparator)
1914 popup.AppendMenu(MF_SEPARATOR, NULL);
1915 requiresSeparator = false;
1918 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1920 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1922 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1923 requiresSeparator = true;
1927 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1929 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1931 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1932 requiresSeparator = true;
1935 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1937 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1938 requiresSeparator = true;
1942 if (requiresSeparator)
1944 popup.AppendMenu(MF_SEPARATOR, NULL);
1945 requiresSeparator = false;
1948 if (isBisectActive)
1950 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1951 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1953 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1954 requiresSeparator = true;
1957 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1959 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1960 requiresSeparator = true;
1962 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1964 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1965 requiresSeparator = true;
1969 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1971 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1973 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1974 requiresSeparator = true;
1978 if (requiresSeparator)
1980 popup.AppendMenu(MF_SEPARATOR, NULL);
1981 requiresSeparator = false;
1984 if (pSelLogEntry->m_CommitHash.IsEmpty())
1986 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
1987 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
1989 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
1990 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
1992 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
1993 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
1995 popup.AppendMenu(MF_SEPARATOR, NULL);
1997 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
1998 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2000 popup.AppendMenu(MF_SEPARATOR, NULL);
2004 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2005 // {
2006 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2007 // }
2008 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2009 // {
2010 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2011 // }
2012 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2013 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2014 // {
2015 // popup.AppendMenu(MF_SEPARATOR, NULL);
2016 // }
2018 CString str;
2019 //if (m_hasWC)
2020 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2022 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2024 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2025 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2027 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2028 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2030 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2032 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2034 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2036 size_t index = (size_t)-1;
2037 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2038 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2039 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2042 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2044 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2045 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2048 // Add Switch Branch express Menu
2049 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2050 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2053 std::vector<const CString*> branchs;
2054 auto addCheck = [&](const CString& ref)
2056 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2057 return;
2058 branchs.push_back(&ref);
2060 size_t index = (size_t)-1;
2061 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2062 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2063 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2064 else
2065 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2067 CString str2;
2068 str2.LoadString(IDS_SWITCH_BRANCH);
2070 if(branchs.size() == 1)
2072 str2 += L' ';
2073 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2074 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2076 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2079 else if(branchs.size() > 1)
2081 subbranchmenu.CreatePopupMenu();
2082 for (size_t i = 0 ; i < branchs.size(); ++i)
2084 if (*branchs[i] != currentBranch)
2086 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2087 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2091 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2095 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2097 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2098 size_t index = (size_t)-1;
2099 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2100 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2101 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2104 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2106 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2108 size_t index = (size_t)-1;
2109 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2110 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2111 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2114 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2115 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2117 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2119 if (pSelLogEntry->m_CommitHash != m_HeadHash && m_hasWC && !isMergeActive && !isStash)
2120 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2121 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2123 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2124 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2126 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2128 if (parentHash.size() == 1)
2129 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2130 else if (parentHash.size() > 1)
2132 revertmenu.CreatePopupMenu();
2133 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2135 for (size_t i = 0; i < parentHash.size(); ++i)
2137 CString str2;
2138 str2.Format(IDS_PARENT, i + 1);
2139 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2144 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2145 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2147 popup.AppendMenu(MF_SEPARATOR, NULL);
2151 if(!pSelLogEntry->m_Ref.IsEmpty())
2153 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2154 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2155 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2156 if (selectedCount <= 2)
2157 popup.AppendMenu(MF_SEPARATOR, NULL);
2160 if (selectedCount >= 2)
2162 bool bAddSeparator = false;
2163 if ((selectedCount == 2) || IsSelectionContinuous())
2165 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2167 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2168 bAddSeparator = true;
2172 if (selectedCount == 2)
2174 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2176 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2177 bAddSeparator = true;
2180 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2182 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2183 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2184 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2185 CString menu;
2186 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2187 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2188 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2189 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2190 bAddSeparator = true;
2194 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2196 bAddSeparator = true;
2197 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2200 if (bAddSeparator)
2202 popup.AppendMenu(MF_SEPARATOR, NULL);
2203 bAddSeparator = false;
2206 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2207 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2209 if (bAddSeparator)
2210 popup.AppendMenu(MF_SEPARATOR, NULL);
2213 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2215 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2216 popup.AppendMenu(MF_SEPARATOR, NULL);
2219 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2221 bool bAddSeparator = false;
2222 if (selectedCount >= 2 && IsSelectionContinuous())
2224 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2226 CString head;
2227 int headindex;
2228 headindex = this->GetHeadIndex();
2229 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2231 head.Format(L"HEAD~%d", FirstSelect - headindex);
2232 CGitHash hashFirst;
2233 int ret = g_Git.GetHash(hashFirst, head);
2234 head.Format(L"HEAD~%d",LastSelect-headindex);
2235 CGitHash hash;
2236 ret = ret || g_Git.GetHash(hash, head);
2237 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2238 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2239 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2241 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2242 bAddSeparator = true;
2247 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2248 if (selectedCount >= 2)
2249 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2250 else
2251 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2252 bAddSeparator = true;
2255 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2256 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2257 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2258 bAddSeparator = true;
2261 if (bAddSeparator)
2262 popup.AppendMenu(MF_SEPARATOR, NULL);
2265 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2267 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2268 popup.AppendMenu(MF_SEPARATOR, NULL);
2271 if (selectedCount == 1)
2273 bool bAddSeparator = false;
2274 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2276 // show the push-option only if the log entry has an associated local branch
2277 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2278 if (isLocal || showExtendedMenu)
2280 CString str;
2281 str.LoadString(IDS_MENUPUSH);
2283 CString branch;
2284 size_t index = (size_t)-1;
2285 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2286 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2287 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2288 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2290 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2292 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2293 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2295 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2296 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2298 bAddSeparator = true;
2301 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2303 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2304 bAddSeparator = true;
2308 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2310 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2312 std::vector<const CString*> branchs;
2313 auto addCheck = [&](const CString& ref)
2315 if (ref == currentBranch)
2316 return;
2317 branchs.push_back(&ref);
2319 size_t index = (size_t)-1;
2320 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2321 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2322 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2323 else
2324 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2326 CString str;
2327 if (branchs.size() == 1)
2329 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2330 str += L' ';
2331 str += *branchs[0];
2332 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2333 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2334 bAddSeparator = true;
2336 else if (branchs.size() > 1)
2338 str.LoadString(IDS_DELETE_BRANCHTAG);
2339 submenu.CreatePopupMenu();
2340 for (size_t i = 0; i < branchs.size(); ++i)
2342 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2343 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2345 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2346 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2348 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2349 bAddSeparator = true;
2352 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2353 if (bAddSeparator)
2354 popup.AppendMenu(MF_SEPARATOR, NULL);
2355 } // selectedCount == 1
2357 CIconMenu clipSubMenu;
2358 if (!clipSubMenu.CreatePopupMenu())
2359 return;
2360 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2362 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2363 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2364 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2365 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2366 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2367 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2368 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2369 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2370 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2372 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2373 size_t index = (size_t)-1;
2374 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2375 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2376 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2379 CString temp;
2380 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2381 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2384 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2385 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2387 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2388 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2390 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2391 // DialogEnableWindow(IDOK, FALSE);
2392 // SetPromptApp(&theApp);
2394 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2396 // EnableOKButton();
2397 } // if (popup.CreatePopupMenu())
2400 bool CGitLogListBase::IsSelectionContinuous()
2402 if ( GetSelectedCount()==1 )
2404 // if only one revision is selected, the selection is of course
2405 // continuous
2406 return true;
2409 POSITION pos = GetFirstSelectedItemPosition();
2410 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2411 if (bContinuous)
2413 int itemindex = GetNextSelectedItem(pos);
2414 while (pos)
2416 int nextindex = GetNextSelectedItem(pos);
2417 if (nextindex - itemindex > 1)
2419 bContinuous = false;
2420 break;
2422 itemindex = nextindex;
2425 return bContinuous;
2428 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2430 CString sClipdata;
2431 POSITION pos = GetFirstSelectedItemPosition();
2432 if (pos)
2434 CString sRev;
2435 sRev.LoadString(IDS_LOG_REVISION);
2436 CString sAuthor;
2437 sAuthor.LoadString(IDS_LOG_AUTHOR);
2438 CString sDate;
2439 sDate.LoadString(IDS_LOG_DATE);
2440 CString sMessage;
2441 sMessage.LoadString(IDS_LOG_MESSAGE);
2442 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2443 bool first = true;
2444 while (pos)
2446 CString sLogCopyText;
2447 CString sPaths;
2448 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2450 if (toCopy == ID_COPYCLIPBOARDFULL)
2452 sPaths = L"----\r\n";
2453 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2455 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2456 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2458 sPaths += L' ';
2459 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2461 sPaths += L"\r\n";
2463 sPaths.Trim();
2464 sPaths += L"\r\n";
2467 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2469 CString sNotesTags;
2470 if (!pLogEntry->m_Notes.IsEmpty())
2472 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2473 sNotesTags += L":\n";
2474 sNotesTags += pLogEntry->m_Notes;
2475 sNotesTags.Replace(L"\n", L"\r\n");
2477 CString tagInfo = GetTagInfo(pLogEntry);
2478 if (!tagInfo.IsEmpty())
2480 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2481 tagInfo.Replace(L"\n", L"\r\n");
2482 sNotesTags += tagInfo;
2485 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s%s\r\n",
2486 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2487 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2488 (LPCTSTR)sDate,
2489 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2490 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2491 (LPCTSTR)sNotesTags,
2492 (LPCTSTR)sPaths);
2493 sClipdata += sLogCopyText;
2495 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2497 if (!first)
2498 sClipdata += L"\r\n";
2499 sClipdata += pLogEntry->GetAuthorName();
2500 sClipdata += L" <";
2501 sClipdata += pLogEntry->GetAuthorEmail();
2502 sClipdata += L">";
2504 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2506 if (!first)
2507 sClipdata += L"\r\n";
2508 sClipdata += pLogEntry->GetAuthorName();
2510 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2512 if (!first)
2513 sClipdata += L"\r\n";
2514 sClipdata += pLogEntry->GetAuthorEmail();
2517 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2519 sClipdata += L"* ";
2520 sClipdata += pLogEntry->GetSubjectBody(true);
2521 sClipdata += L"\r\n\r\n";
2523 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2525 sClipdata += L"* ";
2526 sClipdata += pLogEntry->GetSubject().Trim();
2527 sClipdata += L"\r\n\r\n";
2529 else
2531 if (!first)
2532 sClipdata += L"\r\n";
2533 sClipdata += pLogEntry->m_CommitHash;
2536 first = false;
2538 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2542 void CGitLogListBase::DiffSelectedRevWithPrevious()
2544 if (m_bThreadRunning)
2545 return;
2547 int FirstSelect=-1, LastSelect=-1;
2548 POSITION pos = GetFirstSelectedItemPosition();
2549 FirstSelect = GetNextSelectedItem(pos);
2550 while(pos)
2551 LastSelect = GetNextSelectedItem(pos);
2553 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2556 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2558 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2559 *pResult = -1;
2561 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2562 return;
2563 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2564 return;
2565 if (!pFindInfo->lvfi.psz)
2566 return;
2567 #if 0
2568 CString sCmp = pFindInfo->lvfi.psz;
2569 CString sRev;
2570 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2572 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2573 sRev.Format(L"%ld", pLogEntry->Rev);
2574 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2576 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2578 *pResult = i;
2579 return;
2582 else
2584 if (sCmp.Compare(sRev)==0)
2586 *pResult = i;
2587 return;
2591 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2593 for (int i=0; i<pFindInfo->iStart; ++i)
2595 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2596 sRev.Format(L"%ld", pLogEntry->Rev);
2597 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2599 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2601 *pResult = i;
2602 return;
2605 else
2607 if (sCmp.Compare(sRev)==0)
2609 *pResult = i;
2610 return;
2615 #endif
2616 *pResult = -1;
2619 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2621 ClearText();
2623 this->m_arShownList.SafeRemoveAll();
2625 this->m_logEntries.ClearAll();
2626 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2627 return -1;
2629 SetItemCountEx((int)m_logEntries.size());
2631 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2633 if(m_IsOldFirst)
2635 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2636 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2638 else
2640 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2641 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2645 ReloadHashMap();
2647 if(path)
2648 m_Path=*path;
2649 return 0;
2652 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2654 ClearText();
2656 m_arShownList.SafeRemoveAll();
2658 m_logEntries.ClearAll();
2659 if (m_logEntries.Fill(hashes))
2660 return -1;
2662 SetItemCountEx((int)m_logEntries.size());
2664 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2666 if (m_IsOldFirst)
2668 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2669 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2671 else
2673 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2674 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2678 ReloadHashMap();
2680 return 0;
2683 int CGitLogListBase::BeginFetchLog()
2685 ClearText();
2687 this->m_arShownList.SafeRemoveAll();
2689 this->m_logEntries.ClearAll();
2691 this->m_LogCache.ClearAllParent();
2693 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2695 CTGitPath *path;
2696 if(this->m_Path.IsEmpty())
2697 path = nullptr;
2698 else
2699 path=&this->m_Path;
2701 int mask;
2702 mask = CGit::LOG_INFO_ONLY_HASH;
2703 if (m_bIncludeBoundaryCommits)
2704 mask |= CGit::LOG_INFO_BOUNDARY;
2705 // if(this->m_bAllBranch)
2706 mask |= m_ShowMask ;
2708 if(m_bShowWC)
2710 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2711 ResetWcRev();
2712 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2715 if (m_sRange.IsEmpty())
2716 m_sRange = L"HEAD";
2718 #if 0 /* use tortoiegit filter */
2719 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2720 data.m_Author = this->m_sFilterText;
2722 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2723 data.m_MessageFilter = this->m_sFilterText;
2725 data.m_IsRegex = m_bFilterWithRegex;
2726 #endif
2728 // follow does not work for directories
2729 if (!path || path->IsDirectory())
2730 mask &= ~CGit::LOG_INFO_FOLLOW;
2731 // follow does not work with all branches 8at least in TGit)
2732 if (mask & CGit::LOG_INFO_FOLLOW)
2733 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2735 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2737 //this->m_logEntries.ParserFromLog();
2738 if(IsInWorkingThread())
2740 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2742 else
2744 SetItemCountEx((int)m_logEntries.size());
2749 [] { git_init(); } ();
2751 catch (char* msg)
2753 CString err(msg);
2754 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2755 return -1;
2758 if (!g_Git.CanParseRev(m_sRange))
2760 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2761 return 0;
2763 // if show all branches, pick any ref as dummy entry ref
2764 STRING_VECTOR list;
2765 if (g_Git.GetRefList(list))
2766 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2767 if (list.empty())
2768 return 0;
2770 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2773 g_Git.m_critGitDllSec.Lock();
2774 try {
2775 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2777 g_Git.m_critGitDllSec.Unlock();
2778 return -1;
2781 catch (char* msg)
2783 g_Git.m_critGitDllSec.Unlock();
2784 CString err(msg);
2785 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2786 return -1;
2788 g_Git.m_critGitDllSec.Unlock();
2790 return 0;
2793 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2795 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2797 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2799 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2801 DiffSelectedRevWithPrevious();
2802 return TRUE;
2805 #if 0
2806 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2808 DiffSelectedFile();
2809 return TRUE;
2811 #endif
2813 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2815 // select all entries
2816 for (int i=0; i<GetItemCount(); ++i)
2817 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2818 return TRUE;
2821 #if 0
2822 if (m_hAccel && !bSkipAccelerator)
2824 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2825 if (ret)
2826 return TRUE;
2829 #endif
2830 //m_tooltips.RelayEvent(pMsg);
2831 return __super::PreTranslateMessage(pMsg);
2834 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2836 // a double click on an entry in the revision list has happened
2837 *pResult = 0;
2839 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2840 DiffSelectedRevWithPrevious();
2843 void CGitLogListBase::FetchLogAsync(void* data)
2845 ReloadHashMap();
2846 m_ProcData=data;
2847 StartLoadingThread();
2850 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2852 return ((CGitLogListBase*)pVoid)->LogThread();
2855 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2857 //CTime time;
2858 oldest=CTime::GetCurrentTime();
2859 latest=CTime(1971,1,2,0,0,0);
2860 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2862 if(m_logEntries[i].IsEmpty())
2863 continue;
2865 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2866 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2868 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2869 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2873 if(latest<oldest)
2874 latest=oldest;
2877 UINT CGitLogListBase::LogThread()
2879 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2881 ULONGLONG t1,t2;
2883 if(BeginFetchLog())
2885 InterlockedExchange(&m_bThreadRunning, FALSE);
2886 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2888 return 1;
2891 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
2892 bool bRegex = false;
2893 if (m_bFilterWithRegex)
2894 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2896 TRACE(L"\n===Begin===\n");
2897 //Update work copy item;
2899 if (!m_logEntries.empty())
2901 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2903 m_arShownList.SafeAdd(pRev);
2907 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2909 // store commit number of the last selected commit/line before the refresh or -1
2910 int lastSelectedHashNItem = -1;
2911 if (m_lastSelectedHash.IsEmpty())
2912 lastSelectedHashNItem = 0;
2914 int ret = 0;
2916 bool shouldWalk = true;
2917 if (!g_Git.CanParseRev(m_sRange))
2919 // walk revisions if show all branches and there exists any ref
2920 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2921 shouldWalk = false;
2922 else
2924 STRING_VECTOR list;
2925 if (g_Git.GetRefList(list))
2926 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2927 if (list.empty())
2928 shouldWalk = false;
2932 if (shouldWalk)
2934 g_Git.m_critGitDllSec.Lock();
2935 if (!m_DllGitLog)
2937 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2938 g_Git.m_critGitDllSec.Unlock();
2939 InterlockedExchange(&m_bThreadRunning, FALSE);
2940 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2941 return 1;
2943 int total = 0;
2946 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2947 total = git_get_log_estimate_commit_count(m_DllGitLog);
2949 catch (char* msg)
2951 CString err(msg);
2952 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2953 ret = -1;
2955 g_Git.m_critGitDllSec.Unlock();
2957 GIT_COMMIT commit;
2958 t2 = t1 = GetTickCount64();
2959 int oldprecentage = 0;
2960 size_t oldsize = m_logEntries.size();
2961 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2962 while (ret== 0 && !m_bExitThread)
2964 g_Git.m_critGitDllSec.Lock();
2967 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2969 catch (char* msg)
2971 g_Git.m_critGitDllSec.Unlock();
2972 CString err(msg);
2973 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2974 break;
2976 g_Git.m_critGitDllSec.Unlock();
2978 if(ret)
2980 if (ret != -2) // other than end of revision walking
2981 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2982 break;
2985 if (commit.m_ignore == 1)
2987 git_free_commit(&commit);
2988 continue;
2991 //printf("%s\r\n",commit.GetSubject());
2992 if(m_bExitThread)
2993 break;
2995 CGitHash hash(commit.m_hash);
2997 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
2998 pRev->m_GitCommit = commit;
2999 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3001 char* note = nullptr;
3002 g_Git.m_critGitDllSec.Lock();
3005 git_get_notes(commit.m_hash, &note);
3007 catch (char* msg)
3009 g_Git.m_critGitDllSec.Unlock();
3010 CString err(msg);
3011 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3012 break;
3014 g_Git.m_critGitDllSec.Unlock();
3016 if(note)
3018 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3019 free(note);
3020 note = nullptr;
3023 if(!pRev->m_IsDiffFiles)
3025 pRev->m_CallDiffAsync = DiffAsync;
3028 pRev->ParserParentFromCommit(&commit);
3029 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3031 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3033 const CGitHash &parentHash = pRev->m_ParentHash[i];
3034 auto it = commitChildren.find(parentHash);
3035 if (it == commitChildren.end())
3036 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3037 it->second.insert(pRev->m_CommitHash);
3041 #ifdef DEBUG
3042 pRev->DbgPrint();
3043 TRACE(L"\n");
3044 #endif
3046 bool visible = true;
3047 if (HasFilterText())
3049 if(!IsMatchFilter(bRegex,pRev,pat))
3050 visible = false;
3052 if (visible && !ShouldShowFilter(pRev, commitChildren))
3053 visible = false;
3054 this->m_critSec.Lock();
3055 m_logEntries.append(hash, visible);
3056 if (visible)
3057 m_arShownList.SafeAdd(pRev);
3058 this->m_critSec.Unlock();
3060 if (!visible)
3061 continue;
3063 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3064 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3066 t2 = GetTickCount64();
3068 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3070 //update UI
3071 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3072 if(percent > 99)
3073 percent =99;
3074 if(percent < GITLOG_START)
3075 percent = GITLOG_START +1;
3077 oldsize = m_logEntries.size();
3078 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3080 //if( percent > oldprecentage )
3082 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3083 oldprecentage = percent;
3086 if (lastSelectedHashNItem >= 0)
3087 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3089 t1 = t2;
3092 g_Git.m_critGitDllSec.Lock();
3093 git_close_log(m_DllGitLog);
3094 g_Git.m_critGitDllSec.Unlock();
3098 if (m_bExitThread)
3100 InterlockedExchange(&m_bThreadRunning, FALSE);
3101 return 0;
3104 //Update UI;
3105 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3107 if (lastSelectedHashNItem >= 0)
3108 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3110 if (this->m_hWnd)
3111 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3113 InterlockedExchange(&m_bThreadRunning, FALSE);
3115 return 0;
3118 void CGitLogListBase::FetchRemoteList()
3120 STRING_VECTOR remoteList;
3121 m_SingleRemote.Empty();
3122 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3123 m_SingleRemote = remoteList[0];
3126 void CGitLogListBase::FetchTrackingBranchList()
3128 m_TrackingMap.clear();
3129 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3131 for (const auto& ref : it->second)
3133 CString branchName;
3134 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3136 CString pullRemote, pullBranch;
3137 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3138 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3139 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3145 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3147 SafeTerminateThread();
3149 this->SetItemCountEx(0);
3150 this->Clear();
3152 ResetWcRev();
3154 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3156 if (m_pMailmap)
3158 git_free_mailmap(m_pMailmap);
3159 git_read_mailmap(&m_pMailmap);
3162 //Update branch and Tag info
3163 ReloadHashMap();
3164 if (m_pFindDialog)
3165 m_pFindDialog->RefreshList();
3166 //Assume Thread have exited
3167 //if(!m_bThreadRunning)
3169 m_logEntries.clear();
3171 if(IsCleanFilter)
3173 m_sFilterText.Empty();
3176 SafeTerminateAsyncDiffThread();
3177 m_AsynDiffListLock.Lock();
3178 m_AsynDiffList.clear();
3179 m_AsynDiffListLock.Unlock();
3180 StartAsyncDiffThread();
3182 StartLoadingThread();
3186 void CGitLogListBase::StartAsyncDiffThread()
3188 if (m_AsyncThreadExit)
3189 return;
3190 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3191 return;
3192 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3193 if (!m_DiffingThread)
3195 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3196 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3200 void CGitLogListBase::StartLoadingThread()
3202 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3203 return;
3204 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3205 InterlockedExchange(&m_bExitThread, FALSE);
3206 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3207 if (!m_LoadingThread)
3209 InterlockedExchange(&m_bThreadRunning, FALSE);
3210 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3211 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3215 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::tr1::wregex& pat, bool bMatchCase /* = false */)
3219 std::tr1::regex_constants::syntax_option_type type = std::tr1::regex_constants::ECMAScript;
3220 if (!bMatchCase)
3221 type |= std::tr1::regex_constants::icase;
3222 pat = std::tr1::wregex(regexp_str, type);
3223 return true;
3225 catch (std::exception&) {}
3226 return false;
3228 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::tr1::wregex& pat)
3230 BOOL result = TRUE;
3231 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3232 CString sRev;
3234 if ((bRegex)&&(m_bFilterWithRegex))
3236 if (m_SelectedFilters & LOGFILTER_BUGID)
3238 if(this->m_bShowBugtraqColumn)
3240 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3242 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3243 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3244 return TRUE;
3248 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3250 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3251 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3252 return TRUE;
3255 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3257 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3258 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3259 return TRUE;
3262 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3264 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3265 return TRUE;
3267 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3268 return TRUE;
3271 if (m_SelectedFilters & LOGFILTER_EMAILS)
3273 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3274 return TRUE;
3276 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3277 return TRUE;
3280 if (m_SelectedFilters & LOGFILTER_REVS)
3282 sRev = pRev->m_CommitHash.ToString();
3283 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3285 return TRUE;
3289 if (m_SelectedFilters & LOGFILTER_NOTES)
3291 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3292 return TRUE;
3295 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3297 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3298 for (const auto& ref : refs)
3300 if (std::regex_search(std::wstring(ref), pat, flags))
3301 return TRUE;
3305 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3307 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3308 return TRUE;
3311 if (m_SelectedFilters & LOGFILTER_PATHS)
3313 CTGitPathList* pathList = nullptr;
3314 if( pRev->m_IsDiffFiles)
3315 pathList = &pRev->GetFiles(this);
3316 else
3318 if(!pRev->m_IsSimpleListReady)
3319 pRev->SafeGetSimpleList(&g_Git);
3322 if(pathList)
3323 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3325 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3326 return true;
3327 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3328 return true;
3331 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3333 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3334 return true;
3338 else
3340 CString find = m_sFilterText;
3341 if (!m_bFilterCaseSensitively)
3342 find.MakeLower();
3343 result = find[0] == '!' ? FALSE : TRUE;
3344 if (!result)
3345 find = find.Mid(1);
3347 if (m_SelectedFilters & LOGFILTER_BUGID)
3349 if(this->m_bShowBugtraqColumn)
3351 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3353 if (!m_bFilterCaseSensitively)
3354 sBugIds.MakeLower();
3355 if ((sBugIds.Find(find) >= 0))
3356 return result;
3360 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3362 CString msg = pRev->GetSubject();
3364 if (!m_bFilterCaseSensitively)
3365 msg = msg.MakeLower();
3366 if ((msg.Find(find) >= 0))
3367 return result;
3370 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3372 CString msg = pRev->GetBody();
3374 if (!m_bFilterCaseSensitively)
3375 msg = msg.MakeLower();
3376 if ((msg.Find(find) >= 0))
3377 return result;
3380 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3382 CString msg = pRev->GetAuthorName();
3383 if (!m_bFilterCaseSensitively)
3384 msg = msg.MakeLower();
3385 if ((msg.Find(find) >= 0))
3386 return result;
3389 if (m_SelectedFilters & LOGFILTER_EMAILS)
3391 CString msg = pRev->GetAuthorEmail();
3392 if (!m_bFilterCaseSensitively)
3393 msg = msg.MakeLower();
3394 if ((msg.Find(find) >= 0))
3395 return result;
3398 if (m_SelectedFilters & LOGFILTER_NOTES)
3400 CString msg = pRev->m_Notes;
3401 if (!m_bFilterCaseSensitively)
3402 msg = msg.MakeLower();
3403 if ((msg.Find(find) >= 0))
3404 return result;
3407 if (m_SelectedFilters & LOGFILTER_REVS)
3409 sRev = pRev->m_CommitHash.ToString();
3410 if ((sRev.Find(find) >= 0))
3411 return result;
3414 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3416 CString msg = GetTagInfo(pRev);
3417 if (!m_bFilterCaseSensitively)
3418 msg = msg.MakeLower();
3419 if ((msg.Find(find) >= 0))
3420 return result;
3423 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3425 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3426 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3428 if (it->Find(find) >= 0)
3429 return result;
3433 if (m_SelectedFilters & LOGFILTER_PATHS)
3435 CTGitPathList* pathList = nullptr;
3436 if( pRev->m_IsDiffFiles)
3437 pathList = &pRev->GetFiles(this);
3438 else
3440 if(!pRev->m_IsSimpleListReady)
3441 pRev->SafeGetSimpleList(&g_Git);
3443 if(pathList)
3444 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3446 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3447 CString path = cpath->GetGitOldPathString();
3448 if (!m_bFilterCaseSensitively)
3449 path.MakeLower();
3450 if ((path.Find(find)>=0))
3451 return result;
3452 path = cpath->GetGitPathString();
3453 if (!m_bFilterCaseSensitively)
3454 path.MakeLower();
3455 if ((path.Find(find)>=0))
3456 return result;
3459 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3461 CString path = pRev->m_SimpleFileList[i];
3462 if (!m_bFilterCaseSensitively)
3463 path.MakeLower();
3464 if ((path.Find(find)>=0))
3465 return result;
3468 } // else (from if (bRegex))
3469 return !result;
3472 static bool CStringStartsWith(const CString &str, const CString &prefix)
3474 return str.Left(prefix.GetLength()) == prefix;
3476 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3478 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3479 return true;
3481 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3483 // Keep all refs.
3484 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3485 for (size_t i = 0; i < refList.size(); ++i)
3487 const CString &str = refList[i];
3488 if (CStringStartsWith(str, L"refs/heads/"))
3490 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3491 return true;
3493 else if (CStringStartsWith(str, L"refs/remotes/"))
3495 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3496 return true;
3498 else if (CStringStartsWith(str, L"refs/tags/"))
3500 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3501 return true;
3503 else if (CStringStartsWith(str, L"refs/stash"))
3505 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3506 return true;
3508 else if (CStringStartsWith(str, L"refs/bisect/"))
3510 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3511 return true;
3514 // Keep the head too.
3515 if (pRev->m_CommitHash == m_HeadHash)
3516 return true;
3519 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3521 if (pRev->ParentsCount() > 1)
3522 return true;
3523 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3524 if (childrenIt != commitChildren.end())
3526 const std::unordered_set<CGitHash> &children = childrenIt->second;
3527 if (children.size() > 1)
3528 return true;
3531 return false;
3534 void CGitLogListBase::ShowGraphColumn(bool bShow)
3536 // HACK to hide graph column
3537 if (bShow)
3538 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3539 else
3540 SetColumnWidth(0, 0);
3543 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3545 CString cmd;
3546 CString output;
3548 if (m_HashMap.find(pLogEntry->m_CommitHash) != m_HashMap.end())
3550 STRING_VECTOR &vector = m_HashMap[pLogEntry->m_CommitHash];
3551 for (size_t i = 0; i < vector.size(); ++i)
3553 if (CStringUtils::StartsWith(vector[i], L"refs/tags/"))
3555 CString tag = vector[i];
3556 int start = vector[i].Find(L"^{}");
3557 if (start > 0)
3558 tag = tag.Left(start);
3559 else
3560 continue;
3562 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)tag);
3563 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) == 0)
3564 output.Trim().AppendChar(L'\n');
3569 return output;
3572 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3574 pShownlist->SafeRemoveAll();
3576 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
3577 bool bRegex = false;
3578 if (m_bFilterWithRegex)
3579 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3581 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3582 CString sRev;
3583 for (DWORD i=0; i<m_logEntries.size(); ++i)
3585 if ((bRegex)&&(m_bFilterWithRegex))
3587 #if 0
3588 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3590 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3591 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3593 pShownlist->SafeAdd(m_logEntries[i]);
3594 continue;
3597 #endif
3598 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3600 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3601 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3603 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3604 continue;
3607 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3609 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3610 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3612 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3613 continue;
3616 if (m_SelectedFilters & LOGFILTER_PATHS)
3618 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3620 bool bGoing = true;
3621 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3623 CTGitPath cpath = pathList[cpPathIndex];
3624 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3626 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3627 bGoing = false;
3628 continue;
3630 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3632 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3633 bGoing = false;
3634 continue;
3636 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3638 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3639 bGoing = false;
3640 continue;
3644 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3646 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3648 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3649 continue;
3652 if (m_SelectedFilters & LOGFILTER_EMAILS)
3654 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3656 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3657 continue;
3660 if (m_SelectedFilters & LOGFILTER_REVS)
3662 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3663 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3665 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3666 continue;
3669 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3671 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3672 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3674 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3676 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3677 continue;
3681 } // if (bRegex)
3682 else
3684 CString find = m_sFilterText;
3685 if (!m_bFilterCaseSensitively)
3686 find.MakeLower();
3687 #if 0
3688 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3690 CString sBugIDs = m_logEntries[i]->sBugIDs;
3692 if (!m_bFilterCaseSensitively)
3693 sBugIDs = sBugIDs.MakeLower();
3694 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3696 pShownlist->SafeAdd(m_logEntries[i]);
3697 continue;
3700 #endif
3701 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3703 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3705 if (!m_bFilterCaseSensitively)
3706 msg = msg.MakeLower();
3707 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3709 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3710 continue;
3713 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3715 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3717 if (!m_bFilterCaseSensitively)
3718 msg = msg.MakeLower();
3719 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3721 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3722 continue;
3725 if (m_SelectedFilters & LOGFILTER_PATHS)
3727 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3729 bool bGoing = true;
3730 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3732 CTGitPath cpath = pathList[cpPathIndex];
3733 CString path = cpath.GetGitOldPathString();
3734 if (!m_bFilterCaseSensitively)
3735 path.MakeLower();
3736 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3738 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3739 bGoing = false;
3740 continue;
3742 path = cpath.GetGitPathString();
3743 if (!m_bFilterCaseSensitively)
3744 path.MakeLower();
3745 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3747 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3748 bGoing = false;
3749 continue;
3751 path = cpath.GetActionName();
3752 if (!m_bFilterCaseSensitively)
3753 path.MakeLower();
3754 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3756 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3757 bGoing = false;
3758 continue;
3762 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3764 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3765 if (!m_bFilterCaseSensitively)
3766 msg = msg.MakeLower();
3767 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3769 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3770 continue;
3773 if (m_SelectedFilters & LOGFILTER_EMAILS)
3775 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3776 if (!m_bFilterCaseSensitively)
3777 msg = msg.MakeLower();
3778 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3780 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3781 continue;
3784 if (m_SelectedFilters & LOGFILTER_REVS)
3786 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3787 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3789 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3790 continue;
3793 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3795 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3796 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3798 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3800 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3801 continue;
3805 } // else (from if (bRegex))
3806 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3809 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3812 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3814 if(m_From == -1)
3815 if(m_To == -1)
3816 return true;
3817 else
3818 return time <= m_To;
3819 else
3820 if(m_To == -1)
3821 return time >= m_From;
3822 else
3823 return ((time >= m_From)&&(time <= m_To));
3825 return TRUE; /* git dll will filter time range */
3827 // return TRUE;
3830 void CGitLogListBase::StartFilter()
3832 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3833 RecalculateShownList(&m_arShownList);
3834 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3837 DeleteAllItems();
3838 SetItemCountEx(ShownCountWithStopped());
3839 RedrawItems(0, ShownCountWithStopped());
3840 Invalidate();
3843 void CGitLogListBase::RemoveFilter()
3845 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3847 m_arShownList.SafeRemoveAll();
3849 // reset the time filter too
3850 #if 0
3851 m_timFrom = (__time64_t(m_tFrom));
3852 m_timTo = (__time64_t(m_tTo));
3853 m_DateFrom.SetTime(&m_timFrom);
3854 m_DateTo.SetTime(&m_timTo);
3855 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3856 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3857 #endif
3859 for (DWORD i=0; i<m_logEntries.size(); ++i)
3861 if(this->m_IsOldFirst)
3862 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3863 else
3864 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3866 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3867 DeleteAllItems();
3868 SetItemCountEx(ShownCountWithStopped());
3869 RedrawItems(0, ShownCountWithStopped());
3871 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3874 void CGitLogListBase::Clear()
3876 m_arShownList.SafeRemoveAll();
3877 DeleteAllItems();
3879 m_logEntries.ClearAll();
3882 void CGitLogListBase::OnDestroy()
3884 SafeTerminateThread();
3885 SafeTerminateAsyncDiffThread();
3887 int retry = 0;
3888 while(m_LogCache.SaveCache())
3890 if(retry > 5)
3891 break;
3892 Sleep(1000);
3894 ++retry;
3896 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3897 // MB_YESNO) == IDNO)
3898 // break;
3901 __super::OnDestroy();
3904 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3906 CRect rect;
3907 int i=(int)wParam;
3908 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3909 this->InvalidateRect(rect);
3911 return 0;
3915 * Save column widths to the registry
3917 void CGitLogListBase::SaveColumnWidths()
3919 // HACK that graph column is always shown
3920 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3922 __super::SaveColumnWidths();
3925 int CGitLogListBase::GetHeadIndex()
3927 if(m_HeadHash.IsEmpty())
3928 return -1;
3930 for (size_t i = 0; i < m_arShownList.size(); ++i)
3932 GitRev* pRev = m_arShownList.SafeGetAt(i);
3933 if(pRev)
3935 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3936 return (int)i;
3939 return -1;
3941 void CGitLogListBase::OnFind()
3943 if (!m_pFindDialog)
3945 m_pFindDialog = new CFindDlg(this);
3946 m_pFindDialog->Create(this);
3950 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3952 if (GetSelectedCount() != 0)
3953 return 0;
3955 CGitHash theSelectedHash = m_lastSelectedHash;
3956 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3957 m_lastSelectedHash = theSelectedHash;
3959 int countPerPage = GetCountPerPage();
3960 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3961 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3962 EnsureVisible((int)itemToSelect, FALSE);
3963 return 0;
3966 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3968 CString* ref = reinterpret_cast<CString*>(wParam);
3969 if (!ref || ref->IsEmpty())
3970 return 1;
3972 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3974 CGitHash hash;
3975 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3976 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3978 if (hash.IsEmpty())
3979 return 1;
3981 bool bFound = false;
3982 int cnt = (int)m_arShownList.size();
3983 int i;
3984 for (i = 0; i < cnt; ++i)
3986 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3987 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3989 bFound = true;
3990 break;
3993 if (!bFound)
3994 return 1;
3996 EnsureVisible(i, FALSE);
3997 if (!bShift)
3999 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4000 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4001 SetSelectionMark(i);
4003 else
4005 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4006 if (pLogEntry)
4007 m_highlight = pLogEntry->m_CommitHash;
4009 Invalidate();
4010 UpdateData(FALSE);
4012 return 0;
4015 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4017 ASSERT(m_pFindDialog);
4018 bool bFound = false;
4019 int i=0;
4021 if (m_pFindDialog->IsTerminating())
4023 // invalidate the handle identifying the dialog box.
4024 m_pFindDialog = nullptr;
4025 return 0;
4028 int cnt = (int)m_arShownList.size();
4029 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4031 if(m_pFindDialog->IsRef())
4033 CString str;
4034 str=m_pFindDialog->GetFindString();
4036 CGitHash hash;
4038 if(!str.IsEmpty())
4040 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4041 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4044 if(!hash.IsEmpty())
4046 for (i = 0; i < cnt; ++i)
4048 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4049 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4051 bFound = true;
4052 break;
4056 if (!bFound)
4058 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4059 return 0;
4063 if (m_pFindDialog->FindNext() && !bFound)
4065 //read data from dialog
4066 CString findText = m_pFindDialog->GetFindString();
4067 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4069 std::tr1::wregex pat;
4070 bool bRegex = false;
4071 if (m_pFindDialog->Regex())
4072 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4074 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_not_null;
4076 for (i = m_nSearchIndex + 1; ; ++i)
4078 if (i >= cnt)
4080 i = 0;
4081 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4083 if (m_nSearchIndex >= 0)
4085 if (i == m_nSearchIndex)
4087 ::MessageBeep(0xFFFFFFFF);
4088 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4089 break;
4093 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4095 CString str;
4096 str+=pLogEntry->m_CommitHash.ToString();
4097 str += L'\n';
4099 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4100 if (refList != m_HashMap.cend())
4102 for (const auto& ref : (*refList).second)
4104 str += ref;
4105 str += L'\n';
4109 str+=pLogEntry->GetAuthorEmail();
4110 str += L'\n';
4111 str+=pLogEntry->GetAuthorName();
4112 str += L'\n';
4113 str+=pLogEntry->GetBody();
4114 str += L'\n';
4115 str+=pLogEntry->GetCommitterEmail();
4116 str += L'\n';
4117 str+=pLogEntry->GetCommitterName();
4118 str += L'\n';
4119 str+=pLogEntry->GetSubject();
4120 str += L'\n';
4121 str+=pLogEntry->m_Notes;
4122 str += L'\n';
4123 str+=GetTagInfo(pLogEntry);
4124 str += L'\n';
4127 /*Because changed files list is loaded on demand when gui show,
4128 files will empty when files have not fetched.
4130 we can add it back by using one-way diff(with outnumber changed and rename detect.
4131 here just need changed filename list. one-way is much quicker.
4133 if(pLogEntry->m_IsFull)
4135 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4137 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4138 str += L'\n';
4139 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4140 str += L'\n';
4143 else
4145 if(!pLogEntry->m_IsSimpleListReady)
4146 pLogEntry->SafeGetSimpleList(&g_Git);
4148 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4150 str += pLogEntry->m_SimpleFileList[j];
4151 str += L'\n';
4155 if (bRegex)
4157 if (std::regex_search(std::wstring(str), pat, flags))
4159 bFound = true;
4160 break;
4163 else
4165 if (bMatchCase)
4167 if (str.Find(findText) >= 0)
4169 bFound = true;
4170 break;
4173 else
4175 CString msg = str;
4176 msg = msg.MakeLower();
4177 CString find = findText.MakeLower();
4178 if (msg.Find(find) >= 0)
4180 bFound = TRUE;
4181 break;
4185 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4187 } // if(m_pFindDialog->FindNext())
4188 //UpdateLogInfoLabel();
4190 if (bFound)
4192 m_nSearchIndex = i;
4193 EnsureVisible(i, FALSE);
4194 if (!bShift)
4196 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4197 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4198 SetSelectionMark(i);
4200 else
4202 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4203 if (pLogEntry)
4204 m_highlight = pLogEntry->m_CommitHash;
4206 Invalidate();
4207 //FillLogMessageCtrl();
4208 UpdateData(FALSE);
4211 return 0;
4214 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4216 LVHITTESTINFO lvhitTestInfo;
4218 lvhitTestInfo.pt = point;
4220 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4221 int nSubItem = lvhitTestInfo.iSubItem;
4223 UINT nFlags = lvhitTestInfo.flags;
4225 // nFlags is 0 if the SubItemHitTest fails
4226 // Therefore, 0 & <anything> will equal false
4227 if (nFlags & LVHT_ONITEM)
4229 // Get the client area occupied by this control
4230 RECT rcClient;
4231 GetClientRect(&rcClient);
4233 // Fill in the TOOLINFO structure
4234 pTI->hwnd = m_hWnd;
4235 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4236 pTI->lpszText = LPSTR_TEXTCALLBACK;
4237 pTI->rect = rcClient;
4239 return pTI->uId; // By returning a unique value per listItem,
4240 // we ensure that when the mouse moves over another list item,
4241 // the tooltip will change
4243 else
4245 // Otherwise, we aren't interested, so let the message propagate
4246 return -1;
4250 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4252 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4253 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4255 *pResult = 0;
4257 // Ignore messages from the built in tooltip, we are processing them internally
4258 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4259 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4260 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4261 return FALSE;
4263 // Get the mouse position
4264 const MSG* pMessage = GetCurrentMessage();
4266 CPoint pt;
4267 pt = pMessage->pt;
4268 ScreenToClient(&pt);
4270 // Check if the point falls onto a list item
4271 LVHITTESTINFO lvhitTestInfo;
4272 lvhitTestInfo.pt = pt;
4274 int nItem = SubItemHitTest(&lvhitTestInfo);
4276 if (lvhitTestInfo.flags & LVHT_ONITEM)
4278 // Get branch description first
4279 CString strTipText;
4280 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4282 CString branch;
4283 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4284 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4286 MAP_STRING_STRING descriptions;
4287 g_Git.GetBranchDescriptions(descriptions);
4288 if (descriptions.find(branch) != descriptions.cend())
4290 strTipText.LoadString(IDS_DESCRIPTION);
4291 strTipText += L":\n";
4292 strTipText += descriptions[branch];
4297 bool followMousePos = false;
4298 if (!strTipText.IsEmpty())
4299 followMousePos = true;
4300 else
4301 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4302 if (strTipText.IsEmpty())
4303 return FALSE;
4305 // we want multiline tooltips
4306 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4308 wcscpy_s(m_wszTip, strTipText);
4309 // handle Unicode as well as non-Unicode requests
4310 if (pNMHDR->code == TTN_NEEDTEXTA)
4312 pTTTA->hinst = nullptr;
4313 pTTTA->lpszText = m_szTip;
4314 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4316 else
4318 pTTTW->hinst = nullptr;
4319 pTTTW->lpszText = m_wszTip;
4322 CRect rect;
4323 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4324 if (followMousePos)
4325 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4326 ClientToScreen(rect);
4327 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4329 return TRUE; // We found a tool tip,
4330 // tell the framework this message has been handled
4333 return FALSE; // We didn't handle the message,
4334 // let the framework continue propagating the message
4337 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4339 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4341 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4342 if (pLogEntry == nullptr)
4343 return CString();
4344 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4345 return CString();
4346 return pLogEntry->GetSubject();
4348 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4350 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4351 if (pLogEntry == nullptr)
4352 return CString();
4353 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4355 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4357 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4358 if (pLogEntry == nullptr)
4359 return CString();
4360 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4362 else if (nSubItem == LOGLIST_ACTION)
4364 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4365 if (pLogEntry == nullptr)
4366 return CString();
4368 if (!pLogEntry->m_IsDiffFiles)
4369 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4371 int actions = pLogEntry->GetAction(this);
4372 CString sToolTipText;
4374 CString actionText;
4375 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4376 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4378 if (actions & CTGitPath::LOGACTIONS_ADDED)
4380 if (!actionText.IsEmpty())
4381 actionText += L"\r\n";
4382 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4385 if (actions & CTGitPath::LOGACTIONS_DELETED)
4387 if (!actionText.IsEmpty())
4388 actionText += L"\r\n";
4389 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4392 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4394 if (!actionText.IsEmpty())
4395 actionText += L"\r\n";
4396 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4399 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4401 if (!actionText.IsEmpty())
4402 actionText += L"\r\n";
4403 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4406 if (!actionText.IsEmpty())
4408 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4409 sToolTipText = sTitle + L":\r\n" + actionText;
4411 return sToolTipText;
4413 return CString();
4416 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4418 POINT pt = point;
4419 ScreenToClient(&pt);
4420 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4423 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4425 if (!pLogEntry)
4426 return false;
4428 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4429 if (refList == m_HashMap.cend())
4430 return false;
4432 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4434 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4435 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4436 continue;
4438 CGit::REF_TYPE foundType;
4439 if (pShortname)
4440 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4441 else
4442 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4443 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4444 return false;
4446 type = foundType;
4447 if (pIndex)
4448 *pIndex = i;
4449 return true;
4451 return false;
4454 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4456 *pResult = 0;
4458 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4459 return;
4461 m_bDragging = TRUE;
4462 m_nDropIndex = -1;
4463 m_nDropMarkerLast = -1;
4464 m_nDropMarkerLastHot = GetHotItem();
4465 SetCapture();
4468 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4470 __super::OnMouseMove(nFlags, point);
4472 if (!m_bDragging)
4473 return;
4475 CPoint dropPoint = point;
4476 ClientToScreen(&dropPoint);
4478 if (WindowFromPoint(dropPoint) != this)
4480 SetCursor(LoadCursor(nullptr, IDC_NO));
4481 m_nDropIndex = -1;
4482 DrawDropInsertMarker(m_nDropIndex);
4483 return;
4486 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4487 ScreenToClient(&dropPoint);
4489 dropPoint.y += 10;
4490 m_nDropIndex = HitTest(dropPoint);
4492 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4494 dropPoint.y -= 10;
4495 m_nDropIndex = HitTest(dropPoint);
4496 if (m_nDropIndex != -1)
4497 m_nDropIndex = GetItemCount();
4500 POSITION pos = GetFirstSelectedItemPosition();
4501 int first = GetNextSelectedItem(pos);
4502 int last = first;
4503 while (pos)
4504 last = GetNextSelectedItem(pos);
4505 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4507 SetCursor(LoadCursor(nullptr, IDC_NO));
4508 m_nDropIndex = -1;
4511 // handle auto scrolling
4512 int hotItem = GetHotItem();
4513 int topindex = GetTopIndex();
4514 if (hotItem == topindex && hotItem != 0)
4515 EnsureVisible(hotItem - 1, FALSE);
4516 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4517 EnsureVisible(hotItem + 1, FALSE);
4519 DrawDropInsertMarker(m_nDropIndex);
4522 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4524 if (m_bDragging)
4526 ::ReleaseCapture();
4527 SetCursor(LoadCursor(nullptr, IDC_HAND));
4528 m_bDragging = FALSE;
4530 CRect rect;
4531 GetItemRect(m_nDropMarkerLast, &rect, 0);
4532 rect.bottom = rect.top + 2;
4533 rect.top -= 2;
4534 InvalidateRect(&rect, 0);
4536 CPoint pt(point);
4537 ClientToScreen(&pt);
4538 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4539 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4542 __super::OnLButtonUp(nFlags, point);
4545 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4547 if (m_nDropMarkerLast != nIndex)
4549 CRect rect;
4550 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4552 rect.bottom = rect.top + 2;
4553 rect.top -= 2;
4554 InvalidateRect(&rect, 0);
4556 else if (m_nDropMarkerLast == GetItemCount())
4557 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4558 m_nDropMarkerLast = nIndex;
4560 if (nIndex < 0)
4561 return;
4563 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4565 else if (m_nDropMarkerLastHot != GetHotItem())
4567 m_nDropMarkerLastHot = GetHotItem();
4568 m_nDropMarkerLast = -1;
4572 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4574 CBrush* pBrush = CDC::GetHalftoneBrush();
4575 CDC* pDC = GetDC();
4577 CRect rect;
4578 if (nIndex < GetItemCount())
4580 GetItemRect(nIndex, &rect, 0);
4581 rect.bottom = rect.top + 2;
4582 rect.top -= 2;
4584 else
4586 GetItemRect(nIndex - 1, &rect, 0);
4587 rect.top = rect.bottom - 2;
4588 rect.bottom += 2;
4591 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4592 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4593 pDC->SelectObject(pBrushOld);
4595 ReleaseDC(pDC);