Extend static functions in CAppUtils with a window handle parameter
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blobf5aab8f359bd68d4b9844493cc67f42b6f058b65
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - TortoiseGit
4 // Copyright (C) 2005-2007 Marco Costalba
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // GitLogList.cpp : implementation file
22 #include "stdafx.h"
23 #include "resource.h"
24 #include "GitLogListBase.h"
25 #include "IconMenu.h"
26 #include "GitProgressDlg.h"
27 #include "ProgressDlg.h"
28 #include "MessageBox.h"
29 #include "LoglistUtils.h"
30 #include "StringUtils.h"
31 #include "UnicodeUtils.h"
32 #include "IconMenu.h"
33 #include "../TortoiseShell/Resource.h"
35 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
39 const UINT CGitLogListBase::LOGLIST_RESET_WCREV = RegisterWindowMessage(L"TORTOISEGIT_LOG_RESET_WCREV");
41 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
43 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
44 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
45 ,m_nSearchIndex(0)
46 ,m_bNoDispUpdates(FALSE)
47 , m_bThreadRunning(FALSE)
48 , m_bStrictStopped(false)
49 , m_SelectedFilters(LOGFILTER_ALL)
50 , m_ShowFilter(FILTERSHOW_ALL)
51 , m_bShowWC(false)
52 , m_logEntries(&m_LogCache)
53 , m_pFindDialog(nullptr)
54 , m_dwDefaultColumns(0)
55 , m_arShownList(&m_critSec)
56 , m_hasWC(true)
57 , m_bNoHightlightHead(FALSE)
58 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
59 , m_bFullCommitMessageOnLogLine(false)
60 , m_OldTopIndex(-1)
61 , m_AsyncThreadRunning(FALSE)
62 , m_AsyncThreadExit(FALSE)
63 , m_bIsCherryPick(false)
64 , m_pMailmap(nullptr)
65 , m_bShowBugtraqColumn(false)
66 , m_IsIDReplaceAction(FALSE)
67 , m_ShowMask(0)
68 , m_LoadingThread(nullptr)
69 , m_bExitThread(FALSE)
70 , m_IsOldFirst(FALSE)
71 , m_IsRebaseReplaceGraph(FALSE)
72 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
73 , m_bDragndropEnabled(false)
74 , m_bDragging(FALSE)
75 , m_nDropIndex(-1)
76 , m_nDropMarkerLast(-1)
77 , m_nDropMarkerLastHot(-1)
79 // use the default GUI font, create a copy of it and
80 // change the copy to BOLD (leave the rest of the font
81 // the same)
82 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
83 LOGFONT lf = {0};
84 GetObject(hFont, sizeof(LOGFONT), &lf);
85 lf.lfWeight = FW_BOLD;
86 m_boldFont.CreateFontIndirect(&lf);
87 lf.lfWeight = FW_DONTCARE;
88 lf.lfItalic = TRUE;
89 m_FontItalics.CreateFontIndirect(&lf);
90 lf.lfWeight = FW_BOLD;
91 m_boldItalicsFont.CreateFontIndirect(&lf);
93 this->m_critSec.Init();
94 ResetWcRev(false);
96 int cx = GetSystemMetrics(SM_CXSMICON);
97 int cy = GetSystemMetrics(SM_CYSMICON);
98 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, cx, cy, 0);
99 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, cx, cy, 0);
100 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, cx, cy, 0);
101 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, cx, cy, 0);
102 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, cx, cy, 0);
103 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, cx, cy, 0);
105 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
106 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
108 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
109 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
111 CString key;
112 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
113 key.Replace(L':', L'_');
114 CString lastSelFromDate = CRegString(key);
115 if (lastSelFromDate.GetLength() == 10)
117 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
118 m_Filter.m_From = (DWORD)time.GetTime();
121 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
123 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
125 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
127 // get short/long datetime setting from registry
128 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
129 if ( RegUseShortDateFormat )
131 m_DateFormat = DATE_SHORTDATE;
133 else
135 m_DateFormat = DATE_LONGDATE;
137 // get relative time display setting from registry
138 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
139 m_bRelativeTimes = (regRelativeTimes != 0);
141 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
142 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
143 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
144 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
145 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
146 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
147 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
149 m_ColumnRegKey = L"log";
151 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
152 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
153 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
154 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
156 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
157 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
159 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
160 git_read_mailmap(&m_pMailmap);
162 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
163 m_AsynDiffListLock.Init();
164 StartAsyncDiffThread();
167 HWND CGitLogListBase::GetParentHWND()
169 auto owner = GetSafeOwner();
170 if (!owner)
171 return GetSafeHwnd();
172 return owner->GetSafeHwnd();
175 int CGitLogListBase::AsyncDiffThread()
177 while(!m_AsyncThreadExit)
179 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
181 GitRevLoglist* pRev = nullptr;
182 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
184 m_AsynDiffListLock.Lock();
185 pRev = m_AsynDiffList.back();
186 m_AsynDiffList.pop_back();
187 m_AsynDiffListLock.Unlock();
189 if( pRev->m_CommitHash.IsEmpty() )
191 if(pRev->m_IsDiffFiles)
192 continue;
194 CTGitPathList& files = pRev->GetFiles(this);
195 files.Clear();
196 pRev->m_ParentHash.clear();
197 pRev->m_ParentHash.push_back(m_HeadHash);
198 g_Git.RefreshGitIndex();
199 g_Git.GetWorkingTreeChanges(files);
200 auto& action = pRev->GetAction(this);
201 action = 0;
202 for (int j = 0; j < files.GetCount(); ++j)
203 action |= files[j].m_Action;
205 CString err;
206 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
208 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
209 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
210 return -1;
213 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
214 InterlockedExchange(&pRev->m_IsFull, TRUE);
216 CString body = L"\n";
217 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
218 pRev->GetBody() = body;
219 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
220 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
223 if (!pRev->CheckAndDiff())
224 { // fetch change file list
225 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
227 if (i < (int)m_arShownList.size())
229 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
230 if(data->m_CommitHash == pRev->m_CommitHash)
232 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
233 break;
238 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
240 POSITION pos = GetFirstSelectedItemPosition();
241 int nItem = GetNextSelectedItem(pos);
243 if(nItem>=0)
245 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
246 if(data)
247 if(data->m_CommitHash == pRev->m_CommitHash)
248 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
254 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
255 return 0;
257 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
259 if (exclusivelyShow)
260 m_ContextMenuMask &= hideMask;
261 else
262 m_ContextMenuMask &= ~hideMask;
265 CGitLogListBase::~CGitLogListBase()
267 InterlockedExchange(&m_bNoDispUpdates, TRUE);
268 this->m_arShownList.SafeRemoveAll();
270 DestroyIcon(m_hModifiedIcon);
271 DestroyIcon(m_hReplacedIcon);
272 DestroyIcon(m_hConflictedIcon);
273 DestroyIcon(m_hAddedIcon);
274 DestroyIcon(m_hDeletedIcon);
275 m_logEntries.ClearAll();
277 git_free_mailmap(m_pMailmap);
279 SafeTerminateThread();
280 SafeTerminateAsyncDiffThread();
282 if(m_AsyncDiffEvent)
283 CloseHandle(m_AsyncDiffEvent);
287 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
288 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
289 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
290 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
291 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
292 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
293 ON_WM_CONTEXTMENU()
294 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
295 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
296 ON_WM_CREATE()
297 ON_WM_DESTROY()
298 ON_MESSAGE(MSG_LOADED,OnLoad)
299 ON_WM_MEASUREITEM()
300 ON_WM_MEASUREITEM_REFLECT()
301 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
302 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
303 ON_WM_MOUSEMOVE()
304 ON_WM_LBUTTONUP()
305 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
306 END_MESSAGE_MAP()
308 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
310 //if (m_nRowHeight>0)
311 lpMeasureItemStruct->itemHeight = 50;
314 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
316 PreSubclassWindow();
317 return __super::OnCreate(lpCreateStruct);
320 void CGitLogListBase::SetStyle()
322 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
325 void CGitLogListBase::PreSubclassWindow()
327 SetStyle();
328 // load the icons for the action columns
329 // m_Theme.Open(m_hWnd, L"ListView");
330 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
331 __super::PreSubclassWindow();
334 CString CGitLogListBase::GetRebaseActionName(int action)
336 if (action & LOGACTIONS_REBASE_EDIT)
337 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
338 if (action & LOGACTIONS_REBASE_SQUASH)
339 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
340 if (action & LOGACTIONS_REBASE_PICK)
341 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
342 if (action & LOGACTIONS_REBASE_SKIP)
343 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
345 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
348 void CGitLogListBase::InsertGitColumn()
350 CString temp;
352 Init();
354 // only load properties if we have a repository
355 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
356 UpdateProjectProperties();
358 static UINT normal[] =
360 IDS_LOG_GRAPH,
361 IDS_LOG_REBASE,
362 IDS_LOG_ID,
363 IDS_LOG_HASH,
364 IDS_LOG_ACTIONS,
365 IDS_LOG_MESSAGE,
366 IDS_LOG_AUTHOR,
367 IDS_LOG_DATE,
368 IDS_LOG_EMAIL,
369 IDS_LOG_COMMIT_NAME,
370 IDS_LOG_COMMIT_EMAIL,
371 IDS_LOG_COMMIT_DATE,
372 IDS_LOG_BUGIDS,
373 IDS_LOG_SVNREV,
376 static int with[] =
378 ICONITEMBORDER+16*4,
379 ICONITEMBORDER+16*4,
380 ICONITEMBORDER+16*4,
381 ICONITEMBORDER+16*4,
382 2 * ICONITEMBORDER + GetSystemMetrics(SM_CXSMICON) * 5,
383 LOGLIST_MESSAGE_MIN,
384 ICONITEMBORDER+16*4,
385 ICONITEMBORDER+16*4,
386 ICONITEMBORDER+16*4,
387 ICONITEMBORDER+16*4,
388 ICONITEMBORDER+16*4,
389 ICONITEMBORDER+16*4,
390 ICONITEMBORDER+16*4,
391 ICONITEMBORDER+16*4,
393 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
395 DWORD hideColumns = 0;
396 if(this->m_IsRebaseReplaceGraph)
398 hideColumns |= GIT_LOG_GRAPH;
399 m_dwDefaultColumns |= GIT_LOG_REBASE;
401 else
402 hideColumns |= GIT_LOG_REBASE;
404 if(this->m_IsIDReplaceAction)
406 hideColumns |= GIT_LOG_ACTIONS;
407 m_dwDefaultColumns |= GIT_LOG_ID;
408 m_dwDefaultColumns |= GIT_LOG_HASH;
410 else
411 hideColumns |= GIT_LOG_ID;
412 if(this->m_bShowBugtraqColumn)
413 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
414 else
415 hideColumns |= GIT_LOGLIST_BUG;
416 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
417 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
418 else
419 hideColumns |= GIT_LOGLIST_SVNREV;
420 SetRedraw(false);
422 m_ColumnManager.SetNames(normal, _countof(normal));
423 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
424 m_ColumnManager.SetRightAlign(LOGLIST_ID);
426 if (!(hideColumns & GIT_LOG_ACTIONS))
428 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
429 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
430 // display's font height may be less than small icon height.
431 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
432 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
433 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
436 SetRedraw(true);
439 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
441 LVITEM rItem = { 0 };
442 rItem.mask = LVIF_STATE;
443 rItem.iItem = (int)Index;
444 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
445 GetItem(&rItem);
447 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
448 HBRUSH brush = nullptr;
450 if (!(rItem.state & LVIS_SELECTED))
452 int action = pLogEntry->GetRebaseAction();
453 if (action & LOGACTIONS_REBASE_SQUASH)
454 brush = ::CreateSolidBrush(RGB(156,156,156));
455 else if (action & LOGACTIONS_REBASE_EDIT)
456 brush = ::CreateSolidBrush(RGB(200,200,128));
458 else if (!IsAppThemed())
460 if (rItem.state & LVIS_SELECTED)
462 if (::GetFocus() == m_hWnd)
463 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
464 else
465 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
468 if (brush)
470 ::FillRect(hdc, &rect, brush);
471 ::DeleteObject(brush);
475 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
477 POINT point = { 4, 4 };
478 CRect rt2 = rect;
479 rt2.DeflateRect(1, 1);
480 rt2.OffsetRect(2, 2);
482 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
483 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
484 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
485 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
486 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
488 ::SelectObject(hdc, brush);
489 rt2.OffsetRect(-2, -2);
490 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
491 ::SelectObject(hdc, oldbrush);
492 ::SelectObject(hdc, oldpen);
493 ::DeleteObject(nullPen);
494 ::DeleteObject(darkBrush);
497 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
499 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
500 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
501 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
502 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
503 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
504 ::LineTo(hdc, rect.left, rect.top + 4);
505 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
506 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
507 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
508 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
509 ::SelectObject(hdc, oldpen);
510 ::DeleteObject(pen);
513 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
515 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
516 CRect rt=rect;
517 LVITEM rItem = { 0 };
518 rItem.mask = LVIF_STATE;
519 rItem.iItem = (int)index;
520 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
521 GetItem(&rItem);
523 CDC W_Dc;
524 W_Dc.Attach(hdc);
526 HTHEME hTheme = nullptr;
527 if (IsAppThemed())
528 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
530 SIZE oneSpaceSize;
531 if (m_bTagsBranchesOnRightSide)
533 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
534 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
535 SelectObject(hdc, oldFont);
536 rt.left += oneSpaceSize.cx * 2;
538 else
540 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
541 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
542 rt.left += oneSpaceSize.cx;
545 CString msg = MessageDisplayStr(data);
546 int action = data->GetRebaseAction();
547 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
548 if (IsAppThemed())
550 int txtState = LISS_NORMAL;
551 if (rItem.state & LVIS_SELECTED)
552 txtState = LISS_SELECTED;
554 DTTOPTS opts = { 0 };
555 opts.dwSize = sizeof(opts);
556 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
557 opts.dwFlags = DTT_TEXTCOLOR;
558 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
560 else
562 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
564 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
565 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
566 ::SetTextColor(hdc, clrOld);
568 else
570 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
571 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
572 ::SetTextColor(hdc, clrOld);
576 if (m_bTagsBranchesOnRightSide)
578 SIZE size;
579 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
581 rt.left += oneSpaceSize.cx + size.cx;
583 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
586 if (hTheme)
587 CloseThemeData(hTheme);
589 W_Dc.Detach();
592 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
594 for (unsigned int i = 0; i < refList.size(); ++i)
596 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
597 HBRUSH brush = 0;
598 COLORREF colRef = refList[i].color;
599 bool singleRemote = refList[i].singleRemote;
600 bool hasTracking = refList[i].hasTracking;
601 CGit::REF_TYPE refType = refList[i].refType;
603 //When row selected, ajust label color
604 if (!IsAppThemed())
606 if (rItem.state & LVIS_SELECTED)
607 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
610 brush = ::CreateSolidBrush(colRef);
612 if (!shortname.IsEmpty() && (rt.left < rect.right))
614 SIZE size = { 0 };
615 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
617 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
618 rt.right += 8;
620 int textpos = DT_CENTER;
622 if (rt.right > rect.right)
624 rt.right = rect.right;
625 textpos = 0;
628 CRect textRect = rt;
630 if (singleRemote)
632 rt.right += 5;
633 textRect.OffsetRect(5, 0);
636 if (hasTracking)
637 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
638 else
640 //Fill interior of ref label
641 ::FillRect(hdc, &rt, brush);
644 //Draw edge of label
645 CRect rectEdge = rt;
647 if (!hasTracking)
649 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
650 rectEdge.DeflateRect(1, 1);
651 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
654 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
656 rt.right += 8;
657 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
658 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
659 ::FillRgn(hdc, hrgn, brush);
660 ::DeleteObject(hrgn);
661 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
662 HPEN pen;
663 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
664 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
665 ::DeleteObject(pen);
666 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
667 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
668 ::DeleteObject(pen);
669 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
670 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
671 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
672 ::DeleteObject(pen);
673 SelectObject(hdc, oldpen);
676 //Draw text inside label
677 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
678 if (!customColor && IsAppThemed())
680 int txtState = LISS_NORMAL;
681 if (rItem.state & LVIS_SELECTED)
682 txtState = LISS_SELECTED;
684 DTTOPTS opts = { 0 };
685 opts.dwSize = sizeof(opts);
686 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
687 opts.dwFlags = DTT_TEXTCOLOR;
688 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
690 else
692 W_Dc.SetBkMode(TRANSPARENT);
693 if (customColor || (rItem.state & LVIS_SELECTED))
695 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
696 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
697 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
698 ::SetTextColor(hdc,clrOld);
700 else
702 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
703 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
704 ::SetTextColor(hdc, clrOld);
708 if (singleRemote)
710 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
711 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
712 CRect newRect;
713 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
714 DrawUpstream(hdc, newRect, color, bold);
717 if (!refList[i].fullName.IsEmpty())
718 m_RefLabelPosMap[refList[i].fullName] = rt;
720 rt.left = rt.right + 1;
722 if (brush)
723 ::DeleteObject(brush);
725 rt.right = rect.right;
728 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
729 // Returns ((256 - amount)*col1 + amount*col2) / 256;
730 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
731 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
732 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
735 Gdiplus::Color GetGdiColor(COLORREF col)
737 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
739 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
740 const COLORREF& col,const COLORREF& activeColor, int top
743 int h = laneHeight / 2;
744 int m = (x1 + x2) / 2;
745 int r = (x2 - x1) * m_NodeSize / 30;
746 int d = 2 * r;
748 #define P_CENTER m , h+top
749 #define P_0 x2, h+top
750 #define P_90 m , 0+top-1
751 #define P_180 x1, h+top
752 #define P_270 m , 2 * h+top +1
753 #define R_CENTER m - r, h - r+top, d, d
756 #define DELTA_UR_B 2*(x1 - m), 2*h +top
757 #define DELTA_UR_E 0*16, 90*16 +top // -,
759 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
760 #define DELTA_DR_E 270*16, 90*16 +top // -'
762 #define DELTA_UL_B 2*(x2 - m), 2*h +top
763 #define DELTA_UL_E 90*16, 90*16 +top // ,-
765 #define DELTA_DL_B 2*(x2 - m),2*-h +top
766 #define DELTA_DL_E 180*16, 90*16 // '-
768 #define CENTER_UR x1, 2*h, 225
769 #define CENTER_DR x1, 0 , 135
770 #define CENTER_UL x2, 2*h, 315
771 #define CENTER_DL x2, 0 , 45
774 Gdiplus::Graphics graphics( hdc );
776 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
778 // arc
779 switch (type) {
780 case Lanes::JOIN:
781 case Lanes::JOIN_R:
782 case Lanes::HEAD:
783 case Lanes::HEAD_R:
785 Gdiplus::LinearGradientBrush gradient(
786 Gdiplus::Point(x1-2, h+top-2),
787 Gdiplus::Point(P_270),
788 GetGdiColor(activeColor),GetGdiColor(col));
791 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
792 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
794 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
795 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
796 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
798 break;
800 case Lanes::JOIN_L:
802 Gdiplus::LinearGradientBrush gradient(
803 Gdiplus::Point(P_270),
804 Gdiplus::Point(x2+1, h+top-1),
805 GetGdiColor(col),GetGdiColor(activeColor));
808 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
809 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
811 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
812 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
813 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
816 break;
818 case Lanes::TAIL:
819 case Lanes::TAIL_R:
821 Gdiplus::LinearGradientBrush gradient(
822 Gdiplus::Point(x1-2, h+top-2),
823 Gdiplus::Point(P_90),
824 GetGdiColor(activeColor),GetGdiColor(col));
826 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
828 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
830 #if 0
831 QConicalGradient gradient(CENTER_DR);
832 gradient.setColorAt(0.375, activeCol);
833 gradient.setColorAt(0.625, col);
834 myPen.setBrush(gradient);
835 p->setPen(myPen);
836 p->drawArc(P_CENTER, DELTA_DR);
837 #endif
838 break;
840 default:
841 break;
845 //static QPen myPen(Qt::black, 2); // fast path here
846 CPen pen;
847 pen.CreatePen(PS_SOLID,2,col);
848 //myPen.setColor(col);
849 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
851 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
853 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
855 //p->setPen(myPen);
857 // vertical line
858 switch (type) {
859 case Lanes::ACTIVE:
860 case Lanes::NOT_ACTIVE:
861 case Lanes::MERGE_FORK:
862 case Lanes::MERGE_FORK_R:
863 case Lanes::MERGE_FORK_L:
864 case Lanes::JOIN:
865 case Lanes::JOIN_R:
866 case Lanes::JOIN_L:
867 case Lanes::CROSS:
868 //DrawLine(hdc,P_90,P_270);
869 graphics.DrawLine(&myPen,P_90,P_270);
870 //p->drawLine(P_90, P_270);
871 break;
872 case Lanes::HEAD_L:
873 case Lanes::BRANCH:
874 //DrawLine(hdc,P_CENTER,P_270);
875 graphics.DrawLine(&myPen,P_CENTER,P_270);
876 //p->drawLine(P_CENTER, P_270);
877 break;
878 case Lanes::TAIL_L:
879 case Lanes::INITIAL:
880 case Lanes::MERGE_FORK_L_INITIAL:
881 case Lanes::BOUNDARY:
882 case Lanes::BOUNDARY_C:
883 case Lanes::BOUNDARY_R:
884 case Lanes::BOUNDARY_L:
885 //DrawLine(hdc,P_90, P_CENTER);
886 graphics.DrawLine(&myPen,P_90,P_CENTER);
887 //p->drawLine(P_90, P_CENTER);
888 break;
889 default:
890 break;
893 myPen.SetColor(GetGdiColor(activeColor));
895 // horizontal line
896 switch (type) {
897 case Lanes::MERGE_FORK:
898 case Lanes::JOIN:
899 case Lanes::HEAD:
900 case Lanes::TAIL:
901 case Lanes::CROSS:
902 case Lanes::CROSS_EMPTY:
903 case Lanes::BOUNDARY_C:
904 //DrawLine(hdc,P_180,P_0);
905 graphics.DrawLine(&myPen,P_180,P_0);
906 //p->drawLine(P_180, P_0);
907 break;
908 case Lanes::MERGE_FORK_R:
909 case Lanes::BOUNDARY_R:
910 //DrawLine(hdc,P_180,P_CENTER);
911 graphics.DrawLine(&myPen,P_180,P_CENTER);
912 //p->drawLine(P_180, P_CENTER);
913 break;
914 case Lanes::MERGE_FORK_L:
915 case Lanes::MERGE_FORK_L_INITIAL:
916 case Lanes::HEAD_L:
917 case Lanes::TAIL_L:
918 case Lanes::BOUNDARY_L:
919 //DrawLine(hdc,P_CENTER,P_0);
920 graphics.DrawLine(&myPen,P_CENTER,P_0);
921 //p->drawLine(P_CENTER, P_0);
922 break;
923 default:
924 break;
927 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
929 CBrush brush;
930 brush.CreateSolidBrush(col);
931 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
933 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
934 // center symbol, e.g. rect or ellipse
935 switch (type) {
936 case Lanes::ACTIVE:
937 case Lanes::INITIAL:
938 case Lanes::BRANCH:
940 //p->setPen(Qt::NoPen);
941 //p->setBrush(col);
942 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
943 graphics.FillEllipse(&myBrush, R_CENTER);
944 //p->drawEllipse(R_CENTER);
945 break;
946 case Lanes::MERGE_FORK:
947 case Lanes::MERGE_FORK_R:
948 case Lanes::MERGE_FORK_L:
949 case Lanes::MERGE_FORK_L_INITIAL:
950 //p->setPen(Qt::NoPen);
951 //p->setBrush(col);
952 //p->drawRect(R_CENTER);
953 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
954 graphics.FillRectangle(&myBrush, R_CENTER);
955 break;
956 case Lanes::UNAPPLIED:
957 // Red minus sign
958 //p->setPen(Qt::NoPen);
959 //p->setBrush(Qt::red);
960 //p->drawRect(m - r, h - 1, d, 2);
961 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
962 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
963 break;
964 case Lanes::APPLIED:
965 // Green plus sign
966 //p->setPen(Qt::NoPen);
967 //p->setBrush(DARK_GREEN);
968 //p->drawRect(m - r, h - 1, d, 2);
969 //p->drawRect(m - 1, h - r, 2, d);
970 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
971 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
972 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
973 break;
974 case Lanes::BOUNDARY:
975 //p->setBrush(back);
976 //p->drawEllipse(R_CENTER);
977 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
978 graphics.DrawEllipse(&myPen, R_CENTER);
979 break;
980 case Lanes::BOUNDARY_C:
981 case Lanes::BOUNDARY_R:
982 case Lanes::BOUNDARY_L:
983 //p->setBrush(back);
984 //p->drawRect(R_CENTER);
985 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
986 graphics.FillRectangle(&myBrush,R_CENTER);
987 break;
988 default:
989 break;
992 ::SelectObject(hdc,oldpen);
993 ::SelectObject(hdc,oldbrush);
994 #undef P_CENTER
995 #undef P_0
996 #undef P_90
997 #undef P_180
998 #undef P_270
999 #undef R_CENTER
1002 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
1004 // TODO: unfinished
1005 // return;
1006 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
1007 if(data->m_CommitHash.IsEmpty())
1008 return;
1010 CRect rt=rect;
1011 LVITEM rItem = { 0 };
1012 rItem.mask = LVIF_STATE;
1013 rItem.iItem = (int)index;
1014 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1015 GetItem(&rItem);
1017 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1019 if (data->m_Lanes.empty())
1020 m_logEntries.setLane(data->m_CommitHash);
1022 std::vector<int>& lanes=data->m_Lanes;
1023 size_t laneNum = lanes.size();
1024 UINT activeLane = 0;
1025 for (UINT i = 0; i < laneNum; ++i)
1026 if (Lanes::isMerge(lanes[i])) {
1027 activeLane = i;
1028 break;
1031 int x2 = 0;
1032 int maxWidth = rect.Width();
1033 int lw = 3 * rect.Height() / 4; //laneWidth()
1035 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1036 //if (opt.state & QStyle::State_Selected)
1037 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1039 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1041 int x1 = x2;
1042 x2 += lw;
1044 int ln = lanes[i];
1045 if (ln == Lanes::EMPTY)
1046 continue;
1048 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1049 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1052 #if 0
1053 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1054 int x1 = x2;
1055 x2 += lw;
1057 int ln = lanes[i];
1058 if (ln == Lanes::EMPTY)
1059 continue;
1061 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1062 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1064 if (ln == Lanes::CROSS)
1066 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1067 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1069 else
1070 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1072 #endif
1075 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1077 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1078 // Take the default processing unless we set this to something else below.
1079 *pResult = CDRF_DODEFAULT;
1081 if (m_bNoDispUpdates)
1082 return;
1084 switch (pLVCD->nmcd.dwDrawStage)
1086 case CDDS_PREPAINT:
1088 *pResult = CDRF_NOTIFYITEMDRAW;
1089 return;
1091 break;
1092 case CDDS_ITEMPREPAINT:
1094 // This is the prepaint stage for an item. Here's where we set the
1095 // item's text color.
1097 // Tell Windows to send draw notifications for each subitem.
1098 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1100 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1102 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1104 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1105 if (data)
1107 HGDIOBJ hGdiObj = nullptr;
1108 int action = data->GetRebaseAction();
1109 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1110 crText = RGB(128,128,128);
1112 if (action & LOGACTIONS_REBASE_SQUASH)
1113 pLVCD->clrTextBk = RGB(156,156,156);
1114 else if (action & LOGACTIONS_REBASE_EDIT)
1115 pLVCD->clrTextBk = RGB(200,200,128);
1116 else
1117 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1119 if (action & LOGACTIONS_REBASE_CURRENT)
1120 hGdiObj = m_boldFont.GetSafeHandle();
1122 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1123 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1124 if (isHeadHash && isHighlight)
1125 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1126 else if (isHeadHash)
1127 hGdiObj = m_boldFont.GetSafeHandle();
1128 else if (isHighlight)
1129 hGdiObj = m_FontItalics.GetSafeHandle();
1131 if (hGdiObj)
1133 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1134 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1137 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1138 // crText = GetSysColor(COLOR_GRAYTEXT);
1140 if (data->m_CommitHash.IsEmpty())
1142 //crText = GetSysColor(RGB(200,200,0));
1143 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1144 // We changed the font, so we're returning CDRF_NEWFONT. This
1145 // tells the control to recalculate the extent of the text.
1146 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1150 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1152 if (m_bStrictStopped)
1153 crText = GetSysColor(COLOR_GRAYTEXT);
1155 // Store the color back in the NMLVCUSTOMDRAW struct.
1156 pLVCD->clrText = crText;
1157 return;
1159 break;
1160 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1162 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1164 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1167 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1169 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1171 CRect rect;
1172 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1174 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1175 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1177 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1178 if( !data ->m_CommitHash.IsEmpty())
1179 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1181 *pResult = CDRF_SKIPDEFAULT;
1182 return;
1186 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1188 // If the top index of list is changed, the position map of reference label is outdated.
1189 if (m_OldTopIndex != GetTopIndex())
1191 m_OldTopIndex = GetTopIndex();
1192 m_RefLabelPosMap.clear();
1195 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1197 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1199 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1201 CRect rect;
1202 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1204 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1205 // not in FillBackGround method, because this only affected the message subitem
1206 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1207 return;
1209 int index = (int)pLVCD->nmcd.dwItemSpec;
1210 int state = GetItemState(index, LVIS_SELECTED);
1211 int txtState = LISS_NORMAL;
1212 if (IsAppThemed() && GetHotItem() == (int)index)
1214 if (state & LVIS_SELECTED)
1215 txtState = LISS_HOTSELECTED;
1216 else
1217 txtState = LISS_HOT;
1219 else if (state & LVIS_SELECTED)
1221 if (::GetFocus() == m_hWnd)
1222 txtState = LISS_SELECTED;
1223 else
1224 txtState = LISS_SELECTEDNOTFOCUS;
1227 HTHEME hTheme = nullptr;
1228 if (IsAppThemed())
1229 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1231 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1232 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1233 else
1235 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1236 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1237 ::DeleteObject(brush);
1239 if (hTheme && txtState != LISS_NORMAL)
1241 CRect rt;
1242 // get rect of whole line
1243 GetItemRect(index, rt, LVIR_BOUNDS);
1244 CRect rect2 = rect;
1246 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1247 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1249 CloseThemeData(hTheme);
1251 // END: extended redraw
1253 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1255 std::vector<REFLABEL> refsToShow;
1256 STRING_VECTOR remoteTrackingList;
1257 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1258 for (unsigned int i = 0; i < refList.size(); ++i)
1260 CString str = refList[i];
1262 REFLABEL refLabel;
1263 refLabel.color = RGB(255, 255, 255);
1264 refLabel.singleRemote = false;
1265 refLabel.hasTracking = false;
1266 refLabel.sameName = false;
1267 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1268 refLabel.fullName = str;
1270 switch (refLabel.refType)
1272 case CGit::REF_TYPE::LOCAL_BRANCH:
1274 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1275 continue;
1276 if (refLabel.name == m_CurrentBranch)
1277 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1278 else
1279 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1281 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1282 CString pullRemote = trackingEntry.first;
1283 CString pullBranch = trackingEntry.second;
1284 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1286 CString defaultUpstream;
1287 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1288 refLabel.hasTracking = true;
1289 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1291 bool found = false;
1292 for (size_t j = i + 1; j < refList.size(); ++j)
1294 if (refList[j] == defaultUpstream)
1296 found = true;
1297 break;
1301 if (found)
1303 bool sameName = pullBranch == refLabel.name;
1304 refsToShow.push_back(refLabel);
1305 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1306 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1307 if (m_bSymbolizeRefNames)
1309 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1311 refLabel.simplifiedName = L'/';
1312 if (sameName)
1313 refLabel.simplifiedName += L'≡';
1314 else
1315 refLabel.simplifiedName += pullBranch;
1316 refLabel.singleRemote = true;
1318 else if (sameName)
1319 refLabel.simplifiedName = pullRemote + L"/≡";
1320 refLabel.sameName = sameName;
1322 refLabel.fullName = defaultUpstream;
1323 refsToShow.push_back(refLabel);
1324 remoteTrackingList.push_back(defaultUpstream);
1325 continue;
1329 break;
1331 case CGit::REF_TYPE::REMOTE_BRANCH:
1333 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1334 continue;
1335 bool found = false;
1336 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1338 if (remoteTrackingList[j] == str)
1340 found = true;
1341 break;
1344 if (found)
1345 continue;
1347 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1348 if (m_bSymbolizeRefNames)
1350 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1352 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1353 refLabel.singleRemote = true;
1356 break;
1358 case CGit::REF_TYPE::ANNOTATED_TAG:
1359 case CGit::REF_TYPE::TAG:
1360 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1361 continue;
1362 refLabel.color = m_Colors.GetColor(CColors::Tag);
1363 break;
1364 case CGit::REF_TYPE::STASH:
1365 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1366 continue;
1367 refLabel.color = m_Colors.GetColor(CColors::Stash);
1368 break;
1369 case CGit::REF_TYPE::BISECT_GOOD:
1370 case CGit::REF_TYPE::BISECT_BAD:
1371 case CGit::REF_TYPE::BISECT_SKIP:
1372 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1373 continue;
1374 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));
1375 break;
1376 case CGit::REF_TYPE::NOTES:
1377 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1378 continue;
1379 refLabel.color = m_Colors.GetColor(CColors::NoteNode);
1380 break;
1381 default:
1382 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1383 continue;
1384 refLabel.color = m_Colors.GetColor(CColors::OtherRef);
1385 break;
1387 refsToShow.push_back(refLabel);
1389 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1391 REFLABEL refLabel;
1392 refLabel.color = RGB(246, 153, 253);
1393 refLabel.singleRemote = false;
1394 refLabel.hasTracking = false;
1395 refLabel.sameName = false;
1396 refLabel.name = L"super-project-pointer";
1397 refLabel.fullName = "";
1398 refsToShow.push_back(refLabel);
1401 if (refsToShow.empty())
1403 *pResult = CDRF_DODEFAULT;
1404 return;
1407 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1409 *pResult = CDRF_SKIPDEFAULT;
1410 return;
1417 if (pLVCD->iSubItem == LOGLIST_ACTION)
1419 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1421 *pResult = CDRF_DODEFAULT;
1422 return;
1424 *pResult = CDRF_DODEFAULT;
1426 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1427 return;
1429 int nIcons = 0;
1430 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1431 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1433 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1434 CRect rect;
1435 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1436 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1437 // Get the selected state of the
1438 // item being drawn.
1440 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1441 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1443 // Fill the background if necessary
1444 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1446 // Draw the icon(s) into the compatible DC
1447 int action = pLogEntry->GetAction(this);
1448 if (!pLogEntry->m_IsDiffFiles)
1450 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1451 *pResult = CDRF_SKIPDEFAULT;
1452 return;
1455 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1456 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1460 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1461 ++nIcons;
1463 if (action & CTGitPath::LOGACTIONS_DELETED)
1464 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1465 ++nIcons;
1467 if (action & CTGitPath::LOGACTIONS_REPLACED)
1468 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1469 ++nIcons;
1471 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1472 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1473 ++nIcons;
1475 *pResult = CDRF_SKIPDEFAULT;
1476 return;
1479 break;
1481 *pResult = CDRF_DODEFAULT;
1484 CString FindSVNRev(const CString& msg)
1488 const std::wsregex_iterator end;
1489 std::wstring s = msg;
1490 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1491 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1493 const std::wsmatch match = *it;
1494 if (match.size() == 4)
1496 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1497 return std::wstring(match[2]).c_str();
1500 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1501 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1503 const std::wsmatch match = *it;
1504 if (match.size() == 3)
1506 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1507 return std::wstring(match[1]).c_str();
1511 catch (std::exception&) {}
1513 return L"";
1516 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1518 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1519 return pLogEntry->GetSubject();
1521 CString txt(pLogEntry->GetSubject());
1522 txt += L' ';
1523 txt += pLogEntry->GetBody();
1525 // Deal with CRLF
1526 txt.Replace(L'\n', L' ');
1527 txt.Replace(L'\r', L' ');
1529 return txt;
1532 // CGitLogListBase message handlers
1534 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1536 struct payload_struct { const CString* name; const char* authorName; };
1537 payload_struct payload = { &name, nullptr };
1538 const char* author1 = nullptr;
1539 const char* email1 = nullptr;
1540 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1541 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1542 free((void *)payload.authorName);
1543 if (returnEmail)
1544 return email1;
1545 return author1;
1548 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1550 if (mailmap)
1552 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1553 if (translated)
1555 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1556 return;
1559 if (returnEmail)
1560 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1561 else
1562 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1565 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1567 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1569 // Create a pointer to the item
1570 LV_ITEM* pItem = &(pDispInfo)->item;
1572 // Do the list need text information?
1573 if (!(pItem->mask & LVIF_TEXT))
1574 return;
1576 // By default, clear text buffer.
1577 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1579 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1581 *pResult = 0;
1582 if (m_bNoDispUpdates || bOutOfRange)
1583 return;
1585 // Which item number?
1586 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1588 CString temp;
1589 if(m_IsOldFirst)
1590 temp.Format(L"%d", pItem->iItem + 1);
1591 else
1592 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1594 if (!pLogEntry)
1595 return;
1597 // Which column?
1598 switch (pItem->iSubItem)
1600 case LOGLIST_GRAPH: //Graphic
1601 break;
1602 case LOGLIST_REBASE:
1603 if (m_IsRebaseReplaceGraph)
1604 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1605 break;
1606 case LOGLIST_ACTION: //action -- no text in the column
1607 break;
1608 case LOGLIST_HASH:
1609 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1610 break;
1611 case LOGLIST_ID:
1612 if (this->m_IsIDReplaceAction)
1613 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1614 break;
1615 case LOGLIST_MESSAGE: //Message
1616 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1617 break;
1618 case LOGLIST_AUTHOR: //Author
1619 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1620 break;
1621 case LOGLIST_DATE: //Date
1622 if (!pLogEntry->m_CommitHash.IsEmpty())
1623 lstrcpyn(pItem->pszText,
1624 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1625 pItem->cchTextMax - 1);
1626 break;
1628 case LOGLIST_EMAIL:
1629 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1630 break;
1632 case LOGLIST_COMMIT_NAME: //Commit
1633 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1634 break;
1636 case LOGLIST_COMMIT_EMAIL: //Commit Email
1637 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1638 break;
1640 case LOGLIST_COMMIT_DATE: //Commit Date
1641 if (!pLogEntry->m_CommitHash.IsEmpty())
1642 lstrcpyn(pItem->pszText,
1643 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1644 pItem->cchTextMax - 1);
1645 break;
1646 case LOGLIST_BUG: //Bug ID
1647 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1648 break;
1649 case LOGLIST_SVNREV: //SVN revision
1650 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1651 break;
1653 default:
1654 ASSERT(false);
1658 bool CGitLogListBase::IsOnStash(int index)
1660 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1661 if (IsStash(rev))
1662 return true;
1663 if (index > 0)
1665 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1666 if (IsStash(preRev))
1667 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1669 return false;
1672 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1674 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1675 if (refList == m_HashMap.cend())
1676 return false;
1677 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1680 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1682 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1683 if (refList == m_HashMap.cend())
1684 return false;
1685 return find_if((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1688 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1690 if (pRev->m_ParentHash.empty())
1692 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1693 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1695 parentHash = pRev->m_ParentHash;
1698 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1700 __super::OnContextMenu(pWnd, point);
1702 if (pWnd != this)
1703 return;
1705 int selIndex = GetSelectionMark();
1706 if (selIndex < 0)
1707 return; // nothing selected, nothing to do with a context menu
1709 // if the user selected the info text telling about not all revisions shown due to
1710 // the "stop on copy/rename" option, we also don't show the context menu
1711 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1712 return;
1714 // if the context menu is invoked through the keyboard, we have to use
1715 // a calculated position on where to anchor the menu on
1716 if ((point.x == -1) && (point.y == -1))
1718 CRect rect;
1719 GetItemRect(selIndex, &rect, LVIR_LABEL);
1720 ClientToScreen(&rect);
1721 point = rect.CenterPoint();
1723 m_nSearchIndex = selIndex;
1725 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1727 POSITION pos = GetFirstSelectedItemPosition();
1728 int FirstSelect = GetNextSelectedItem(pos);
1729 if (FirstSelect < 0)
1730 return;
1732 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1733 if (pSelLogEntry == nullptr)
1734 return;
1736 int LastSelect = -1;
1737 UINT selectedCount = 1;
1738 while (pos)
1740 LastSelect = GetNextSelectedItem(pos);
1741 ++selectedCount;
1744 ASSERT(GetSelectedCount() == selectedCount);
1746 #if 0
1747 GitRev revSelected = pSelLogEntry->Rev;
1748 GitRev revPrevious = git_revnum_t(revSelected)-1;
1749 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1751 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1753 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1754 if (changedpath->lCopyFromRev)
1755 revPrevious = changedpath->lCopyFromRev;
1758 GitRev revSelected2;
1759 if (pos)
1761 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1762 revSelected2 = pLogEntry->Rev;
1764 bool bAllFromTheSameAuthor = true;
1765 CString firstAuthor;
1766 CLogDataVector selEntries;
1767 GitRev revLowest, revHighest;
1768 GitRevRangeArray revisionRanges;
1770 POSITION pos = GetFirstSelectedItemPosition();
1771 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1772 revisionRanges.AddRevision(pLogEntry->Rev);
1773 selEntries.push_back(pLogEntry);
1774 firstAuthor = pLogEntry->sAuthor;
1775 revLowest = pLogEntry->Rev;
1776 revHighest = pLogEntry->Rev;
1777 while (pos)
1779 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1780 revisionRanges.AddRevision(pLogEntry->Rev);
1781 selEntries.push_back(pLogEntry);
1782 if (firstAuthor.Compare(pLogEntry->sAuthor))
1783 bAllFromTheSameAuthor = false;
1784 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1785 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1789 #endif
1791 //entry is selected, now show the popup menu
1792 CIconMenu popup;
1793 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1795 if (popup.CreatePopupMenu())
1797 CGitHash headHash;
1798 if (g_Git.GetHash(headHash, L"HEAD"))
1800 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1801 return;
1803 bool isHeadCommit = (pSelLogEntry->m_CommitHash == headHash);
1804 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1805 CTGitPath workingTree(g_Git.m_CurrentDir);
1806 bool isMergeActive = workingTree.IsMergeActive();
1807 bool isBisectActive = workingTree.IsBisectActive();
1808 bool isStash = IsOnStash(FirstSelect);
1809 GIT_REV_LIST parentHash;
1810 GetParentHashes(pSelLogEntry, parentHash);
1812 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1813 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1815 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SQUASH) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)) && FirstSelect != GetItemCount() - 1 && LastSelect != GetItemCount() - 1 && (m_bIsCherryPick || pSelLogEntry->ParentsCount() == 1))
1816 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1818 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1819 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1821 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1822 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1824 if (m_ContextMenuMask & (GetContextMenuBit(ID_REBASE_SKIP) | GetContextMenuBit(ID_REBASE_EDIT) | GetContextMenuBit(ID_REBASE_SQUASH) | GetContextMenuBit(ID_REBASE_PICK)) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1825 popup.AppendMenu(MF_SEPARATOR, NULL);
1827 if (selectedCount == 1)
1830 bool requiresSeparator = false;
1831 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1833 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1835 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1836 requiresSeparator = true;
1839 else
1841 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1843 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1844 requiresSeparator = true;
1846 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1848 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1849 requiresSeparator = true;
1853 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1855 if (parentHash.size() == 1)
1857 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1858 requiresSeparator = true;
1860 else if (parentHash.size() > 1)
1862 blamemenu.CreatePopupMenu();
1863 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1864 for (size_t i = 0; i < parentHash.size(); ++i)
1866 CString str;
1867 str.Format(IDS_PARENT, i + 1);
1868 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1870 requiresSeparator = true;
1874 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1876 if (parentHash.size() == 1)
1878 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1879 requiresSeparator = true;
1881 else if (parentHash.size() > 1)
1883 gnudiffmenu.CreatePopupMenu();
1884 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1886 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1887 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1888 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1890 for (size_t i = 0; i < parentHash.size(); ++i)
1892 CString str;
1893 str.Format(IDS_PARENT, i + 1);
1894 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1896 requiresSeparator = true;
1900 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1902 if (parentHash.size() == 1)
1904 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1905 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1906 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1907 requiresSeparator = true;
1909 else if (parentHash.size() > 1)
1911 diffmenu.CreatePopupMenu();
1912 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1913 for (size_t i = 0; i < parentHash.size(); ++i)
1915 CString str;
1916 str.Format(IDS_PARENT, i + 1);
1917 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1918 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1920 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1921 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1924 requiresSeparator = true;
1928 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1930 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1931 requiresSeparator = true;
1934 if (requiresSeparator)
1936 popup.AppendMenu(MF_SEPARATOR, NULL);
1937 requiresSeparator = false;
1940 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1942 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1944 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1945 requiresSeparator = true;
1949 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1951 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1953 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1954 requiresSeparator = true;
1957 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1959 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1960 requiresSeparator = true;
1964 if (requiresSeparator)
1966 popup.AppendMenu(MF_SEPARATOR, NULL);
1967 requiresSeparator = false;
1970 if (isBisectActive)
1972 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1973 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1975 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1976 requiresSeparator = true;
1979 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1981 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1982 requiresSeparator = true;
1984 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1986 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1987 requiresSeparator = true;
1991 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1993 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1995 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1996 requiresSeparator = true;
2000 if (requiresSeparator)
2002 popup.AppendMenu(MF_SEPARATOR, NULL);
2003 requiresSeparator = false;
2006 if (pSelLogEntry->m_CommitHash.IsEmpty())
2008 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
2009 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2011 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
2012 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
2014 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2015 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2017 popup.AppendMenu(MF_SEPARATOR, NULL);
2019 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2020 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2022 popup.AppendMenu(MF_SEPARATOR, NULL);
2026 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2027 // {
2028 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2029 // }
2030 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2031 // {
2032 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2033 // }
2034 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2035 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2036 // {
2037 // popup.AppendMenu(MF_SEPARATOR, NULL);
2038 // }
2040 CString str;
2041 //if (m_hasWC)
2042 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2044 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2046 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2047 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2049 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2050 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2052 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2054 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2056 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2058 size_t index = (size_t)-1;
2059 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2060 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2061 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2064 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2066 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2067 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2070 // Add Switch Branch express Menu
2071 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2072 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2075 std::vector<const CString*> branchs;
2076 auto addCheck = [&](const CString& ref)
2078 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2079 return;
2080 branchs.push_back(&ref);
2082 size_t index = (size_t)-1;
2083 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2084 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2085 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2086 else
2087 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2089 CString str2;
2090 str2.LoadString(IDS_SWITCH_BRANCH);
2092 if(branchs.size() == 1)
2094 str2 += L' ';
2095 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2096 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2098 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2101 else if(branchs.size() > 1)
2103 subbranchmenu.CreatePopupMenu();
2104 for (size_t i = 0 ; i < branchs.size(); ++i)
2106 if (*branchs[i] != currentBranch)
2108 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2109 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2113 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2117 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2119 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2120 size_t index = (size_t)-1;
2121 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2122 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2123 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2126 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2128 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2130 size_t index = (size_t)-1;
2131 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2132 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2133 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2136 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2137 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2139 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2141 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2142 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2143 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2145 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2146 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2148 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2150 if (parentHash.size() == 1)
2151 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2152 else if (parentHash.size() > 1)
2154 revertmenu.CreatePopupMenu();
2155 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2157 for (size_t i = 0; i < parentHash.size(); ++i)
2159 CString str2;
2160 str2.Format(IDS_PARENT, i + 1);
2161 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2166 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2167 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2169 popup.AppendMenu(MF_SEPARATOR, NULL);
2173 if(!pSelLogEntry->m_Ref.IsEmpty())
2175 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2176 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2177 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2178 if (selectedCount <= 2)
2179 popup.AppendMenu(MF_SEPARATOR, NULL);
2182 if (selectedCount >= 2)
2184 bool bAddSeparator = false;
2185 if ((selectedCount == 2) || IsSelectionContinuous())
2187 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2189 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2190 bAddSeparator = true;
2194 if (selectedCount == 2)
2196 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2198 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2199 bAddSeparator = true;
2202 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2204 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2205 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2206 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2207 CString menu;
2208 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2209 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2210 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2211 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2212 bAddSeparator = true;
2216 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2218 bAddSeparator = true;
2219 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2222 if (bAddSeparator)
2224 popup.AppendMenu(MF_SEPARATOR, NULL);
2225 bAddSeparator = false;
2228 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2229 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2231 if (bAddSeparator)
2232 popup.AppendMenu(MF_SEPARATOR, NULL);
2235 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2237 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2238 popup.AppendMenu(MF_SEPARATOR, NULL);
2241 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2243 bool bAddSeparator = false;
2244 if (selectedCount >= 2 && IsSelectionContinuous())
2246 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2248 CString head;
2249 int headindex;
2250 headindex = this->GetHeadIndex();
2251 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2253 head.Format(L"HEAD~%d", FirstSelect - headindex);
2254 CGitHash hashFirst;
2255 int ret = g_Git.GetHash(hashFirst, head);
2256 head.Format(L"HEAD~%d",LastSelect-headindex);
2257 CGitHash hash;
2258 ret = ret || g_Git.GetHash(hash, head);
2259 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2260 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2261 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2263 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2264 bAddSeparator = true;
2269 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2270 if (selectedCount >= 2)
2271 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2272 else
2273 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2274 bAddSeparator = true;
2277 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2278 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2279 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2280 bAddSeparator = true;
2283 if (bAddSeparator)
2284 popup.AppendMenu(MF_SEPARATOR, NULL);
2287 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2289 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2290 popup.AppendMenu(MF_SEPARATOR, NULL);
2293 if (selectedCount == 1)
2295 bool bAddSeparator = false;
2296 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2298 // show the push-option only if the log entry has an associated local branch
2299 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2300 if (isLocal || showExtendedMenu)
2302 CString str;
2303 str.LoadString(IDS_MENUPUSH);
2305 CString branch;
2306 size_t index = (size_t)-1;
2307 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2308 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2309 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2310 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2312 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2314 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2315 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2317 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2318 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2320 bAddSeparator = true;
2323 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2325 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2326 bAddSeparator = true;
2330 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2332 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2334 std::vector<const CString*> branchs;
2335 auto addCheck = [&](const CString& ref)
2337 if (ref == currentBranch)
2338 return;
2339 branchs.push_back(&ref);
2341 size_t index = (size_t)-1;
2342 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2343 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2344 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2345 else
2346 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2348 CString str;
2349 if (branchs.size() == 1)
2351 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2352 str += L' ';
2353 str += *branchs[0];
2354 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2355 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2356 bAddSeparator = true;
2358 else if (branchs.size() > 1)
2360 str.LoadString(IDS_DELETE_BRANCHTAG);
2361 submenu.CreatePopupMenu();
2362 for (size_t i = 0; i < branchs.size(); ++i)
2364 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2365 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2367 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2368 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2370 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2371 bAddSeparator = true;
2374 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2375 if (bAddSeparator)
2376 popup.AppendMenu(MF_SEPARATOR, NULL);
2377 } // selectedCount == 1
2379 CIconMenu clipSubMenu;
2380 if (!clipSubMenu.CreatePopupMenu())
2381 return;
2382 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2384 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2385 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2386 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2387 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2388 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2389 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2390 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2391 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2392 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2394 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2395 size_t index = (size_t)-1;
2396 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2397 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2398 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2401 CString temp;
2402 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2403 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2406 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2407 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2409 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2410 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2412 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2413 // DialogEnableWindow(IDOK, FALSE);
2414 // SetPromptApp(&theApp);
2416 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2418 // EnableOKButton();
2419 } // if (popup.CreatePopupMenu())
2422 bool CGitLogListBase::IsSelectionContinuous()
2424 if ( GetSelectedCount()==1 )
2426 // if only one revision is selected, the selection is of course
2427 // continuous
2428 return true;
2431 POSITION pos = GetFirstSelectedItemPosition();
2432 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2433 if (bContinuous)
2435 int itemindex = GetNextSelectedItem(pos);
2436 while (pos)
2438 int nextindex = GetNextSelectedItem(pos);
2439 if (nextindex - itemindex > 1)
2441 bContinuous = false;
2442 break;
2444 itemindex = nextindex;
2447 return bContinuous;
2450 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2452 CString sClipdata;
2453 POSITION pos = GetFirstSelectedItemPosition();
2454 if (pos)
2456 CString sRev;
2457 sRev.LoadString(IDS_LOG_REVISION);
2458 CString sAuthor;
2459 sAuthor.LoadString(IDS_LOG_AUTHOR);
2460 CString sDate;
2461 sDate.LoadString(IDS_LOG_DATE);
2462 CString sMessage;
2463 sMessage.LoadString(IDS_LOG_MESSAGE);
2464 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2465 bool first = true;
2466 while (pos)
2468 CString sLogCopyText;
2469 CString sPaths;
2470 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2472 if (toCopy == ID_COPYCLIPBOARDFULL)
2474 sPaths = L"----\r\n";
2475 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2477 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2478 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2480 sPaths += L' ';
2481 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2483 sPaths += L"\r\n";
2485 sPaths.Trim();
2486 sPaths += L"\r\n";
2489 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2491 CString sNotesTags;
2492 if (!pLogEntry->m_Notes.IsEmpty())
2494 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2495 sNotesTags += L":\n";
2496 sNotesTags += pLogEntry->m_Notes;
2497 sNotesTags.Replace(L"\n", L"\r\n");
2499 CString tagInfo = GetTagInfo(pLogEntry);
2500 if (!tagInfo.IsEmpty())
2502 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2503 tagInfo.Replace(L"\n", L"\r\n");
2504 sNotesTags += tagInfo;
2507 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s%s\r\n",
2508 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2509 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2510 (LPCTSTR)sDate,
2511 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2512 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2513 (LPCTSTR)sNotesTags,
2514 (LPCTSTR)sPaths);
2515 sClipdata += sLogCopyText;
2517 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2519 if (!first)
2520 sClipdata += L"\r\n";
2521 sClipdata += pLogEntry->GetAuthorName();
2522 sClipdata += L" <";
2523 sClipdata += pLogEntry->GetAuthorEmail();
2524 sClipdata += L">";
2526 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2528 if (!first)
2529 sClipdata += L"\r\n";
2530 sClipdata += pLogEntry->GetAuthorName();
2532 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2534 if (!first)
2535 sClipdata += L"\r\n";
2536 sClipdata += pLogEntry->GetAuthorEmail();
2539 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2541 sClipdata += L"* ";
2542 sClipdata += pLogEntry->GetSubjectBody(true);
2543 sClipdata += L"\r\n\r\n";
2545 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2547 sClipdata += L"* ";
2548 sClipdata += pLogEntry->GetSubject().Trim();
2549 sClipdata += L"\r\n\r\n";
2551 else
2553 if (!first)
2554 sClipdata += L"\r\n";
2555 sClipdata += pLogEntry->m_CommitHash;
2558 first = false;
2560 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2564 void CGitLogListBase::DiffSelectedRevWithPrevious()
2566 if (m_bThreadRunning)
2567 return;
2569 int FirstSelect=-1, LastSelect=-1;
2570 POSITION pos = GetFirstSelectedItemPosition();
2571 FirstSelect = GetNextSelectedItem(pos);
2572 while(pos)
2573 LastSelect = GetNextSelectedItem(pos);
2575 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2578 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2580 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2581 *pResult = -1;
2583 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2584 return;
2585 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2586 return;
2587 if (!pFindInfo->lvfi.psz)
2588 return;
2589 #if 0
2590 CString sCmp = pFindInfo->lvfi.psz;
2591 CString sRev;
2592 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2594 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2595 sRev.Format(L"%ld", pLogEntry->Rev);
2596 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2598 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2600 *pResult = i;
2601 return;
2604 else
2606 if (sCmp.Compare(sRev)==0)
2608 *pResult = i;
2609 return;
2613 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2615 for (int i=0; i<pFindInfo->iStart; ++i)
2617 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2618 sRev.Format(L"%ld", pLogEntry->Rev);
2619 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2621 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2623 *pResult = i;
2624 return;
2627 else
2629 if (sCmp.Compare(sRev)==0)
2631 *pResult = i;
2632 return;
2637 #endif
2638 *pResult = -1;
2641 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2643 ClearText();
2645 this->m_arShownList.SafeRemoveAll();
2647 this->m_logEntries.ClearAll();
2648 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2649 return -1;
2651 SetItemCountEx((int)m_logEntries.size());
2653 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2655 if(m_IsOldFirst)
2657 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2658 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2660 else
2662 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2663 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2667 ReloadHashMap();
2669 if(path)
2670 m_Path=*path;
2671 return 0;
2674 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2676 ClearText();
2678 m_arShownList.SafeRemoveAll();
2680 m_logEntries.ClearAll();
2681 if (m_logEntries.Fill(hashes))
2682 return -1;
2684 SetItemCountEx((int)m_logEntries.size());
2686 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2688 if (m_IsOldFirst)
2690 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2691 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2693 else
2695 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2696 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2700 ReloadHashMap();
2702 return 0;
2705 int CGitLogListBase::BeginFetchLog()
2707 ClearText();
2709 this->m_arShownList.SafeRemoveAll();
2711 this->m_logEntries.ClearAll();
2713 this->m_LogCache.ClearAllParent();
2715 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2717 CTGitPath *path;
2718 if(this->m_Path.IsEmpty())
2719 path = nullptr;
2720 else
2721 path=&this->m_Path;
2723 int mask;
2724 mask = CGit::LOG_INFO_ONLY_HASH;
2725 if (m_bIncludeBoundaryCommits)
2726 mask |= CGit::LOG_INFO_BOUNDARY;
2727 // if(this->m_bAllBranch)
2728 mask |= m_ShowMask ;
2730 if(m_bShowWC)
2732 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2733 ResetWcRev();
2734 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2737 if (m_sRange.IsEmpty())
2738 m_sRange = L"HEAD";
2740 #if 0 /* use tortoiegit filter */
2741 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2742 data.m_Author = this->m_sFilterText;
2744 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2745 data.m_MessageFilter = this->m_sFilterText;
2747 data.m_IsRegex = m_bFilterWithRegex;
2748 #endif
2750 // follow does not work for directories
2751 if (!path || path->IsDirectory())
2752 mask &= ~CGit::LOG_INFO_FOLLOW;
2753 // follow does not work with all branches 8at least in TGit)
2754 if (mask & CGit::LOG_INFO_FOLLOW)
2755 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2757 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2759 //this->m_logEntries.ParserFromLog();
2760 if(IsInWorkingThread())
2762 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2764 else
2766 SetItemCountEx((int)m_logEntries.size());
2771 [] { git_init(); } ();
2773 catch (char* msg)
2775 CString err(msg);
2776 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2777 return -1;
2780 if (!g_Git.CanParseRev(m_sRange))
2782 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2783 return 0;
2785 // if show all branches, pick any ref as dummy entry ref
2786 STRING_VECTOR list;
2787 if (g_Git.GetRefList(list))
2788 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2789 if (list.empty())
2790 return 0;
2792 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2795 g_Git.m_critGitDllSec.Lock();
2796 try {
2797 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2799 g_Git.m_critGitDllSec.Unlock();
2800 return -1;
2803 catch (char* msg)
2805 g_Git.m_critGitDllSec.Unlock();
2806 CString err(msg);
2807 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2808 return -1;
2810 g_Git.m_critGitDllSec.Unlock();
2812 return 0;
2815 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2817 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2819 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2821 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2823 DiffSelectedRevWithPrevious();
2824 return TRUE;
2827 #if 0
2828 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2830 DiffSelectedFile();
2831 return TRUE;
2833 #endif
2835 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2837 // select all entries
2838 for (int i=0; i<GetItemCount(); ++i)
2839 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2840 return TRUE;
2843 #if 0
2844 if (m_hAccel && !bSkipAccelerator)
2846 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2847 if (ret)
2848 return TRUE;
2851 #endif
2852 //m_tooltips.RelayEvent(pMsg);
2853 return __super::PreTranslateMessage(pMsg);
2856 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2858 // a double click on an entry in the revision list has happened
2859 *pResult = 0;
2861 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2862 DiffSelectedRevWithPrevious();
2865 void CGitLogListBase::FetchLogAsync(void* data)
2867 ReloadHashMap();
2868 m_ProcData=data;
2869 StartLoadingThread();
2872 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2874 return ((CGitLogListBase*)pVoid)->LogThread();
2877 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2879 //CTime time;
2880 oldest=CTime::GetCurrentTime();
2881 latest=CTime(1971,1,2,0,0,0);
2882 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2884 if(m_logEntries[i].IsEmpty())
2885 continue;
2887 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2888 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2890 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2891 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2895 if(latest<oldest)
2896 latest=oldest;
2899 UINT CGitLogListBase::LogThread()
2901 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2903 ULONGLONG t1,t2;
2905 if(BeginFetchLog())
2907 InterlockedExchange(&m_bThreadRunning, FALSE);
2908 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2910 return 1;
2913 std::wregex pat;//(L"Remove", regex_constants::icase);
2914 bool bRegex = false;
2915 if (m_bFilterWithRegex)
2916 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2918 TRACE(L"\n===Begin===\n");
2919 //Update work copy item;
2921 if (!m_logEntries.empty())
2923 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2925 m_arShownList.SafeAdd(pRev);
2929 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2931 // store commit number of the last selected commit/line before the refresh or -1
2932 int lastSelectedHashNItem = -1;
2933 if (m_lastSelectedHash.IsEmpty())
2934 lastSelectedHashNItem = 0;
2936 int ret = 0;
2938 bool shouldWalk = true;
2939 if (!g_Git.CanParseRev(m_sRange))
2941 // walk revisions if show all branches and there exists any ref
2942 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2943 shouldWalk = false;
2944 else
2946 STRING_VECTOR list;
2947 if (g_Git.GetRefList(list))
2948 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2949 if (list.empty())
2950 shouldWalk = false;
2954 if (shouldWalk)
2956 g_Git.m_critGitDllSec.Lock();
2957 if (!m_DllGitLog)
2959 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2960 g_Git.m_critGitDllSec.Unlock();
2961 InterlockedExchange(&m_bThreadRunning, FALSE);
2962 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2963 return 1;
2965 int total = 0;
2968 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2969 total = git_get_log_estimate_commit_count(m_DllGitLog);
2971 catch (char* msg)
2973 CString err(msg);
2974 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2975 ret = -1;
2977 g_Git.m_critGitDllSec.Unlock();
2979 GIT_COMMIT commit;
2980 t2 = t1 = GetTickCount64();
2981 int oldprecentage = 0;
2982 size_t oldsize = m_logEntries.size();
2983 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2984 while (ret== 0 && !m_bExitThread)
2986 g_Git.m_critGitDllSec.Lock();
2989 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2991 catch (char* msg)
2993 g_Git.m_critGitDllSec.Unlock();
2994 CString err(msg);
2995 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2996 break;
2998 g_Git.m_critGitDllSec.Unlock();
3000 if(ret)
3002 if (ret != -2) // other than end of revision walking
3003 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
3004 break;
3007 if (commit.m_ignore == 1)
3009 git_free_commit(&commit);
3010 continue;
3013 //printf("%s\r\n",commit.GetSubject());
3014 if(m_bExitThread)
3015 break;
3017 CGitHash hash(commit.m_hash);
3019 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3020 pRev->m_GitCommit = commit;
3021 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3023 char* note = nullptr;
3024 g_Git.m_critGitDllSec.Lock();
3027 git_get_notes(commit.m_hash, &note);
3029 catch (char* msg)
3031 g_Git.m_critGitDllSec.Unlock();
3032 CString err(msg);
3033 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3034 break;
3036 g_Git.m_critGitDllSec.Unlock();
3038 if(note)
3040 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3041 free(note);
3042 note = nullptr;
3045 if(!pRev->m_IsDiffFiles)
3047 pRev->m_CallDiffAsync = DiffAsync;
3050 pRev->ParserParentFromCommit(&commit);
3051 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3053 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3055 const CGitHash &parentHash = pRev->m_ParentHash[i];
3056 auto it = commitChildren.find(parentHash);
3057 if (it == commitChildren.end())
3058 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3059 it->second.insert(pRev->m_CommitHash);
3063 #ifdef DEBUG
3064 pRev->DbgPrint();
3065 TRACE(L"\n");
3066 #endif
3068 bool visible = true;
3069 if (HasFilterText())
3071 if(!IsMatchFilter(bRegex,pRev,pat))
3072 visible = false;
3074 if (visible && !ShouldShowFilter(pRev, commitChildren))
3075 visible = false;
3076 this->m_critSec.Lock();
3077 m_logEntries.append(hash, visible);
3078 if (visible)
3079 m_arShownList.SafeAdd(pRev);
3080 this->m_critSec.Unlock();
3082 if (!visible)
3083 continue;
3085 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3086 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3088 t2 = GetTickCount64();
3090 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3092 //update UI
3093 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3094 if(percent > 99)
3095 percent =99;
3096 if(percent < GITLOG_START)
3097 percent = GITLOG_START +1;
3099 oldsize = m_logEntries.size();
3100 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3102 //if( percent > oldprecentage )
3104 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3105 oldprecentage = percent;
3108 if (lastSelectedHashNItem >= 0)
3109 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3111 t1 = t2;
3114 g_Git.m_critGitDllSec.Lock();
3115 git_close_log(m_DllGitLog);
3116 g_Git.m_critGitDllSec.Unlock();
3120 if (m_bExitThread)
3122 InterlockedExchange(&m_bThreadRunning, FALSE);
3123 return 0;
3126 //Update UI;
3127 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3129 if (lastSelectedHashNItem >= 0)
3130 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3132 if (this->m_hWnd)
3133 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3135 InterlockedExchange(&m_bThreadRunning, FALSE);
3137 return 0;
3140 void CGitLogListBase::FetchRemoteList()
3142 STRING_VECTOR remoteList;
3143 m_SingleRemote.Empty();
3144 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3145 m_SingleRemote = remoteList[0];
3148 void CGitLogListBase::FetchTrackingBranchList()
3150 m_TrackingMap.clear();
3151 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3153 for (const auto& ref : it->second)
3155 CString branchName;
3156 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3158 CString pullRemote, pullBranch;
3159 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3160 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3161 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3167 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3169 SafeTerminateThread();
3171 this->SetItemCountEx(0);
3172 this->Clear();
3174 ResetWcRev();
3176 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3178 if (m_pMailmap)
3180 git_free_mailmap(m_pMailmap);
3181 git_read_mailmap(&m_pMailmap);
3184 //Update branch and Tag info
3185 ReloadHashMap();
3186 if (m_pFindDialog)
3187 m_pFindDialog->RefreshList();
3188 //Assume Thread have exited
3189 //if(!m_bThreadRunning)
3191 m_logEntries.clear();
3193 if(IsCleanFilter)
3195 m_sFilterText.Empty();
3198 SafeTerminateAsyncDiffThread();
3199 m_AsynDiffListLock.Lock();
3200 m_AsynDiffList.clear();
3201 m_AsynDiffListLock.Unlock();
3202 StartAsyncDiffThread();
3204 StartLoadingThread();
3208 void CGitLogListBase::StartAsyncDiffThread()
3210 if (m_AsyncThreadExit)
3211 return;
3212 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3213 return;
3214 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3215 if (!m_DiffingThread)
3217 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3218 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3222 void CGitLogListBase::StartLoadingThread()
3224 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3225 return;
3226 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3227 InterlockedExchange(&m_bExitThread, FALSE);
3228 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3229 if (!m_LoadingThread)
3231 InterlockedExchange(&m_bThreadRunning, FALSE);
3232 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3233 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3237 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::wregex& pat, bool bMatchCase /* = false */)
3241 std::regex_constants::syntax_option_type type = std::regex_constants::ECMAScript;
3242 if (!bMatchCase)
3243 type |= std::regex_constants::icase;
3244 pat = std::wregex(regexp_str, type);
3245 return true;
3247 catch (std::exception&) {}
3248 return false;
3250 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::wregex& pat)
3252 BOOL result = TRUE;
3253 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3254 CString sRev;
3256 if ((bRegex)&&(m_bFilterWithRegex))
3258 if (m_SelectedFilters & LOGFILTER_BUGID)
3260 if(this->m_bShowBugtraqColumn)
3262 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3264 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3265 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3266 return TRUE;
3270 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3272 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3273 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3274 return TRUE;
3277 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3279 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3280 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3281 return TRUE;
3284 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3286 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3287 return TRUE;
3289 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3290 return TRUE;
3293 if (m_SelectedFilters & LOGFILTER_EMAILS)
3295 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3296 return TRUE;
3298 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3299 return TRUE;
3302 if (m_SelectedFilters & LOGFILTER_REVS)
3304 sRev = pRev->m_CommitHash.ToString();
3305 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3307 return TRUE;
3311 if (m_SelectedFilters & LOGFILTER_NOTES)
3313 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3314 return TRUE;
3317 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3319 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3320 for (const auto& ref : refs)
3322 if (std::regex_search(std::wstring(ref), pat, flags))
3323 return TRUE;
3327 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3329 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3330 return TRUE;
3333 if (m_SelectedFilters & LOGFILTER_PATHS)
3335 CTGitPathList* pathList = nullptr;
3336 if( pRev->m_IsDiffFiles)
3337 pathList = &pRev->GetFiles(this);
3338 else
3340 if(!pRev->m_IsSimpleListReady)
3341 pRev->SafeGetSimpleList(&g_Git);
3344 if(pathList)
3345 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3347 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3348 return true;
3349 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3350 return true;
3353 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3355 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3356 return true;
3360 else
3362 CString find = m_sFilterText;
3363 if (!m_bFilterCaseSensitively)
3364 find.MakeLower();
3365 result = find[0] == '!' ? FALSE : TRUE;
3366 if (!result)
3367 find = find.Mid(1);
3369 if (m_SelectedFilters & LOGFILTER_BUGID)
3371 if(this->m_bShowBugtraqColumn)
3373 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3375 if (!m_bFilterCaseSensitively)
3376 sBugIds.MakeLower();
3377 if ((sBugIds.Find(find) >= 0))
3378 return result;
3382 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3384 CString msg = pRev->GetSubject();
3386 if (!m_bFilterCaseSensitively)
3387 msg = msg.MakeLower();
3388 if ((msg.Find(find) >= 0))
3389 return result;
3392 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3394 CString msg = pRev->GetBody();
3396 if (!m_bFilterCaseSensitively)
3397 msg = msg.MakeLower();
3398 if ((msg.Find(find) >= 0))
3399 return result;
3402 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3404 CString msg = pRev->GetAuthorName();
3405 if (!m_bFilterCaseSensitively)
3406 msg = msg.MakeLower();
3407 if ((msg.Find(find) >= 0))
3408 return result;
3411 if (m_SelectedFilters & LOGFILTER_EMAILS)
3413 CString msg = pRev->GetAuthorEmail();
3414 if (!m_bFilterCaseSensitively)
3415 msg = msg.MakeLower();
3416 if ((msg.Find(find) >= 0))
3417 return result;
3420 if (m_SelectedFilters & LOGFILTER_NOTES)
3422 CString msg = pRev->m_Notes;
3423 if (!m_bFilterCaseSensitively)
3424 msg = msg.MakeLower();
3425 if ((msg.Find(find) >= 0))
3426 return result;
3429 if (m_SelectedFilters & LOGFILTER_REVS)
3431 sRev = pRev->m_CommitHash.ToString();
3432 if ((sRev.Find(find) >= 0))
3433 return result;
3436 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3438 CString msg = GetTagInfo(pRev);
3439 if (!m_bFilterCaseSensitively)
3440 msg = msg.MakeLower();
3441 if ((msg.Find(find) >= 0))
3442 return result;
3445 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3447 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3448 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3450 if (it->Find(find) >= 0)
3451 return result;
3455 if (m_SelectedFilters & LOGFILTER_PATHS)
3457 CTGitPathList* pathList = nullptr;
3458 if( pRev->m_IsDiffFiles)
3459 pathList = &pRev->GetFiles(this);
3460 else
3462 if(!pRev->m_IsSimpleListReady)
3463 pRev->SafeGetSimpleList(&g_Git);
3465 if(pathList)
3466 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3468 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3469 CString path = cpath->GetGitOldPathString();
3470 if (!m_bFilterCaseSensitively)
3471 path.MakeLower();
3472 if ((path.Find(find)>=0))
3473 return result;
3474 path = cpath->GetGitPathString();
3475 if (!m_bFilterCaseSensitively)
3476 path.MakeLower();
3477 if ((path.Find(find)>=0))
3478 return result;
3481 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3483 CString path = pRev->m_SimpleFileList[i];
3484 if (!m_bFilterCaseSensitively)
3485 path.MakeLower();
3486 if ((path.Find(find)>=0))
3487 return result;
3490 } // else (from if (bRegex))
3491 return !result;
3494 static bool CStringStartsWith(const CString &str, const CString &prefix)
3496 return str.Left(prefix.GetLength()) == prefix;
3498 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3500 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3501 return true;
3503 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3505 // Keep all refs.
3506 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3507 for (size_t i = 0; i < refList.size(); ++i)
3509 const CString &str = refList[i];
3510 if (CStringStartsWith(str, L"refs/heads/"))
3512 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3513 return true;
3515 else if (CStringStartsWith(str, L"refs/remotes/"))
3517 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3518 return true;
3520 else if (CStringStartsWith(str, L"refs/tags/"))
3522 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3523 return true;
3525 else if (CStringStartsWith(str, L"refs/stash"))
3527 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3528 return true;
3530 else if (CStringStartsWith(str, L"refs/bisect/"))
3532 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3533 return true;
3536 // Keep the head too.
3537 if (pRev->m_CommitHash == m_HeadHash)
3538 return true;
3541 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3543 if (pRev->ParentsCount() > 1)
3544 return true;
3545 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3546 if (childrenIt != commitChildren.end())
3548 const std::unordered_set<CGitHash> &children = childrenIt->second;
3549 if (children.size() > 1)
3550 return true;
3553 return false;
3556 void CGitLogListBase::ShowGraphColumn(bool bShow)
3558 // HACK to hide graph column
3559 if (bShow)
3560 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3561 else
3562 SetColumnWidth(0, 0);
3565 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3567 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3568 return L"";
3570 CString tagInfo;
3571 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3572 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3574 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3575 continue;
3576 if (!CStringUtils::EndsWith((*it), L"^{}"))
3577 continue;
3579 CString cmd;
3580 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3581 CString output;
3582 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3583 continue;
3585 // parse tag date
3588 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3589 int pos1 = output.Find(L'>');
3590 if (pos1 < 0)
3591 break;
3592 ++pos1;
3593 if (output[pos1] == L' ')
3594 ++pos1;
3595 int pos2 = output.Find(L'\n', pos1);
3596 if (pos2 < 0)
3597 break;
3599 CString str = output.Mid(pos1, pos2 - pos1);
3600 wchar_t* pEnd = nullptr;
3601 errno = 0;
3602 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3603 if (str.GetBuffer() == pEnd)
3604 break;
3605 if (errno == ERANGE)
3606 break;
3608 output.Delete(pos1, pos2 - pos1);
3609 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3610 } while (0);
3611 output.Trim().AppendChar(L'\n');
3612 tagInfo += output;
3614 return tagInfo;
3617 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3619 pShownlist->SafeRemoveAll();
3621 std::wregex pat;//(L"Remove", regex_constants::icase);
3622 bool bRegex = false;
3623 if (m_bFilterWithRegex)
3624 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3626 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3627 CString sRev;
3628 for (DWORD i=0; i<m_logEntries.size(); ++i)
3630 if ((bRegex)&&(m_bFilterWithRegex))
3632 #if 0
3633 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3635 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3636 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3638 pShownlist->SafeAdd(m_logEntries[i]);
3639 continue;
3642 #endif
3643 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3645 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3646 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3648 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3649 continue;
3652 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3654 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3655 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3657 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3658 continue;
3661 if (m_SelectedFilters & LOGFILTER_PATHS)
3663 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3665 bool bGoing = true;
3666 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3668 CTGitPath cpath = pathList[cpPathIndex];
3669 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3671 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3672 bGoing = false;
3673 continue;
3675 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3677 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3678 bGoing = false;
3679 continue;
3681 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3683 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3684 bGoing = false;
3685 continue;
3689 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3691 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3693 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3694 continue;
3697 if (m_SelectedFilters & LOGFILTER_EMAILS)
3699 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3701 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3702 continue;
3705 if (m_SelectedFilters & LOGFILTER_REVS)
3707 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3708 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3710 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3711 continue;
3714 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3716 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3717 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3719 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3721 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3722 continue;
3726 } // if (bRegex)
3727 else
3729 CString find = m_sFilterText;
3730 if (!m_bFilterCaseSensitively)
3731 find.MakeLower();
3732 #if 0
3733 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3735 CString sBugIDs = m_logEntries[i]->sBugIDs;
3737 if (!m_bFilterCaseSensitively)
3738 sBugIDs = sBugIDs.MakeLower();
3739 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3741 pShownlist->SafeAdd(m_logEntries[i]);
3742 continue;
3745 #endif
3746 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3748 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3750 if (!m_bFilterCaseSensitively)
3751 msg = msg.MakeLower();
3752 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3754 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3755 continue;
3758 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3760 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3762 if (!m_bFilterCaseSensitively)
3763 msg = msg.MakeLower();
3764 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3766 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3767 continue;
3770 if (m_SelectedFilters & LOGFILTER_PATHS)
3772 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3774 bool bGoing = true;
3775 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3777 CTGitPath cpath = pathList[cpPathIndex];
3778 CString path = cpath.GetGitOldPathString();
3779 if (!m_bFilterCaseSensitively)
3780 path.MakeLower();
3781 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3783 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3784 bGoing = false;
3785 continue;
3787 path = cpath.GetGitPathString();
3788 if (!m_bFilterCaseSensitively)
3789 path.MakeLower();
3790 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3792 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3793 bGoing = false;
3794 continue;
3796 path = cpath.GetActionName();
3797 if (!m_bFilterCaseSensitively)
3798 path.MakeLower();
3799 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3801 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3802 bGoing = false;
3803 continue;
3807 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3809 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3810 if (!m_bFilterCaseSensitively)
3811 msg = msg.MakeLower();
3812 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3814 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3815 continue;
3818 if (m_SelectedFilters & LOGFILTER_EMAILS)
3820 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3821 if (!m_bFilterCaseSensitively)
3822 msg = msg.MakeLower();
3823 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3825 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3826 continue;
3829 if (m_SelectedFilters & LOGFILTER_REVS)
3831 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3832 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3834 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3835 continue;
3838 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3840 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3841 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3843 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3845 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3846 continue;
3850 } // else (from if (bRegex))
3851 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3854 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3857 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3859 if(m_From == -1)
3860 if(m_To == -1)
3861 return true;
3862 else
3863 return time <= m_To;
3864 else
3865 if(m_To == -1)
3866 return time >= m_From;
3867 else
3868 return ((time >= m_From)&&(time <= m_To));
3870 return TRUE; /* git dll will filter time range */
3872 // return TRUE;
3875 void CGitLogListBase::StartFilter()
3877 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3878 RecalculateShownList(&m_arShownList);
3879 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3882 DeleteAllItems();
3883 SetItemCountEx(ShownCountWithStopped());
3884 RedrawItems(0, ShownCountWithStopped());
3885 Invalidate();
3888 void CGitLogListBase::RemoveFilter()
3890 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3892 m_arShownList.SafeRemoveAll();
3894 // reset the time filter too
3895 #if 0
3896 m_timFrom = (__time64_t(m_tFrom));
3897 m_timTo = (__time64_t(m_tTo));
3898 m_DateFrom.SetTime(&m_timFrom);
3899 m_DateTo.SetTime(&m_timTo);
3900 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3901 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3902 #endif
3904 for (DWORD i=0; i<m_logEntries.size(); ++i)
3906 if(this->m_IsOldFirst)
3907 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3908 else
3909 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3911 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3912 DeleteAllItems();
3913 SetItemCountEx(ShownCountWithStopped());
3914 RedrawItems(0, ShownCountWithStopped());
3916 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3919 void CGitLogListBase::Clear()
3921 m_arShownList.SafeRemoveAll();
3922 DeleteAllItems();
3924 m_logEntries.ClearAll();
3927 void CGitLogListBase::OnDestroy()
3929 SafeTerminateThread();
3930 SafeTerminateAsyncDiffThread();
3932 int retry = 0;
3933 while(m_LogCache.SaveCache())
3935 if(retry > 5)
3936 break;
3937 Sleep(1000);
3939 ++retry;
3941 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3942 // MB_YESNO) == IDNO)
3943 // break;
3946 __super::OnDestroy();
3949 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3951 CRect rect;
3952 int i=(int)wParam;
3953 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3954 this->InvalidateRect(rect);
3956 return 0;
3960 * Save column widths to the registry
3962 void CGitLogListBase::SaveColumnWidths()
3964 // HACK that graph column is always shown
3965 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3967 __super::SaveColumnWidths();
3970 int CGitLogListBase::GetHeadIndex()
3972 if(m_HeadHash.IsEmpty())
3973 return -1;
3975 for (size_t i = 0; i < m_arShownList.size(); ++i)
3977 GitRev* pRev = m_arShownList.SafeGetAt(i);
3978 if(pRev)
3980 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3981 return (int)i;
3984 return -1;
3986 void CGitLogListBase::OnFind()
3988 if (!m_pFindDialog)
3990 m_pFindDialog = new CFindDlg(this);
3991 m_pFindDialog->Create(this);
3995 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3997 if (GetSelectedCount() != 0)
3998 return 0;
4000 CGitHash theSelectedHash = m_lastSelectedHash;
4001 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4002 m_lastSelectedHash = theSelectedHash;
4004 int countPerPage = GetCountPerPage();
4005 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
4006 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
4007 EnsureVisible((int)itemToSelect, FALSE);
4008 return 0;
4011 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
4013 CString* ref = reinterpret_cast<CString*>(wParam);
4014 if (!ref || ref->IsEmpty())
4015 return 1;
4017 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4019 CGitHash hash;
4020 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4021 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4023 if (hash.IsEmpty())
4024 return 1;
4026 bool bFound = false;
4027 int cnt = (int)m_arShownList.size();
4028 int i;
4029 for (i = 0; i < cnt; ++i)
4031 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4032 if (pLogEntry && pLogEntry->m_CommitHash == hash)
4034 bFound = true;
4035 break;
4038 if (!bFound)
4039 return 1;
4041 EnsureVisible(i, FALSE);
4042 if (!bShift)
4044 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4045 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4046 SetSelectionMark(i);
4048 else
4050 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4051 if (pLogEntry)
4052 m_highlight = pLogEntry->m_CommitHash;
4054 Invalidate();
4055 UpdateData(FALSE);
4057 return 0;
4060 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4062 ASSERT(m_pFindDialog);
4063 bool bFound = false;
4064 int i=0;
4066 if (m_pFindDialog->IsTerminating())
4068 // invalidate the handle identifying the dialog box.
4069 m_pFindDialog = nullptr;
4070 return 0;
4073 int cnt = (int)m_arShownList.size();
4074 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4076 if(m_pFindDialog->IsRef())
4078 CString str;
4079 str=m_pFindDialog->GetFindString();
4081 CGitHash hash;
4083 if(!str.IsEmpty())
4085 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4086 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4089 if(!hash.IsEmpty())
4091 for (i = 0; i < cnt; ++i)
4093 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4094 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4096 bFound = true;
4097 break;
4101 if (!bFound)
4103 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4104 return 0;
4108 if (m_pFindDialog->FindNext() && !bFound)
4110 //read data from dialog
4111 CString findText = m_pFindDialog->GetFindString();
4112 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4114 std::wregex pat;
4115 bool bRegex = false;
4116 if (m_pFindDialog->Regex())
4117 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4119 std::regex_constants::match_flag_type flags = std::regex_constants::match_not_null;
4121 for (i = m_nSearchIndex + 1; ; ++i)
4123 if (i >= cnt)
4125 i = 0;
4126 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4128 if (m_nSearchIndex >= 0)
4130 if (i == m_nSearchIndex)
4132 ::MessageBeep(0xFFFFFFFF);
4133 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4134 break;
4138 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4140 CString str;
4141 str+=pLogEntry->m_CommitHash.ToString();
4142 str += L'\n';
4144 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4145 if (refList != m_HashMap.cend())
4147 for (const auto& ref : (*refList).second)
4149 str += ref;
4150 str += L'\n';
4154 str+=pLogEntry->GetAuthorEmail();
4155 str += L'\n';
4156 str+=pLogEntry->GetAuthorName();
4157 str += L'\n';
4158 str+=pLogEntry->GetBody();
4159 str += L'\n';
4160 str+=pLogEntry->GetCommitterEmail();
4161 str += L'\n';
4162 str+=pLogEntry->GetCommitterName();
4163 str += L'\n';
4164 str+=pLogEntry->GetSubject();
4165 str += L'\n';
4166 str+=pLogEntry->m_Notes;
4167 str += L'\n';
4168 str+=GetTagInfo(pLogEntry);
4169 str += L'\n';
4172 /*Because changed files list is loaded on demand when gui show,
4173 files will empty when files have not fetched.
4175 we can add it back by using one-way diff(with outnumber changed and rename detect.
4176 here just need changed filename list. one-way is much quicker.
4178 if(pLogEntry->m_IsFull)
4180 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4182 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4183 str += L'\n';
4184 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4185 str += L'\n';
4188 else
4190 if(!pLogEntry->m_IsSimpleListReady)
4191 pLogEntry->SafeGetSimpleList(&g_Git);
4193 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4195 str += pLogEntry->m_SimpleFileList[j];
4196 str += L'\n';
4200 if (bRegex)
4202 if (std::regex_search(std::wstring(str), pat, flags))
4204 bFound = true;
4205 break;
4208 else
4210 if (bMatchCase)
4212 if (str.Find(findText) >= 0)
4214 bFound = true;
4215 break;
4218 else
4220 CString msg = str;
4221 msg = msg.MakeLower();
4222 CString find = findText.MakeLower();
4223 if (msg.Find(find) >= 0)
4225 bFound = TRUE;
4226 break;
4230 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4232 } // if(m_pFindDialog->FindNext())
4233 //UpdateLogInfoLabel();
4235 if (bFound)
4237 m_nSearchIndex = i;
4238 EnsureVisible(i, FALSE);
4239 if (!bShift)
4241 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4242 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4243 SetSelectionMark(i);
4245 else
4247 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4248 if (pLogEntry)
4249 m_highlight = pLogEntry->m_CommitHash;
4251 Invalidate();
4252 //FillLogMessageCtrl();
4253 UpdateData(FALSE);
4256 return 0;
4259 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4261 LVHITTESTINFO lvhitTestInfo;
4263 lvhitTestInfo.pt = point;
4265 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4266 int nSubItem = lvhitTestInfo.iSubItem;
4268 UINT nFlags = lvhitTestInfo.flags;
4270 // nFlags is 0 if the SubItemHitTest fails
4271 // Therefore, 0 & <anything> will equal false
4272 if (nFlags & LVHT_ONITEM)
4274 // Get the client area occupied by this control
4275 RECT rcClient;
4276 GetClientRect(&rcClient);
4278 // Fill in the TOOLINFO structure
4279 pTI->hwnd = m_hWnd;
4280 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4281 pTI->lpszText = LPSTR_TEXTCALLBACK;
4282 pTI->rect = rcClient;
4284 return pTI->uId; // By returning a unique value per listItem,
4285 // we ensure that when the mouse moves over another list item,
4286 // the tooltip will change
4288 else
4290 // Otherwise, we aren't interested, so let the message propagate
4291 return -1;
4295 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4297 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4298 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4300 *pResult = 0;
4302 // Ignore messages from the built in tooltip, we are processing them internally
4303 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4304 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4305 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4306 return FALSE;
4308 // Get the mouse position
4309 const MSG* pMessage = GetCurrentMessage();
4311 CPoint pt;
4312 pt = pMessage->pt;
4313 ScreenToClient(&pt);
4315 // Check if the point falls onto a list item
4316 LVHITTESTINFO lvhitTestInfo;
4317 lvhitTestInfo.pt = pt;
4319 int nItem = SubItemHitTest(&lvhitTestInfo);
4321 if (lvhitTestInfo.flags & LVHT_ONITEM)
4323 // Get branch description first
4324 CString strTipText;
4325 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4327 CString branch;
4328 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4329 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4331 MAP_STRING_STRING descriptions;
4332 g_Git.GetBranchDescriptions(descriptions);
4333 if (descriptions.find(branch) != descriptions.cend())
4335 strTipText.LoadString(IDS_DESCRIPTION);
4336 strTipText += L":\n";
4337 strTipText += descriptions[branch];
4342 bool followMousePos = false;
4343 if (!strTipText.IsEmpty())
4344 followMousePos = true;
4345 else
4346 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4347 if (strTipText.IsEmpty())
4348 return FALSE;
4350 // we want multiline tooltips
4351 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4353 wcscpy_s(m_wszTip, strTipText);
4354 // handle Unicode as well as non-Unicode requests
4355 if (pNMHDR->code == TTN_NEEDTEXTA)
4357 pTTTA->hinst = nullptr;
4358 pTTTA->lpszText = m_szTip;
4359 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4361 else
4363 pTTTW->hinst = nullptr;
4364 pTTTW->lpszText = m_wszTip;
4367 CRect rect;
4368 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4369 if (followMousePos)
4370 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4371 ClientToScreen(rect);
4372 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4374 return TRUE; // We found a tool tip,
4375 // tell the framework this message has been handled
4378 return FALSE; // We didn't handle the message,
4379 // let the framework continue propagating the message
4382 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4384 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4386 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4387 if (pLogEntry == nullptr)
4388 return CString();
4389 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4390 return CString();
4391 return pLogEntry->GetSubject();
4393 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4395 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4396 if (pLogEntry == nullptr)
4397 return CString();
4398 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4400 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4402 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4403 if (pLogEntry == nullptr)
4404 return CString();
4405 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4407 else if (nSubItem == LOGLIST_ACTION)
4409 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4410 if (pLogEntry == nullptr)
4411 return CString();
4413 if (!pLogEntry->m_IsDiffFiles)
4414 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4416 int actions = pLogEntry->GetAction(this);
4417 CString sToolTipText;
4419 CString actionText;
4420 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4421 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4423 if (actions & CTGitPath::LOGACTIONS_ADDED)
4425 if (!actionText.IsEmpty())
4426 actionText += L"\r\n";
4427 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4430 if (actions & CTGitPath::LOGACTIONS_DELETED)
4432 if (!actionText.IsEmpty())
4433 actionText += L"\r\n";
4434 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4437 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4439 if (!actionText.IsEmpty())
4440 actionText += L"\r\n";
4441 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4444 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4446 if (!actionText.IsEmpty())
4447 actionText += L"\r\n";
4448 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4451 if (!actionText.IsEmpty())
4453 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4454 sToolTipText = sTitle + L":\r\n" + actionText;
4456 return sToolTipText;
4458 return CString();
4461 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4463 POINT pt = point;
4464 ScreenToClient(&pt);
4465 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4468 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4470 if (!pLogEntry)
4471 return false;
4473 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4474 if (refList == m_HashMap.cend())
4475 return false;
4477 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4479 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4480 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4481 continue;
4483 CGit::REF_TYPE foundType;
4484 if (pShortname)
4485 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4486 else
4487 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4488 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4489 return false;
4491 type = foundType;
4492 if (pIndex)
4493 *pIndex = i;
4494 return true;
4496 return false;
4499 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4501 *pResult = 0;
4503 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4504 return;
4506 m_bDragging = TRUE;
4507 m_nDropIndex = -1;
4508 m_nDropMarkerLast = -1;
4509 m_nDropMarkerLastHot = GetHotItem();
4510 SetCapture();
4513 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4515 __super::OnMouseMove(nFlags, point);
4517 if (!m_bDragging)
4518 return;
4520 CPoint dropPoint = point;
4521 ClientToScreen(&dropPoint);
4523 if (WindowFromPoint(dropPoint) != this)
4525 SetCursor(LoadCursor(nullptr, IDC_NO));
4526 m_nDropIndex = -1;
4527 DrawDropInsertMarker(m_nDropIndex);
4528 return;
4531 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4532 ScreenToClient(&dropPoint);
4534 dropPoint.y += 10;
4535 m_nDropIndex = HitTest(dropPoint);
4537 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4539 dropPoint.y -= 10;
4540 m_nDropIndex = HitTest(dropPoint);
4541 if (m_nDropIndex != -1)
4542 m_nDropIndex = GetItemCount();
4545 POSITION pos = GetFirstSelectedItemPosition();
4546 int first = GetNextSelectedItem(pos);
4547 int last = first;
4548 while (pos)
4549 last = GetNextSelectedItem(pos);
4550 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4552 SetCursor(LoadCursor(nullptr, IDC_NO));
4553 m_nDropIndex = -1;
4556 // handle auto scrolling
4557 int hotItem = GetHotItem();
4558 int topindex = GetTopIndex();
4559 if (hotItem == topindex && hotItem != 0)
4560 EnsureVisible(hotItem - 1, FALSE);
4561 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4562 EnsureVisible(hotItem + 1, FALSE);
4564 DrawDropInsertMarker(m_nDropIndex);
4567 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4569 if (m_bDragging)
4571 ::ReleaseCapture();
4572 SetCursor(LoadCursor(nullptr, IDC_HAND));
4573 m_bDragging = FALSE;
4575 CRect rect;
4576 GetItemRect(m_nDropMarkerLast, &rect, 0);
4577 rect.bottom = rect.top + 2;
4578 rect.top -= 2;
4579 InvalidateRect(&rect, 0);
4581 CPoint pt(point);
4582 ClientToScreen(&pt);
4583 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4584 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4587 __super::OnLButtonUp(nFlags, point);
4590 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4592 if (m_nDropMarkerLast != nIndex)
4594 CRect rect;
4595 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4597 rect.bottom = rect.top + 2;
4598 rect.top -= 2;
4599 InvalidateRect(&rect, 0);
4601 else if (m_nDropMarkerLast == GetItemCount())
4602 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4603 m_nDropMarkerLast = nIndex;
4605 if (nIndex < 0)
4606 return;
4608 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4610 else if (m_nDropMarkerLastHot != GetHotItem())
4612 m_nDropMarkerLastHot = GetHotItem();
4613 m_nDropMarkerLast = -1;
4617 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4619 CBrush* pBrush = CDC::GetHalftoneBrush();
4620 CDC* pDC = GetDC();
4622 CRect rect;
4623 if (nIndex < GetItemCount())
4625 GetItemRect(nIndex, &rect, 0);
4626 rect.bottom = rect.top + 2;
4627 rect.top -= 2;
4629 else
4631 GetItemRect(nIndex - 1, &rect, 0);
4632 rect.top = rect.bottom - 2;
4633 rect.bottom += 2;
4636 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4637 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4638 pDC->SelectObject(pBrushOld);
4640 ReleaseDC(pDC);
4643 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
4645 return 0;