Fixed issue #2082: RebaseDlg: Reorder commits via drag'n'drop
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
bloba014c8a9c02ebd83e710a53e1ea368a81789cab6
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 "cursor.h"
27 #include "GitProgressDlg.h"
28 #include "ProgressDlg.h"
29 #include "MessageBox.h"
30 #include "registry.h"
31 #include "LoglistUtils.h"
32 #include "StringUtils.h"
33 #include "UnicodeUtils.h"
34 #include "IconMenu.h"
35 #include "GitStatus.h"
36 #include "..\TortoiseShell\Resource.h"
37 #include "FindDlg.h"
39 template < typename Cont, typename Pred>
40 void for_each(Cont& c, Pred p)
42 std::for_each(cbegin(c), cend(c), p);
45 template<typename T>
46 using const_iterator = typename T::const_iterator;
48 template <typename Cont, typename Pred>
49 const_iterator<Cont> find_if(Cont& c, Pred p)
51 return std::find_if(cbegin(c), cend(c), p);
54 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
55 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
56 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
57 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
59 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
61 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
62 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
63 ,m_nSearchIndex(0)
64 ,m_bNoDispUpdates(FALSE)
65 , m_bThreadRunning(FALSE)
66 , m_bStrictStopped(false)
67 , m_SelectedFilters(LOGFILTER_ALL)
68 , m_ShowFilter(FILTERSHOW_ALL)
69 , m_bShowWC(false)
70 , m_logEntries(&m_LogCache)
71 , m_pFindDialog(nullptr)
72 , m_dwDefaultColumns(0)
73 , m_arShownList(&m_critSec)
74 , m_hasWC(true)
75 , m_bNoHightlightHead(FALSE)
76 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
77 , m_bFullCommitMessageOnLogLine(false)
78 , m_OldTopIndex(-1)
79 , m_AsyncThreadRunning(FALSE)
80 , m_AsyncThreadExit(FALSE)
81 , m_bIsCherryPick(false)
82 , m_pMailmap(nullptr)
83 , m_bShowBugtraqColumn(false)
84 , m_IsIDReplaceAction(FALSE)
85 , m_ShowMask(0)
86 , m_LoadingThread(nullptr)
87 , m_bExitThread(FALSE)
88 , m_IsOldFirst(FALSE)
89 , m_IsRebaseReplaceGraph(FALSE)
90 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
91 , m_bDragndropEnabled(false)
92 , m_bDragging(FALSE)
93 , m_nDropIndex(-1)
94 , m_nDropMarkerLast(-1)
95 , m_nDropMarkerLastHot(-1)
97 // use the default GUI font, create a copy of it and
98 // change the copy to BOLD (leave the rest of the font
99 // the same)
100 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
101 LOGFONT lf = {0};
102 GetObject(hFont, sizeof(LOGFONT), &lf);
103 lf.lfWeight = FW_BOLD;
104 m_boldFont.CreateFontIndirect(&lf);
105 lf.lfWeight = FW_DONTCARE;
106 lf.lfItalic = TRUE;
107 m_FontItalics.CreateFontIndirect(&lf);
108 lf.lfWeight = FW_BOLD;
109 m_boldItalicsFont.CreateFontIndirect(&lf);
111 this->m_critSec.Init();
112 ResetWcRev(false);
114 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
115 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
116 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
117 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
118 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
119 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
121 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
122 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
124 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
125 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
127 CString key;
128 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
129 key.Replace(L':', L'_');
130 CString lastSelFromDate = CRegString(key);
131 if (lastSelFromDate.GetLength() == 10)
133 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
134 m_Filter.m_From = (DWORD)time.GetTime();
137 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
139 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
141 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
143 // get short/long datetime setting from registry
144 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
145 if ( RegUseShortDateFormat )
147 m_DateFormat = DATE_SHORTDATE;
149 else
151 m_DateFormat = DATE_LONGDATE;
153 // get relative time display setting from registry
154 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
155 m_bRelativeTimes = (regRelativeTimes != 0);
157 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
158 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
159 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
160 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
161 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
162 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
163 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
165 m_ColumnRegKey = L"log";
167 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
168 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
169 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
170 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
172 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
173 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
175 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
176 git_read_mailmap(&m_pMailmap);
178 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
179 m_AsynDiffListLock.Init();
180 StartAsyncDiffThread();
183 int CGitLogListBase::AsyncDiffThread()
185 while(!m_AsyncThreadExit)
187 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
189 GitRevLoglist* pRev = nullptr;
190 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
192 m_AsynDiffListLock.Lock();
193 pRev = m_AsynDiffList.back();
194 m_AsynDiffList.pop_back();
195 m_AsynDiffListLock.Unlock();
197 if( pRev->m_CommitHash.IsEmpty() )
199 if(pRev->m_IsDiffFiles)
200 continue;
202 CTGitPathList& files = pRev->GetFiles(this);
203 files.Clear();
204 pRev->m_ParentHash.clear();
205 pRev->m_ParentHash.push_back(m_HeadHash);
206 g_Git.RefreshGitIndex();
207 g_Git.GetWorkingTreeChanges(files);
208 int& action = pRev->GetAction(this);
209 action = 0;
210 for (int j = 0; j < files.GetCount(); ++j)
211 action |= files[j].m_Action;
213 CString err;
214 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
216 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
217 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
218 return -1;
221 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
222 InterlockedExchange(&pRev->m_IsFull, TRUE);
224 CString body = L"\n";
225 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
226 pRev->GetBody() = body;
227 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
228 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
231 if (!pRev->CheckAndDiff())
232 { // fetch change file list
233 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
235 if (i < (int)m_arShownList.size())
237 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
238 if(data->m_CommitHash == pRev->m_CommitHash)
240 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
241 break;
246 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
248 POSITION pos = GetFirstSelectedItemPosition();
249 int nItem = GetNextSelectedItem(pos);
251 if(nItem>=0)
253 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
254 if(data)
255 if(data->m_CommitHash == pRev->m_CommitHash)
256 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
262 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
263 return 0;
265 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
267 if (exclusivelyShow)
268 m_ContextMenuMask &= hideMask;
269 else
270 m_ContextMenuMask &= ~hideMask;
273 CGitLogListBase::~CGitLogListBase()
275 InterlockedExchange(&m_bNoDispUpdates, TRUE);
276 this->m_arShownList.SafeRemoveAll();
278 DestroyIcon(m_hModifiedIcon);
279 DestroyIcon(m_hReplacedIcon);
280 DestroyIcon(m_hConflictedIcon);
281 DestroyIcon(m_hAddedIcon);
282 DestroyIcon(m_hDeletedIcon);
283 m_logEntries.ClearAll();
285 git_free_mailmap(m_pMailmap);
287 SafeTerminateThread();
288 SafeTerminateAsyncDiffThread();
290 if(m_AsyncDiffEvent)
291 CloseHandle(m_AsyncDiffEvent);
295 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
296 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
297 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
298 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
299 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
300 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
301 ON_WM_CONTEXTMENU()
302 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
303 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
304 ON_WM_CREATE()
305 ON_WM_DESTROY()
306 ON_MESSAGE(MSG_LOADED,OnLoad)
307 ON_WM_MEASUREITEM()
308 ON_WM_MEASUREITEM_REFLECT()
309 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
310 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
311 ON_WM_MOUSEMOVE()
312 ON_WM_LBUTTONUP()
313 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
314 END_MESSAGE_MAP()
316 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
318 //if (m_nRowHeight>0)
319 lpMeasureItemStruct->itemHeight = 50;
322 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
324 PreSubclassWindow();
325 return __super::OnCreate(lpCreateStruct);
328 void CGitLogListBase::SetStyle()
330 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
333 void CGitLogListBase::PreSubclassWindow()
335 SetStyle();
336 // load the icons for the action columns
337 // m_Theme.Open(m_hWnd, L"ListView");
338 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
339 __super::PreSubclassWindow();
342 CString CGitLogListBase::GetRebaseActionName(int action)
344 if (action & LOGACTIONS_REBASE_EDIT)
345 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
346 if (action & LOGACTIONS_REBASE_SQUASH)
347 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
348 if (action & LOGACTIONS_REBASE_PICK)
349 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
350 if (action & LOGACTIONS_REBASE_SKIP)
351 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
353 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
356 void CGitLogListBase::InsertGitColumn()
358 CString temp;
360 Init();
362 // only load properties if we have a repository
363 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
364 UpdateProjectProperties();
366 static UINT normal[] =
368 IDS_LOG_GRAPH,
369 IDS_LOG_REBASE,
370 IDS_LOG_ID,
371 IDS_LOG_HASH,
372 IDS_LOG_ACTIONS,
373 IDS_LOG_MESSAGE,
374 IDS_LOG_AUTHOR,
375 IDS_LOG_DATE,
376 IDS_LOG_EMAIL,
377 IDS_LOG_COMMIT_NAME,
378 IDS_LOG_COMMIT_EMAIL,
379 IDS_LOG_COMMIT_DATE,
380 IDS_LOG_BUGIDS,
381 IDS_LOG_SVNREV,
384 static int with[] =
386 ICONITEMBORDER+16*4,
387 ICONITEMBORDER+16*4,
388 ICONITEMBORDER+16*4,
389 ICONITEMBORDER+16*4,
390 2*ICONITEMBORDER+16*5,
391 LOGLIST_MESSAGE_MIN,
392 ICONITEMBORDER+16*4,
393 ICONITEMBORDER+16*4,
394 ICONITEMBORDER+16*4,
395 ICONITEMBORDER+16*4,
396 ICONITEMBORDER+16*4,
397 ICONITEMBORDER+16*4,
398 ICONITEMBORDER+16*4,
399 ICONITEMBORDER+16*4,
401 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
403 DWORD hideColumns = 0;
404 if(this->m_IsRebaseReplaceGraph)
406 hideColumns |= GIT_LOG_GRAPH;
407 m_dwDefaultColumns |= GIT_LOG_REBASE;
409 else
410 hideColumns |= GIT_LOG_REBASE;
412 if(this->m_IsIDReplaceAction)
414 hideColumns |= GIT_LOG_ACTIONS;
415 m_dwDefaultColumns |= GIT_LOG_ID;
416 m_dwDefaultColumns |= GIT_LOG_HASH;
418 else
419 hideColumns |= GIT_LOG_ID;
420 if(this->m_bShowBugtraqColumn)
421 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
422 else
423 hideColumns |= GIT_LOGLIST_BUG;
424 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
425 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
426 else
427 hideColumns |= GIT_LOGLIST_SVNREV;
428 SetRedraw(false);
430 m_ColumnManager.SetNames(normal, _countof(normal));
431 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
432 m_ColumnManager.SetRightAlign(LOGLIST_ID);
434 SetRedraw(true);
437 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
439 LVITEM rItem = { 0 };
440 rItem.mask = LVIF_STATE;
441 rItem.iItem = (int)Index;
442 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
443 GetItem(&rItem);
445 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
446 HBRUSH brush = nullptr;
448 if (!(rItem.state & LVIS_SELECTED))
450 int action = pLogEntry->GetRebaseAction();
451 if (action & LOGACTIONS_REBASE_SQUASH)
452 brush = ::CreateSolidBrush(RGB(156,156,156));
453 else if (action & LOGACTIONS_REBASE_EDIT)
454 brush = ::CreateSolidBrush(RGB(200,200,128));
456 else if (!IsAppThemed())
458 if (rItem.state & LVIS_SELECTED)
460 if (::GetFocus() == m_hWnd)
461 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
462 else
463 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
466 if (brush)
468 ::FillRect(hdc, &rect, brush);
469 ::DeleteObject(brush);
473 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
475 POINT point = { 4, 4 };
476 CRect rt2 = rect;
477 rt2.DeflateRect(1, 1);
478 rt2.OffsetRect(2, 2);
480 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
481 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
482 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
483 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
484 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
486 ::SelectObject(hdc, brush);
487 rt2.OffsetRect(-2, -2);
488 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
489 ::SelectObject(hdc, oldbrush);
490 ::SelectObject(hdc, oldpen);
491 ::DeleteObject(nullPen);
492 ::DeleteObject(darkBrush);
495 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
497 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
498 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
499 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
500 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
501 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
502 ::LineTo(hdc, rect.left, rect.top + 4);
503 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
504 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
505 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
506 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
507 ::SelectObject(hdc, oldpen);
508 ::DeleteObject(pen);
511 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
513 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
514 CRect rt=rect;
515 LVITEM rItem = { 0 };
516 rItem.mask = LVIF_STATE;
517 rItem.iItem = (int)index;
518 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
519 GetItem(&rItem);
521 CDC W_Dc;
522 W_Dc.Attach(hdc);
524 HTHEME hTheme = nullptr;
525 if (IsAppThemed())
526 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
528 SIZE oneSpaceSize;
529 if (m_bTagsBranchesOnRightSide)
531 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
532 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
533 SelectObject(hdc, oldFont);
534 rt.left += oneSpaceSize.cx * 2;
536 else
538 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
539 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
540 rt.left += oneSpaceSize.cx;
543 CString msg = MessageDisplayStr(data);
544 int action = data->GetRebaseAction();
545 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
546 if (IsAppThemed())
548 int txtState = LISS_NORMAL;
549 if (rItem.state & LVIS_SELECTED)
550 txtState = LISS_SELECTED;
552 DTTOPTS opts = { 0 };
553 opts.dwSize = sizeof(opts);
554 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
555 opts.dwFlags = DTT_TEXTCOLOR;
556 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
558 else
560 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
562 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
563 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
564 ::SetTextColor(hdc, clrOld);
566 else
568 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
569 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
570 ::SetTextColor(hdc, clrOld);
574 if (m_bTagsBranchesOnRightSide)
576 SIZE size;
577 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
579 rt.left += oneSpaceSize.cx + size.cx;
581 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
584 if (hTheme)
585 CloseThemeData(hTheme);
587 W_Dc.Detach();
590 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
592 for (unsigned int i = 0; i < refList.size(); ++i)
594 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
595 HBRUSH brush = 0;
596 COLORREF colRef = refList[i].color;
597 bool singleRemote = refList[i].singleRemote;
598 bool hasTracking = refList[i].hasTracking;
599 CGit::REF_TYPE refType = refList[i].refType;
601 //When row selected, ajust label color
602 if (!IsAppThemed())
604 if (rItem.state & LVIS_SELECTED)
605 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
608 brush = ::CreateSolidBrush(colRef);
610 if (!shortname.IsEmpty() && (rt.left < rect.right))
612 SIZE size = { 0 };
613 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
615 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
616 rt.right += 8;
618 int textpos = DT_CENTER;
620 if (rt.right > rect.right)
622 rt.right = rect.right;
623 textpos = 0;
626 CRect textRect = rt;
628 if (singleRemote)
630 rt.right += 5;
631 textRect.OffsetRect(5, 0);
634 if (hasTracking)
635 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
636 else
638 //Fill interior of ref label
639 ::FillRect(hdc, &rt, brush);
642 //Draw edge of label
643 CRect rectEdge = rt;
645 if (!hasTracking)
647 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
648 rectEdge.DeflateRect(1, 1);
649 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
652 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
654 rt.right += 8;
655 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
656 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
657 ::FillRgn(hdc, hrgn, brush);
658 ::DeleteObject(hrgn);
659 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
660 HPEN pen;
661 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
662 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
663 ::DeleteObject(pen);
664 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
665 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
666 ::DeleteObject(pen);
667 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
668 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
669 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
670 ::DeleteObject(pen);
671 SelectObject(hdc, oldpen);
674 //Draw text inside label
675 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
676 if (!customColor && IsAppThemed())
678 int txtState = LISS_NORMAL;
679 if (rItem.state & LVIS_SELECTED)
680 txtState = LISS_SELECTED;
682 DTTOPTS opts = { 0 };
683 opts.dwSize = sizeof(opts);
684 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
685 opts.dwFlags = DTT_TEXTCOLOR;
686 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
688 else
690 W_Dc.SetBkMode(TRANSPARENT);
691 if (customColor || (rItem.state & LVIS_SELECTED))
693 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
694 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
695 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
696 ::SetTextColor(hdc,clrOld);
698 else
700 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
701 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
702 ::SetTextColor(hdc, clrOld);
706 if (singleRemote)
708 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
709 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
710 CRect newRect;
711 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
712 DrawUpstream(hdc, newRect, color, bold);
715 if (!refList[i].fullName.IsEmpty())
716 m_RefLabelPosMap[refList[i].fullName] = rt;
718 rt.left = rt.right + 1;
720 if (brush)
721 ::DeleteObject(brush);
723 rt.right = rect.right;
726 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
727 // Returns ((256 - amount)*col1 + amount*col2) / 256;
728 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
729 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
730 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
733 Gdiplus::Color GetGdiColor(COLORREF col)
735 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
737 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
738 const COLORREF& col,const COLORREF& activeColor, int top
741 int h = laneHeight / 2;
742 int m = (x1 + x2) / 2;
743 int r = (x2 - x1) * m_NodeSize / 30;
744 int d = 2 * r;
746 #define P_CENTER m , h+top
747 #define P_0 x2, h+top
748 #define P_90 m , 0+top-1
749 #define P_180 x1, h+top
750 #define P_270 m , 2 * h+top +1
751 #define R_CENTER m - r, h - r+top, d, d
754 #define DELTA_UR_B 2*(x1 - m), 2*h +top
755 #define DELTA_UR_E 0*16, 90*16 +top // -,
757 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
758 #define DELTA_DR_E 270*16, 90*16 +top // -'
760 #define DELTA_UL_B 2*(x2 - m), 2*h +top
761 #define DELTA_UL_E 90*16, 90*16 +top // ,-
763 #define DELTA_DL_B 2*(x2 - m),2*-h +top
764 #define DELTA_DL_E 180*16, 90*16 // '-
766 #define CENTER_UR x1, 2*h, 225
767 #define CENTER_DR x1, 0 , 135
768 #define CENTER_UL x2, 2*h, 315
769 #define CENTER_DL x2, 0 , 45
772 Gdiplus::Graphics graphics( hdc );
774 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
776 // arc
777 switch (type) {
778 case Lanes::JOIN:
779 case Lanes::JOIN_R:
780 case Lanes::HEAD:
781 case Lanes::HEAD_R:
783 Gdiplus::LinearGradientBrush gradient(
784 Gdiplus::Point(x1-2, h+top-2),
785 Gdiplus::Point(P_270),
786 GetGdiColor(activeColor),GetGdiColor(col));
789 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
790 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
792 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
793 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
794 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
796 break;
798 case Lanes::JOIN_L:
800 Gdiplus::LinearGradientBrush gradient(
801 Gdiplus::Point(P_270),
802 Gdiplus::Point(x2+1, h+top-1),
803 GetGdiColor(col),GetGdiColor(activeColor));
806 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
807 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
809 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
810 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
811 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
814 break;
816 case Lanes::TAIL:
817 case Lanes::TAIL_R:
819 Gdiplus::LinearGradientBrush gradient(
820 Gdiplus::Point(x1-2, h+top-2),
821 Gdiplus::Point(P_90),
822 GetGdiColor(activeColor),GetGdiColor(col));
824 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
826 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
828 #if 0
829 QConicalGradient gradient(CENTER_DR);
830 gradient.setColorAt(0.375, activeCol);
831 gradient.setColorAt(0.625, col);
832 myPen.setBrush(gradient);
833 p->setPen(myPen);
834 p->drawArc(P_CENTER, DELTA_DR);
835 #endif
836 break;
838 default:
839 break;
843 //static QPen myPen(Qt::black, 2); // fast path here
844 CPen pen;
845 pen.CreatePen(PS_SOLID,2,col);
846 //myPen.setColor(col);
847 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
849 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
851 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
853 //p->setPen(myPen);
855 // vertical line
856 switch (type) {
857 case Lanes::ACTIVE:
858 case Lanes::NOT_ACTIVE:
859 case Lanes::MERGE_FORK:
860 case Lanes::MERGE_FORK_R:
861 case Lanes::MERGE_FORK_L:
862 case Lanes::JOIN:
863 case Lanes::JOIN_R:
864 case Lanes::JOIN_L:
865 case Lanes::CROSS:
866 //DrawLine(hdc,P_90,P_270);
867 graphics.DrawLine(&myPen,P_90,P_270);
868 //p->drawLine(P_90, P_270);
869 break;
870 case Lanes::HEAD_L:
871 case Lanes::BRANCH:
872 //DrawLine(hdc,P_CENTER,P_270);
873 graphics.DrawLine(&myPen,P_CENTER,P_270);
874 //p->drawLine(P_CENTER, P_270);
875 break;
876 case Lanes::TAIL_L:
877 case Lanes::INITIAL:
878 case Lanes::BOUNDARY:
879 case Lanes::BOUNDARY_C:
880 case Lanes::BOUNDARY_R:
881 case Lanes::BOUNDARY_L:
882 //DrawLine(hdc,P_90, P_CENTER);
883 graphics.DrawLine(&myPen,P_90,P_CENTER);
884 //p->drawLine(P_90, P_CENTER);
885 break;
886 default:
887 break;
890 myPen.SetColor(GetGdiColor(activeColor));
892 // horizontal line
893 switch (type) {
894 case Lanes::MERGE_FORK:
895 case Lanes::JOIN:
896 case Lanes::HEAD:
897 case Lanes::TAIL:
898 case Lanes::CROSS:
899 case Lanes::CROSS_EMPTY:
900 case Lanes::BOUNDARY_C:
901 //DrawLine(hdc,P_180,P_0);
902 graphics.DrawLine(&myPen,P_180,P_0);
903 //p->drawLine(P_180, P_0);
904 break;
905 case Lanes::MERGE_FORK_R:
906 case Lanes::BOUNDARY_R:
907 //DrawLine(hdc,P_180,P_CENTER);
908 graphics.DrawLine(&myPen,P_180,P_CENTER);
909 //p->drawLine(P_180, P_CENTER);
910 break;
911 case Lanes::MERGE_FORK_L:
912 case Lanes::HEAD_L:
913 case Lanes::TAIL_L:
914 case Lanes::BOUNDARY_L:
915 //DrawLine(hdc,P_CENTER,P_0);
916 graphics.DrawLine(&myPen,P_CENTER,P_0);
917 //p->drawLine(P_CENTER, P_0);
918 break;
919 default:
920 break;
923 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
925 CBrush brush;
926 brush.CreateSolidBrush(col);
927 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
929 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
930 // center symbol, e.g. rect or ellipse
931 switch (type) {
932 case Lanes::ACTIVE:
933 case Lanes::INITIAL:
934 case Lanes::BRANCH:
936 //p->setPen(Qt::NoPen);
937 //p->setBrush(col);
938 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
939 graphics.FillEllipse(&myBrush, R_CENTER);
940 //p->drawEllipse(R_CENTER);
941 break;
942 case Lanes::MERGE_FORK:
943 case Lanes::MERGE_FORK_R:
944 case Lanes::MERGE_FORK_L:
945 //p->setPen(Qt::NoPen);
946 //p->setBrush(col);
947 //p->drawRect(R_CENTER);
948 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
949 graphics.FillRectangle(&myBrush, R_CENTER);
950 break;
951 case Lanes::UNAPPLIED:
952 // Red minus sign
953 //p->setPen(Qt::NoPen);
954 //p->setBrush(Qt::red);
955 //p->drawRect(m - r, h - 1, d, 2);
956 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
957 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
958 break;
959 case Lanes::APPLIED:
960 // Green plus sign
961 //p->setPen(Qt::NoPen);
962 //p->setBrush(DARK_GREEN);
963 //p->drawRect(m - r, h - 1, d, 2);
964 //p->drawRect(m - 1, h - r, 2, d);
965 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
966 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
967 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
968 break;
969 case Lanes::BOUNDARY:
970 //p->setBrush(back);
971 //p->drawEllipse(R_CENTER);
972 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
973 graphics.DrawEllipse(&myPen, R_CENTER);
974 break;
975 case Lanes::BOUNDARY_C:
976 case Lanes::BOUNDARY_R:
977 case Lanes::BOUNDARY_L:
978 //p->setBrush(back);
979 //p->drawRect(R_CENTER);
980 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
981 graphics.FillRectangle(&myBrush,R_CENTER);
982 break;
983 default:
984 break;
987 ::SelectObject(hdc,oldpen);
988 ::SelectObject(hdc,oldbrush);
989 #undef P_CENTER
990 #undef P_0
991 #undef P_90
992 #undef P_180
993 #undef P_270
994 #undef R_CENTER
997 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
999 // TODO: unfinished
1000 // return;
1001 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1002 if(data->m_CommitHash.IsEmpty())
1003 return;
1005 CRect rt=rect;
1006 LVITEM rItem = { 0 };
1007 rItem.mask = LVIF_STATE;
1008 rItem.iItem = (int)index;
1009 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1010 GetItem(&rItem);
1012 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1014 if (data->m_Lanes.empty())
1015 m_logEntries.setLane(data->m_CommitHash);
1017 std::vector<int>& lanes=data->m_Lanes;
1018 size_t laneNum = lanes.size();
1019 UINT activeLane = 0;
1020 for (UINT i = 0; i < laneNum; ++i)
1021 if (Lanes::isMerge(lanes[i])) {
1022 activeLane = i;
1023 break;
1026 int x2 = 0;
1027 int maxWidth = rect.Width();
1028 int lw = 3 * rect.Height() / 4; //laneWidth()
1030 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1031 //if (opt.state & QStyle::State_Selected)
1032 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1034 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1036 int x1 = x2;
1037 x2 += lw;
1039 int ln = lanes[i];
1040 if (ln == Lanes::EMPTY)
1041 continue;
1043 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1044 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1047 #if 0
1048 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1049 int x1 = x2;
1050 x2 += lw;
1052 int ln = lanes[i];
1053 if (ln == Lanes::EMPTY)
1054 continue;
1056 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1057 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1059 if (ln == Lanes::CROSS)
1061 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1062 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1064 else
1065 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1067 #endif
1070 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1072 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1073 // Take the default processing unless we set this to something else below.
1074 *pResult = CDRF_DODEFAULT;
1076 if (m_bNoDispUpdates)
1077 return;
1079 switch (pLVCD->nmcd.dwDrawStage)
1081 case CDDS_PREPAINT:
1083 *pResult = CDRF_NOTIFYITEMDRAW;
1084 return;
1086 break;
1087 case CDDS_ITEMPREPAINT:
1089 // This is the prepaint stage for an item. Here's where we set the
1090 // item's text color.
1092 // Tell Windows to send draw notifications for each subitem.
1093 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1095 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1097 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1099 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1100 if (data)
1102 HGDIOBJ hGdiObj = nullptr;
1103 int action = data->GetRebaseAction();
1104 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1105 crText = RGB(128,128,128);
1107 if (action & LOGACTIONS_REBASE_SQUASH)
1108 pLVCD->clrTextBk = RGB(156,156,156);
1109 else if (action & LOGACTIONS_REBASE_EDIT)
1110 pLVCD->clrTextBk = RGB(200,200,128);
1111 else
1112 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1114 if (action & LOGACTIONS_REBASE_CURRENT)
1115 hGdiObj = m_boldFont.GetSafeHandle();
1117 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1118 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1119 if (isHeadHash && isHighlight)
1120 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1121 else if (isHeadHash)
1122 hGdiObj = m_boldFont.GetSafeHandle();
1123 else if (isHighlight)
1124 hGdiObj = m_FontItalics.GetSafeHandle();
1126 if (hGdiObj)
1128 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1129 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1132 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1133 // crText = GetSysColor(COLOR_GRAYTEXT);
1135 if (data->m_CommitHash.IsEmpty())
1137 //crText = GetSysColor(RGB(200,200,0));
1138 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1139 // We changed the font, so we're returning CDRF_NEWFONT. This
1140 // tells the control to recalculate the extent of the text.
1141 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1145 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1147 if (m_bStrictStopped)
1148 crText = GetSysColor(COLOR_GRAYTEXT);
1150 // Store the color back in the NMLVCUSTOMDRAW struct.
1151 pLVCD->clrText = crText;
1152 return;
1154 break;
1155 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1157 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1159 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1162 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1164 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1166 CRect rect;
1167 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1169 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1170 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1172 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1173 if( !data ->m_CommitHash.IsEmpty())
1174 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1176 *pResult = CDRF_SKIPDEFAULT;
1177 return;
1181 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1183 // If the top index of list is changed, the position map of reference label is outdated.
1184 if (m_OldTopIndex != GetTopIndex())
1186 m_OldTopIndex = GetTopIndex();
1187 m_RefLabelPosMap.clear();
1190 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1192 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1194 if ((!m_HashMap[data->m_CommitHash].empty() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1196 CRect rect;
1197 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1199 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1200 // not in FillBackGround method, because this only affected the message subitem
1201 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1202 return;
1204 int index = (int)pLVCD->nmcd.dwItemSpec;
1205 int state = GetItemState(index, LVIS_SELECTED);
1206 int txtState = LISS_NORMAL;
1207 if (IsAppThemed() && GetHotItem() == (int)index)
1209 if (state & LVIS_SELECTED)
1210 txtState = LISS_HOTSELECTED;
1211 else
1212 txtState = LISS_HOT;
1214 else if (state & LVIS_SELECTED)
1216 if (::GetFocus() == m_hWnd)
1217 txtState = LISS_SELECTED;
1218 else
1219 txtState = LISS_SELECTEDNOTFOCUS;
1222 HTHEME hTheme = nullptr;
1223 if (IsAppThemed())
1224 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1226 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1227 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1228 else
1230 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1231 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1232 ::DeleteObject(brush);
1234 if (hTheme && txtState != LISS_NORMAL)
1236 CRect rt;
1237 // get rect of whole line
1238 GetItemRect(index, rt, LVIR_BOUNDS);
1239 CRect rect2 = rect;
1241 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1242 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1244 CloseThemeData(hTheme);
1246 // END: extended redraw
1248 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1250 std::vector<REFLABEL> refsToShow;
1251 STRING_VECTOR remoteTrackingList;
1252 STRING_VECTOR refList = m_HashMap[data->m_CommitHash];
1253 for (unsigned int i = 0; i < refList.size(); ++i)
1255 CString str = refList[i];
1257 REFLABEL refLabel;
1258 refLabel.color = RGB(255, 255, 255);
1259 refLabel.singleRemote = false;
1260 refLabel.hasTracking = false;
1261 refLabel.sameName = false;
1262 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1263 refLabel.fullName = str;
1265 switch (refLabel.refType)
1267 case CGit::REF_TYPE::LOCAL_BRANCH:
1269 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1270 continue;
1271 if (refLabel.name == m_CurrentBranch)
1272 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1273 else
1274 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1276 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1277 CString pullRemote = trackingEntry.first;
1278 CString pullBranch = trackingEntry.second;
1279 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1281 CString defaultUpstream;
1282 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1283 refLabel.hasTracking = true;
1284 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1286 bool found = false;
1287 for (size_t j = i + 1; j < refList.size(); ++j)
1289 if (refList[j] == defaultUpstream)
1291 found = true;
1292 break;
1296 if (found)
1298 bool sameName = pullBranch == refLabel.name;
1299 refsToShow.push_back(refLabel);
1300 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1301 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1302 if (m_bSymbolizeRefNames)
1304 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1306 refLabel.simplifiedName = L'/';
1307 if (sameName)
1308 refLabel.simplifiedName += L'≡';
1309 else
1310 refLabel.simplifiedName += pullBranch;
1311 refLabel.singleRemote = true;
1313 else if (sameName)
1314 refLabel.simplifiedName = pullRemote + L"/≡";
1315 refLabel.sameName = sameName;
1317 refLabel.fullName = defaultUpstream;
1318 refsToShow.push_back(refLabel);
1319 remoteTrackingList.push_back(defaultUpstream);
1320 continue;
1324 break;
1326 case CGit::REF_TYPE::REMOTE_BRANCH:
1328 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1329 continue;
1330 bool found = false;
1331 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1333 if (remoteTrackingList[j] == str)
1335 found = true;
1336 break;
1339 if (found)
1340 continue;
1342 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1343 if (m_bSymbolizeRefNames)
1345 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1347 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1348 refLabel.singleRemote = true;
1351 break;
1353 case CGit::REF_TYPE::ANNOTATED_TAG:
1354 case CGit::REF_TYPE::TAG:
1355 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1356 continue;
1357 refLabel.color = m_Colors.GetColor(CColors::Tag);
1358 break;
1359 case CGit::REF_TYPE::STASH:
1360 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1361 continue;
1362 refLabel.color = m_Colors.GetColor(CColors::Stash);
1363 break;
1364 case CGit::REF_TYPE::BISECT_GOOD:
1365 case CGit::REF_TYPE::BISECT_BAD:
1366 case CGit::REF_TYPE::BISECT_SKIP:
1367 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1368 continue;
1369 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));
1370 break;
1371 default:
1372 continue;
1374 refsToShow.push_back(refLabel);
1376 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1378 REFLABEL refLabel;
1379 refLabel.color = RGB(246, 153, 253);
1380 refLabel.singleRemote = false;
1381 refLabel.hasTracking = false;
1382 refLabel.sameName = false;
1383 refLabel.name = L"super-project-pointer";
1384 refLabel.fullName = "";
1385 refsToShow.push_back(refLabel);
1388 if (refsToShow.empty())
1390 *pResult = CDRF_DODEFAULT;
1391 return;
1394 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1396 *pResult = CDRF_SKIPDEFAULT;
1397 return;
1404 if (pLVCD->iSubItem == LOGLIST_ACTION)
1406 if(this->m_IsIDReplaceAction)
1408 *pResult = CDRF_DODEFAULT;
1409 return;
1411 *pResult = CDRF_DODEFAULT;
1413 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1414 return;
1416 int nIcons = 0;
1417 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1418 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1420 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1421 CRect rect;
1422 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1423 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1424 // Get the selected state of the
1425 // item being drawn.
1427 // Fill the background if necessary
1428 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec, rect);
1430 // Draw the icon(s) into the compatible DC
1431 int action = pLogEntry->GetAction(this);
1432 if (!pLogEntry->m_IsDiffFiles)
1434 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1435 *pResult = CDRF_SKIPDEFAULT;
1436 return;
1439 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1440 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1441 ++nIcons;
1443 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1444 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1445 ++nIcons;
1447 if (action & CTGitPath::LOGACTIONS_DELETED)
1448 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1449 ++nIcons;
1451 if (action & CTGitPath::LOGACTIONS_REPLACED)
1452 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1453 ++nIcons;
1455 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1456 ::DrawIconEx(pLVCD->nmcd.hdc, rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 *pResult = CDRF_SKIPDEFAULT;
1460 return;
1463 break;
1465 *pResult = CDRF_DODEFAULT;
1468 CString FindSVNRev(const CString& msg)
1472 const std::tr1::wsregex_iterator end;
1473 std::wstring s = msg;
1474 std::tr1::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1475 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1477 const std::tr1::wsmatch match = *it;
1478 if (match.size() == 4)
1480 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1481 return std::wstring(match[2]).c_str();
1484 std::tr1::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1485 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1487 const std::tr1::wsmatch match = *it;
1488 if (match.size() == 3)
1490 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1491 return std::wstring(match[1]).c_str();
1495 catch (std::exception&) {}
1497 return L"";
1500 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1502 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1503 return pLogEntry->GetSubject();
1505 CString txt(pLogEntry->GetSubject());
1506 txt += L' ';
1507 txt += pLogEntry->GetBody();
1509 // Deal with CRLF
1510 txt.Replace(L'\n', L' ');
1511 txt.Replace(L'\r', L' ');
1513 return txt;
1516 // CGitLogListBase message handlers
1518 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1520 struct payload_struct { const CString* name; const char* authorName; };
1521 payload_struct payload = { &name, nullptr };
1522 const char* author1 = nullptr;
1523 const char* email1 = nullptr;
1524 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1525 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1526 free((void *)payload.authorName);
1527 if (returnEmail)
1528 return email1;
1529 return author1;
1532 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1534 if (mailmap)
1536 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1537 if (translated)
1539 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1540 return;
1543 if (returnEmail)
1544 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1545 else
1546 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1549 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1551 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1553 // Create a pointer to the item
1554 LV_ITEM* pItem = &(pDispInfo)->item;
1556 // Do the list need text information?
1557 if (!(pItem->mask & LVIF_TEXT))
1558 return;
1560 // By default, clear text buffer.
1561 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1563 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1565 *pResult = 0;
1566 if (m_bNoDispUpdates || bOutOfRange)
1567 return;
1569 // Which item number?
1570 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1572 CString temp;
1573 if(m_IsOldFirst)
1574 temp.Format(L"%d", pItem->iItem + 1);
1575 else
1576 temp.Format(L"%d", m_arShownList.size() - pItem->iItem);
1578 if (!pLogEntry)
1579 return;
1581 // Which column?
1582 switch (pItem->iSubItem)
1584 case LOGLIST_GRAPH: //Graphic
1585 break;
1586 case LOGLIST_REBASE:
1587 if (m_IsRebaseReplaceGraph)
1588 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1589 break;
1590 case LOGLIST_ACTION: //action -- no text in the column
1591 break;
1592 case LOGLIST_HASH:
1593 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1594 break;
1595 case LOGLIST_ID:
1596 if (this->m_IsIDReplaceAction)
1597 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1598 break;
1599 case LOGLIST_MESSAGE: //Message
1600 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1601 break;
1602 case LOGLIST_AUTHOR: //Author
1603 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1604 break;
1605 case LOGLIST_DATE: //Date
1606 if (!pLogEntry->m_CommitHash.IsEmpty())
1607 lstrcpyn(pItem->pszText,
1608 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1609 pItem->cchTextMax - 1);
1610 break;
1612 case LOGLIST_EMAIL:
1613 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1614 break;
1616 case LOGLIST_COMMIT_NAME: //Commit
1617 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1618 break;
1620 case LOGLIST_COMMIT_EMAIL: //Commit Email
1621 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1622 break;
1624 case LOGLIST_COMMIT_DATE: //Commit Date
1625 if (!pLogEntry->m_CommitHash.IsEmpty())
1626 lstrcpyn(pItem->pszText,
1627 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1628 pItem->cchTextMax - 1);
1629 break;
1630 case LOGLIST_BUG: //Bug ID
1631 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1632 break;
1633 case LOGLIST_SVNREV: //SVN revision
1634 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1635 break;
1637 default:
1638 ASSERT(false);
1642 bool CGitLogListBase::IsOnStash(int index)
1644 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1645 if (IsStash(rev))
1646 return true;
1647 if (index > 0)
1649 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1650 if (IsStash(preRev))
1651 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1653 return false;
1656 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1658 for (size_t i = 0; i < m_HashMap[pSelLogEntry->m_CommitHash].size(); ++i)
1660 if (m_HashMap[pSelLogEntry->m_CommitHash][i] == L"refs/stash")
1661 return true;
1663 return false;
1666 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1668 for (size_t i = 0; i < m_HashMap[pSelLogEntry->m_CommitHash].size(); ++i)
1670 if (CStringUtils::StartsWith(m_HashMap[pSelLogEntry->m_CommitHash][i], L"refs/bisect/"))
1671 return true;
1673 return false;
1676 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1678 if (pRev->m_ParentHash.empty())
1680 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1681 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1683 parentHash = pRev->m_ParentHash;
1686 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1688 __super::OnContextMenu(pWnd, point);
1690 if (pWnd != this)
1691 return;
1693 int selIndex = GetSelectionMark();
1694 if (selIndex < 0)
1695 return; // nothing selected, nothing to do with a context menu
1697 // if the user selected the info text telling about not all revisions shown due to
1698 // the "stop on copy/rename" option, we also don't show the context menu
1699 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1700 return;
1702 // if the context menu is invoked through the keyboard, we have to use
1703 // a calculated position on where to anchor the menu on
1704 if ((point.x == -1) && (point.y == -1))
1706 CRect rect;
1707 GetItemRect(selIndex, &rect, LVIR_LABEL);
1708 ClientToScreen(&rect);
1709 point = rect.CenterPoint();
1711 m_nSearchIndex = selIndex;
1712 m_bCancelled = FALSE;
1714 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1716 POSITION pos = GetFirstSelectedItemPosition();
1717 int FirstSelect = GetNextSelectedItem(pos);
1718 if (FirstSelect < 0)
1719 return;
1721 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1722 if (pSelLogEntry == nullptr)
1723 return;
1725 int LastSelect = -1;
1726 UINT selectedCount = 1;
1727 while (pos)
1729 LastSelect = GetNextSelectedItem(pos);
1730 ++selectedCount;
1733 ASSERT(GetSelectedCount() == selectedCount);
1735 #if 0
1736 GitRev revSelected = pSelLogEntry->Rev;
1737 GitRev revPrevious = git_revnum_t(revSelected)-1;
1738 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1740 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1742 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1743 if (changedpath->lCopyFromRev)
1744 revPrevious = changedpath->lCopyFromRev;
1747 GitRev revSelected2;
1748 if (pos)
1750 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1751 revSelected2 = pLogEntry->Rev;
1753 bool bAllFromTheSameAuthor = true;
1754 CString firstAuthor;
1755 CLogDataVector selEntries;
1756 GitRev revLowest, revHighest;
1757 GitRevRangeArray revisionRanges;
1759 POSITION pos = GetFirstSelectedItemPosition();
1760 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1761 revisionRanges.AddRevision(pLogEntry->Rev);
1762 selEntries.push_back(pLogEntry);
1763 firstAuthor = pLogEntry->sAuthor;
1764 revLowest = pLogEntry->Rev;
1765 revHighest = pLogEntry->Rev;
1766 while (pos)
1768 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1769 revisionRanges.AddRevision(pLogEntry->Rev);
1770 selEntries.push_back(pLogEntry);
1771 if (firstAuthor.Compare(pLogEntry->sAuthor))
1772 bAllFromTheSameAuthor = false;
1773 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1774 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1778 #endif
1780 //entry is selected, now show the popup menu
1781 CIconMenu popup;
1782 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1784 if (popup.CreatePopupMenu())
1786 bool isHeadCommit = (pSelLogEntry->m_CommitHash == m_HeadHash);
1787 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1788 CTGitPath workingTree(g_Git.m_CurrentDir);
1789 bool isMergeActive = workingTree.IsMergeActive();
1790 bool isBisectActive = workingTree.IsBisectActive();
1791 bool isStash = IsOnStash(FirstSelect);
1792 GIT_REV_LIST parentHash;
1793 GetParentHashes(pSelLogEntry, parentHash);
1795 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1796 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1798 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))
1799 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1801 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1802 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1804 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1805 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1807 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)))
1808 popup.AppendMenu(MF_SEPARATOR, NULL);
1810 if (selectedCount == 1)
1813 bool requiresSeparator = false;
1814 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1816 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1818 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1819 requiresSeparator = true;
1822 else
1824 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1826 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1827 requiresSeparator = true;
1829 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1831 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1832 requiresSeparator = true;
1836 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1838 if (parentHash.size() == 1)
1840 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1841 requiresSeparator = true;
1843 else if (parentHash.size() > 1)
1845 blamemenu.CreatePopupMenu();
1846 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1847 for (size_t i = 0; i < parentHash.size(); ++i)
1849 CString str;
1850 str.Format(IDS_PARENT, i + 1);
1851 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1853 requiresSeparator = true;
1857 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1859 if (parentHash.size() == 1)
1861 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1862 requiresSeparator = true;
1864 else if (parentHash.size() > 1)
1866 gnudiffmenu.CreatePopupMenu();
1867 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1869 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1870 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1871 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1873 for (size_t i = 0; i < parentHash.size(); ++i)
1875 CString str;
1876 str.Format(IDS_PARENT, i + 1);
1877 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1879 requiresSeparator = true;
1883 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1885 if (parentHash.size() == 1)
1887 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1888 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1889 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1890 requiresSeparator = true;
1892 else if (parentHash.size() > 1)
1894 diffmenu.CreatePopupMenu();
1895 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1896 for (size_t i = 0; i < parentHash.size(); ++i)
1898 CString str;
1899 str.Format(IDS_PARENT, i + 1);
1900 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1901 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1903 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1904 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1907 requiresSeparator = true;
1911 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1913 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1914 requiresSeparator = true;
1917 if (requiresSeparator)
1919 popup.AppendMenu(MF_SEPARATOR, NULL);
1920 requiresSeparator = false;
1923 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1925 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1927 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1928 requiresSeparator = true;
1932 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1934 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1936 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1937 requiresSeparator = true;
1940 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1942 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1943 requiresSeparator = true;
1947 if (requiresSeparator)
1949 popup.AppendMenu(MF_SEPARATOR, NULL);
1950 requiresSeparator = false;
1953 if (isBisectActive)
1955 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1956 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1958 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1959 requiresSeparator = true;
1962 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1964 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1965 requiresSeparator = true;
1967 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1969 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1970 requiresSeparator = true;
1974 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1976 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1978 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1979 requiresSeparator = true;
1983 if (requiresSeparator)
1985 popup.AppendMenu(MF_SEPARATOR, NULL);
1986 requiresSeparator = false;
1989 if (pSelLogEntry->m_CommitHash.IsEmpty())
1991 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
1992 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
1994 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
1995 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
1997 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
1998 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2000 popup.AppendMenu(MF_SEPARATOR, NULL);
2002 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2003 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2005 popup.AppendMenu(MF_SEPARATOR, NULL);
2009 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2010 // {
2011 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2012 // }
2013 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2014 // {
2015 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2016 // }
2017 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2018 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2019 // {
2020 // popup.AppendMenu(MF_SEPARATOR, NULL);
2021 // }
2023 CString str;
2024 //if (m_hasWC)
2025 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2027 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2029 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2030 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2032 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2033 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2035 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2037 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2039 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2041 size_t index = (size_t)-1;
2042 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2043 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2044 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2047 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2049 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2050 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2053 // Add Switch Branch express Menu
2054 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2055 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2058 std::vector<const CString*> branchs;
2059 auto addCheck = [&](const CString& ref)
2061 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2062 return;
2063 branchs.push_back(&ref);
2065 size_t index = (size_t)-1;
2066 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2067 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2068 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2069 else
2070 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2072 CString str2;
2073 str2.LoadString(IDS_SWITCH_BRANCH);
2075 if(branchs.size() == 1)
2077 str2 += L' ';
2078 str2 += L'"' + branchs[0]->Mid(11) + L'"'; // 11 = len("refs/heads/")
2079 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2081 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2084 else if(branchs.size() > 1)
2086 subbranchmenu.CreatePopupMenu();
2087 for (size_t i = 0 ; i < branchs.size(); ++i)
2089 if (*branchs[i] != currentBranch)
2091 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2092 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2096 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2100 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2102 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2103 size_t index = (size_t)-1;
2104 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2105 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2106 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2109 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2111 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2113 size_t index = (size_t)-1;
2114 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2115 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2116 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2119 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2120 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2122 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2124 if (pSelLogEntry->m_CommitHash != m_HeadHash && m_hasWC && !isMergeActive && !isStash)
2125 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2126 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2128 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2129 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2131 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2133 if (parentHash.size() == 1)
2134 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2135 else if (parentHash.size() > 1)
2137 revertmenu.CreatePopupMenu();
2138 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2140 for (size_t i = 0; i < parentHash.size(); ++i)
2142 CString str2;
2143 str2.Format(IDS_PARENT, i + 1);
2144 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2149 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2150 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2152 popup.AppendMenu(MF_SEPARATOR, NULL);
2156 if(!pSelLogEntry->m_Ref.IsEmpty())
2158 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2159 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2160 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2161 if (selectedCount <= 2)
2162 popup.AppendMenu(MF_SEPARATOR, NULL);
2165 if (selectedCount >= 2)
2167 bool bAddSeparator = false;
2168 if ((selectedCount == 2) || IsSelectionContinuous())
2170 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2171 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2174 if (selectedCount == 2)
2176 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2177 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2179 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2181 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2182 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2183 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2184 CString menu;
2185 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2186 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2187 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2188 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2191 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 (m_hasWC)
2201 bAddSeparator = true;
2203 if (bAddSeparator)
2205 popup.AppendMenu(MF_SEPARATOR, NULL);
2206 bAddSeparator = false;
2209 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2210 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2212 if (bAddSeparator)
2213 popup.AppendMenu(MF_SEPARATOR, NULL);
2216 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2218 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2219 popup.AppendMenu(MF_SEPARATOR, NULL);
2222 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2224 bool bAddSeparator = false;
2225 if (selectedCount >= 2 && IsSelectionContinuous())
2227 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2229 CString head;
2230 int headindex;
2231 headindex = this->GetHeadIndex();
2232 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2234 head.Format(L"HEAD~%d", FirstSelect - headindex);
2235 CGitHash hashFirst;
2236 int ret = g_Git.GetHash(hashFirst, head);
2237 head.Format(L"HEAD~%d",LastSelect-headindex);
2238 CGitHash hash;
2239 ret = ret || g_Git.GetHash(hash, head);
2240 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2241 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2242 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2244 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2245 bAddSeparator = true;
2250 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2251 if (selectedCount >= 2)
2252 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2253 else
2254 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2255 bAddSeparator = true;
2258 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2259 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2260 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2261 bAddSeparator = true;
2264 if (bAddSeparator)
2265 popup.AppendMenu(MF_SEPARATOR, NULL);
2268 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2270 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2271 popup.AppendMenu(MF_SEPARATOR, NULL);
2274 if (selectedCount == 1)
2276 bool bAddSeparator = false;
2277 if (m_ContextMenuMask&GetContextMenuBit(ID_PUSH) && ((!isStash && !m_HashMap[pSelLogEntry->m_CommitHash].empty()) || showExtendedMenu))
2279 // show the push-option only if the log entry has an associated local branch
2280 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2281 if (isLocal || showExtendedMenu)
2283 CString str;
2284 str.LoadString(IDS_LOG_PUSH);
2286 CString branch;
2287 size_t index = (size_t)-1;
2288 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
2289 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2290 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2292 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2294 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2295 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2297 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2298 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2300 bAddSeparator = true;
2303 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2305 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2306 bAddSeparator = true;
2310 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2312 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2314 std::vector<const CString*> branchs;
2315 auto addCheck = [&](const CString& ref)
2317 if (ref == currentBranch)
2318 return;
2319 branchs.push_back(&ref);
2321 size_t index = (size_t)-1;
2322 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2323 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2324 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2325 else
2326 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2328 CString str;
2329 if (branchs.size() == 1)
2331 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2332 str += L' ';
2333 str += *branchs[0];
2334 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2335 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2336 bAddSeparator = true;
2338 else if (branchs.size() > 1)
2340 str.LoadString(IDS_DELETE_BRANCHTAG);
2341 submenu.CreatePopupMenu();
2342 for (size_t i = 0; i < branchs.size(); ++i)
2344 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2345 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2347 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2348 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2350 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2351 bAddSeparator = true;
2354 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2355 if (bAddSeparator)
2356 popup.AppendMenu(MF_SEPARATOR, NULL);
2357 } // selectedCount == 1
2359 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYHASH))
2360 popup.AppendMenuIcon(ID_COPYHASH, IDS_COPY_COMMIT_HASH, IDI_COPYCLIP);
2361 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2362 popup.AppendMenuIcon(ID_COPYCLIPBOARD, IDS_LOG_POPUP_COPYTOCLIPBOARD, IDI_COPYCLIP);
2363 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARDMESSAGES))
2364 popup.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_COPYTOCLIPBOARDMESSAGES, IDI_COPYCLIP);
2366 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2367 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2369 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2370 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2372 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2373 // DialogEnableWindow(IDOK, FALSE);
2374 // SetPromptApp(&theApp);
2376 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2378 // EnableOKButton();
2379 } // if (popup.CreatePopupMenu())
2382 bool CGitLogListBase::IsSelectionContinuous()
2384 if ( GetSelectedCount()==1 )
2386 // if only one revision is selected, the selection is of course
2387 // continuous
2388 return true;
2391 POSITION pos = GetFirstSelectedItemPosition();
2392 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2393 if (bContinuous)
2395 int itemindex = GetNextSelectedItem(pos);
2396 while (pos)
2398 int nextindex = GetNextSelectedItem(pos);
2399 if (nextindex - itemindex > 1)
2401 bContinuous = false;
2402 break;
2404 itemindex = nextindex;
2407 return bContinuous;
2410 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2412 CString sClipdata;
2413 POSITION pos = GetFirstSelectedItemPosition();
2414 if (pos)
2416 CString sRev;
2417 sRev.LoadString(IDS_LOG_REVISION);
2418 CString sAuthor;
2419 sAuthor.LoadString(IDS_LOG_AUTHOR);
2420 CString sDate;
2421 sDate.LoadString(IDS_LOG_DATE);
2422 CString sMessage;
2423 sMessage.LoadString(IDS_LOG_MESSAGE);
2424 bool first = true;
2425 while (pos)
2427 CString sLogCopyText;
2428 CString sPaths;
2429 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2431 if (toCopy == ID_COPY_ALL)
2433 //pLogEntry->GetFiles(this)
2434 //LogChangedPathArray * cpatharray = pLogEntry->pArChangedPaths;
2436 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2437 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2439 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2440 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2442 sPaths += L' ';
2443 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2445 sPaths += L"\r\n";
2447 sPaths.Trim();
2449 CString sNotesTags;
2450 if (!pLogEntry->m_Notes.IsEmpty())
2452 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2453 sNotesTags += L":\n";
2454 sNotesTags += pLogEntry->m_Notes;
2455 sNotesTags.Replace(L"\n", L"\r\n");
2457 CString tagInfo = GetTagInfo(pLogEntry);
2458 if (!tagInfo.IsEmpty())
2460 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2461 tagInfo.Replace(L"\n", L"\r\n");
2462 sNotesTags += tagInfo;
2465 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s----\r\n%s\r\n\r\n",
2466 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2467 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2468 (LPCTSTR)sDate,
2469 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2470 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2471 (LPCTSTR)sNotesTags,
2472 (LPCTSTR)sPaths);
2473 sClipdata += sLogCopyText;
2475 else if (toCopy == ID_COPY_MESSAGE)
2477 sClipdata += L"* ";
2478 sClipdata += pLogEntry->GetSubjectBody(true);
2479 sClipdata += L"\r\n\r\n";
2481 else if (toCopy == ID_COPY_SUBJECT)
2483 sClipdata += L"* ";
2484 sClipdata += pLogEntry->GetSubject().Trim();
2485 sClipdata += L"\r\n\r\n";
2487 else
2489 if (!first)
2490 sClipdata += L"\r\n";
2491 sClipdata += pLogEntry->m_CommitHash;
2494 first = false;
2496 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2500 void CGitLogListBase::DiffSelectedRevWithPrevious()
2502 if (m_bThreadRunning)
2503 return;
2505 int FirstSelect=-1, LastSelect=-1;
2506 POSITION pos = GetFirstSelectedItemPosition();
2507 FirstSelect = GetNextSelectedItem(pos);
2508 while(pos)
2509 LastSelect = GetNextSelectedItem(pos);
2511 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2514 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2516 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2517 *pResult = -1;
2519 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2520 return;
2521 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2522 return;
2523 if (!pFindInfo->lvfi.psz)
2524 return;
2525 #if 0
2526 CString sCmp = pFindInfo->lvfi.psz;
2527 CString sRev;
2528 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2530 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2531 sRev.Format(L"%ld", pLogEntry->Rev);
2532 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2534 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2536 *pResult = i;
2537 return;
2540 else
2542 if (sCmp.Compare(sRev)==0)
2544 *pResult = i;
2545 return;
2549 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2551 for (int i=0; i<pFindInfo->iStart; ++i)
2553 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2554 sRev.Format(L"%ld", pLogEntry->Rev);
2555 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2557 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2559 *pResult = i;
2560 return;
2563 else
2565 if (sCmp.Compare(sRev)==0)
2567 *pResult = i;
2568 return;
2573 #endif
2574 *pResult = -1;
2577 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2579 ClearText();
2581 this->m_arShownList.SafeRemoveAll();
2583 this->m_logEntries.ClearAll();
2584 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2585 return -1;
2587 SetItemCountEx((int)m_logEntries.size());
2589 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2591 if(m_IsOldFirst)
2593 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2594 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2596 else
2598 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2599 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2603 ReloadHashMap();
2605 if(path)
2606 m_Path=*path;
2607 return 0;
2610 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2612 ClearText();
2614 m_arShownList.SafeRemoveAll();
2616 m_logEntries.ClearAll();
2617 if (m_logEntries.Fill(hashes))
2618 return -1;
2620 SetItemCountEx((int)m_logEntries.size());
2622 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2624 if (m_IsOldFirst)
2626 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2627 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2629 else
2631 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2632 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2636 ReloadHashMap();
2638 return 0;
2641 int CGitLogListBase::BeginFetchLog()
2643 ClearText();
2645 this->m_arShownList.SafeRemoveAll();
2647 this->m_logEntries.ClearAll();
2649 this->m_LogCache.ClearAllParent();
2651 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2653 CTGitPath *path;
2654 if(this->m_Path.IsEmpty())
2655 path = nullptr;
2656 else
2657 path=&this->m_Path;
2659 int mask;
2660 mask = CGit::LOG_INFO_ONLY_HASH;
2661 if (m_bIncludeBoundaryCommits)
2662 mask |= CGit::LOG_INFO_BOUNDARY;
2663 // if(this->m_bAllBranch)
2664 mask |= m_ShowMask ;
2666 if(m_bShowWC)
2668 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2669 ResetWcRev();
2670 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2673 if (m_sRange.IsEmpty())
2674 m_sRange = L"HEAD";
2676 #if 0 /* use tortoiegit filter */
2677 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2678 data.m_Author = this->m_sFilterText;
2680 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2681 data.m_MessageFilter = this->m_sFilterText;
2683 data.m_IsRegex = m_bFilterWithRegex;
2684 #endif
2686 // follow does not work for directories
2687 if (!path || path->IsDirectory())
2688 mask &= ~CGit::LOG_INFO_FOLLOW;
2689 // follow does not work with all branches 8at least in TGit)
2690 if (mask & CGit::LOG_INFO_FOLLOW)
2691 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2693 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2695 //this->m_logEntries.ParserFromLog();
2696 if(IsInWorkingThread())
2698 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2700 else
2702 SetItemCountEx((int)m_logEntries.size());
2707 [] { git_init(); } ();
2709 catch (char* msg)
2711 CString err(msg);
2712 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2713 return -1;
2716 if (!g_Git.CanParseRev(m_sRange))
2718 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2719 return 0;
2721 // if show all branches, pick any ref as dummy entry ref
2722 STRING_VECTOR list;
2723 if (g_Git.GetRefList(list))
2724 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2725 if (list.empty())
2726 return 0;
2728 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2731 g_Git.m_critGitDllSec.Lock();
2732 try {
2733 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2735 g_Git.m_critGitDllSec.Unlock();
2736 return -1;
2739 catch (char* msg)
2741 g_Git.m_critGitDllSec.Unlock();
2742 CString err(msg);
2743 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2744 return -1;
2746 g_Git.m_critGitDllSec.Unlock();
2748 return 0;
2751 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2753 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2755 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2757 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2759 DiffSelectedRevWithPrevious();
2760 return TRUE;
2763 #if 0
2764 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2766 DiffSelectedFile();
2767 return TRUE;
2769 #endif
2771 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2773 // select all entries
2774 for (int i=0; i<GetItemCount(); ++i)
2775 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2776 return TRUE;
2779 #if 0
2780 if (m_hAccel && !bSkipAccelerator)
2782 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2783 if (ret)
2784 return TRUE;
2787 #endif
2788 //m_tooltips.RelayEvent(pMsg);
2789 return __super::PreTranslateMessage(pMsg);
2792 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2794 // a double click on an entry in the revision list has happened
2795 *pResult = 0;
2797 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2798 DiffSelectedRevWithPrevious();
2801 void CGitLogListBase::FetchLogAsync(void* data)
2803 ReloadHashMap();
2804 m_ProcData=data;
2805 StartLoadingThread();
2808 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2810 return ((CGitLogListBase*)pVoid)->LogThread();
2813 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2815 //CTime time;
2816 oldest=CTime::GetCurrentTime();
2817 latest=CTime(1971,1,2,0,0,0);
2818 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2820 if(m_logEntries[i].IsEmpty())
2821 continue;
2823 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2824 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2826 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2827 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2831 if(latest<oldest)
2832 latest=oldest;
2835 UINT CGitLogListBase::LogThread()
2837 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2839 ULONGLONG t1,t2;
2841 if(BeginFetchLog())
2843 InterlockedExchange(&m_bThreadRunning, FALSE);
2844 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2846 return 1;
2849 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
2850 bool bRegex = false;
2851 if (m_bFilterWithRegex)
2852 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2854 TRACE(L"\n===Begin===\n");
2855 //Update work copy item;
2857 if (!m_logEntries.empty())
2859 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2861 m_arShownList.SafeAdd(pRev);
2865 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2867 // store commit number of the last selected commit/line before the refresh or -1
2868 int lastSelectedHashNItem = -1;
2869 if (m_lastSelectedHash.IsEmpty())
2870 lastSelectedHashNItem = 0;
2872 int ret = 0;
2874 bool shouldWalk = true;
2875 if (!g_Git.CanParseRev(m_sRange))
2877 // walk revisions if show all branches and there exists any ref
2878 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2879 shouldWalk = false;
2880 else
2882 STRING_VECTOR list;
2883 if (g_Git.GetRefList(list))
2884 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2885 if (list.empty())
2886 shouldWalk = false;
2890 if (shouldWalk)
2892 g_Git.m_critGitDllSec.Lock();
2893 int total = 0;
2896 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2897 total = git_get_log_estimate_commit_count(m_DllGitLog);
2899 catch (char* msg)
2901 CString err(msg);
2902 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2903 ret = -1;
2905 g_Git.m_critGitDllSec.Unlock();
2907 GIT_COMMIT commit;
2908 t2 = t1 = GetTickCount64();
2909 int oldprecentage = 0;
2910 size_t oldsize = m_logEntries.size();
2911 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2912 while (ret== 0 && !m_bExitThread)
2914 g_Git.m_critGitDllSec.Lock();
2917 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2919 catch (char* msg)
2921 g_Git.m_critGitDllSec.Unlock();
2922 CString err(msg);
2923 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2924 break;
2926 g_Git.m_critGitDllSec.Unlock();
2928 if(ret)
2930 if (ret != -2) // other than end of revision walking
2931 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2932 break;
2935 if (commit.m_ignore == 1)
2937 git_free_commit(&commit);
2938 continue;
2941 //printf("%s\r\n",commit.GetSubject());
2942 if(m_bExitThread)
2943 break;
2945 CGitHash hash(commit.m_hash);
2947 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
2948 pRev->m_GitCommit = commit;
2949 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
2951 char* note = nullptr;
2952 g_Git.m_critGitDllSec.Lock();
2955 git_get_notes(commit.m_hash, &note);
2957 catch (char* msg)
2959 g_Git.m_critGitDllSec.Unlock();
2960 CString err(msg);
2961 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2962 break;
2964 g_Git.m_critGitDllSec.Unlock();
2966 if(note)
2968 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
2969 free(note);
2970 note = nullptr;
2973 if(!pRev->m_IsDiffFiles)
2975 pRev->m_CallDiffAsync = DiffAsync;
2978 pRev->ParserParentFromCommit(&commit);
2979 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
2981 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
2983 const CGitHash &parentHash = pRev->m_ParentHash[i];
2984 auto it = commitChildren.find(parentHash);
2985 if (it == commitChildren.end())
2986 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
2987 it->second.insert(pRev->m_CommitHash);
2991 #ifdef DEBUG
2992 pRev->DbgPrint();
2993 TRACE(L"\n");
2994 #endif
2996 bool visible = true;
2997 if (HasFilterText())
2999 if(!IsMatchFilter(bRegex,pRev,pat))
3000 visible = false;
3002 if (visible && !ShouldShowFilter(pRev, commitChildren))
3003 visible = false;
3004 this->m_critSec.Lock();
3005 m_logEntries.append(hash, visible);
3006 if (visible)
3007 m_arShownList.SafeAdd(pRev);
3008 this->m_critSec.Unlock();
3010 if (!visible)
3011 continue;
3013 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3014 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3016 t2 = GetTickCount64();
3018 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3020 //update UI
3021 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3022 if(percent > 99)
3023 percent =99;
3024 if(percent < GITLOG_START)
3025 percent = GITLOG_START +1;
3027 oldsize = m_logEntries.size();
3028 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3030 //if( percent > oldprecentage )
3032 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3033 oldprecentage = percent;
3036 if (lastSelectedHashNItem >= 0)
3037 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3039 t1 = t2;
3042 g_Git.m_critGitDllSec.Lock();
3043 git_close_log(m_DllGitLog);
3044 g_Git.m_critGitDllSec.Unlock();
3048 if (m_bExitThread)
3050 InterlockedExchange(&m_bThreadRunning, FALSE);
3051 return 0;
3054 //Update UI;
3055 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3057 if (lastSelectedHashNItem >= 0)
3058 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3060 if (this->m_hWnd)
3061 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3063 InterlockedExchange(&m_bThreadRunning, FALSE);
3065 return 0;
3068 void CGitLogListBase::FetchRemoteList()
3070 STRING_VECTOR remoteList;
3071 m_SingleRemote.Empty();
3072 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3073 m_SingleRemote = remoteList[0];
3076 void CGitLogListBase::FetchTrackingBranchList()
3078 m_TrackingMap.clear();
3079 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3081 for (const auto& ref : it->second)
3083 CString branchName;
3084 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3086 CString pullRemote, pullBranch;
3087 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3088 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3089 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3095 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3097 SafeTerminateThread();
3099 this->SetItemCountEx(0);
3100 this->Clear();
3102 ResetWcRev();
3104 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3106 if (m_pMailmap)
3108 git_free_mailmap(m_pMailmap);
3109 git_read_mailmap(&m_pMailmap);
3112 //Update branch and Tag info
3113 ReloadHashMap();
3114 if (m_pFindDialog)
3115 m_pFindDialog->RefreshList();
3116 //Assume Thread have exited
3117 //if(!m_bThreadRunning)
3119 m_logEntries.clear();
3121 if(IsCleanFilter)
3123 m_sFilterText.Empty();
3126 SafeTerminateAsyncDiffThread();
3127 m_AsynDiffListLock.Lock();
3128 m_AsynDiffList.clear();
3129 m_AsynDiffListLock.Unlock();
3130 StartAsyncDiffThread();
3132 StartLoadingThread();
3136 void CGitLogListBase::StartAsyncDiffThread()
3138 if (m_AsyncThreadExit)
3139 return;
3140 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3141 return;
3142 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3143 if (!m_DiffingThread)
3145 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3146 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3150 void CGitLogListBase::StartLoadingThread()
3152 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3153 return;
3154 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3155 InterlockedExchange(&m_bExitThread, FALSE);
3156 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3157 if (!m_LoadingThread)
3159 InterlockedExchange(&m_bThreadRunning, FALSE);
3160 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3161 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3165 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::tr1::wregex& pat, bool bMatchCase /* = false */)
3169 std::tr1::regex_constants::syntax_option_type type = std::tr1::regex_constants::ECMAScript;
3170 if (!bMatchCase)
3171 type |= std::tr1::regex_constants::icase;
3172 pat = std::tr1::wregex(regexp_str, type);
3173 return true;
3175 catch (std::exception&) {}
3176 return false;
3178 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::tr1::wregex& pat)
3180 BOOL result = TRUE;
3181 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3182 CString sRev;
3184 if ((bRegex)&&(m_bFilterWithRegex))
3186 if (m_SelectedFilters & LOGFILTER_BUGID)
3188 if(this->m_bShowBugtraqColumn)
3190 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3192 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3193 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3194 return TRUE;
3198 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3200 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3201 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3202 return TRUE;
3205 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3207 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3208 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3209 return TRUE;
3212 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3214 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3215 return TRUE;
3217 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3218 return TRUE;
3221 if (m_SelectedFilters & LOGFILTER_EMAILS)
3223 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3224 return TRUE;
3226 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3227 return TRUE;
3230 if (m_SelectedFilters & LOGFILTER_REVS)
3232 sRev = pRev->m_CommitHash.ToString();
3233 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3235 return TRUE;
3239 if (m_SelectedFilters & LOGFILTER_NOTES)
3241 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3242 return TRUE;
3245 if (m_SelectedFilters & LOGFILTER_REFNAME)
3247 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3248 for (const auto& ref : refs)
3250 if (std::regex_search(std::wstring(ref), pat, flags))
3251 return TRUE;
3255 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3257 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3258 return TRUE;
3261 if (m_SelectedFilters & LOGFILTER_PATHS)
3263 CTGitPathList* pathList = nullptr;
3264 if( pRev->m_IsDiffFiles)
3265 pathList = &pRev->GetFiles(this);
3266 else
3268 if(!pRev->m_IsSimpleListReady)
3269 pRev->SafeGetSimpleList(&g_Git);
3272 if(pathList)
3273 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3275 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3276 return true;
3277 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3278 return true;
3281 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3283 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3284 return true;
3288 else
3290 CString find = m_sFilterText;
3291 if (!m_bFilterCaseSensitively)
3292 find.MakeLower();
3293 result = find[0] == '!' ? FALSE : TRUE;
3294 if (!result)
3295 find = find.Mid(1);
3297 if (m_SelectedFilters & LOGFILTER_BUGID)
3299 if(this->m_bShowBugtraqColumn)
3301 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3303 if (!m_bFilterCaseSensitively)
3304 sBugIds.MakeLower();
3305 if ((sBugIds.Find(find) >= 0))
3306 return result;
3310 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3312 CString msg = pRev->GetSubject();
3314 if (!m_bFilterCaseSensitively)
3315 msg = msg.MakeLower();
3316 if ((msg.Find(find) >= 0))
3317 return result;
3320 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3322 CString msg = pRev->GetBody();
3324 if (!m_bFilterCaseSensitively)
3325 msg = msg.MakeLower();
3326 if ((msg.Find(find) >= 0))
3327 return result;
3330 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3332 CString msg = pRev->GetAuthorName();
3333 if (!m_bFilterCaseSensitively)
3334 msg = msg.MakeLower();
3335 if ((msg.Find(find) >= 0))
3336 return result;
3339 if (m_SelectedFilters & LOGFILTER_EMAILS)
3341 CString msg = pRev->GetAuthorEmail();
3342 if (!m_bFilterCaseSensitively)
3343 msg = msg.MakeLower();
3344 if ((msg.Find(find) >= 0))
3345 return result;
3348 if (m_SelectedFilters & LOGFILTER_NOTES)
3350 CString msg = pRev->m_Notes;
3351 if (!m_bFilterCaseSensitively)
3352 msg = msg.MakeLower();
3353 if ((msg.Find(find) >= 0))
3354 return result;
3357 if (m_SelectedFilters & LOGFILTER_REVS)
3359 sRev = pRev->m_CommitHash.ToString();
3360 if ((sRev.Find(find) >= 0))
3361 return result;
3364 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3366 CString msg = GetTagInfo(pRev);
3367 if (!m_bFilterCaseSensitively)
3368 msg = msg.MakeLower();
3369 if ((msg.Find(find) >= 0))
3370 return result;
3373 if (m_SelectedFilters & LOGFILTER_REFNAME)
3375 STRING_VECTOR refs = m_HashMap[pRev->m_CommitHash];
3376 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3378 if (it->Find(find) >= 0)
3379 return result;
3383 if (m_SelectedFilters & LOGFILTER_PATHS)
3385 CTGitPathList* pathList = nullptr;
3386 if( pRev->m_IsDiffFiles)
3387 pathList = &pRev->GetFiles(this);
3388 else
3390 if(!pRev->m_IsSimpleListReady)
3391 pRev->SafeGetSimpleList(&g_Git);
3393 if(pathList)
3394 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3396 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3397 CString path = cpath->GetGitOldPathString();
3398 if (!m_bFilterCaseSensitively)
3399 path.MakeLower();
3400 if ((path.Find(find)>=0))
3401 return result;
3402 path = cpath->GetGitPathString();
3403 if (!m_bFilterCaseSensitively)
3404 path.MakeLower();
3405 if ((path.Find(find)>=0))
3406 return result;
3409 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3411 CString path = pRev->m_SimpleFileList[i];
3412 if (!m_bFilterCaseSensitively)
3413 path.MakeLower();
3414 if ((path.Find(find)>=0))
3415 return result;
3418 } // else (from if (bRegex))
3419 return !result;
3422 static bool CStringStartsWith(const CString &str, const CString &prefix)
3424 return str.Left(prefix.GetLength()) == prefix;
3426 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3428 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3429 return true;
3431 if (m_ShowFilter & FILTERSHOW_REFS)
3433 // Keep all refs.
3434 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3435 for (size_t i = 0; i < refList.size(); ++i)
3437 const CString &str = refList[i];
3438 if (CStringStartsWith(str, L"refs/heads/"))
3440 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3441 return true;
3443 else if (CStringStartsWith(str, L"refs/remotes/"))
3445 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3446 return true;
3448 else if (CStringStartsWith(str, L"refs/tags/"))
3450 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3451 return true;
3453 else if (CStringStartsWith(str, L"refs/stash"))
3455 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3456 return true;
3458 else if (CStringStartsWith(str, L"refs/bisect/"))
3460 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3461 return true;
3464 // Keep the head too.
3465 if (pRev->m_CommitHash == m_HeadHash)
3466 return true;
3469 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3471 if (pRev->ParentsCount() > 1)
3472 return true;
3473 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3474 if (childrenIt != commitChildren.end())
3476 const std::unordered_set<CGitHash> &children = childrenIt->second;
3477 if (children.size() > 1)
3478 return true;
3481 return false;
3484 void CGitLogListBase::ShowGraphColumn(bool bShow)
3486 // HACK to hide graph column
3487 if (bShow)
3488 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3489 else
3490 SetColumnWidth(0, 0);
3493 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3495 CString cmd;
3496 CString output;
3498 if (m_HashMap.find(pLogEntry->m_CommitHash) != m_HashMap.end())
3500 STRING_VECTOR &vector = m_HashMap[pLogEntry->m_CommitHash];
3501 for (size_t i = 0; i < vector.size(); ++i)
3503 if (CStringUtils::StartsWith(vector[i], L"refs/tags/"))
3505 CString tag = vector[i];
3506 int start = vector[i].Find(L"^{}");
3507 if (start > 0)
3508 tag = tag.Left(start);
3509 else
3510 continue;
3512 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)tag);
3513 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) == 0)
3514 output.Trim().AppendChar(L'\n');
3519 return output;
3522 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3524 pShownlist->SafeRemoveAll();
3526 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
3527 bool bRegex = false;
3528 if (m_bFilterWithRegex)
3529 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3531 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3532 CString sRev;
3533 for (DWORD i=0; i<m_logEntries.size(); ++i)
3535 if ((bRegex)&&(m_bFilterWithRegex))
3537 #if 0
3538 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3540 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3541 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3543 pShownlist->SafeAdd(m_logEntries[i]);
3544 continue;
3547 #endif
3548 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3550 ATLTRACE(L"messge = \"%s\"\n", m_logEntries.GetGitRevAt(i).GetSubject());
3551 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3553 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3554 continue;
3557 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3559 ATLTRACE("messge = \"%s\"\n", m_logEntries.GetGitRevAt(i).GetBody());
3560 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3562 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3563 continue;
3566 if (m_SelectedFilters & LOGFILTER_PATHS)
3568 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3570 bool bGoing = true;
3571 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3573 CTGitPath cpath = pathList[cpPathIndex];
3574 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3576 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3577 bGoing = false;
3578 continue;
3580 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3582 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3583 bGoing = false;
3584 continue;
3586 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3588 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3589 bGoing = false;
3590 continue;
3594 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3596 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3598 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3599 continue;
3602 if (m_SelectedFilters & LOGFILTER_EMAILS)
3604 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3606 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3607 continue;
3610 if (m_SelectedFilters & LOGFILTER_REVS)
3612 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3613 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3615 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3616 continue;
3619 if (m_SelectedFilters & LOGFILTER_REFNAME)
3621 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3622 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3624 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3626 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3627 continue;
3631 } // if (bRegex)
3632 else
3634 CString find = m_sFilterText;
3635 if (!m_bFilterCaseSensitively)
3636 find.MakeLower();
3637 #if 0
3638 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3640 CString sBugIDs = m_logEntries[i]->sBugIDs;
3642 if (!m_bFilterCaseSensitively)
3643 sBugIDs = sBugIDs.MakeLower();
3644 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3646 pShownlist->SafeAdd(m_logEntries[i]);
3647 continue;
3650 #endif
3651 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3653 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3655 if (!m_bFilterCaseSensitively)
3656 msg = msg.MakeLower();
3657 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3659 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3660 continue;
3663 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3665 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3667 if (!m_bFilterCaseSensitively)
3668 msg = msg.MakeLower();
3669 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3671 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3672 continue;
3675 if (m_SelectedFilters & LOGFILTER_PATHS)
3677 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3679 bool bGoing = true;
3680 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3682 CTGitPath cpath = pathList[cpPathIndex];
3683 CString path = cpath.GetGitOldPathString();
3684 if (!m_bFilterCaseSensitively)
3685 path.MakeLower();
3686 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3688 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3689 bGoing = false;
3690 continue;
3692 path = cpath.GetGitPathString();
3693 if (!m_bFilterCaseSensitively)
3694 path.MakeLower();
3695 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3697 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3698 bGoing = false;
3699 continue;
3701 path = cpath.GetActionName();
3702 if (!m_bFilterCaseSensitively)
3703 path.MakeLower();
3704 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3706 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3707 bGoing = false;
3708 continue;
3712 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3714 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3715 if (!m_bFilterCaseSensitively)
3716 msg = msg.MakeLower();
3717 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3719 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3720 continue;
3723 if (m_SelectedFilters & LOGFILTER_EMAILS)
3725 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3726 if (!m_bFilterCaseSensitively)
3727 msg = msg.MakeLower();
3728 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3730 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3731 continue;
3734 if (m_SelectedFilters & LOGFILTER_REVS)
3736 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3737 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3739 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3740 continue;
3743 if (m_SelectedFilters & LOGFILTER_REFNAME)
3745 STRING_VECTOR refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3746 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3748 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3750 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3751 continue;
3755 } // else (from if (bRegex))
3756 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3759 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3762 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3764 if(m_From == -1)
3765 if(m_To == -1)
3766 return true;
3767 else
3768 return time <= m_To;
3769 else
3770 if(m_To == -1)
3771 return time >= m_From;
3772 else
3773 return ((time >= m_From)&&(time <= m_To));
3775 return TRUE; /* git dll will filter time range */
3777 // return TRUE;
3780 void CGitLogListBase::StartFilter()
3782 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3783 RecalculateShownList(&m_arShownList);
3784 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3787 DeleteAllItems();
3788 SetItemCountEx(ShownCountWithStopped());
3789 RedrawItems(0, ShownCountWithStopped());
3790 Invalidate();
3793 void CGitLogListBase::RemoveFilter()
3795 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3797 m_arShownList.SafeRemoveAll();
3799 // reset the time filter too
3800 #if 0
3801 m_timFrom = (__time64_t(m_tFrom));
3802 m_timTo = (__time64_t(m_tTo));
3803 m_DateFrom.SetTime(&m_timFrom);
3804 m_DateTo.SetTime(&m_timTo);
3805 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3806 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3807 #endif
3809 for (DWORD i=0; i<m_logEntries.size(); ++i)
3811 if(this->m_IsOldFirst)
3812 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3813 else
3814 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3816 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3817 DeleteAllItems();
3818 SetItemCountEx(ShownCountWithStopped());
3819 RedrawItems(0, ShownCountWithStopped());
3821 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3824 void CGitLogListBase::Clear()
3826 m_arShownList.SafeRemoveAll();
3827 DeleteAllItems();
3829 m_logEntries.ClearAll();
3832 void CGitLogListBase::OnDestroy()
3834 SafeTerminateThread();
3835 SafeTerminateAsyncDiffThread();
3837 int retry = 0;
3838 while(m_LogCache.SaveCache())
3840 if(retry > 5)
3841 break;
3842 Sleep(1000);
3844 ++retry;
3846 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3847 // MB_YESNO) == IDNO)
3848 // break;
3851 __super::OnDestroy();
3854 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3856 CRect rect;
3857 int i=(int)wParam;
3858 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3859 this->InvalidateRect(rect);
3861 return 0;
3865 * Save column widths to the registry
3867 void CGitLogListBase::SaveColumnWidths()
3869 // HACK that graph column is always shown
3870 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3872 __super::SaveColumnWidths();
3875 int CGitLogListBase::GetHeadIndex()
3877 if(m_HeadHash.IsEmpty())
3878 return -1;
3880 for (size_t i = 0; i < m_arShownList.size(); ++i)
3882 GitRev* pRev = m_arShownList.SafeGetAt(i);
3883 if(pRev)
3885 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3886 return (int)i;
3889 return -1;
3891 void CGitLogListBase::OnFind()
3893 if (!m_pFindDialog)
3895 m_pFindDialog = new CFindDlg(this);
3896 m_pFindDialog->Create(this);
3900 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3902 if (GetSelectedCount() != 0)
3903 return 0;
3905 CGitHash theSelectedHash = m_lastSelectedHash;
3906 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3907 m_lastSelectedHash = theSelectedHash;
3909 int countPerPage = GetCountPerPage();
3910 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3911 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3912 EnsureVisible((int)itemToSelect, FALSE);
3913 return 0;
3916 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3918 CString* ref = reinterpret_cast<CString*>(wParam);
3919 if (!ref || ref->IsEmpty())
3920 return 1;
3922 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3924 CGitHash hash;
3925 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3926 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3928 if (hash.IsEmpty())
3929 return 1;
3931 bool bFound = false;
3932 int cnt = (int)m_arShownList.size();
3933 int i;
3934 for (i = 0; i < cnt; ++i)
3936 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3937 if (pLogEntry && pLogEntry->m_CommitHash == hash)
3939 bFound = true;
3940 break;
3943 if (!bFound)
3944 return 1;
3946 EnsureVisible(i, FALSE);
3947 if (!bShift)
3949 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
3950 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3951 SetSelectionMark(i);
3953 else
3955 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3956 if (pLogEntry)
3957 m_highlight = pLogEntry->m_CommitHash;
3959 Invalidate();
3960 UpdateData(FALSE);
3962 return 0;
3965 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
3967 ASSERT(m_pFindDialog);
3968 bool bFound = false;
3969 int i=0;
3971 if (m_pFindDialog->IsTerminating())
3973 // invalidate the handle identifying the dialog box.
3974 m_pFindDialog = nullptr;
3975 return 0;
3978 int cnt = (int)m_arShownList.size();
3979 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3981 if(m_pFindDialog->IsRef())
3983 CString str;
3984 str=m_pFindDialog->GetFindString();
3986 CGitHash hash;
3988 if(!str.IsEmpty())
3990 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3991 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
3994 if(!hash.IsEmpty())
3996 for (i = 0; i < cnt; ++i)
3998 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
3999 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4001 bFound = true;
4002 break;
4006 if (!bFound)
4008 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4009 return 0;
4013 if (m_pFindDialog->FindNext() && !bFound)
4015 //read data from dialog
4016 CString findText = m_pFindDialog->GetFindString();
4017 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4019 std::tr1::wregex pat;
4020 bool bRegex = false;
4021 if (m_pFindDialog->Regex())
4022 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4024 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_not_null;
4026 for (i = m_nSearchIndex + 1; ; ++i)
4028 if (i >= cnt)
4030 i = 0;
4031 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4033 if (m_nSearchIndex >= 0)
4035 if (i == m_nSearchIndex)
4037 ::MessageBeep(0xFFFFFFFF);
4038 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4039 break;
4043 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4045 CString str;
4046 str+=pLogEntry->m_CommitHash.ToString();
4047 str += L'\n';
4049 for (size_t j = 0; j < this->m_HashMap[pLogEntry->m_CommitHash].size(); ++j)
4051 str+=m_HashMap[pLogEntry->m_CommitHash][j];
4052 str += L'\n';
4055 str+=pLogEntry->GetAuthorEmail();
4056 str += L'\n';
4057 str+=pLogEntry->GetAuthorName();
4058 str += L'\n';
4059 str+=pLogEntry->GetBody();
4060 str += L'\n';
4061 str+=pLogEntry->GetCommitterEmail();
4062 str += L'\n';
4063 str+=pLogEntry->GetCommitterName();
4064 str += L'\n';
4065 str+=pLogEntry->GetSubject();
4066 str += L'\n';
4067 str+=pLogEntry->m_Notes;
4068 str += L'\n';
4069 str+=GetTagInfo(pLogEntry);
4070 str += L'\n';
4073 /*Because changed files list is loaded on demand when gui show,
4074 files will empty when files have not fetched.
4076 we can add it back by using one-way diff(with outnumber changed and rename detect.
4077 here just need changed filename list. one-way is much quicker.
4079 if(pLogEntry->m_IsFull)
4081 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4083 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4084 str += L'\n';
4085 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4086 str += L'\n';
4089 else
4091 if(!pLogEntry->m_IsSimpleListReady)
4092 pLogEntry->SafeGetSimpleList(&g_Git);
4094 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4096 str += pLogEntry->m_SimpleFileList[j];
4097 str += L'\n';
4101 if (bRegex)
4103 if (std::regex_search(std::wstring(str), pat, flags))
4105 bFound = true;
4106 break;
4109 else
4111 if (bMatchCase)
4113 if (str.Find(findText) >= 0)
4115 bFound = true;
4116 break;
4119 else
4121 CString msg = str;
4122 msg = msg.MakeLower();
4123 CString find = findText.MakeLower();
4124 if (msg.Find(find) >= 0)
4126 bFound = TRUE;
4127 break;
4131 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4133 } // if(m_pFindDialog->FindNext())
4134 //UpdateLogInfoLabel();
4136 if (bFound)
4138 m_nSearchIndex = i;
4139 EnsureVisible(i, FALSE);
4140 if (!bShift)
4142 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4143 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4144 SetSelectionMark(i);
4146 else
4148 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4149 if (pLogEntry)
4150 m_highlight = pLogEntry->m_CommitHash;
4152 Invalidate();
4153 //FillLogMessageCtrl();
4154 UpdateData(FALSE);
4157 return 0;
4160 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4162 LVHITTESTINFO lvhitTestInfo;
4164 lvhitTestInfo.pt = point;
4166 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4167 int nSubItem = lvhitTestInfo.iSubItem;
4169 UINT nFlags = lvhitTestInfo.flags;
4171 // nFlags is 0 if the SubItemHitTest fails
4172 // Therefore, 0 & <anything> will equal false
4173 if (nFlags & LVHT_ONITEM)
4175 // Get the client area occupied by this control
4176 RECT rcClient;
4177 GetClientRect(&rcClient);
4179 // Fill in the TOOLINFO structure
4180 pTI->hwnd = m_hWnd;
4181 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4182 pTI->lpszText = LPSTR_TEXTCALLBACK;
4183 pTI->rect = rcClient;
4185 return pTI->uId; // By returning a unique value per listItem,
4186 // we ensure that when the mouse moves over another list item,
4187 // the tooltip will change
4189 else
4191 // Otherwise, we aren't interested, so let the message propagate
4192 return -1;
4196 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4198 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4199 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4201 *pResult = 0;
4203 // Ignore messages from the built in tooltip, we are processing them internally
4204 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4205 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4206 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4207 return FALSE;
4209 // Get the mouse position
4210 const MSG* pMessage = GetCurrentMessage();
4212 CPoint pt;
4213 pt = pMessage->pt;
4214 ScreenToClient(&pt);
4216 // Check if the point falls onto a list item
4217 LVHITTESTINFO lvhitTestInfo;
4218 lvhitTestInfo.pt = pt;
4220 int nItem = SubItemHitTest(&lvhitTestInfo);
4222 if (lvhitTestInfo.flags & LVHT_ONITEM)
4224 // Get branch description first
4225 CString strTipText;
4226 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4228 CString branch;
4229 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4230 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4232 MAP_STRING_STRING descriptions;
4233 g_Git.GetBranchDescriptions(descriptions);
4234 if (descriptions.find(branch) != descriptions.cend())
4236 strTipText.LoadString(IDS_DESCRIPTION);
4237 strTipText += L":\n";
4238 strTipText += descriptions[branch];
4243 bool followMousePos = false;
4244 if (!strTipText.IsEmpty())
4245 followMousePos = true;
4246 else
4247 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4248 if (strTipText.IsEmpty())
4249 return FALSE;
4251 // we want multiline tooltips
4252 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, INT_MAX);
4254 wcscpy_s(m_wszTip, strTipText);
4255 // handle Unicode as well as non-Unicode requests
4256 if (pNMHDR->code == TTN_NEEDTEXTA)
4258 pTTTA->hinst = nullptr;
4259 pTTTA->lpszText = m_szTip;
4260 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4262 else
4264 pTTTW->hinst = nullptr;
4265 pTTTW->lpszText = m_wszTip;
4268 CRect rect;
4269 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4270 if (followMousePos)
4271 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4272 ClientToScreen(rect);
4273 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4275 return TRUE; // We found a tool tip,
4276 // tell the framework this message has been handled
4279 return FALSE; // We didn't handle the message,
4280 // let the framework continue propagating the message
4283 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4285 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4287 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4288 if (pLogEntry == nullptr)
4289 return CString();
4290 if (m_HashMap[pLogEntry->m_CommitHash].empty() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4291 return CString();
4292 return pLogEntry->GetSubject();
4294 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4296 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4297 if (pLogEntry == nullptr)
4298 return CString();
4299 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4301 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4303 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4304 if (pLogEntry == nullptr)
4305 return CString();
4306 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4308 else if (nSubItem == LOGLIST_ACTION)
4310 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4311 if (pLogEntry == nullptr)
4312 return CString();
4314 if (!pLogEntry->m_IsDiffFiles)
4315 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4317 int actions = pLogEntry->GetAction(this);
4318 CString sToolTipText;
4320 CString actionText;
4321 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4322 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4324 if (actions & CTGitPath::LOGACTIONS_ADDED)
4326 if (!actionText.IsEmpty())
4327 actionText += L"\r\n";
4328 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4331 if (actions & CTGitPath::LOGACTIONS_DELETED)
4333 if (!actionText.IsEmpty())
4334 actionText += L"\r\n";
4335 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4338 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4340 if (!actionText.IsEmpty())
4341 actionText += L"\r\n";
4342 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4345 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4347 if (!actionText.IsEmpty())
4348 actionText += L"\r\n";
4349 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4352 if (!actionText.IsEmpty())
4354 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4355 sToolTipText = sTitle + L":\r\n" + actionText;
4357 return sToolTipText;
4359 return CString();
4362 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4364 POINT pt = point;
4365 ScreenToClient(&pt);
4366 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4369 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4371 if (!pLogEntry)
4372 return false;
4374 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4376 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4377 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4378 continue;
4380 CGit::REF_TYPE foundType;
4381 if (pShortname)
4382 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4383 else
4384 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4385 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4386 return false;
4388 type = foundType;
4389 if (pIndex)
4390 *pIndex = i;
4391 return true;
4393 return false;
4396 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4398 *pResult = 0;
4400 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4401 return;
4403 m_bDragging = TRUE;
4404 m_nDropIndex = -1;
4405 m_nDropMarkerLast = -1;
4406 m_nDropMarkerLastHot = GetHotItem();
4407 SetCapture();
4410 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4412 __super::OnMouseMove(nFlags, point);
4414 if (!m_bDragging)
4415 return;
4417 CPoint dropPoint = point;
4418 ClientToScreen(&dropPoint);
4420 if (WindowFromPoint(dropPoint) != this)
4422 SetCursor(LoadCursor(nullptr, IDC_NO));
4423 m_nDropIndex = -1;
4424 DrawDropInsertMarker(m_nDropIndex);
4425 return;
4428 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4429 ScreenToClient(&dropPoint);
4431 dropPoint.y += 10;
4432 m_nDropIndex = HitTest(dropPoint);
4434 POSITION pos = GetFirstSelectedItemPosition();
4435 int first = GetNextSelectedItem(pos);
4436 int last = first;
4437 while (pos)
4438 last = GetNextSelectedItem(pos);
4439 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4441 SetCursor(LoadCursor(nullptr, IDC_NO));
4442 m_nDropIndex = -1;
4444 DrawDropInsertMarker(m_nDropIndex);
4447 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4449 if (m_bDragging)
4451 ::ReleaseCapture();
4452 SetCursor(LoadCursor(nullptr, IDC_HAND));
4453 m_bDragging = FALSE;
4455 CRect rect;
4456 GetItemRect(m_nDropMarkerLast, &rect, 0);
4457 rect.bottom = rect.top + 2;
4458 rect.top -= 2;
4459 InvalidateRect(&rect, 0);
4461 CPoint pt(point);
4462 ClientToScreen(&pt);
4463 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4464 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4467 __super::OnLButtonUp(nFlags, point);
4470 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4472 if (m_nDropMarkerLast != nIndex)
4474 CRect rect;
4475 GetItemRect(m_nDropMarkerLast, &rect, 0);
4476 rect.bottom = rect.top + 2;
4477 rect.top -= 2;
4478 InvalidateRect(&rect, 0);
4479 m_nDropMarkerLast = nIndex;
4481 if (nIndex < 0)
4482 return;
4484 CBrush* pBrush = CDC::GetHalftoneBrush();
4485 CDC* pDC = GetDC();
4487 GetItemRect(nIndex, &rect, 0);
4488 rect.bottom = rect.top + 2;
4489 rect.top -= 2;
4491 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4492 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4493 pDC->SelectObject(pBrushOld);
4495 ReleaseDC(pDC);
4497 else if (m_nDropMarkerLastHot != GetHotItem())
4499 m_nDropMarkerLastHot = GetHotItem();
4500 m_nDropMarkerLast = -1;