Optimize readability of version numbers
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blobca1cd75ffb3e8e0344b066abafa5d206b4bee9ff
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 int CGitLogListBase::AsyncDiffThread()
169 while(!m_AsyncThreadExit)
171 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
173 GitRevLoglist* pRev = nullptr;
174 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
176 m_AsynDiffListLock.Lock();
177 pRev = m_AsynDiffList.back();
178 m_AsynDiffList.pop_back();
179 m_AsynDiffListLock.Unlock();
181 if( pRev->m_CommitHash.IsEmpty() )
183 if(pRev->m_IsDiffFiles)
184 continue;
186 CTGitPathList& files = pRev->GetFiles(this);
187 files.Clear();
188 pRev->m_ParentHash.clear();
189 pRev->m_ParentHash.push_back(m_HeadHash);
190 g_Git.RefreshGitIndex();
191 g_Git.GetWorkingTreeChanges(files);
192 auto& action = pRev->GetAction(this);
193 action = 0;
194 for (int j = 0; j < files.GetCount(); ++j)
195 action |= files[j].m_Action;
197 CString err;
198 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
200 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
201 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
202 return -1;
205 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
206 InterlockedExchange(&pRev->m_IsFull, TRUE);
208 CString body = L"\n";
209 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
210 pRev->GetBody() = body;
211 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
212 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
215 if (!pRev->CheckAndDiff())
216 { // fetch change file list
217 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
219 if (i < (int)m_arShownList.size())
221 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
222 if(data->m_CommitHash == pRev->m_CommitHash)
224 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
225 break;
230 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
232 POSITION pos = GetFirstSelectedItemPosition();
233 int nItem = GetNextSelectedItem(pos);
235 if(nItem>=0)
237 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
238 if(data)
239 if(data->m_CommitHash == pRev->m_CommitHash)
240 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
246 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
247 return 0;
249 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
251 if (exclusivelyShow)
252 m_ContextMenuMask &= hideMask;
253 else
254 m_ContextMenuMask &= ~hideMask;
257 CGitLogListBase::~CGitLogListBase()
259 InterlockedExchange(&m_bNoDispUpdates, TRUE);
260 this->m_arShownList.SafeRemoveAll();
262 DestroyIcon(m_hModifiedIcon);
263 DestroyIcon(m_hReplacedIcon);
264 DestroyIcon(m_hConflictedIcon);
265 DestroyIcon(m_hAddedIcon);
266 DestroyIcon(m_hDeletedIcon);
267 m_logEntries.ClearAll();
269 git_free_mailmap(m_pMailmap);
271 SafeTerminateThread();
272 SafeTerminateAsyncDiffThread();
274 if(m_AsyncDiffEvent)
275 CloseHandle(m_AsyncDiffEvent);
279 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
280 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
281 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
282 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
283 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
284 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
285 ON_WM_CONTEXTMENU()
286 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
287 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
288 ON_WM_CREATE()
289 ON_WM_DESTROY()
290 ON_MESSAGE(MSG_LOADED,OnLoad)
291 ON_WM_MEASUREITEM()
292 ON_WM_MEASUREITEM_REFLECT()
293 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
294 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
295 ON_WM_MOUSEMOVE()
296 ON_WM_LBUTTONUP()
297 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
298 END_MESSAGE_MAP()
300 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
302 //if (m_nRowHeight>0)
303 lpMeasureItemStruct->itemHeight = 50;
306 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
308 PreSubclassWindow();
309 return __super::OnCreate(lpCreateStruct);
312 void CGitLogListBase::SetStyle()
314 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
317 void CGitLogListBase::PreSubclassWindow()
319 SetStyle();
320 // load the icons for the action columns
321 // m_Theme.Open(m_hWnd, L"ListView");
322 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
323 __super::PreSubclassWindow();
326 CString CGitLogListBase::GetRebaseActionName(int action)
328 if (action & LOGACTIONS_REBASE_EDIT)
329 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
330 if (action & LOGACTIONS_REBASE_SQUASH)
331 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
332 if (action & LOGACTIONS_REBASE_PICK)
333 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
334 if (action & LOGACTIONS_REBASE_SKIP)
335 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
337 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
340 void CGitLogListBase::InsertGitColumn()
342 CString temp;
344 Init();
346 // only load properties if we have a repository
347 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
348 UpdateProjectProperties();
350 static UINT normal[] =
352 IDS_LOG_GRAPH,
353 IDS_LOG_REBASE,
354 IDS_LOG_ID,
355 IDS_LOG_HASH,
356 IDS_LOG_ACTIONS,
357 IDS_LOG_MESSAGE,
358 IDS_LOG_AUTHOR,
359 IDS_LOG_DATE,
360 IDS_LOG_EMAIL,
361 IDS_LOG_COMMIT_NAME,
362 IDS_LOG_COMMIT_EMAIL,
363 IDS_LOG_COMMIT_DATE,
364 IDS_LOG_BUGIDS,
365 IDS_LOG_SVNREV,
368 static int with[] =
370 ICONITEMBORDER+16*4,
371 ICONITEMBORDER+16*4,
372 ICONITEMBORDER+16*4,
373 ICONITEMBORDER+16*4,
374 2 * ICONITEMBORDER + GetSystemMetrics(SM_CXSMICON) * 5,
375 LOGLIST_MESSAGE_MIN,
376 ICONITEMBORDER+16*4,
377 ICONITEMBORDER+16*4,
378 ICONITEMBORDER+16*4,
379 ICONITEMBORDER+16*4,
380 ICONITEMBORDER+16*4,
381 ICONITEMBORDER+16*4,
382 ICONITEMBORDER+16*4,
383 ICONITEMBORDER+16*4,
385 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
387 DWORD hideColumns = 0;
388 if(this->m_IsRebaseReplaceGraph)
390 hideColumns |= GIT_LOG_GRAPH;
391 m_dwDefaultColumns |= GIT_LOG_REBASE;
393 else
394 hideColumns |= GIT_LOG_REBASE;
396 if(this->m_IsIDReplaceAction)
398 hideColumns |= GIT_LOG_ACTIONS;
399 m_dwDefaultColumns |= GIT_LOG_ID;
400 m_dwDefaultColumns |= GIT_LOG_HASH;
402 else
403 hideColumns |= GIT_LOG_ID;
404 if(this->m_bShowBugtraqColumn)
405 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
406 else
407 hideColumns |= GIT_LOGLIST_BUG;
408 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
409 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
410 else
411 hideColumns |= GIT_LOGLIST_SVNREV;
412 SetRedraw(false);
414 m_ColumnManager.SetNames(normal, _countof(normal));
415 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
416 m_ColumnManager.SetRightAlign(LOGLIST_ID);
418 if (!(hideColumns & GIT_LOG_ACTIONS))
420 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
421 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
422 // display's font height may be less than small icon height.
423 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
424 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
425 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
428 SetRedraw(true);
431 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
433 LVITEM rItem = { 0 };
434 rItem.mask = LVIF_STATE;
435 rItem.iItem = (int)Index;
436 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
437 GetItem(&rItem);
439 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
440 HBRUSH brush = nullptr;
442 if (!(rItem.state & LVIS_SELECTED))
444 int action = pLogEntry->GetRebaseAction();
445 if (action & LOGACTIONS_REBASE_SQUASH)
446 brush = ::CreateSolidBrush(RGB(156,156,156));
447 else if (action & LOGACTIONS_REBASE_EDIT)
448 brush = ::CreateSolidBrush(RGB(200,200,128));
450 else if (!IsAppThemed())
452 if (rItem.state & LVIS_SELECTED)
454 if (::GetFocus() == m_hWnd)
455 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
456 else
457 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
460 if (brush)
462 ::FillRect(hdc, &rect, brush);
463 ::DeleteObject(brush);
467 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
469 POINT point = { 4, 4 };
470 CRect rt2 = rect;
471 rt2.DeflateRect(1, 1);
472 rt2.OffsetRect(2, 2);
474 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
475 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
476 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
477 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
478 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
480 ::SelectObject(hdc, brush);
481 rt2.OffsetRect(-2, -2);
482 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
483 ::SelectObject(hdc, oldbrush);
484 ::SelectObject(hdc, oldpen);
485 ::DeleteObject(nullPen);
486 ::DeleteObject(darkBrush);
489 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
491 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
492 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
493 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
494 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
495 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
496 ::LineTo(hdc, rect.left, rect.top + 4);
497 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
498 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
499 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
500 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
501 ::SelectObject(hdc, oldpen);
502 ::DeleteObject(pen);
505 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
507 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
508 CRect rt=rect;
509 LVITEM rItem = { 0 };
510 rItem.mask = LVIF_STATE;
511 rItem.iItem = (int)index;
512 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
513 GetItem(&rItem);
515 CDC W_Dc;
516 W_Dc.Attach(hdc);
518 HTHEME hTheme = nullptr;
519 if (IsAppThemed())
520 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
522 SIZE oneSpaceSize;
523 if (m_bTagsBranchesOnRightSide)
525 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
526 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
527 SelectObject(hdc, oldFont);
528 rt.left += oneSpaceSize.cx * 2;
530 else
532 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
533 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
534 rt.left += oneSpaceSize.cx;
537 CString msg = MessageDisplayStr(data);
538 int action = data->GetRebaseAction();
539 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
540 if (IsAppThemed())
542 int txtState = LISS_NORMAL;
543 if (rItem.state & LVIS_SELECTED)
544 txtState = LISS_SELECTED;
546 DTTOPTS opts = { 0 };
547 opts.dwSize = sizeof(opts);
548 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
549 opts.dwFlags = DTT_TEXTCOLOR;
550 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
552 else
554 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
556 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
557 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
558 ::SetTextColor(hdc, clrOld);
560 else
562 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
563 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
564 ::SetTextColor(hdc, clrOld);
568 if (m_bTagsBranchesOnRightSide)
570 SIZE size;
571 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
573 rt.left += oneSpaceSize.cx + size.cx;
575 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
578 if (hTheme)
579 CloseThemeData(hTheme);
581 W_Dc.Detach();
584 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
586 for (unsigned int i = 0; i < refList.size(); ++i)
588 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
589 HBRUSH brush = 0;
590 COLORREF colRef = refList[i].color;
591 bool singleRemote = refList[i].singleRemote;
592 bool hasTracking = refList[i].hasTracking;
593 CGit::REF_TYPE refType = refList[i].refType;
595 //When row selected, ajust label color
596 if (!IsAppThemed())
598 if (rItem.state & LVIS_SELECTED)
599 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
602 brush = ::CreateSolidBrush(colRef);
604 if (!shortname.IsEmpty() && (rt.left < rect.right))
606 SIZE size = { 0 };
607 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
609 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
610 rt.right += 8;
612 int textpos = DT_CENTER;
614 if (rt.right > rect.right)
616 rt.right = rect.right;
617 textpos = 0;
620 CRect textRect = rt;
622 if (singleRemote)
624 rt.right += 5;
625 textRect.OffsetRect(5, 0);
628 if (hasTracking)
629 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
630 else
632 //Fill interior of ref label
633 ::FillRect(hdc, &rt, brush);
636 //Draw edge of label
637 CRect rectEdge = rt;
639 if (!hasTracking)
641 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
642 rectEdge.DeflateRect(1, 1);
643 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
646 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
648 rt.right += 8;
649 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
650 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
651 ::FillRgn(hdc, hrgn, brush);
652 ::DeleteObject(hrgn);
653 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
654 HPEN pen;
655 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
656 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
657 ::DeleteObject(pen);
658 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
659 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
660 ::DeleteObject(pen);
661 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
662 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
663 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
664 ::DeleteObject(pen);
665 SelectObject(hdc, oldpen);
668 //Draw text inside label
669 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
670 if (!customColor && IsAppThemed())
672 int txtState = LISS_NORMAL;
673 if (rItem.state & LVIS_SELECTED)
674 txtState = LISS_SELECTED;
676 DTTOPTS opts = { 0 };
677 opts.dwSize = sizeof(opts);
678 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
679 opts.dwFlags = DTT_TEXTCOLOR;
680 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
682 else
684 W_Dc.SetBkMode(TRANSPARENT);
685 if (customColor || (rItem.state & LVIS_SELECTED))
687 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
688 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
689 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
690 ::SetTextColor(hdc,clrOld);
692 else
694 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
695 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
696 ::SetTextColor(hdc, clrOld);
700 if (singleRemote)
702 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
703 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
704 CRect newRect;
705 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
706 DrawUpstream(hdc, newRect, color, bold);
709 if (!refList[i].fullName.IsEmpty())
710 m_RefLabelPosMap[refList[i].fullName] = rt;
712 rt.left = rt.right + 1;
714 if (brush)
715 ::DeleteObject(brush);
717 rt.right = rect.right;
720 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
721 // Returns ((256 - amount)*col1 + amount*col2) / 256;
722 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
723 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
724 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
727 Gdiplus::Color GetGdiColor(COLORREF col)
729 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
731 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
732 const COLORREF& col,const COLORREF& activeColor, int top
735 int h = laneHeight / 2;
736 int m = (x1 + x2) / 2;
737 int r = (x2 - x1) * m_NodeSize / 30;
738 int d = 2 * r;
740 #define P_CENTER m , h+top
741 #define P_0 x2, h+top
742 #define P_90 m , 0+top-1
743 #define P_180 x1, h+top
744 #define P_270 m , 2 * h+top +1
745 #define R_CENTER m - r, h - r+top, d, d
748 #define DELTA_UR_B 2*(x1 - m), 2*h +top
749 #define DELTA_UR_E 0*16, 90*16 +top // -,
751 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
752 #define DELTA_DR_E 270*16, 90*16 +top // -'
754 #define DELTA_UL_B 2*(x2 - m), 2*h +top
755 #define DELTA_UL_E 90*16, 90*16 +top // ,-
757 #define DELTA_DL_B 2*(x2 - m),2*-h +top
758 #define DELTA_DL_E 180*16, 90*16 // '-
760 #define CENTER_UR x1, 2*h, 225
761 #define CENTER_DR x1, 0 , 135
762 #define CENTER_UL x2, 2*h, 315
763 #define CENTER_DL x2, 0 , 45
766 Gdiplus::Graphics graphics( hdc );
768 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
770 // arc
771 switch (type) {
772 case Lanes::JOIN:
773 case Lanes::JOIN_R:
774 case Lanes::HEAD:
775 case Lanes::HEAD_R:
777 Gdiplus::LinearGradientBrush gradient(
778 Gdiplus::Point(x1-2, h+top-2),
779 Gdiplus::Point(P_270),
780 GetGdiColor(activeColor),GetGdiColor(col));
783 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
784 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
786 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
787 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
788 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
790 break;
792 case Lanes::JOIN_L:
794 Gdiplus::LinearGradientBrush gradient(
795 Gdiplus::Point(P_270),
796 Gdiplus::Point(x2+1, h+top-1),
797 GetGdiColor(col),GetGdiColor(activeColor));
800 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
801 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
803 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
804 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
805 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
808 break;
810 case Lanes::TAIL:
811 case Lanes::TAIL_R:
813 Gdiplus::LinearGradientBrush gradient(
814 Gdiplus::Point(x1-2, h+top-2),
815 Gdiplus::Point(P_90),
816 GetGdiColor(activeColor),GetGdiColor(col));
818 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
820 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
822 #if 0
823 QConicalGradient gradient(CENTER_DR);
824 gradient.setColorAt(0.375, activeCol);
825 gradient.setColorAt(0.625, col);
826 myPen.setBrush(gradient);
827 p->setPen(myPen);
828 p->drawArc(P_CENTER, DELTA_DR);
829 #endif
830 break;
832 default:
833 break;
837 //static QPen myPen(Qt::black, 2); // fast path here
838 CPen pen;
839 pen.CreatePen(PS_SOLID,2,col);
840 //myPen.setColor(col);
841 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
843 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
845 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
847 //p->setPen(myPen);
849 // vertical line
850 switch (type) {
851 case Lanes::ACTIVE:
852 case Lanes::NOT_ACTIVE:
853 case Lanes::MERGE_FORK:
854 case Lanes::MERGE_FORK_R:
855 case Lanes::MERGE_FORK_L:
856 case Lanes::JOIN:
857 case Lanes::JOIN_R:
858 case Lanes::JOIN_L:
859 case Lanes::CROSS:
860 //DrawLine(hdc,P_90,P_270);
861 graphics.DrawLine(&myPen,P_90,P_270);
862 //p->drawLine(P_90, P_270);
863 break;
864 case Lanes::HEAD_L:
865 case Lanes::BRANCH:
866 //DrawLine(hdc,P_CENTER,P_270);
867 graphics.DrawLine(&myPen,P_CENTER,P_270);
868 //p->drawLine(P_CENTER, P_270);
869 break;
870 case Lanes::TAIL_L:
871 case Lanes::INITIAL:
872 case Lanes::MERGE_FORK_L_INITIAL:
873 case Lanes::BOUNDARY:
874 case Lanes::BOUNDARY_C:
875 case Lanes::BOUNDARY_R:
876 case Lanes::BOUNDARY_L:
877 //DrawLine(hdc,P_90, P_CENTER);
878 graphics.DrawLine(&myPen,P_90,P_CENTER);
879 //p->drawLine(P_90, P_CENTER);
880 break;
881 default:
882 break;
885 myPen.SetColor(GetGdiColor(activeColor));
887 // horizontal line
888 switch (type) {
889 case Lanes::MERGE_FORK:
890 case Lanes::JOIN:
891 case Lanes::HEAD:
892 case Lanes::TAIL:
893 case Lanes::CROSS:
894 case Lanes::CROSS_EMPTY:
895 case Lanes::BOUNDARY_C:
896 //DrawLine(hdc,P_180,P_0);
897 graphics.DrawLine(&myPen,P_180,P_0);
898 //p->drawLine(P_180, P_0);
899 break;
900 case Lanes::MERGE_FORK_R:
901 case Lanes::BOUNDARY_R:
902 //DrawLine(hdc,P_180,P_CENTER);
903 graphics.DrawLine(&myPen,P_180,P_CENTER);
904 //p->drawLine(P_180, P_CENTER);
905 break;
906 case Lanes::MERGE_FORK_L:
907 case Lanes::MERGE_FORK_L_INITIAL:
908 case Lanes::HEAD_L:
909 case Lanes::TAIL_L:
910 case Lanes::BOUNDARY_L:
911 //DrawLine(hdc,P_CENTER,P_0);
912 graphics.DrawLine(&myPen,P_CENTER,P_0);
913 //p->drawLine(P_CENTER, P_0);
914 break;
915 default:
916 break;
919 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
921 CBrush brush;
922 brush.CreateSolidBrush(col);
923 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
925 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
926 // center symbol, e.g. rect or ellipse
927 switch (type) {
928 case Lanes::ACTIVE:
929 case Lanes::INITIAL:
930 case Lanes::BRANCH:
932 //p->setPen(Qt::NoPen);
933 //p->setBrush(col);
934 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
935 graphics.FillEllipse(&myBrush, R_CENTER);
936 //p->drawEllipse(R_CENTER);
937 break;
938 case Lanes::MERGE_FORK:
939 case Lanes::MERGE_FORK_R:
940 case Lanes::MERGE_FORK_L:
941 case Lanes::MERGE_FORK_L_INITIAL:
942 //p->setPen(Qt::NoPen);
943 //p->setBrush(col);
944 //p->drawRect(R_CENTER);
945 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
946 graphics.FillRectangle(&myBrush, R_CENTER);
947 break;
948 case Lanes::UNAPPLIED:
949 // Red minus sign
950 //p->setPen(Qt::NoPen);
951 //p->setBrush(Qt::red);
952 //p->drawRect(m - r, h - 1, d, 2);
953 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
954 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
955 break;
956 case Lanes::APPLIED:
957 // Green plus sign
958 //p->setPen(Qt::NoPen);
959 //p->setBrush(DARK_GREEN);
960 //p->drawRect(m - r, h - 1, d, 2);
961 //p->drawRect(m - 1, h - r, 2, d);
962 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
963 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
964 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
965 break;
966 case Lanes::BOUNDARY:
967 //p->setBrush(back);
968 //p->drawEllipse(R_CENTER);
969 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
970 graphics.DrawEllipse(&myPen, R_CENTER);
971 break;
972 case Lanes::BOUNDARY_C:
973 case Lanes::BOUNDARY_R:
974 case Lanes::BOUNDARY_L:
975 //p->setBrush(back);
976 //p->drawRect(R_CENTER);
977 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
978 graphics.FillRectangle(&myBrush,R_CENTER);
979 break;
980 default:
981 break;
984 ::SelectObject(hdc,oldpen);
985 ::SelectObject(hdc,oldbrush);
986 #undef P_CENTER
987 #undef P_0
988 #undef P_90
989 #undef P_180
990 #undef P_270
991 #undef R_CENTER
994 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
996 // TODO: unfinished
997 // return;
998 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
999 if(data->m_CommitHash.IsEmpty())
1000 return;
1002 CRect rt=rect;
1003 LVITEM rItem = { 0 };
1004 rItem.mask = LVIF_STATE;
1005 rItem.iItem = (int)index;
1006 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1007 GetItem(&rItem);
1009 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1011 if (data->m_Lanes.empty())
1012 m_logEntries.setLane(data->m_CommitHash);
1014 std::vector<int>& lanes=data->m_Lanes;
1015 size_t laneNum = lanes.size();
1016 UINT activeLane = 0;
1017 for (UINT i = 0; i < laneNum; ++i)
1018 if (Lanes::isMerge(lanes[i])) {
1019 activeLane = i;
1020 break;
1023 int x2 = 0;
1024 int maxWidth = rect.Width();
1025 int lw = 3 * rect.Height() / 4; //laneWidth()
1027 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1028 //if (opt.state & QStyle::State_Selected)
1029 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1031 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1033 int x1 = x2;
1034 x2 += lw;
1036 int ln = lanes[i];
1037 if (ln == Lanes::EMPTY)
1038 continue;
1040 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1041 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1044 #if 0
1045 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1046 int x1 = x2;
1047 x2 += lw;
1049 int ln = lanes[i];
1050 if (ln == Lanes::EMPTY)
1051 continue;
1053 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1054 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1056 if (ln == Lanes::CROSS)
1058 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1059 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1061 else
1062 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1064 #endif
1067 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1069 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1070 // Take the default processing unless we set this to something else below.
1071 *pResult = CDRF_DODEFAULT;
1073 if (m_bNoDispUpdates)
1074 return;
1076 switch (pLVCD->nmcd.dwDrawStage)
1078 case CDDS_PREPAINT:
1080 *pResult = CDRF_NOTIFYITEMDRAW;
1081 return;
1083 break;
1084 case CDDS_ITEMPREPAINT:
1086 // This is the prepaint stage for an item. Here's where we set the
1087 // item's text color.
1089 // Tell Windows to send draw notifications for each subitem.
1090 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1092 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1094 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1096 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1097 if (data)
1099 HGDIOBJ hGdiObj = nullptr;
1100 int action = data->GetRebaseAction();
1101 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1102 crText = RGB(128,128,128);
1104 if (action & LOGACTIONS_REBASE_SQUASH)
1105 pLVCD->clrTextBk = RGB(156,156,156);
1106 else if (action & LOGACTIONS_REBASE_EDIT)
1107 pLVCD->clrTextBk = RGB(200,200,128);
1108 else
1109 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1111 if (action & LOGACTIONS_REBASE_CURRENT)
1112 hGdiObj = m_boldFont.GetSafeHandle();
1114 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1115 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1116 if (isHeadHash && isHighlight)
1117 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1118 else if (isHeadHash)
1119 hGdiObj = m_boldFont.GetSafeHandle();
1120 else if (isHighlight)
1121 hGdiObj = m_FontItalics.GetSafeHandle();
1123 if (hGdiObj)
1125 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1126 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1129 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1130 // crText = GetSysColor(COLOR_GRAYTEXT);
1132 if (data->m_CommitHash.IsEmpty())
1134 //crText = GetSysColor(RGB(200,200,0));
1135 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1136 // We changed the font, so we're returning CDRF_NEWFONT. This
1137 // tells the control to recalculate the extent of the text.
1138 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1142 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1144 if (m_bStrictStopped)
1145 crText = GetSysColor(COLOR_GRAYTEXT);
1147 // Store the color back in the NMLVCUSTOMDRAW struct.
1148 pLVCD->clrText = crText;
1149 return;
1151 break;
1152 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1154 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1156 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1159 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1161 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1163 CRect rect;
1164 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1166 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1167 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1169 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1170 if( !data ->m_CommitHash.IsEmpty())
1171 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1173 *pResult = CDRF_SKIPDEFAULT;
1174 return;
1178 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1180 // If the top index of list is changed, the position map of reference label is outdated.
1181 if (m_OldTopIndex != GetTopIndex())
1183 m_OldTopIndex = GetTopIndex();
1184 m_RefLabelPosMap.clear();
1187 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1189 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1191 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1193 CRect rect;
1194 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1196 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1197 // not in FillBackGround method, because this only affected the message subitem
1198 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1199 return;
1201 int index = (int)pLVCD->nmcd.dwItemSpec;
1202 int state = GetItemState(index, LVIS_SELECTED);
1203 int txtState = LISS_NORMAL;
1204 if (IsAppThemed() && GetHotItem() == (int)index)
1206 if (state & LVIS_SELECTED)
1207 txtState = LISS_HOTSELECTED;
1208 else
1209 txtState = LISS_HOT;
1211 else if (state & LVIS_SELECTED)
1213 if (::GetFocus() == m_hWnd)
1214 txtState = LISS_SELECTED;
1215 else
1216 txtState = LISS_SELECTEDNOTFOCUS;
1219 HTHEME hTheme = nullptr;
1220 if (IsAppThemed())
1221 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1223 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1224 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1225 else
1227 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1228 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1229 ::DeleteObject(brush);
1231 if (hTheme && txtState != LISS_NORMAL)
1233 CRect rt;
1234 // get rect of whole line
1235 GetItemRect(index, rt, LVIR_BOUNDS);
1236 CRect rect2 = rect;
1238 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1239 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1241 CloseThemeData(hTheme);
1243 // END: extended redraw
1245 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1247 std::vector<REFLABEL> refsToShow;
1248 STRING_VECTOR remoteTrackingList;
1249 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1250 for (unsigned int i = 0; i < refList.size(); ++i)
1252 CString str = refList[i];
1254 REFLABEL refLabel;
1255 refLabel.color = RGB(255, 255, 255);
1256 refLabel.singleRemote = false;
1257 refLabel.hasTracking = false;
1258 refLabel.sameName = false;
1259 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1260 refLabel.fullName = str;
1262 switch (refLabel.refType)
1264 case CGit::REF_TYPE::LOCAL_BRANCH:
1266 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1267 continue;
1268 if (refLabel.name == m_CurrentBranch)
1269 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1270 else
1271 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1273 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1274 CString pullRemote = trackingEntry.first;
1275 CString pullBranch = trackingEntry.second;
1276 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1278 CString defaultUpstream;
1279 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1280 refLabel.hasTracking = true;
1281 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1283 bool found = false;
1284 for (size_t j = i + 1; j < refList.size(); ++j)
1286 if (refList[j] == defaultUpstream)
1288 found = true;
1289 break;
1293 if (found)
1295 bool sameName = pullBranch == refLabel.name;
1296 refsToShow.push_back(refLabel);
1297 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1298 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1299 if (m_bSymbolizeRefNames)
1301 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1303 refLabel.simplifiedName = L'/';
1304 if (sameName)
1305 refLabel.simplifiedName += L'≡';
1306 else
1307 refLabel.simplifiedName += pullBranch;
1308 refLabel.singleRemote = true;
1310 else if (sameName)
1311 refLabel.simplifiedName = pullRemote + L"/≡";
1312 refLabel.sameName = sameName;
1314 refLabel.fullName = defaultUpstream;
1315 refsToShow.push_back(refLabel);
1316 remoteTrackingList.push_back(defaultUpstream);
1317 continue;
1321 break;
1323 case CGit::REF_TYPE::REMOTE_BRANCH:
1325 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1326 continue;
1327 bool found = false;
1328 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1330 if (remoteTrackingList[j] == str)
1332 found = true;
1333 break;
1336 if (found)
1337 continue;
1339 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1340 if (m_bSymbolizeRefNames)
1342 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1344 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1345 refLabel.singleRemote = true;
1348 break;
1350 case CGit::REF_TYPE::ANNOTATED_TAG:
1351 case CGit::REF_TYPE::TAG:
1352 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1353 continue;
1354 refLabel.color = m_Colors.GetColor(CColors::Tag);
1355 break;
1356 case CGit::REF_TYPE::STASH:
1357 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1358 continue;
1359 refLabel.color = m_Colors.GetColor(CColors::Stash);
1360 break;
1361 case CGit::REF_TYPE::BISECT_GOOD:
1362 case CGit::REF_TYPE::BISECT_BAD:
1363 case CGit::REF_TYPE::BISECT_SKIP:
1364 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1365 continue;
1366 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));
1367 break;
1368 case CGit::REF_TYPE::NOTES:
1369 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1370 continue;
1371 refLabel.color = m_Colors.GetColor(CColors::NoteNode);
1372 break;
1373 default:
1374 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1375 continue;
1376 refLabel.color = m_Colors.GetColor(CColors::OtherRef);
1377 break;
1379 refsToShow.push_back(refLabel);
1381 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1383 REFLABEL refLabel;
1384 refLabel.color = RGB(246, 153, 253);
1385 refLabel.singleRemote = false;
1386 refLabel.hasTracking = false;
1387 refLabel.sameName = false;
1388 refLabel.name = L"super-project-pointer";
1389 refLabel.fullName = "";
1390 refsToShow.push_back(refLabel);
1393 if (refsToShow.empty())
1395 *pResult = CDRF_DODEFAULT;
1396 return;
1399 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1401 *pResult = CDRF_SKIPDEFAULT;
1402 return;
1409 if (pLVCD->iSubItem == LOGLIST_ACTION)
1411 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1413 *pResult = CDRF_DODEFAULT;
1414 return;
1416 *pResult = CDRF_DODEFAULT;
1418 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1419 return;
1421 int nIcons = 0;
1422 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1423 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1425 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1426 CRect rect;
1427 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1428 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1429 // Get the selected state of the
1430 // item being drawn.
1432 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1433 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1435 // Fill the background if necessary
1436 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1438 // Draw the icon(s) into the compatible DC
1439 int action = pLogEntry->GetAction(this);
1440 if (!pLogEntry->m_IsDiffFiles)
1442 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1443 *pResult = CDRF_SKIPDEFAULT;
1444 return;
1447 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1448 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1449 ++nIcons;
1451 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1452 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1453 ++nIcons;
1455 if (action & CTGitPath::LOGACTIONS_DELETED)
1456 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 if (action & CTGitPath::LOGACTIONS_REPLACED)
1460 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1461 ++nIcons;
1463 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1464 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1465 ++nIcons;
1467 *pResult = CDRF_SKIPDEFAULT;
1468 return;
1471 break;
1473 *pResult = CDRF_DODEFAULT;
1476 CString FindSVNRev(const CString& msg)
1480 const std::wsregex_iterator end;
1481 std::wstring s = msg;
1482 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1483 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1485 const std::wsmatch match = *it;
1486 if (match.size() == 4)
1488 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1489 return std::wstring(match[2]).c_str();
1492 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1493 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1495 const std::wsmatch match = *it;
1496 if (match.size() == 3)
1498 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1499 return std::wstring(match[1]).c_str();
1503 catch (std::exception&) {}
1505 return L"";
1508 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1510 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1511 return pLogEntry->GetSubject();
1513 CString txt(pLogEntry->GetSubject());
1514 txt += L' ';
1515 txt += pLogEntry->GetBody();
1517 // Deal with CRLF
1518 txt.Replace(L'\n', L' ');
1519 txt.Replace(L'\r', L' ');
1521 return txt;
1524 // CGitLogListBase message handlers
1526 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1528 struct payload_struct { const CString* name; const char* authorName; };
1529 payload_struct payload = { &name, nullptr };
1530 const char* author1 = nullptr;
1531 const char* email1 = nullptr;
1532 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1533 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1534 free((void *)payload.authorName);
1535 if (returnEmail)
1536 return email1;
1537 return author1;
1540 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1542 if (mailmap)
1544 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1545 if (translated)
1547 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1548 return;
1551 if (returnEmail)
1552 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1553 else
1554 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1557 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1559 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1561 // Create a pointer to the item
1562 LV_ITEM* pItem = &(pDispInfo)->item;
1564 // Do the list need text information?
1565 if (!(pItem->mask & LVIF_TEXT))
1566 return;
1568 // By default, clear text buffer.
1569 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1571 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1573 *pResult = 0;
1574 if (m_bNoDispUpdates || bOutOfRange)
1575 return;
1577 // Which item number?
1578 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1580 CString temp;
1581 if(m_IsOldFirst)
1582 temp.Format(L"%d", pItem->iItem + 1);
1583 else
1584 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1586 if (!pLogEntry)
1587 return;
1589 // Which column?
1590 switch (pItem->iSubItem)
1592 case LOGLIST_GRAPH: //Graphic
1593 break;
1594 case LOGLIST_REBASE:
1595 if (m_IsRebaseReplaceGraph)
1596 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1597 break;
1598 case LOGLIST_ACTION: //action -- no text in the column
1599 break;
1600 case LOGLIST_HASH:
1601 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1602 break;
1603 case LOGLIST_ID:
1604 if (this->m_IsIDReplaceAction)
1605 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1606 break;
1607 case LOGLIST_MESSAGE: //Message
1608 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1609 break;
1610 case LOGLIST_AUTHOR: //Author
1611 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1612 break;
1613 case LOGLIST_DATE: //Date
1614 if (!pLogEntry->m_CommitHash.IsEmpty())
1615 lstrcpyn(pItem->pszText,
1616 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1617 pItem->cchTextMax - 1);
1618 break;
1620 case LOGLIST_EMAIL:
1621 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1622 break;
1624 case LOGLIST_COMMIT_NAME: //Commit
1625 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1626 break;
1628 case LOGLIST_COMMIT_EMAIL: //Commit Email
1629 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1630 break;
1632 case LOGLIST_COMMIT_DATE: //Commit Date
1633 if (!pLogEntry->m_CommitHash.IsEmpty())
1634 lstrcpyn(pItem->pszText,
1635 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1636 pItem->cchTextMax - 1);
1637 break;
1638 case LOGLIST_BUG: //Bug ID
1639 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1640 break;
1641 case LOGLIST_SVNREV: //SVN revision
1642 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1643 break;
1645 default:
1646 ASSERT(false);
1650 bool CGitLogListBase::IsOnStash(int index)
1652 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1653 if (IsStash(rev))
1654 return true;
1655 if (index > 0)
1657 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1658 if (IsStash(preRev))
1659 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1661 return false;
1664 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1666 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1667 if (refList == m_HashMap.cend())
1668 return false;
1669 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1672 bool CGitLogListBase::IsBisect(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 CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1680 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1682 if (pRev->m_ParentHash.empty())
1684 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1685 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1687 parentHash = pRev->m_ParentHash;
1690 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1692 __super::OnContextMenu(pWnd, point);
1694 if (pWnd != this)
1695 return;
1697 int selIndex = GetSelectionMark();
1698 if (selIndex < 0)
1699 return; // nothing selected, nothing to do with a context menu
1701 // if the user selected the info text telling about not all revisions shown due to
1702 // the "stop on copy/rename" option, we also don't show the context menu
1703 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1704 return;
1706 // if the context menu is invoked through the keyboard, we have to use
1707 // a calculated position on where to anchor the menu on
1708 if ((point.x == -1) && (point.y == -1))
1710 CRect rect;
1711 GetItemRect(selIndex, &rect, LVIR_LABEL);
1712 ClientToScreen(&rect);
1713 point = rect.CenterPoint();
1715 m_nSearchIndex = selIndex;
1717 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1719 POSITION pos = GetFirstSelectedItemPosition();
1720 int FirstSelect = GetNextSelectedItem(pos);
1721 if (FirstSelect < 0)
1722 return;
1724 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1725 if (pSelLogEntry == nullptr)
1726 return;
1728 int LastSelect = -1;
1729 UINT selectedCount = 1;
1730 while (pos)
1732 LastSelect = GetNextSelectedItem(pos);
1733 ++selectedCount;
1736 ASSERT(GetSelectedCount() == selectedCount);
1738 #if 0
1739 GitRev revSelected = pSelLogEntry->Rev;
1740 GitRev revPrevious = git_revnum_t(revSelected)-1;
1741 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1743 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1745 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1746 if (changedpath->lCopyFromRev)
1747 revPrevious = changedpath->lCopyFromRev;
1750 GitRev revSelected2;
1751 if (pos)
1753 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1754 revSelected2 = pLogEntry->Rev;
1756 bool bAllFromTheSameAuthor = true;
1757 CString firstAuthor;
1758 CLogDataVector selEntries;
1759 GitRev revLowest, revHighest;
1760 GitRevRangeArray revisionRanges;
1762 POSITION pos = GetFirstSelectedItemPosition();
1763 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1764 revisionRanges.AddRevision(pLogEntry->Rev);
1765 selEntries.push_back(pLogEntry);
1766 firstAuthor = pLogEntry->sAuthor;
1767 revLowest = pLogEntry->Rev;
1768 revHighest = pLogEntry->Rev;
1769 while (pos)
1771 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1772 revisionRanges.AddRevision(pLogEntry->Rev);
1773 selEntries.push_back(pLogEntry);
1774 if (firstAuthor.Compare(pLogEntry->sAuthor))
1775 bAllFromTheSameAuthor = false;
1776 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1777 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1781 #endif
1783 //entry is selected, now show the popup menu
1784 CIconMenu popup;
1785 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1787 if (popup.CreatePopupMenu())
1789 CGitHash headHash;
1790 if (g_Git.GetHash(headHash, L"HEAD"))
1792 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1793 return;
1795 bool isHeadCommit = (pSelLogEntry->m_CommitHash == headHash);
1796 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1797 CTGitPath workingTree(g_Git.m_CurrentDir);
1798 bool isMergeActive = workingTree.IsMergeActive();
1799 bool isBisectActive = workingTree.IsBisectActive();
1800 bool isStash = IsOnStash(FirstSelect);
1801 GIT_REV_LIST parentHash;
1802 GetParentHashes(pSelLogEntry, parentHash);
1804 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1805 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1807 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))
1808 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1810 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1811 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1813 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1814 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1816 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)))
1817 popup.AppendMenu(MF_SEPARATOR, NULL);
1819 if (selectedCount == 1)
1822 bool requiresSeparator = false;
1823 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1825 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1827 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1828 requiresSeparator = true;
1831 else
1833 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1835 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1836 requiresSeparator = true;
1838 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1840 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1841 requiresSeparator = true;
1845 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1847 if (parentHash.size() == 1)
1849 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1850 requiresSeparator = true;
1852 else if (parentHash.size() > 1)
1854 blamemenu.CreatePopupMenu();
1855 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1856 for (size_t i = 0; i < parentHash.size(); ++i)
1858 CString str;
1859 str.Format(IDS_PARENT, i + 1);
1860 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1862 requiresSeparator = true;
1866 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1868 if (parentHash.size() == 1)
1870 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1871 requiresSeparator = true;
1873 else if (parentHash.size() > 1)
1875 gnudiffmenu.CreatePopupMenu();
1876 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1878 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1879 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1880 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1882 for (size_t i = 0; i < parentHash.size(); ++i)
1884 CString str;
1885 str.Format(IDS_PARENT, i + 1);
1886 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1888 requiresSeparator = true;
1892 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1894 if (parentHash.size() == 1)
1896 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1897 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1898 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1899 requiresSeparator = true;
1901 else if (parentHash.size() > 1)
1903 diffmenu.CreatePopupMenu();
1904 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1905 for (size_t i = 0; i < parentHash.size(); ++i)
1907 CString str;
1908 str.Format(IDS_PARENT, i + 1);
1909 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1910 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1912 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1913 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1916 requiresSeparator = true;
1920 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1922 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1923 requiresSeparator = true;
1926 if (requiresSeparator)
1928 popup.AppendMenu(MF_SEPARATOR, NULL);
1929 requiresSeparator = false;
1932 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1934 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1936 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1937 requiresSeparator = true;
1941 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1943 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1945 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1946 requiresSeparator = true;
1949 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1951 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1952 requiresSeparator = true;
1956 if (requiresSeparator)
1958 popup.AppendMenu(MF_SEPARATOR, NULL);
1959 requiresSeparator = false;
1962 if (isBisectActive)
1964 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1965 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1967 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1968 requiresSeparator = true;
1971 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1973 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1974 requiresSeparator = true;
1976 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1978 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1979 requiresSeparator = true;
1983 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1985 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1987 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1988 requiresSeparator = true;
1992 if (requiresSeparator)
1994 popup.AppendMenu(MF_SEPARATOR, NULL);
1995 requiresSeparator = false;
1998 if (pSelLogEntry->m_CommitHash.IsEmpty())
2000 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
2001 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2003 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
2004 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
2006 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2007 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2009 popup.AppendMenu(MF_SEPARATOR, NULL);
2011 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2012 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2014 popup.AppendMenu(MF_SEPARATOR, NULL);
2018 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2019 // {
2020 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2021 // }
2022 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2023 // {
2024 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2025 // }
2026 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2027 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2028 // {
2029 // popup.AppendMenu(MF_SEPARATOR, NULL);
2030 // }
2032 CString str;
2033 //if (m_hasWC)
2034 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2036 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2038 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2039 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2041 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2042 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2044 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2046 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2048 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2050 size_t index = (size_t)-1;
2051 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2052 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2053 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2056 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2058 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2059 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2062 // Add Switch Branch express Menu
2063 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2064 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2067 std::vector<const CString*> branchs;
2068 auto addCheck = [&](const CString& ref)
2070 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2071 return;
2072 branchs.push_back(&ref);
2074 size_t index = (size_t)-1;
2075 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2076 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2077 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2078 else
2079 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2081 CString str2;
2082 str2.LoadString(IDS_SWITCH_BRANCH);
2084 if(branchs.size() == 1)
2086 str2 += L' ';
2087 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2088 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2090 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2093 else if(branchs.size() > 1)
2095 subbranchmenu.CreatePopupMenu();
2096 for (size_t i = 0 ; i < branchs.size(); ++i)
2098 if (*branchs[i] != currentBranch)
2100 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2101 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2105 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2109 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2111 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2112 size_t index = (size_t)-1;
2113 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2114 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2115 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2118 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2120 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2122 size_t index = (size_t)-1;
2123 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2124 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2125 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2128 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2129 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2131 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2133 if (pSelLogEntry->m_CommitHash != headHash && m_hasWC && !isMergeActive && !isStash)
2134 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2135 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2137 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2138 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2140 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2142 if (parentHash.size() == 1)
2143 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2144 else if (parentHash.size() > 1)
2146 revertmenu.CreatePopupMenu();
2147 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2149 for (size_t i = 0; i < parentHash.size(); ++i)
2151 CString str2;
2152 str2.Format(IDS_PARENT, i + 1);
2153 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2158 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2159 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2161 popup.AppendMenu(MF_SEPARATOR, NULL);
2165 if(!pSelLogEntry->m_Ref.IsEmpty())
2167 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2168 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2169 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2170 if (selectedCount <= 2)
2171 popup.AppendMenu(MF_SEPARATOR, NULL);
2174 if (selectedCount >= 2)
2176 bool bAddSeparator = false;
2177 if ((selectedCount == 2) || IsSelectionContinuous())
2179 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2181 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2182 bAddSeparator = true;
2186 if (selectedCount == 2)
2188 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2190 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2191 bAddSeparator = true;
2194 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2196 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2197 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2198 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2199 CString menu;
2200 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2201 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2202 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2203 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2204 bAddSeparator = true;
2208 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2210 bAddSeparator = true;
2211 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2214 if (bAddSeparator)
2216 popup.AppendMenu(MF_SEPARATOR, NULL);
2217 bAddSeparator = false;
2220 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2221 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2223 if (bAddSeparator)
2224 popup.AppendMenu(MF_SEPARATOR, NULL);
2227 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2229 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2230 popup.AppendMenu(MF_SEPARATOR, NULL);
2233 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2235 bool bAddSeparator = false;
2236 if (selectedCount >= 2 && IsSelectionContinuous())
2238 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2240 CString head;
2241 int headindex;
2242 headindex = this->GetHeadIndex();
2243 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2245 head.Format(L"HEAD~%d", FirstSelect - headindex);
2246 CGitHash hashFirst;
2247 int ret = g_Git.GetHash(hashFirst, head);
2248 head.Format(L"HEAD~%d",LastSelect-headindex);
2249 CGitHash hash;
2250 ret = ret || g_Git.GetHash(hash, head);
2251 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2252 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2253 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2255 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2256 bAddSeparator = true;
2261 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2262 if (selectedCount >= 2)
2263 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2264 else
2265 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2266 bAddSeparator = true;
2269 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2270 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2271 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2272 bAddSeparator = true;
2275 if (bAddSeparator)
2276 popup.AppendMenu(MF_SEPARATOR, NULL);
2279 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2281 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2282 popup.AppendMenu(MF_SEPARATOR, NULL);
2285 if (selectedCount == 1)
2287 bool bAddSeparator = false;
2288 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2290 // show the push-option only if the log entry has an associated local branch
2291 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();
2292 if (isLocal || showExtendedMenu)
2294 CString str;
2295 str.LoadString(IDS_MENUPUSH);
2297 CString branch;
2298 size_t index = (size_t)-1;
2299 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2300 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2301 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2302 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2304 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2306 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2307 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2309 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2310 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2312 bAddSeparator = true;
2315 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2317 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2318 bAddSeparator = true;
2322 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2324 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2326 std::vector<const CString*> branchs;
2327 auto addCheck = [&](const CString& ref)
2329 if (ref == currentBranch)
2330 return;
2331 branchs.push_back(&ref);
2333 size_t index = (size_t)-1;
2334 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2335 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2336 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2337 else
2338 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2340 CString str;
2341 if (branchs.size() == 1)
2343 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2344 str += L' ';
2345 str += *branchs[0];
2346 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2347 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2348 bAddSeparator = true;
2350 else if (branchs.size() > 1)
2352 str.LoadString(IDS_DELETE_BRANCHTAG);
2353 submenu.CreatePopupMenu();
2354 for (size_t i = 0; i < branchs.size(); ++i)
2356 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2357 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2359 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2360 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2362 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2363 bAddSeparator = true;
2366 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2367 if (bAddSeparator)
2368 popup.AppendMenu(MF_SEPARATOR, NULL);
2369 } // selectedCount == 1
2371 CIconMenu clipSubMenu;
2372 if (!clipSubMenu.CreatePopupMenu())
2373 return;
2374 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2376 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2377 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2378 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2379 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2380 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2381 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2382 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2383 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2384 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2386 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2387 size_t index = (size_t)-1;
2388 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2389 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2390 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2393 CString temp;
2394 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2395 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2398 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2399 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2401 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2402 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2404 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2405 // DialogEnableWindow(IDOK, FALSE);
2406 // SetPromptApp(&theApp);
2408 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2410 // EnableOKButton();
2411 } // if (popup.CreatePopupMenu())
2414 bool CGitLogListBase::IsSelectionContinuous()
2416 if ( GetSelectedCount()==1 )
2418 // if only one revision is selected, the selection is of course
2419 // continuous
2420 return true;
2423 POSITION pos = GetFirstSelectedItemPosition();
2424 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2425 if (bContinuous)
2427 int itemindex = GetNextSelectedItem(pos);
2428 while (pos)
2430 int nextindex = GetNextSelectedItem(pos);
2431 if (nextindex - itemindex > 1)
2433 bContinuous = false;
2434 break;
2436 itemindex = nextindex;
2439 return bContinuous;
2442 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2444 CString sClipdata;
2445 POSITION pos = GetFirstSelectedItemPosition();
2446 if (pos)
2448 CString sRev;
2449 sRev.LoadString(IDS_LOG_REVISION);
2450 CString sAuthor;
2451 sAuthor.LoadString(IDS_LOG_AUTHOR);
2452 CString sDate;
2453 sDate.LoadString(IDS_LOG_DATE);
2454 CString sMessage;
2455 sMessage.LoadString(IDS_LOG_MESSAGE);
2456 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2457 bool first = true;
2458 while (pos)
2460 CString sLogCopyText;
2461 CString sPaths;
2462 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2464 if (toCopy == ID_COPYCLIPBOARDFULL)
2466 sPaths = L"----\r\n";
2467 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2469 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2470 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2472 sPaths += L' ';
2473 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2475 sPaths += L"\r\n";
2477 sPaths.Trim();
2478 sPaths += L"\r\n";
2481 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2483 CString sNotesTags;
2484 if (!pLogEntry->m_Notes.IsEmpty())
2486 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2487 sNotesTags += L":\n";
2488 sNotesTags += pLogEntry->m_Notes;
2489 sNotesTags.Replace(L"\n", L"\r\n");
2491 CString tagInfo = GetTagInfo(pLogEntry);
2492 if (!tagInfo.IsEmpty())
2494 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2495 tagInfo.Replace(L"\n", L"\r\n");
2496 sNotesTags += tagInfo;
2499 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",
2500 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2501 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2502 (LPCTSTR)sDate,
2503 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2504 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2505 (LPCTSTR)sNotesTags,
2506 (LPCTSTR)sPaths);
2507 sClipdata += sLogCopyText;
2509 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2511 if (!first)
2512 sClipdata += L"\r\n";
2513 sClipdata += pLogEntry->GetAuthorName();
2514 sClipdata += L" <";
2515 sClipdata += pLogEntry->GetAuthorEmail();
2516 sClipdata += L">";
2518 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2520 if (!first)
2521 sClipdata += L"\r\n";
2522 sClipdata += pLogEntry->GetAuthorName();
2524 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2526 if (!first)
2527 sClipdata += L"\r\n";
2528 sClipdata += pLogEntry->GetAuthorEmail();
2531 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2533 sClipdata += L"* ";
2534 sClipdata += pLogEntry->GetSubjectBody(true);
2535 sClipdata += L"\r\n\r\n";
2537 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2539 sClipdata += L"* ";
2540 sClipdata += pLogEntry->GetSubject().Trim();
2541 sClipdata += L"\r\n\r\n";
2543 else
2545 if (!first)
2546 sClipdata += L"\r\n";
2547 sClipdata += pLogEntry->m_CommitHash;
2550 first = false;
2552 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2556 void CGitLogListBase::DiffSelectedRevWithPrevious()
2558 if (m_bThreadRunning)
2559 return;
2561 int FirstSelect=-1, LastSelect=-1;
2562 POSITION pos = GetFirstSelectedItemPosition();
2563 FirstSelect = GetNextSelectedItem(pos);
2564 while(pos)
2565 LastSelect = GetNextSelectedItem(pos);
2567 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2570 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2572 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2573 *pResult = -1;
2575 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2576 return;
2577 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2578 return;
2579 if (!pFindInfo->lvfi.psz)
2580 return;
2581 #if 0
2582 CString sCmp = pFindInfo->lvfi.psz;
2583 CString sRev;
2584 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2586 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2587 sRev.Format(L"%ld", pLogEntry->Rev);
2588 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2590 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2592 *pResult = i;
2593 return;
2596 else
2598 if (sCmp.Compare(sRev)==0)
2600 *pResult = i;
2601 return;
2605 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2607 for (int i=0; i<pFindInfo->iStart; ++i)
2609 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2610 sRev.Format(L"%ld", pLogEntry->Rev);
2611 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2613 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2615 *pResult = i;
2616 return;
2619 else
2621 if (sCmp.Compare(sRev)==0)
2623 *pResult = i;
2624 return;
2629 #endif
2630 *pResult = -1;
2633 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2635 ClearText();
2637 this->m_arShownList.SafeRemoveAll();
2639 this->m_logEntries.ClearAll();
2640 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2641 return -1;
2643 SetItemCountEx((int)m_logEntries.size());
2645 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2647 if(m_IsOldFirst)
2649 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2650 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2652 else
2654 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2655 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2659 ReloadHashMap();
2661 if(path)
2662 m_Path=*path;
2663 return 0;
2666 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2668 ClearText();
2670 m_arShownList.SafeRemoveAll();
2672 m_logEntries.ClearAll();
2673 if (m_logEntries.Fill(hashes))
2674 return -1;
2676 SetItemCountEx((int)m_logEntries.size());
2678 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2680 if (m_IsOldFirst)
2682 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2683 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2685 else
2687 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2688 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2692 ReloadHashMap();
2694 return 0;
2697 int CGitLogListBase::BeginFetchLog()
2699 ClearText();
2701 this->m_arShownList.SafeRemoveAll();
2703 this->m_logEntries.ClearAll();
2705 this->m_LogCache.ClearAllParent();
2707 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2709 CTGitPath *path;
2710 if(this->m_Path.IsEmpty())
2711 path = nullptr;
2712 else
2713 path=&this->m_Path;
2715 int mask;
2716 mask = CGit::LOG_INFO_ONLY_HASH;
2717 if (m_bIncludeBoundaryCommits)
2718 mask |= CGit::LOG_INFO_BOUNDARY;
2719 // if(this->m_bAllBranch)
2720 mask |= m_ShowMask ;
2722 if(m_bShowWC)
2724 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2725 ResetWcRev();
2726 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2729 if (m_sRange.IsEmpty())
2730 m_sRange = L"HEAD";
2732 #if 0 /* use tortoiegit filter */
2733 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2734 data.m_Author = this->m_sFilterText;
2736 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2737 data.m_MessageFilter = this->m_sFilterText;
2739 data.m_IsRegex = m_bFilterWithRegex;
2740 #endif
2742 // follow does not work for directories
2743 if (!path || path->IsDirectory())
2744 mask &= ~CGit::LOG_INFO_FOLLOW;
2745 // follow does not work with all branches 8at least in TGit)
2746 if (mask & CGit::LOG_INFO_FOLLOW)
2747 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2749 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2751 //this->m_logEntries.ParserFromLog();
2752 if(IsInWorkingThread())
2754 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2756 else
2758 SetItemCountEx((int)m_logEntries.size());
2763 [] { git_init(); } ();
2765 catch (char* msg)
2767 CString err(msg);
2768 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2769 return -1;
2772 if (!g_Git.CanParseRev(m_sRange))
2774 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2775 return 0;
2777 // if show all branches, pick any ref as dummy entry ref
2778 STRING_VECTOR list;
2779 if (g_Git.GetRefList(list))
2780 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2781 if (list.empty())
2782 return 0;
2784 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2787 g_Git.m_critGitDllSec.Lock();
2788 try {
2789 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2791 g_Git.m_critGitDllSec.Unlock();
2792 return -1;
2795 catch (char* msg)
2797 g_Git.m_critGitDllSec.Unlock();
2798 CString err(msg);
2799 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2800 return -1;
2802 g_Git.m_critGitDllSec.Unlock();
2804 return 0;
2807 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2809 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2811 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2813 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2815 DiffSelectedRevWithPrevious();
2816 return TRUE;
2819 #if 0
2820 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2822 DiffSelectedFile();
2823 return TRUE;
2825 #endif
2827 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2829 // select all entries
2830 for (int i=0; i<GetItemCount(); ++i)
2831 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2832 return TRUE;
2835 #if 0
2836 if (m_hAccel && !bSkipAccelerator)
2838 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2839 if (ret)
2840 return TRUE;
2843 #endif
2844 //m_tooltips.RelayEvent(pMsg);
2845 return __super::PreTranslateMessage(pMsg);
2848 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2850 // a double click on an entry in the revision list has happened
2851 *pResult = 0;
2853 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2854 DiffSelectedRevWithPrevious();
2857 void CGitLogListBase::FetchLogAsync(void* data)
2859 ReloadHashMap();
2860 m_ProcData=data;
2861 StartLoadingThread();
2864 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2866 return ((CGitLogListBase*)pVoid)->LogThread();
2869 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2871 //CTime time;
2872 oldest=CTime::GetCurrentTime();
2873 latest=CTime(1971,1,2,0,0,0);
2874 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2876 if(m_logEntries[i].IsEmpty())
2877 continue;
2879 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2880 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2882 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2883 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2887 if(latest<oldest)
2888 latest=oldest;
2891 UINT CGitLogListBase::LogThread()
2893 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2895 ULONGLONG t1,t2;
2897 if(BeginFetchLog())
2899 InterlockedExchange(&m_bThreadRunning, FALSE);
2900 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2902 return 1;
2905 std::wregex pat;//(L"Remove", regex_constants::icase);
2906 bool bRegex = false;
2907 if (m_bFilterWithRegex)
2908 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2910 TRACE(L"\n===Begin===\n");
2911 //Update work copy item;
2913 if (!m_logEntries.empty())
2915 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2917 m_arShownList.SafeAdd(pRev);
2921 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2923 // store commit number of the last selected commit/line before the refresh or -1
2924 int lastSelectedHashNItem = -1;
2925 if (m_lastSelectedHash.IsEmpty())
2926 lastSelectedHashNItem = 0;
2928 int ret = 0;
2930 bool shouldWalk = true;
2931 if (!g_Git.CanParseRev(m_sRange))
2933 // walk revisions if show all branches and there exists any ref
2934 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2935 shouldWalk = false;
2936 else
2938 STRING_VECTOR list;
2939 if (g_Git.GetRefList(list))
2940 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2941 if (list.empty())
2942 shouldWalk = false;
2946 if (shouldWalk)
2948 g_Git.m_critGitDllSec.Lock();
2949 if (!m_DllGitLog)
2951 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2952 g_Git.m_critGitDllSec.Unlock();
2953 InterlockedExchange(&m_bThreadRunning, FALSE);
2954 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2955 return 1;
2957 int total = 0;
2960 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2961 total = git_get_log_estimate_commit_count(m_DllGitLog);
2963 catch (char* msg)
2965 CString err(msg);
2966 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2967 ret = -1;
2969 g_Git.m_critGitDllSec.Unlock();
2971 GIT_COMMIT commit;
2972 t2 = t1 = GetTickCount64();
2973 int oldprecentage = 0;
2974 size_t oldsize = m_logEntries.size();
2975 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2976 while (ret== 0 && !m_bExitThread)
2978 g_Git.m_critGitDllSec.Lock();
2981 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2983 catch (char* msg)
2985 g_Git.m_critGitDllSec.Unlock();
2986 CString err(msg);
2987 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2988 break;
2990 g_Git.m_critGitDllSec.Unlock();
2992 if(ret)
2994 if (ret != -2) // other than end of revision walking
2995 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2996 break;
2999 if (commit.m_ignore == 1)
3001 git_free_commit(&commit);
3002 continue;
3005 //printf("%s\r\n",commit.GetSubject());
3006 if(m_bExitThread)
3007 break;
3009 CGitHash hash(commit.m_hash);
3011 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3012 pRev->m_GitCommit = commit;
3013 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3015 char* note = nullptr;
3016 g_Git.m_critGitDllSec.Lock();
3019 git_get_notes(commit.m_hash, &note);
3021 catch (char* msg)
3023 g_Git.m_critGitDllSec.Unlock();
3024 CString err(msg);
3025 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3026 break;
3028 g_Git.m_critGitDllSec.Unlock();
3030 if(note)
3032 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3033 free(note);
3034 note = nullptr;
3037 if(!pRev->m_IsDiffFiles)
3039 pRev->m_CallDiffAsync = DiffAsync;
3042 pRev->ParserParentFromCommit(&commit);
3043 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3045 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3047 const CGitHash &parentHash = pRev->m_ParentHash[i];
3048 auto it = commitChildren.find(parentHash);
3049 if (it == commitChildren.end())
3050 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3051 it->second.insert(pRev->m_CommitHash);
3055 #ifdef DEBUG
3056 pRev->DbgPrint();
3057 TRACE(L"\n");
3058 #endif
3060 bool visible = true;
3061 if (HasFilterText())
3063 if(!IsMatchFilter(bRegex,pRev,pat))
3064 visible = false;
3066 if (visible && !ShouldShowFilter(pRev, commitChildren))
3067 visible = false;
3068 this->m_critSec.Lock();
3069 m_logEntries.append(hash, visible);
3070 if (visible)
3071 m_arShownList.SafeAdd(pRev);
3072 this->m_critSec.Unlock();
3074 if (!visible)
3075 continue;
3077 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3078 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3080 t2 = GetTickCount64();
3082 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3084 //update UI
3085 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3086 if(percent > 99)
3087 percent =99;
3088 if(percent < GITLOG_START)
3089 percent = GITLOG_START +1;
3091 oldsize = m_logEntries.size();
3092 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3094 //if( percent > oldprecentage )
3096 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3097 oldprecentage = percent;
3100 if (lastSelectedHashNItem >= 0)
3101 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3103 t1 = t2;
3106 g_Git.m_critGitDllSec.Lock();
3107 git_close_log(m_DllGitLog);
3108 g_Git.m_critGitDllSec.Unlock();
3112 if (m_bExitThread)
3114 InterlockedExchange(&m_bThreadRunning, FALSE);
3115 return 0;
3118 //Update UI;
3119 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3121 if (lastSelectedHashNItem >= 0)
3122 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3124 if (this->m_hWnd)
3125 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3127 InterlockedExchange(&m_bThreadRunning, FALSE);
3129 return 0;
3132 void CGitLogListBase::FetchRemoteList()
3134 STRING_VECTOR remoteList;
3135 m_SingleRemote.Empty();
3136 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3137 m_SingleRemote = remoteList[0];
3140 void CGitLogListBase::FetchTrackingBranchList()
3142 m_TrackingMap.clear();
3143 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3145 for (const auto& ref : it->second)
3147 CString branchName;
3148 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3150 CString pullRemote, pullBranch;
3151 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3152 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3153 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3159 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3161 SafeTerminateThread();
3163 this->SetItemCountEx(0);
3164 this->Clear();
3166 ResetWcRev();
3168 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3170 if (m_pMailmap)
3172 git_free_mailmap(m_pMailmap);
3173 git_read_mailmap(&m_pMailmap);
3176 //Update branch and Tag info
3177 ReloadHashMap();
3178 if (m_pFindDialog)
3179 m_pFindDialog->RefreshList();
3180 //Assume Thread have exited
3181 //if(!m_bThreadRunning)
3183 m_logEntries.clear();
3185 if(IsCleanFilter)
3187 m_sFilterText.Empty();
3190 SafeTerminateAsyncDiffThread();
3191 m_AsynDiffListLock.Lock();
3192 m_AsynDiffList.clear();
3193 m_AsynDiffListLock.Unlock();
3194 StartAsyncDiffThread();
3196 StartLoadingThread();
3200 void CGitLogListBase::StartAsyncDiffThread()
3202 if (m_AsyncThreadExit)
3203 return;
3204 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3205 return;
3206 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3207 if (!m_DiffingThread)
3209 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3210 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3214 void CGitLogListBase::StartLoadingThread()
3216 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3217 return;
3218 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3219 InterlockedExchange(&m_bExitThread, FALSE);
3220 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3221 if (!m_LoadingThread)
3223 InterlockedExchange(&m_bThreadRunning, FALSE);
3224 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3225 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3229 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::wregex& pat, bool bMatchCase /* = false */)
3233 std::regex_constants::syntax_option_type type = std::regex_constants::ECMAScript;
3234 if (!bMatchCase)
3235 type |= std::regex_constants::icase;
3236 pat = std::wregex(regexp_str, type);
3237 return true;
3239 catch (std::exception&) {}
3240 return false;
3242 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::wregex& pat)
3244 BOOL result = TRUE;
3245 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3246 CString sRev;
3248 if ((bRegex)&&(m_bFilterWithRegex))
3250 if (m_SelectedFilters & LOGFILTER_BUGID)
3252 if(this->m_bShowBugtraqColumn)
3254 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3256 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3257 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3258 return TRUE;
3262 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3264 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3265 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3266 return TRUE;
3269 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3271 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3272 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3273 return TRUE;
3276 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3278 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3279 return TRUE;
3281 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3282 return TRUE;
3285 if (m_SelectedFilters & LOGFILTER_EMAILS)
3287 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3288 return TRUE;
3290 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3291 return TRUE;
3294 if (m_SelectedFilters & LOGFILTER_REVS)
3296 sRev = pRev->m_CommitHash.ToString();
3297 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3299 return TRUE;
3303 if (m_SelectedFilters & LOGFILTER_NOTES)
3305 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3306 return TRUE;
3309 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3311 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3312 for (const auto& ref : refs)
3314 if (std::regex_search(std::wstring(ref), pat, flags))
3315 return TRUE;
3319 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3321 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3322 return TRUE;
3325 if (m_SelectedFilters & LOGFILTER_PATHS)
3327 CTGitPathList* pathList = nullptr;
3328 if( pRev->m_IsDiffFiles)
3329 pathList = &pRev->GetFiles(this);
3330 else
3332 if(!pRev->m_IsSimpleListReady)
3333 pRev->SafeGetSimpleList(&g_Git);
3336 if(pathList)
3337 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3339 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3340 return true;
3341 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3342 return true;
3345 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3347 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3348 return true;
3352 else
3354 CString find = m_sFilterText;
3355 if (!m_bFilterCaseSensitively)
3356 find.MakeLower();
3357 result = find[0] == '!' ? FALSE : TRUE;
3358 if (!result)
3359 find = find.Mid(1);
3361 if (m_SelectedFilters & LOGFILTER_BUGID)
3363 if(this->m_bShowBugtraqColumn)
3365 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3367 if (!m_bFilterCaseSensitively)
3368 sBugIds.MakeLower();
3369 if ((sBugIds.Find(find) >= 0))
3370 return result;
3374 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3376 CString msg = pRev->GetSubject();
3378 if (!m_bFilterCaseSensitively)
3379 msg = msg.MakeLower();
3380 if ((msg.Find(find) >= 0))
3381 return result;
3384 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3386 CString msg = pRev->GetBody();
3388 if (!m_bFilterCaseSensitively)
3389 msg = msg.MakeLower();
3390 if ((msg.Find(find) >= 0))
3391 return result;
3394 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3396 CString msg = pRev->GetAuthorName();
3397 if (!m_bFilterCaseSensitively)
3398 msg = msg.MakeLower();
3399 if ((msg.Find(find) >= 0))
3400 return result;
3403 if (m_SelectedFilters & LOGFILTER_EMAILS)
3405 CString msg = pRev->GetAuthorEmail();
3406 if (!m_bFilterCaseSensitively)
3407 msg = msg.MakeLower();
3408 if ((msg.Find(find) >= 0))
3409 return result;
3412 if (m_SelectedFilters & LOGFILTER_NOTES)
3414 CString msg = pRev->m_Notes;
3415 if (!m_bFilterCaseSensitively)
3416 msg = msg.MakeLower();
3417 if ((msg.Find(find) >= 0))
3418 return result;
3421 if (m_SelectedFilters & LOGFILTER_REVS)
3423 sRev = pRev->m_CommitHash.ToString();
3424 if ((sRev.Find(find) >= 0))
3425 return result;
3428 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3430 CString msg = GetTagInfo(pRev);
3431 if (!m_bFilterCaseSensitively)
3432 msg = msg.MakeLower();
3433 if ((msg.Find(find) >= 0))
3434 return result;
3437 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3439 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3440 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3442 if (it->Find(find) >= 0)
3443 return result;
3447 if (m_SelectedFilters & LOGFILTER_PATHS)
3449 CTGitPathList* pathList = nullptr;
3450 if( pRev->m_IsDiffFiles)
3451 pathList = &pRev->GetFiles(this);
3452 else
3454 if(!pRev->m_IsSimpleListReady)
3455 pRev->SafeGetSimpleList(&g_Git);
3457 if(pathList)
3458 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3460 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3461 CString path = cpath->GetGitOldPathString();
3462 if (!m_bFilterCaseSensitively)
3463 path.MakeLower();
3464 if ((path.Find(find)>=0))
3465 return result;
3466 path = cpath->GetGitPathString();
3467 if (!m_bFilterCaseSensitively)
3468 path.MakeLower();
3469 if ((path.Find(find)>=0))
3470 return result;
3473 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3475 CString path = pRev->m_SimpleFileList[i];
3476 if (!m_bFilterCaseSensitively)
3477 path.MakeLower();
3478 if ((path.Find(find)>=0))
3479 return result;
3482 } // else (from if (bRegex))
3483 return !result;
3486 static bool CStringStartsWith(const CString &str, const CString &prefix)
3488 return str.Left(prefix.GetLength()) == prefix;
3490 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3492 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3493 return true;
3495 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3497 // Keep all refs.
3498 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3499 for (size_t i = 0; i < refList.size(); ++i)
3501 const CString &str = refList[i];
3502 if (CStringStartsWith(str, L"refs/heads/"))
3504 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3505 return true;
3507 else if (CStringStartsWith(str, L"refs/remotes/"))
3509 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3510 return true;
3512 else if (CStringStartsWith(str, L"refs/tags/"))
3514 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3515 return true;
3517 else if (CStringStartsWith(str, L"refs/stash"))
3519 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3520 return true;
3522 else if (CStringStartsWith(str, L"refs/bisect/"))
3524 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3525 return true;
3528 // Keep the head too.
3529 if (pRev->m_CommitHash == m_HeadHash)
3530 return true;
3533 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3535 if (pRev->ParentsCount() > 1)
3536 return true;
3537 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3538 if (childrenIt != commitChildren.end())
3540 const std::unordered_set<CGitHash> &children = childrenIt->second;
3541 if (children.size() > 1)
3542 return true;
3545 return false;
3548 void CGitLogListBase::ShowGraphColumn(bool bShow)
3550 // HACK to hide graph column
3551 if (bShow)
3552 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3553 else
3554 SetColumnWidth(0, 0);
3557 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3559 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3560 return L"";
3562 CString tagInfo;
3563 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3564 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3566 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3567 continue;
3568 if (!CStringUtils::EndsWith((*it), L"^{}"))
3569 continue;
3571 CString cmd;
3572 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3573 CString output;
3574 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3575 continue;
3577 // parse tag date
3580 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3581 int pos1 = output.Find(L'>');
3582 if (pos1 < 0)
3583 break;
3584 ++pos1;
3585 if (output[pos1] == L' ')
3586 ++pos1;
3587 int pos2 = output.Find(L'\n', pos1);
3588 if (pos2 < 0)
3589 break;
3591 CString str = output.Mid(pos1, pos2 - pos1);
3592 wchar_t* pEnd = nullptr;
3593 errno = 0;
3594 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3595 if (str.GetBuffer() == pEnd)
3596 break;
3597 if (errno == ERANGE)
3598 break;
3600 output.Delete(pos1, pos2 - pos1);
3601 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3602 } while (0);
3603 output.Trim().AppendChar(L'\n');
3604 tagInfo += output;
3606 return tagInfo;
3609 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3611 pShownlist->SafeRemoveAll();
3613 std::wregex pat;//(L"Remove", regex_constants::icase);
3614 bool bRegex = false;
3615 if (m_bFilterWithRegex)
3616 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3618 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3619 CString sRev;
3620 for (DWORD i=0; i<m_logEntries.size(); ++i)
3622 if ((bRegex)&&(m_bFilterWithRegex))
3624 #if 0
3625 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3627 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3628 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3630 pShownlist->SafeAdd(m_logEntries[i]);
3631 continue;
3634 #endif
3635 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3637 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3638 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3640 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3641 continue;
3644 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3646 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3647 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3649 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3650 continue;
3653 if (m_SelectedFilters & LOGFILTER_PATHS)
3655 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3657 bool bGoing = true;
3658 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3660 CTGitPath cpath = pathList[cpPathIndex];
3661 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3663 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3664 bGoing = false;
3665 continue;
3667 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3669 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3670 bGoing = false;
3671 continue;
3673 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3675 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3676 bGoing = false;
3677 continue;
3681 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3683 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3685 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3686 continue;
3689 if (m_SelectedFilters & LOGFILTER_EMAILS)
3691 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3693 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3694 continue;
3697 if (m_SelectedFilters & LOGFILTER_REVS)
3699 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3700 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3702 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3703 continue;
3706 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3708 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3709 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3711 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3713 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3714 continue;
3718 } // if (bRegex)
3719 else
3721 CString find = m_sFilterText;
3722 if (!m_bFilterCaseSensitively)
3723 find.MakeLower();
3724 #if 0
3725 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3727 CString sBugIDs = m_logEntries[i]->sBugIDs;
3729 if (!m_bFilterCaseSensitively)
3730 sBugIDs = sBugIDs.MakeLower();
3731 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3733 pShownlist->SafeAdd(m_logEntries[i]);
3734 continue;
3737 #endif
3738 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3740 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3742 if (!m_bFilterCaseSensitively)
3743 msg = msg.MakeLower();
3744 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3746 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3747 continue;
3750 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3752 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3754 if (!m_bFilterCaseSensitively)
3755 msg = msg.MakeLower();
3756 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3758 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3759 continue;
3762 if (m_SelectedFilters & LOGFILTER_PATHS)
3764 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3766 bool bGoing = true;
3767 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3769 CTGitPath cpath = pathList[cpPathIndex];
3770 CString path = cpath.GetGitOldPathString();
3771 if (!m_bFilterCaseSensitively)
3772 path.MakeLower();
3773 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3775 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3776 bGoing = false;
3777 continue;
3779 path = cpath.GetGitPathString();
3780 if (!m_bFilterCaseSensitively)
3781 path.MakeLower();
3782 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3784 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3785 bGoing = false;
3786 continue;
3788 path = cpath.GetActionName();
3789 if (!m_bFilterCaseSensitively)
3790 path.MakeLower();
3791 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3793 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3794 bGoing = false;
3795 continue;
3799 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3801 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3802 if (!m_bFilterCaseSensitively)
3803 msg = msg.MakeLower();
3804 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3806 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3807 continue;
3810 if (m_SelectedFilters & LOGFILTER_EMAILS)
3812 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3813 if (!m_bFilterCaseSensitively)
3814 msg = msg.MakeLower();
3815 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3817 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3818 continue;
3821 if (m_SelectedFilters & LOGFILTER_REVS)
3823 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3824 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3826 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3827 continue;
3830 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3832 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3833 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3835 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3837 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3838 continue;
3842 } // else (from if (bRegex))
3843 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3846 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3849 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3851 if(m_From == -1)
3852 if(m_To == -1)
3853 return true;
3854 else
3855 return time <= m_To;
3856 else
3857 if(m_To == -1)
3858 return time >= m_From;
3859 else
3860 return ((time >= m_From)&&(time <= m_To));
3862 return TRUE; /* git dll will filter time range */
3864 // return TRUE;
3867 void CGitLogListBase::StartFilter()
3869 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3870 RecalculateShownList(&m_arShownList);
3871 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3874 DeleteAllItems();
3875 SetItemCountEx(ShownCountWithStopped());
3876 RedrawItems(0, ShownCountWithStopped());
3877 Invalidate();
3880 void CGitLogListBase::RemoveFilter()
3882 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3884 m_arShownList.SafeRemoveAll();
3886 // reset the time filter too
3887 #if 0
3888 m_timFrom = (__time64_t(m_tFrom));
3889 m_timTo = (__time64_t(m_tTo));
3890 m_DateFrom.SetTime(&m_timFrom);
3891 m_DateTo.SetTime(&m_timTo);
3892 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3893 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3894 #endif
3896 for (DWORD i=0; i<m_logEntries.size(); ++i)
3898 if(this->m_IsOldFirst)
3899 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3900 else
3901 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3903 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3904 DeleteAllItems();
3905 SetItemCountEx(ShownCountWithStopped());
3906 RedrawItems(0, ShownCountWithStopped());
3908 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3911 void CGitLogListBase::Clear()
3913 m_arShownList.SafeRemoveAll();
3914 DeleteAllItems();
3916 m_logEntries.ClearAll();
3919 void CGitLogListBase::OnDestroy()
3921 SafeTerminateThread();
3922 SafeTerminateAsyncDiffThread();
3924 int retry = 0;
3925 while(m_LogCache.SaveCache())
3927 if(retry > 5)
3928 break;
3929 Sleep(1000);
3931 ++retry;
3933 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3934 // MB_YESNO) == IDNO)
3935 // break;
3938 __super::OnDestroy();
3941 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3943 CRect rect;
3944 int i=(int)wParam;
3945 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3946 this->InvalidateRect(rect);
3948 return 0;
3952 * Save column widths to the registry
3954 void CGitLogListBase::SaveColumnWidths()
3956 // HACK that graph column is always shown
3957 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3959 __super::SaveColumnWidths();
3962 int CGitLogListBase::GetHeadIndex()
3964 if(m_HeadHash.IsEmpty())
3965 return -1;
3967 for (size_t i = 0; i < m_arShownList.size(); ++i)
3969 GitRev* pRev = m_arShownList.SafeGetAt(i);
3970 if(pRev)
3972 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3973 return (int)i;
3976 return -1;
3978 void CGitLogListBase::OnFind()
3980 if (!m_pFindDialog)
3982 m_pFindDialog = new CFindDlg(this);
3983 m_pFindDialog->Create(this);
3987 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3989 if (GetSelectedCount() != 0)
3990 return 0;
3992 CGitHash theSelectedHash = m_lastSelectedHash;
3993 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3994 m_lastSelectedHash = theSelectedHash;
3996 int countPerPage = GetCountPerPage();
3997 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3998 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3999 EnsureVisible((int)itemToSelect, FALSE);
4000 return 0;
4003 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
4005 CString* ref = reinterpret_cast<CString*>(wParam);
4006 if (!ref || ref->IsEmpty())
4007 return 1;
4009 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4011 CGitHash hash;
4012 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4013 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4015 if (hash.IsEmpty())
4016 return 1;
4018 bool bFound = false;
4019 int cnt = (int)m_arShownList.size();
4020 int i;
4021 for (i = 0; i < cnt; ++i)
4023 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4024 if (pLogEntry && pLogEntry->m_CommitHash == hash)
4026 bFound = true;
4027 break;
4030 if (!bFound)
4031 return 1;
4033 EnsureVisible(i, FALSE);
4034 if (!bShift)
4036 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4037 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4038 SetSelectionMark(i);
4040 else
4042 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4043 if (pLogEntry)
4044 m_highlight = pLogEntry->m_CommitHash;
4046 Invalidate();
4047 UpdateData(FALSE);
4049 return 0;
4052 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4054 ASSERT(m_pFindDialog);
4055 bool bFound = false;
4056 int i=0;
4058 if (m_pFindDialog->IsTerminating())
4060 // invalidate the handle identifying the dialog box.
4061 m_pFindDialog = nullptr;
4062 return 0;
4065 int cnt = (int)m_arShownList.size();
4066 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4068 if(m_pFindDialog->IsRef())
4070 CString str;
4071 str=m_pFindDialog->GetFindString();
4073 CGitHash hash;
4075 if(!str.IsEmpty())
4077 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4078 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4081 if(!hash.IsEmpty())
4083 for (i = 0; i < cnt; ++i)
4085 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4086 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4088 bFound = true;
4089 break;
4093 if (!bFound)
4095 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4096 return 0;
4100 if (m_pFindDialog->FindNext() && !bFound)
4102 //read data from dialog
4103 CString findText = m_pFindDialog->GetFindString();
4104 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4106 std::wregex pat;
4107 bool bRegex = false;
4108 if (m_pFindDialog->Regex())
4109 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4111 std::regex_constants::match_flag_type flags = std::regex_constants::match_not_null;
4113 for (i = m_nSearchIndex + 1; ; ++i)
4115 if (i >= cnt)
4117 i = 0;
4118 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4120 if (m_nSearchIndex >= 0)
4122 if (i == m_nSearchIndex)
4124 ::MessageBeep(0xFFFFFFFF);
4125 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4126 break;
4130 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4132 CString str;
4133 str+=pLogEntry->m_CommitHash.ToString();
4134 str += L'\n';
4136 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4137 if (refList != m_HashMap.cend())
4139 for (const auto& ref : (*refList).second)
4141 str += ref;
4142 str += L'\n';
4146 str+=pLogEntry->GetAuthorEmail();
4147 str += L'\n';
4148 str+=pLogEntry->GetAuthorName();
4149 str += L'\n';
4150 str+=pLogEntry->GetBody();
4151 str += L'\n';
4152 str+=pLogEntry->GetCommitterEmail();
4153 str += L'\n';
4154 str+=pLogEntry->GetCommitterName();
4155 str += L'\n';
4156 str+=pLogEntry->GetSubject();
4157 str += L'\n';
4158 str+=pLogEntry->m_Notes;
4159 str += L'\n';
4160 str+=GetTagInfo(pLogEntry);
4161 str += L'\n';
4164 /*Because changed files list is loaded on demand when gui show,
4165 files will empty when files have not fetched.
4167 we can add it back by using one-way diff(with outnumber changed and rename detect.
4168 here just need changed filename list. one-way is much quicker.
4170 if(pLogEntry->m_IsFull)
4172 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4174 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4175 str += L'\n';
4176 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4177 str += L'\n';
4180 else
4182 if(!pLogEntry->m_IsSimpleListReady)
4183 pLogEntry->SafeGetSimpleList(&g_Git);
4185 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4187 str += pLogEntry->m_SimpleFileList[j];
4188 str += L'\n';
4192 if (bRegex)
4194 if (std::regex_search(std::wstring(str), pat, flags))
4196 bFound = true;
4197 break;
4200 else
4202 if (bMatchCase)
4204 if (str.Find(findText) >= 0)
4206 bFound = true;
4207 break;
4210 else
4212 CString msg = str;
4213 msg = msg.MakeLower();
4214 CString find = findText.MakeLower();
4215 if (msg.Find(find) >= 0)
4217 bFound = TRUE;
4218 break;
4222 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4224 } // if(m_pFindDialog->FindNext())
4225 //UpdateLogInfoLabel();
4227 if (bFound)
4229 m_nSearchIndex = i;
4230 EnsureVisible(i, FALSE);
4231 if (!bShift)
4233 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4234 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4235 SetSelectionMark(i);
4237 else
4239 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4240 if (pLogEntry)
4241 m_highlight = pLogEntry->m_CommitHash;
4243 Invalidate();
4244 //FillLogMessageCtrl();
4245 UpdateData(FALSE);
4248 return 0;
4251 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4253 LVHITTESTINFO lvhitTestInfo;
4255 lvhitTestInfo.pt = point;
4257 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4258 int nSubItem = lvhitTestInfo.iSubItem;
4260 UINT nFlags = lvhitTestInfo.flags;
4262 // nFlags is 0 if the SubItemHitTest fails
4263 // Therefore, 0 & <anything> will equal false
4264 if (nFlags & LVHT_ONITEM)
4266 // Get the client area occupied by this control
4267 RECT rcClient;
4268 GetClientRect(&rcClient);
4270 // Fill in the TOOLINFO structure
4271 pTI->hwnd = m_hWnd;
4272 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4273 pTI->lpszText = LPSTR_TEXTCALLBACK;
4274 pTI->rect = rcClient;
4276 return pTI->uId; // By returning a unique value per listItem,
4277 // we ensure that when the mouse moves over another list item,
4278 // the tooltip will change
4280 else
4282 // Otherwise, we aren't interested, so let the message propagate
4283 return -1;
4287 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4289 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4290 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4292 *pResult = 0;
4294 // Ignore messages from the built in tooltip, we are processing them internally
4295 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4296 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4297 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4298 return FALSE;
4300 // Get the mouse position
4301 const MSG* pMessage = GetCurrentMessage();
4303 CPoint pt;
4304 pt = pMessage->pt;
4305 ScreenToClient(&pt);
4307 // Check if the point falls onto a list item
4308 LVHITTESTINFO lvhitTestInfo;
4309 lvhitTestInfo.pt = pt;
4311 int nItem = SubItemHitTest(&lvhitTestInfo);
4313 if (lvhitTestInfo.flags & LVHT_ONITEM)
4315 // Get branch description first
4316 CString strTipText;
4317 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4319 CString branch;
4320 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4321 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4323 MAP_STRING_STRING descriptions;
4324 g_Git.GetBranchDescriptions(descriptions);
4325 if (descriptions.find(branch) != descriptions.cend())
4327 strTipText.LoadString(IDS_DESCRIPTION);
4328 strTipText += L":\n";
4329 strTipText += descriptions[branch];
4334 bool followMousePos = false;
4335 if (!strTipText.IsEmpty())
4336 followMousePos = true;
4337 else
4338 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4339 if (strTipText.IsEmpty())
4340 return FALSE;
4342 // we want multiline tooltips
4343 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4345 wcscpy_s(m_wszTip, strTipText);
4346 // handle Unicode as well as non-Unicode requests
4347 if (pNMHDR->code == TTN_NEEDTEXTA)
4349 pTTTA->hinst = nullptr;
4350 pTTTA->lpszText = m_szTip;
4351 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4353 else
4355 pTTTW->hinst = nullptr;
4356 pTTTW->lpszText = m_wszTip;
4359 CRect rect;
4360 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4361 if (followMousePos)
4362 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4363 ClientToScreen(rect);
4364 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4366 return TRUE; // We found a tool tip,
4367 // tell the framework this message has been handled
4370 return FALSE; // We didn't handle the message,
4371 // let the framework continue propagating the message
4374 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4376 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4378 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4379 if (pLogEntry == nullptr)
4380 return CString();
4381 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4382 return CString();
4383 return pLogEntry->GetSubject();
4385 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4387 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4388 if (pLogEntry == nullptr)
4389 return CString();
4390 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4392 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4394 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4395 if (pLogEntry == nullptr)
4396 return CString();
4397 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4399 else if (nSubItem == LOGLIST_ACTION)
4401 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4402 if (pLogEntry == nullptr)
4403 return CString();
4405 if (!pLogEntry->m_IsDiffFiles)
4406 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4408 int actions = pLogEntry->GetAction(this);
4409 CString sToolTipText;
4411 CString actionText;
4412 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4413 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4415 if (actions & CTGitPath::LOGACTIONS_ADDED)
4417 if (!actionText.IsEmpty())
4418 actionText += L"\r\n";
4419 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4422 if (actions & CTGitPath::LOGACTIONS_DELETED)
4424 if (!actionText.IsEmpty())
4425 actionText += L"\r\n";
4426 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4429 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4431 if (!actionText.IsEmpty())
4432 actionText += L"\r\n";
4433 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4436 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4438 if (!actionText.IsEmpty())
4439 actionText += L"\r\n";
4440 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4443 if (!actionText.IsEmpty())
4445 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4446 sToolTipText = sTitle + L":\r\n" + actionText;
4448 return sToolTipText;
4450 return CString();
4453 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4455 POINT pt = point;
4456 ScreenToClient(&pt);
4457 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4460 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4462 if (!pLogEntry)
4463 return false;
4465 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4466 if (refList == m_HashMap.cend())
4467 return false;
4469 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4471 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4472 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4473 continue;
4475 CGit::REF_TYPE foundType;
4476 if (pShortname)
4477 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4478 else
4479 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4480 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4481 return false;
4483 type = foundType;
4484 if (pIndex)
4485 *pIndex = i;
4486 return true;
4488 return false;
4491 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4493 *pResult = 0;
4495 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4496 return;
4498 m_bDragging = TRUE;
4499 m_nDropIndex = -1;
4500 m_nDropMarkerLast = -1;
4501 m_nDropMarkerLastHot = GetHotItem();
4502 SetCapture();
4505 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4507 __super::OnMouseMove(nFlags, point);
4509 if (!m_bDragging)
4510 return;
4512 CPoint dropPoint = point;
4513 ClientToScreen(&dropPoint);
4515 if (WindowFromPoint(dropPoint) != this)
4517 SetCursor(LoadCursor(nullptr, IDC_NO));
4518 m_nDropIndex = -1;
4519 DrawDropInsertMarker(m_nDropIndex);
4520 return;
4523 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4524 ScreenToClient(&dropPoint);
4526 dropPoint.y += 10;
4527 m_nDropIndex = HitTest(dropPoint);
4529 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4531 dropPoint.y -= 10;
4532 m_nDropIndex = HitTest(dropPoint);
4533 if (m_nDropIndex != -1)
4534 m_nDropIndex = GetItemCount();
4537 POSITION pos = GetFirstSelectedItemPosition();
4538 int first = GetNextSelectedItem(pos);
4539 int last = first;
4540 while (pos)
4541 last = GetNextSelectedItem(pos);
4542 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4544 SetCursor(LoadCursor(nullptr, IDC_NO));
4545 m_nDropIndex = -1;
4548 // handle auto scrolling
4549 int hotItem = GetHotItem();
4550 int topindex = GetTopIndex();
4551 if (hotItem == topindex && hotItem != 0)
4552 EnsureVisible(hotItem - 1, FALSE);
4553 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4554 EnsureVisible(hotItem + 1, FALSE);
4556 DrawDropInsertMarker(m_nDropIndex);
4559 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4561 if (m_bDragging)
4563 ::ReleaseCapture();
4564 SetCursor(LoadCursor(nullptr, IDC_HAND));
4565 m_bDragging = FALSE;
4567 CRect rect;
4568 GetItemRect(m_nDropMarkerLast, &rect, 0);
4569 rect.bottom = rect.top + 2;
4570 rect.top -= 2;
4571 InvalidateRect(&rect, 0);
4573 CPoint pt(point);
4574 ClientToScreen(&pt);
4575 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4576 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4579 __super::OnLButtonUp(nFlags, point);
4582 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4584 if (m_nDropMarkerLast != nIndex)
4586 CRect rect;
4587 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4589 rect.bottom = rect.top + 2;
4590 rect.top -= 2;
4591 InvalidateRect(&rect, 0);
4593 else if (m_nDropMarkerLast == GetItemCount())
4594 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4595 m_nDropMarkerLast = nIndex;
4597 if (nIndex < 0)
4598 return;
4600 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4602 else if (m_nDropMarkerLastHot != GetHotItem())
4604 m_nDropMarkerLastHot = GetHotItem();
4605 m_nDropMarkerLast = -1;
4609 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4611 CBrush* pBrush = CDC::GetHalftoneBrush();
4612 CDC* pDC = GetDC();
4614 CRect rect;
4615 if (nIndex < GetItemCount())
4617 GetItemRect(nIndex, &rect, 0);
4618 rect.bottom = rect.top + 2;
4619 rect.top -= 2;
4621 else
4623 GetItemRect(nIndex - 1, &rect, 0);
4624 rect.top = rect.bottom - 2;
4625 rect.bottom += 2;
4628 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4629 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4630 pDC->SelectObject(pBrushOld);
4632 ReleaseDC(pDC);
4635 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
4637 return 0;