Make tag date readable
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
bloba85e16e5f8ec1f79b7612d64684f7b41b2963795
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - TortoiseGit
4 // Copyright (C) 2005-2007 Marco Costalba
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // GitLogList.cpp : implementation file
22 #include "stdafx.h"
23 #include "resource.h"
24 #include "GitLogListBase.h"
25 #include "IconMenu.h"
26 #include "GitProgressDlg.h"
27 #include "ProgressDlg.h"
28 #include "MessageBox.h"
29 #include "LoglistUtils.h"
30 #include "StringUtils.h"
31 #include "UnicodeUtils.h"
32 #include "IconMenu.h"
33 #include "../TortoiseShell/Resource.h"
35 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
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 int& 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 default:
1369 continue;
1371 refsToShow.push_back(refLabel);
1373 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1375 REFLABEL refLabel;
1376 refLabel.color = RGB(246, 153, 253);
1377 refLabel.singleRemote = false;
1378 refLabel.hasTracking = false;
1379 refLabel.sameName = false;
1380 refLabel.name = L"super-project-pointer";
1381 refLabel.fullName = "";
1382 refsToShow.push_back(refLabel);
1385 if (refsToShow.empty())
1387 *pResult = CDRF_DODEFAULT;
1388 return;
1391 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1393 *pResult = CDRF_SKIPDEFAULT;
1394 return;
1401 if (pLVCD->iSubItem == LOGLIST_ACTION)
1403 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1405 *pResult = CDRF_DODEFAULT;
1406 return;
1408 *pResult = CDRF_DODEFAULT;
1410 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1411 return;
1413 int nIcons = 0;
1414 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1415 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1417 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1418 CRect rect;
1419 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1420 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1421 // Get the selected state of the
1422 // item being drawn.
1424 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1425 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1427 // Fill the background if necessary
1428 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1430 // Draw the icon(s) into the compatible DC
1431 int action = pLogEntry->GetAction(this);
1432 if (!pLogEntry->m_IsDiffFiles)
1434 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1435 *pResult = CDRF_SKIPDEFAULT;
1436 return;
1439 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1440 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1441 ++nIcons;
1443 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1444 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1445 ++nIcons;
1447 if (action & CTGitPath::LOGACTIONS_DELETED)
1448 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1449 ++nIcons;
1451 if (action & CTGitPath::LOGACTIONS_REPLACED)
1452 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1453 ++nIcons;
1455 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1456 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 *pResult = CDRF_SKIPDEFAULT;
1460 return;
1463 break;
1465 *pResult = CDRF_DODEFAULT;
1468 CString FindSVNRev(const CString& msg)
1472 const std::tr1::wsregex_iterator end;
1473 std::wstring s = msg;
1474 std::tr1::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1475 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1477 const std::tr1::wsmatch match = *it;
1478 if (match.size() == 4)
1480 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1481 return std::wstring(match[2]).c_str();
1484 std::tr1::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1485 for (std::tr1::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1487 const std::tr1::wsmatch match = *it;
1488 if (match.size() == 3)
1490 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1491 return std::wstring(match[1]).c_str();
1495 catch (std::exception&) {}
1497 return L"";
1500 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1502 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1503 return pLogEntry->GetSubject();
1505 CString txt(pLogEntry->GetSubject());
1506 txt += L' ';
1507 txt += pLogEntry->GetBody();
1509 // Deal with CRLF
1510 txt.Replace(L'\n', L' ');
1511 txt.Replace(L'\r', L' ');
1513 return txt;
1516 // CGitLogListBase message handlers
1518 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1520 struct payload_struct { const CString* name; const char* authorName; };
1521 payload_struct payload = { &name, nullptr };
1522 const char* author1 = nullptr;
1523 const char* email1 = nullptr;
1524 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1525 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1526 free((void *)payload.authorName);
1527 if (returnEmail)
1528 return email1;
1529 return author1;
1532 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1534 if (mailmap)
1536 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1537 if (translated)
1539 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1540 return;
1543 if (returnEmail)
1544 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1545 else
1546 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1549 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1551 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1553 // Create a pointer to the item
1554 LV_ITEM* pItem = &(pDispInfo)->item;
1556 // Do the list need text information?
1557 if (!(pItem->mask & LVIF_TEXT))
1558 return;
1560 // By default, clear text buffer.
1561 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1563 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1565 *pResult = 0;
1566 if (m_bNoDispUpdates || bOutOfRange)
1567 return;
1569 // Which item number?
1570 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1572 CString temp;
1573 if(m_IsOldFirst)
1574 temp.Format(L"%d", pItem->iItem + 1);
1575 else
1576 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1578 if (!pLogEntry)
1579 return;
1581 // Which column?
1582 switch (pItem->iSubItem)
1584 case LOGLIST_GRAPH: //Graphic
1585 break;
1586 case LOGLIST_REBASE:
1587 if (m_IsRebaseReplaceGraph)
1588 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1589 break;
1590 case LOGLIST_ACTION: //action -- no text in the column
1591 break;
1592 case LOGLIST_HASH:
1593 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1594 break;
1595 case LOGLIST_ID:
1596 if (this->m_IsIDReplaceAction)
1597 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1598 break;
1599 case LOGLIST_MESSAGE: //Message
1600 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1601 break;
1602 case LOGLIST_AUTHOR: //Author
1603 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1604 break;
1605 case LOGLIST_DATE: //Date
1606 if (!pLogEntry->m_CommitHash.IsEmpty())
1607 lstrcpyn(pItem->pszText,
1608 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1609 pItem->cchTextMax - 1);
1610 break;
1612 case LOGLIST_EMAIL:
1613 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1614 break;
1616 case LOGLIST_COMMIT_NAME: //Commit
1617 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1618 break;
1620 case LOGLIST_COMMIT_EMAIL: //Commit Email
1621 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1622 break;
1624 case LOGLIST_COMMIT_DATE: //Commit Date
1625 if (!pLogEntry->m_CommitHash.IsEmpty())
1626 lstrcpyn(pItem->pszText,
1627 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1628 pItem->cchTextMax - 1);
1629 break;
1630 case LOGLIST_BUG: //Bug ID
1631 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1632 break;
1633 case LOGLIST_SVNREV: //SVN revision
1634 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1635 break;
1637 default:
1638 ASSERT(false);
1642 bool CGitLogListBase::IsOnStash(int index)
1644 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1645 if (IsStash(rev))
1646 return true;
1647 if (index > 0)
1649 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1650 if (IsStash(preRev))
1651 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1653 return false;
1656 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1658 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1659 if (refList == m_HashMap.cend())
1660 return false;
1661 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1664 bool CGitLogListBase::IsBisect(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 CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1672 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1674 if (pRev->m_ParentHash.empty())
1676 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1677 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1679 parentHash = pRev->m_ParentHash;
1682 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1684 __super::OnContextMenu(pWnd, point);
1686 if (pWnd != this)
1687 return;
1689 int selIndex = GetSelectionMark();
1690 if (selIndex < 0)
1691 return; // nothing selected, nothing to do with a context menu
1693 // if the user selected the info text telling about not all revisions shown due to
1694 // the "stop on copy/rename" option, we also don't show the context menu
1695 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1696 return;
1698 // if the context menu is invoked through the keyboard, we have to use
1699 // a calculated position on where to anchor the menu on
1700 if ((point.x == -1) && (point.y == -1))
1702 CRect rect;
1703 GetItemRect(selIndex, &rect, LVIR_LABEL);
1704 ClientToScreen(&rect);
1705 point = rect.CenterPoint();
1707 m_nSearchIndex = selIndex;
1709 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1711 POSITION pos = GetFirstSelectedItemPosition();
1712 int FirstSelect = GetNextSelectedItem(pos);
1713 if (FirstSelect < 0)
1714 return;
1716 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1717 if (pSelLogEntry == nullptr)
1718 return;
1720 int LastSelect = -1;
1721 UINT selectedCount = 1;
1722 while (pos)
1724 LastSelect = GetNextSelectedItem(pos);
1725 ++selectedCount;
1728 ASSERT(GetSelectedCount() == selectedCount);
1730 #if 0
1731 GitRev revSelected = pSelLogEntry->Rev;
1732 GitRev revPrevious = git_revnum_t(revSelected)-1;
1733 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1735 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1737 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1738 if (changedpath->lCopyFromRev)
1739 revPrevious = changedpath->lCopyFromRev;
1742 GitRev revSelected2;
1743 if (pos)
1745 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1746 revSelected2 = pLogEntry->Rev;
1748 bool bAllFromTheSameAuthor = true;
1749 CString firstAuthor;
1750 CLogDataVector selEntries;
1751 GitRev revLowest, revHighest;
1752 GitRevRangeArray revisionRanges;
1754 POSITION pos = GetFirstSelectedItemPosition();
1755 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1756 revisionRanges.AddRevision(pLogEntry->Rev);
1757 selEntries.push_back(pLogEntry);
1758 firstAuthor = pLogEntry->sAuthor;
1759 revLowest = pLogEntry->Rev;
1760 revHighest = pLogEntry->Rev;
1761 while (pos)
1763 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1764 revisionRanges.AddRevision(pLogEntry->Rev);
1765 selEntries.push_back(pLogEntry);
1766 if (firstAuthor.Compare(pLogEntry->sAuthor))
1767 bAllFromTheSameAuthor = false;
1768 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1769 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1773 #endif
1775 //entry is selected, now show the popup menu
1776 CIconMenu popup;
1777 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1779 if (popup.CreatePopupMenu())
1781 bool isHeadCommit = (pSelLogEntry->m_CommitHash == m_HeadHash);
1782 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1783 CTGitPath workingTree(g_Git.m_CurrentDir);
1784 bool isMergeActive = workingTree.IsMergeActive();
1785 bool isBisectActive = workingTree.IsBisectActive();
1786 bool isStash = IsOnStash(FirstSelect);
1787 GIT_REV_LIST parentHash;
1788 GetParentHashes(pSelLogEntry, parentHash);
1790 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1791 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1793 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SQUASH) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)) && FirstSelect != GetItemCount() - 1 && LastSelect != GetItemCount() - 1 && (m_bIsCherryPick || pSelLogEntry->ParentsCount() == 1))
1794 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1796 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1797 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1799 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1800 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1802 if (m_ContextMenuMask & (GetContextMenuBit(ID_REBASE_SKIP) | GetContextMenuBit(ID_REBASE_EDIT) | GetContextMenuBit(ID_REBASE_SQUASH) | GetContextMenuBit(ID_REBASE_PICK)) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1803 popup.AppendMenu(MF_SEPARATOR, NULL);
1805 if (selectedCount == 1)
1808 bool requiresSeparator = false;
1809 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1811 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1813 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1814 requiresSeparator = true;
1817 else
1819 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1821 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1822 requiresSeparator = true;
1824 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1826 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1827 requiresSeparator = true;
1831 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1833 if (parentHash.size() == 1)
1835 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1836 requiresSeparator = true;
1838 else if (parentHash.size() > 1)
1840 blamemenu.CreatePopupMenu();
1841 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1842 for (size_t i = 0; i < parentHash.size(); ++i)
1844 CString str;
1845 str.Format(IDS_PARENT, i + 1);
1846 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1848 requiresSeparator = true;
1852 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1854 if (parentHash.size() == 1)
1856 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1857 requiresSeparator = true;
1859 else if (parentHash.size() > 1)
1861 gnudiffmenu.CreatePopupMenu();
1862 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1864 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1865 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1866 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1868 for (size_t i = 0; i < parentHash.size(); ++i)
1870 CString str;
1871 str.Format(IDS_PARENT, i + 1);
1872 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1874 requiresSeparator = true;
1878 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1880 if (parentHash.size() == 1)
1882 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1883 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1884 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1885 requiresSeparator = true;
1887 else if (parentHash.size() > 1)
1889 diffmenu.CreatePopupMenu();
1890 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1891 for (size_t i = 0; i < parentHash.size(); ++i)
1893 CString str;
1894 str.Format(IDS_PARENT, i + 1);
1895 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1896 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1898 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1899 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1902 requiresSeparator = true;
1906 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1908 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1909 requiresSeparator = true;
1912 if (requiresSeparator)
1914 popup.AppendMenu(MF_SEPARATOR, NULL);
1915 requiresSeparator = false;
1918 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1920 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1922 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1923 requiresSeparator = true;
1927 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1929 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1931 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1932 requiresSeparator = true;
1935 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1937 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1938 requiresSeparator = true;
1942 if (requiresSeparator)
1944 popup.AppendMenu(MF_SEPARATOR, NULL);
1945 requiresSeparator = false;
1948 if (isBisectActive)
1950 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1951 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1953 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1954 requiresSeparator = true;
1957 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1959 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1960 requiresSeparator = true;
1962 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1964 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1965 requiresSeparator = true;
1969 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1971 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1973 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1974 requiresSeparator = true;
1978 if (requiresSeparator)
1980 popup.AppendMenu(MF_SEPARATOR, NULL);
1981 requiresSeparator = false;
1984 if (pSelLogEntry->m_CommitHash.IsEmpty())
1986 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
1987 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
1989 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
1990 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
1992 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
1993 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
1995 popup.AppendMenu(MF_SEPARATOR, NULL);
1997 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
1998 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2000 popup.AppendMenu(MF_SEPARATOR, NULL);
2004 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2005 // {
2006 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2007 // }
2008 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2009 // {
2010 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2011 // }
2012 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2013 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2014 // {
2015 // popup.AppendMenu(MF_SEPARATOR, NULL);
2016 // }
2018 CString str;
2019 //if (m_hasWC)
2020 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2022 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2024 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2025 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2027 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2028 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2030 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2032 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2034 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2036 size_t index = (size_t)-1;
2037 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2038 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2039 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2042 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2044 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2045 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2048 // Add Switch Branch express Menu
2049 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2050 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2053 std::vector<const CString*> branchs;
2054 auto addCheck = [&](const CString& ref)
2056 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2057 return;
2058 branchs.push_back(&ref);
2060 size_t index = (size_t)-1;
2061 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2062 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2063 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2064 else
2065 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2067 CString str2;
2068 str2.LoadString(IDS_SWITCH_BRANCH);
2070 if(branchs.size() == 1)
2072 str2 += L' ';
2073 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2074 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2076 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2079 else if(branchs.size() > 1)
2081 subbranchmenu.CreatePopupMenu();
2082 for (size_t i = 0 ; i < branchs.size(); ++i)
2084 if (*branchs[i] != currentBranch)
2086 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2087 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2091 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2095 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2097 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2098 size_t index = (size_t)-1;
2099 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2100 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2101 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2104 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2106 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2108 size_t index = (size_t)-1;
2109 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2110 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2111 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2114 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2115 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2117 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2119 if (pSelLogEntry->m_CommitHash != m_HeadHash && m_hasWC && !isMergeActive && !isStash)
2120 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2121 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2123 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2124 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2126 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2128 if (parentHash.size() == 1)
2129 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2130 else if (parentHash.size() > 1)
2132 revertmenu.CreatePopupMenu();
2133 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2135 for (size_t i = 0; i < parentHash.size(); ++i)
2137 CString str2;
2138 str2.Format(IDS_PARENT, i + 1);
2139 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2144 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2145 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2147 popup.AppendMenu(MF_SEPARATOR, NULL);
2151 if(!pSelLogEntry->m_Ref.IsEmpty())
2153 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2154 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2155 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2156 if (selectedCount <= 2)
2157 popup.AppendMenu(MF_SEPARATOR, NULL);
2160 if (selectedCount >= 2)
2162 bool bAddSeparator = false;
2163 if ((selectedCount == 2) || IsSelectionContinuous())
2165 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2167 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2168 bAddSeparator = true;
2172 if (selectedCount == 2)
2174 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2176 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2177 bAddSeparator = true;
2180 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2182 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2183 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2184 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2185 CString menu;
2186 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2187 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2188 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2189 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2190 bAddSeparator = true;
2194 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2196 bAddSeparator = true;
2197 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2200 if (bAddSeparator)
2202 popup.AppendMenu(MF_SEPARATOR, NULL);
2203 bAddSeparator = false;
2206 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2207 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2209 if (bAddSeparator)
2210 popup.AppendMenu(MF_SEPARATOR, NULL);
2213 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2215 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2216 popup.AppendMenu(MF_SEPARATOR, NULL);
2219 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2221 bool bAddSeparator = false;
2222 if (selectedCount >= 2 && IsSelectionContinuous())
2224 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2226 CString head;
2227 int headindex;
2228 headindex = this->GetHeadIndex();
2229 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2231 head.Format(L"HEAD~%d", FirstSelect - headindex);
2232 CGitHash hashFirst;
2233 int ret = g_Git.GetHash(hashFirst, head);
2234 head.Format(L"HEAD~%d",LastSelect-headindex);
2235 CGitHash hash;
2236 ret = ret || g_Git.GetHash(hash, head);
2237 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2238 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2239 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2241 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2242 bAddSeparator = true;
2247 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2248 if (selectedCount >= 2)
2249 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2250 else
2251 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2252 bAddSeparator = true;
2255 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2256 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2257 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2258 bAddSeparator = true;
2261 if (bAddSeparator)
2262 popup.AppendMenu(MF_SEPARATOR, NULL);
2265 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2267 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2268 popup.AppendMenu(MF_SEPARATOR, NULL);
2271 if (selectedCount == 1)
2273 bool bAddSeparator = false;
2274 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2276 // show the push-option only if the log entry has an associated local branch
2277 bool isLocal = find_if(m_HashMap[pSelLogEntry->m_CommitHash], [](const CString& ref) { return CStringUtils::StartsWith(ref, L"refs/heads/") || CStringUtils::StartsWith(ref, L"refs/tags/"); }) != m_HashMap[pSelLogEntry->m_CommitHash].cend();
2278 if (isLocal || showExtendedMenu)
2280 CString str;
2281 str.LoadString(IDS_MENUPUSH);
2283 CString branch;
2284 size_t index = (size_t)-1;
2285 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2286 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2287 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2288 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2290 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2292 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2293 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2295 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2296 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2298 bAddSeparator = true;
2301 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2303 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2304 bAddSeparator = true;
2308 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2310 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2312 std::vector<const CString*> branchs;
2313 auto addCheck = [&](const CString& ref)
2315 if (ref == currentBranch)
2316 return;
2317 branchs.push_back(&ref);
2319 size_t index = (size_t)-1;
2320 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2321 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2322 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2323 else
2324 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2326 CString str;
2327 if (branchs.size() == 1)
2329 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2330 str += L' ';
2331 str += *branchs[0];
2332 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2333 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2334 bAddSeparator = true;
2336 else if (branchs.size() > 1)
2338 str.LoadString(IDS_DELETE_BRANCHTAG);
2339 submenu.CreatePopupMenu();
2340 for (size_t i = 0; i < branchs.size(); ++i)
2342 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2343 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2345 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2346 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2348 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2349 bAddSeparator = true;
2352 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2353 if (bAddSeparator)
2354 popup.AppendMenu(MF_SEPARATOR, NULL);
2355 } // selectedCount == 1
2357 CIconMenu clipSubMenu;
2358 if (!clipSubMenu.CreatePopupMenu())
2359 return;
2360 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2362 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2363 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2364 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2365 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2366 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2367 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2368 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2369 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2370 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2372 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2373 size_t index = (size_t)-1;
2374 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2375 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2376 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2379 CString temp;
2380 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2381 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2384 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2385 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2387 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2388 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2390 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2391 // DialogEnableWindow(IDOK, FALSE);
2392 // SetPromptApp(&theApp);
2394 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2396 // EnableOKButton();
2397 } // if (popup.CreatePopupMenu())
2400 bool CGitLogListBase::IsSelectionContinuous()
2402 if ( GetSelectedCount()==1 )
2404 // if only one revision is selected, the selection is of course
2405 // continuous
2406 return true;
2409 POSITION pos = GetFirstSelectedItemPosition();
2410 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2411 if (bContinuous)
2413 int itemindex = GetNextSelectedItem(pos);
2414 while (pos)
2416 int nextindex = GetNextSelectedItem(pos);
2417 if (nextindex - itemindex > 1)
2419 bContinuous = false;
2420 break;
2422 itemindex = nextindex;
2425 return bContinuous;
2428 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2430 CString sClipdata;
2431 POSITION pos = GetFirstSelectedItemPosition();
2432 if (pos)
2434 CString sRev;
2435 sRev.LoadString(IDS_LOG_REVISION);
2436 CString sAuthor;
2437 sAuthor.LoadString(IDS_LOG_AUTHOR);
2438 CString sDate;
2439 sDate.LoadString(IDS_LOG_DATE);
2440 CString sMessage;
2441 sMessage.LoadString(IDS_LOG_MESSAGE);
2442 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2443 bool first = true;
2444 while (pos)
2446 CString sLogCopyText;
2447 CString sPaths;
2448 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2450 if (toCopy == ID_COPYCLIPBOARDFULL)
2452 sPaths = L"----\r\n";
2453 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2455 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2456 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2458 sPaths += L' ';
2459 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2461 sPaths += L"\r\n";
2463 sPaths.Trim();
2464 sPaths += L"\r\n";
2467 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2469 CString sNotesTags;
2470 if (!pLogEntry->m_Notes.IsEmpty())
2472 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2473 sNotesTags += L":\n";
2474 sNotesTags += pLogEntry->m_Notes;
2475 sNotesTags.Replace(L"\n", L"\r\n");
2477 CString tagInfo = GetTagInfo(pLogEntry);
2478 if (!tagInfo.IsEmpty())
2480 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2481 tagInfo.Replace(L"\n", L"\r\n");
2482 sNotesTags += tagInfo;
2485 sLogCopyText.Format(L"%s: %s\r\n%s: %s <%s>\r\n%s: %s\r\n%s:\r\n%s\r\n%s%s\r\n",
2486 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2487 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2488 (LPCTSTR)sDate,
2489 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2490 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2491 (LPCTSTR)sNotesTags,
2492 (LPCTSTR)sPaths);
2493 sClipdata += sLogCopyText;
2495 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2497 if (!first)
2498 sClipdata += L"\r\n";
2499 sClipdata += pLogEntry->GetAuthorName();
2500 sClipdata += L" <";
2501 sClipdata += pLogEntry->GetAuthorEmail();
2502 sClipdata += L">";
2504 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2506 if (!first)
2507 sClipdata += L"\r\n";
2508 sClipdata += pLogEntry->GetAuthorName();
2510 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2512 if (!first)
2513 sClipdata += L"\r\n";
2514 sClipdata += pLogEntry->GetAuthorEmail();
2517 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2519 sClipdata += L"* ";
2520 sClipdata += pLogEntry->GetSubjectBody(true);
2521 sClipdata += L"\r\n\r\n";
2523 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2525 sClipdata += L"* ";
2526 sClipdata += pLogEntry->GetSubject().Trim();
2527 sClipdata += L"\r\n\r\n";
2529 else
2531 if (!first)
2532 sClipdata += L"\r\n";
2533 sClipdata += pLogEntry->m_CommitHash;
2536 first = false;
2538 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2542 void CGitLogListBase::DiffSelectedRevWithPrevious()
2544 if (m_bThreadRunning)
2545 return;
2547 int FirstSelect=-1, LastSelect=-1;
2548 POSITION pos = GetFirstSelectedItemPosition();
2549 FirstSelect = GetNextSelectedItem(pos);
2550 while(pos)
2551 LastSelect = GetNextSelectedItem(pos);
2553 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2556 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2558 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2559 *pResult = -1;
2561 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2562 return;
2563 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2564 return;
2565 if (!pFindInfo->lvfi.psz)
2566 return;
2567 #if 0
2568 CString sCmp = pFindInfo->lvfi.psz;
2569 CString sRev;
2570 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2572 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2573 sRev.Format(L"%ld", pLogEntry->Rev);
2574 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2576 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2578 *pResult = i;
2579 return;
2582 else
2584 if (sCmp.Compare(sRev)==0)
2586 *pResult = i;
2587 return;
2591 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2593 for (int i=0; i<pFindInfo->iStart; ++i)
2595 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2596 sRev.Format(L"%ld", pLogEntry->Rev);
2597 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2599 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2601 *pResult = i;
2602 return;
2605 else
2607 if (sCmp.Compare(sRev)==0)
2609 *pResult = i;
2610 return;
2615 #endif
2616 *pResult = -1;
2619 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2621 ClearText();
2623 this->m_arShownList.SafeRemoveAll();
2625 this->m_logEntries.ClearAll();
2626 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2627 return -1;
2629 SetItemCountEx((int)m_logEntries.size());
2631 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2633 if(m_IsOldFirst)
2635 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2636 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2638 else
2640 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2641 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2645 ReloadHashMap();
2647 if(path)
2648 m_Path=*path;
2649 return 0;
2652 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2654 ClearText();
2656 m_arShownList.SafeRemoveAll();
2658 m_logEntries.ClearAll();
2659 if (m_logEntries.Fill(hashes))
2660 return -1;
2662 SetItemCountEx((int)m_logEntries.size());
2664 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2666 if (m_IsOldFirst)
2668 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2669 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2671 else
2673 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2674 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2678 ReloadHashMap();
2680 return 0;
2683 int CGitLogListBase::BeginFetchLog()
2685 ClearText();
2687 this->m_arShownList.SafeRemoveAll();
2689 this->m_logEntries.ClearAll();
2691 this->m_LogCache.ClearAllParent();
2693 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2695 CTGitPath *path;
2696 if(this->m_Path.IsEmpty())
2697 path = nullptr;
2698 else
2699 path=&this->m_Path;
2701 int mask;
2702 mask = CGit::LOG_INFO_ONLY_HASH;
2703 if (m_bIncludeBoundaryCommits)
2704 mask |= CGit::LOG_INFO_BOUNDARY;
2705 // if(this->m_bAllBranch)
2706 mask |= m_ShowMask ;
2708 if(m_bShowWC)
2710 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2711 ResetWcRev();
2712 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2715 if (m_sRange.IsEmpty())
2716 m_sRange = L"HEAD";
2718 #if 0 /* use tortoiegit filter */
2719 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2720 data.m_Author = this->m_sFilterText;
2722 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2723 data.m_MessageFilter = this->m_sFilterText;
2725 data.m_IsRegex = m_bFilterWithRegex;
2726 #endif
2728 // follow does not work for directories
2729 if (!path || path->IsDirectory())
2730 mask &= ~CGit::LOG_INFO_FOLLOW;
2731 // follow does not work with all branches 8at least in TGit)
2732 if (mask & CGit::LOG_INFO_FOLLOW)
2733 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2735 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2737 //this->m_logEntries.ParserFromLog();
2738 if(IsInWorkingThread())
2740 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2742 else
2744 SetItemCountEx((int)m_logEntries.size());
2749 [] { git_init(); } ();
2751 catch (char* msg)
2753 CString err(msg);
2754 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2755 return -1;
2758 if (!g_Git.CanParseRev(m_sRange))
2760 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2761 return 0;
2763 // if show all branches, pick any ref as dummy entry ref
2764 STRING_VECTOR list;
2765 if (g_Git.GetRefList(list))
2766 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2767 if (list.empty())
2768 return 0;
2770 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2773 g_Git.m_critGitDllSec.Lock();
2774 try {
2775 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2777 g_Git.m_critGitDllSec.Unlock();
2778 return -1;
2781 catch (char* msg)
2783 g_Git.m_critGitDllSec.Unlock();
2784 CString err(msg);
2785 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2786 return -1;
2788 g_Git.m_critGitDllSec.Unlock();
2790 return 0;
2793 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2795 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2797 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2799 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2801 DiffSelectedRevWithPrevious();
2802 return TRUE;
2805 #if 0
2806 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2808 DiffSelectedFile();
2809 return TRUE;
2811 #endif
2813 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2815 // select all entries
2816 for (int i=0; i<GetItemCount(); ++i)
2817 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2818 return TRUE;
2821 #if 0
2822 if (m_hAccel && !bSkipAccelerator)
2824 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2825 if (ret)
2826 return TRUE;
2829 #endif
2830 //m_tooltips.RelayEvent(pMsg);
2831 return __super::PreTranslateMessage(pMsg);
2834 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2836 // a double click on an entry in the revision list has happened
2837 *pResult = 0;
2839 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2840 DiffSelectedRevWithPrevious();
2843 void CGitLogListBase::FetchLogAsync(void* data)
2845 ReloadHashMap();
2846 m_ProcData=data;
2847 StartLoadingThread();
2850 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2852 return ((CGitLogListBase*)pVoid)->LogThread();
2855 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2857 //CTime time;
2858 oldest=CTime::GetCurrentTime();
2859 latest=CTime(1971,1,2,0,0,0);
2860 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2862 if(m_logEntries[i].IsEmpty())
2863 continue;
2865 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2866 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2868 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2869 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2873 if(latest<oldest)
2874 latest=oldest;
2877 UINT CGitLogListBase::LogThread()
2879 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2881 ULONGLONG t1,t2;
2883 if(BeginFetchLog())
2885 InterlockedExchange(&m_bThreadRunning, FALSE);
2886 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2888 return 1;
2891 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
2892 bool bRegex = false;
2893 if (m_bFilterWithRegex)
2894 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2896 TRACE(L"\n===Begin===\n");
2897 //Update work copy item;
2899 if (!m_logEntries.empty())
2901 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2903 m_arShownList.SafeAdd(pRev);
2907 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2909 // store commit number of the last selected commit/line before the refresh or -1
2910 int lastSelectedHashNItem = -1;
2911 if (m_lastSelectedHash.IsEmpty())
2912 lastSelectedHashNItem = 0;
2914 int ret = 0;
2916 bool shouldWalk = true;
2917 if (!g_Git.CanParseRev(m_sRange))
2919 // walk revisions if show all branches and there exists any ref
2920 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2921 shouldWalk = false;
2922 else
2924 STRING_VECTOR list;
2925 if (g_Git.GetRefList(list))
2926 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2927 if (list.empty())
2928 shouldWalk = false;
2932 if (shouldWalk)
2934 g_Git.m_critGitDllSec.Lock();
2935 if (!m_DllGitLog)
2937 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2938 g_Git.m_critGitDllSec.Unlock();
2939 InterlockedExchange(&m_bThreadRunning, FALSE);
2940 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2941 return 1;
2943 int total = 0;
2946 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2947 total = git_get_log_estimate_commit_count(m_DllGitLog);
2949 catch (char* msg)
2951 CString err(msg);
2952 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2953 ret = -1;
2955 g_Git.m_critGitDllSec.Unlock();
2957 GIT_COMMIT commit;
2958 t2 = t1 = GetTickCount64();
2959 int oldprecentage = 0;
2960 size_t oldsize = m_logEntries.size();
2961 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2962 while (ret== 0 && !m_bExitThread)
2964 g_Git.m_critGitDllSec.Lock();
2967 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2969 catch (char* msg)
2971 g_Git.m_critGitDllSec.Unlock();
2972 CString err(msg);
2973 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2974 break;
2976 g_Git.m_critGitDllSec.Unlock();
2978 if(ret)
2980 if (ret != -2) // other than end of revision walking
2981 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2982 break;
2985 if (commit.m_ignore == 1)
2987 git_free_commit(&commit);
2988 continue;
2991 //printf("%s\r\n",commit.GetSubject());
2992 if(m_bExitThread)
2993 break;
2995 CGitHash hash(commit.m_hash);
2997 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
2998 pRev->m_GitCommit = commit;
2999 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3001 char* note = nullptr;
3002 g_Git.m_critGitDllSec.Lock();
3005 git_get_notes(commit.m_hash, &note);
3007 catch (char* msg)
3009 g_Git.m_critGitDllSec.Unlock();
3010 CString err(msg);
3011 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3012 break;
3014 g_Git.m_critGitDllSec.Unlock();
3016 if(note)
3018 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3019 free(note);
3020 note = nullptr;
3023 if(!pRev->m_IsDiffFiles)
3025 pRev->m_CallDiffAsync = DiffAsync;
3028 pRev->ParserParentFromCommit(&commit);
3029 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3031 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3033 const CGitHash &parentHash = pRev->m_ParentHash[i];
3034 auto it = commitChildren.find(parentHash);
3035 if (it == commitChildren.end())
3036 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3037 it->second.insert(pRev->m_CommitHash);
3041 #ifdef DEBUG
3042 pRev->DbgPrint();
3043 TRACE(L"\n");
3044 #endif
3046 bool visible = true;
3047 if (HasFilterText())
3049 if(!IsMatchFilter(bRegex,pRev,pat))
3050 visible = false;
3052 if (visible && !ShouldShowFilter(pRev, commitChildren))
3053 visible = false;
3054 this->m_critSec.Lock();
3055 m_logEntries.append(hash, visible);
3056 if (visible)
3057 m_arShownList.SafeAdd(pRev);
3058 this->m_critSec.Unlock();
3060 if (!visible)
3061 continue;
3063 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3064 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3066 t2 = GetTickCount64();
3068 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3070 //update UI
3071 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3072 if(percent > 99)
3073 percent =99;
3074 if(percent < GITLOG_START)
3075 percent = GITLOG_START +1;
3077 oldsize = m_logEntries.size();
3078 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3080 //if( percent > oldprecentage )
3082 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3083 oldprecentage = percent;
3086 if (lastSelectedHashNItem >= 0)
3087 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3089 t1 = t2;
3092 g_Git.m_critGitDllSec.Lock();
3093 git_close_log(m_DllGitLog);
3094 g_Git.m_critGitDllSec.Unlock();
3098 if (m_bExitThread)
3100 InterlockedExchange(&m_bThreadRunning, FALSE);
3101 return 0;
3104 //Update UI;
3105 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3107 if (lastSelectedHashNItem >= 0)
3108 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3110 if (this->m_hWnd)
3111 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3113 InterlockedExchange(&m_bThreadRunning, FALSE);
3115 return 0;
3118 void CGitLogListBase::FetchRemoteList()
3120 STRING_VECTOR remoteList;
3121 m_SingleRemote.Empty();
3122 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3123 m_SingleRemote = remoteList[0];
3126 void CGitLogListBase::FetchTrackingBranchList()
3128 m_TrackingMap.clear();
3129 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3131 for (const auto& ref : it->second)
3133 CString branchName;
3134 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3136 CString pullRemote, pullBranch;
3137 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3138 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3139 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3145 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3147 SafeTerminateThread();
3149 this->SetItemCountEx(0);
3150 this->Clear();
3152 ResetWcRev();
3154 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3156 if (m_pMailmap)
3158 git_free_mailmap(m_pMailmap);
3159 git_read_mailmap(&m_pMailmap);
3162 //Update branch and Tag info
3163 ReloadHashMap();
3164 if (m_pFindDialog)
3165 m_pFindDialog->RefreshList();
3166 //Assume Thread have exited
3167 //if(!m_bThreadRunning)
3169 m_logEntries.clear();
3171 if(IsCleanFilter)
3173 m_sFilterText.Empty();
3176 SafeTerminateAsyncDiffThread();
3177 m_AsynDiffListLock.Lock();
3178 m_AsynDiffList.clear();
3179 m_AsynDiffListLock.Unlock();
3180 StartAsyncDiffThread();
3182 StartLoadingThread();
3186 void CGitLogListBase::StartAsyncDiffThread()
3188 if (m_AsyncThreadExit)
3189 return;
3190 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3191 return;
3192 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3193 if (!m_DiffingThread)
3195 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3196 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3200 void CGitLogListBase::StartLoadingThread()
3202 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3203 return;
3204 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3205 InterlockedExchange(&m_bExitThread, FALSE);
3206 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3207 if (!m_LoadingThread)
3209 InterlockedExchange(&m_bThreadRunning, FALSE);
3210 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3211 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3215 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::tr1::wregex& pat, bool bMatchCase /* = false */)
3219 std::tr1::regex_constants::syntax_option_type type = std::tr1::regex_constants::ECMAScript;
3220 if (!bMatchCase)
3221 type |= std::tr1::regex_constants::icase;
3222 pat = std::tr1::wregex(regexp_str, type);
3223 return true;
3225 catch (std::exception&) {}
3226 return false;
3228 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::tr1::wregex& pat)
3230 BOOL result = TRUE;
3231 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3232 CString sRev;
3234 if ((bRegex)&&(m_bFilterWithRegex))
3236 if (m_SelectedFilters & LOGFILTER_BUGID)
3238 if(this->m_bShowBugtraqColumn)
3240 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3242 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3243 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3244 return TRUE;
3248 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3250 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3251 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3252 return TRUE;
3255 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3257 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3258 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3259 return TRUE;
3262 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3264 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3265 return TRUE;
3267 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3268 return TRUE;
3271 if (m_SelectedFilters & LOGFILTER_EMAILS)
3273 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3274 return TRUE;
3276 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3277 return TRUE;
3280 if (m_SelectedFilters & LOGFILTER_REVS)
3282 sRev = pRev->m_CommitHash.ToString();
3283 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3285 return TRUE;
3289 if (m_SelectedFilters & LOGFILTER_NOTES)
3291 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3292 return TRUE;
3295 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3297 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3298 for (const auto& ref : refs)
3300 if (std::regex_search(std::wstring(ref), pat, flags))
3301 return TRUE;
3305 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3307 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3308 return TRUE;
3311 if (m_SelectedFilters & LOGFILTER_PATHS)
3313 CTGitPathList* pathList = nullptr;
3314 if( pRev->m_IsDiffFiles)
3315 pathList = &pRev->GetFiles(this);
3316 else
3318 if(!pRev->m_IsSimpleListReady)
3319 pRev->SafeGetSimpleList(&g_Git);
3322 if(pathList)
3323 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3325 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3326 return true;
3327 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3328 return true;
3331 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3333 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3334 return true;
3338 else
3340 CString find = m_sFilterText;
3341 if (!m_bFilterCaseSensitively)
3342 find.MakeLower();
3343 result = find[0] == '!' ? FALSE : TRUE;
3344 if (!result)
3345 find = find.Mid(1);
3347 if (m_SelectedFilters & LOGFILTER_BUGID)
3349 if(this->m_bShowBugtraqColumn)
3351 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3353 if (!m_bFilterCaseSensitively)
3354 sBugIds.MakeLower();
3355 if ((sBugIds.Find(find) >= 0))
3356 return result;
3360 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3362 CString msg = pRev->GetSubject();
3364 if (!m_bFilterCaseSensitively)
3365 msg = msg.MakeLower();
3366 if ((msg.Find(find) >= 0))
3367 return result;
3370 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3372 CString msg = pRev->GetBody();
3374 if (!m_bFilterCaseSensitively)
3375 msg = msg.MakeLower();
3376 if ((msg.Find(find) >= 0))
3377 return result;
3380 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3382 CString msg = pRev->GetAuthorName();
3383 if (!m_bFilterCaseSensitively)
3384 msg = msg.MakeLower();
3385 if ((msg.Find(find) >= 0))
3386 return result;
3389 if (m_SelectedFilters & LOGFILTER_EMAILS)
3391 CString msg = pRev->GetAuthorEmail();
3392 if (!m_bFilterCaseSensitively)
3393 msg = msg.MakeLower();
3394 if ((msg.Find(find) >= 0))
3395 return result;
3398 if (m_SelectedFilters & LOGFILTER_NOTES)
3400 CString msg = pRev->m_Notes;
3401 if (!m_bFilterCaseSensitively)
3402 msg = msg.MakeLower();
3403 if ((msg.Find(find) >= 0))
3404 return result;
3407 if (m_SelectedFilters & LOGFILTER_REVS)
3409 sRev = pRev->m_CommitHash.ToString();
3410 if ((sRev.Find(find) >= 0))
3411 return result;
3414 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3416 CString msg = GetTagInfo(pRev);
3417 if (!m_bFilterCaseSensitively)
3418 msg = msg.MakeLower();
3419 if ((msg.Find(find) >= 0))
3420 return result;
3423 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3425 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3426 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3428 if (it->Find(find) >= 0)
3429 return result;
3433 if (m_SelectedFilters & LOGFILTER_PATHS)
3435 CTGitPathList* pathList = nullptr;
3436 if( pRev->m_IsDiffFiles)
3437 pathList = &pRev->GetFiles(this);
3438 else
3440 if(!pRev->m_IsSimpleListReady)
3441 pRev->SafeGetSimpleList(&g_Git);
3443 if(pathList)
3444 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3446 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3447 CString path = cpath->GetGitOldPathString();
3448 if (!m_bFilterCaseSensitively)
3449 path.MakeLower();
3450 if ((path.Find(find)>=0))
3451 return result;
3452 path = cpath->GetGitPathString();
3453 if (!m_bFilterCaseSensitively)
3454 path.MakeLower();
3455 if ((path.Find(find)>=0))
3456 return result;
3459 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3461 CString path = pRev->m_SimpleFileList[i];
3462 if (!m_bFilterCaseSensitively)
3463 path.MakeLower();
3464 if ((path.Find(find)>=0))
3465 return result;
3468 } // else (from if (bRegex))
3469 return !result;
3472 static bool CStringStartsWith(const CString &str, const CString &prefix)
3474 return str.Left(prefix.GetLength()) == prefix;
3476 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3478 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3479 return true;
3481 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3483 // Keep all refs.
3484 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3485 for (size_t i = 0; i < refList.size(); ++i)
3487 const CString &str = refList[i];
3488 if (CStringStartsWith(str, L"refs/heads/"))
3490 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3491 return true;
3493 else if (CStringStartsWith(str, L"refs/remotes/"))
3495 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3496 return true;
3498 else if (CStringStartsWith(str, L"refs/tags/"))
3500 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3501 return true;
3503 else if (CStringStartsWith(str, L"refs/stash"))
3505 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3506 return true;
3508 else if (CStringStartsWith(str, L"refs/bisect/"))
3510 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3511 return true;
3514 // Keep the head too.
3515 if (pRev->m_CommitHash == m_HeadHash)
3516 return true;
3519 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3521 if (pRev->ParentsCount() > 1)
3522 return true;
3523 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3524 if (childrenIt != commitChildren.end())
3526 const std::unordered_set<CGitHash> &children = childrenIt->second;
3527 if (children.size() > 1)
3528 return true;
3531 return false;
3534 void CGitLogListBase::ShowGraphColumn(bool bShow)
3536 // HACK to hide graph column
3537 if (bShow)
3538 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3539 else
3540 SetColumnWidth(0, 0);
3543 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3545 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3546 return L"";
3548 CString tagInfo;
3549 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3550 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3552 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3553 continue;
3554 if (!CStringUtils::EndsWith((*it), L"^{}"))
3555 continue;
3557 CString cmd;
3558 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3559 CString output;
3560 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3561 continue;
3563 // parse tag date
3566 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3567 int pos1 = output.Find(L'>');
3568 if (pos1 < 0)
3569 break;
3570 ++pos1;
3571 if (output[pos1] == L' ')
3572 ++pos1;
3573 int pos2 = output.Find(L'\n', pos1);
3574 if (pos2 < 0)
3575 break;
3577 CString str = output.Mid(pos1, pos2 - pos1);
3578 wchar_t* pEnd = nullptr;
3579 errno = 0;
3580 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3581 if (str.GetBuffer() == pEnd)
3582 break;
3583 if (errno == ERANGE)
3584 break;
3586 output.Delete(pos1, pos2 - pos1);
3587 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3588 } while (0);
3589 output.Trim().AppendChar(L'\n');
3590 tagInfo += output;
3592 return tagInfo;
3595 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3597 pShownlist->SafeRemoveAll();
3599 std::tr1::wregex pat;//(L"Remove", tr1::regex_constants::icase);
3600 bool bRegex = false;
3601 if (m_bFilterWithRegex)
3602 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3604 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_any;
3605 CString sRev;
3606 for (DWORD i=0; i<m_logEntries.size(); ++i)
3608 if ((bRegex)&&(m_bFilterWithRegex))
3610 #if 0
3611 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3613 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3614 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3616 pShownlist->SafeAdd(m_logEntries[i]);
3617 continue;
3620 #endif
3621 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3623 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3624 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3626 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3627 continue;
3630 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3632 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3633 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3635 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3636 continue;
3639 if (m_SelectedFilters & LOGFILTER_PATHS)
3641 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3643 bool bGoing = true;
3644 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3646 CTGitPath cpath = pathList[cpPathIndex];
3647 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3649 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3650 bGoing = false;
3651 continue;
3653 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3655 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3656 bGoing = false;
3657 continue;
3659 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3661 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3662 bGoing = false;
3663 continue;
3667 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3669 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3671 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3672 continue;
3675 if (m_SelectedFilters & LOGFILTER_EMAILS)
3677 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3679 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3680 continue;
3683 if (m_SelectedFilters & LOGFILTER_REVS)
3685 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3686 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3688 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3689 continue;
3692 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3694 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3695 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3697 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3699 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3700 continue;
3704 } // if (bRegex)
3705 else
3707 CString find = m_sFilterText;
3708 if (!m_bFilterCaseSensitively)
3709 find.MakeLower();
3710 #if 0
3711 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3713 CString sBugIDs = m_logEntries[i]->sBugIDs;
3715 if (!m_bFilterCaseSensitively)
3716 sBugIDs = sBugIDs.MakeLower();
3717 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3719 pShownlist->SafeAdd(m_logEntries[i]);
3720 continue;
3723 #endif
3724 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3726 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3728 if (!m_bFilterCaseSensitively)
3729 msg = msg.MakeLower();
3730 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3732 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3733 continue;
3736 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3738 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3740 if (!m_bFilterCaseSensitively)
3741 msg = msg.MakeLower();
3742 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3744 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3745 continue;
3748 if (m_SelectedFilters & LOGFILTER_PATHS)
3750 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3752 bool bGoing = true;
3753 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3755 CTGitPath cpath = pathList[cpPathIndex];
3756 CString path = cpath.GetGitOldPathString();
3757 if (!m_bFilterCaseSensitively)
3758 path.MakeLower();
3759 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3761 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3762 bGoing = false;
3763 continue;
3765 path = cpath.GetGitPathString();
3766 if (!m_bFilterCaseSensitively)
3767 path.MakeLower();
3768 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3770 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3771 bGoing = false;
3772 continue;
3774 path = cpath.GetActionName();
3775 if (!m_bFilterCaseSensitively)
3776 path.MakeLower();
3777 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3779 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3780 bGoing = false;
3781 continue;
3785 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3787 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3788 if (!m_bFilterCaseSensitively)
3789 msg = msg.MakeLower();
3790 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3792 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3793 continue;
3796 if (m_SelectedFilters & LOGFILTER_EMAILS)
3798 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3799 if (!m_bFilterCaseSensitively)
3800 msg = msg.MakeLower();
3801 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3803 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3804 continue;
3807 if (m_SelectedFilters & LOGFILTER_REVS)
3809 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3810 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3812 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3813 continue;
3816 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3818 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3819 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3821 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3823 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3824 continue;
3828 } // else (from if (bRegex))
3829 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3832 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3835 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3837 if(m_From == -1)
3838 if(m_To == -1)
3839 return true;
3840 else
3841 return time <= m_To;
3842 else
3843 if(m_To == -1)
3844 return time >= m_From;
3845 else
3846 return ((time >= m_From)&&(time <= m_To));
3848 return TRUE; /* git dll will filter time range */
3850 // return TRUE;
3853 void CGitLogListBase::StartFilter()
3855 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3856 RecalculateShownList(&m_arShownList);
3857 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3860 DeleteAllItems();
3861 SetItemCountEx(ShownCountWithStopped());
3862 RedrawItems(0, ShownCountWithStopped());
3863 Invalidate();
3866 void CGitLogListBase::RemoveFilter()
3868 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3870 m_arShownList.SafeRemoveAll();
3872 // reset the time filter too
3873 #if 0
3874 m_timFrom = (__time64_t(m_tFrom));
3875 m_timTo = (__time64_t(m_tTo));
3876 m_DateFrom.SetTime(&m_timFrom);
3877 m_DateTo.SetTime(&m_timTo);
3878 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3879 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3880 #endif
3882 for (DWORD i=0; i<m_logEntries.size(); ++i)
3884 if(this->m_IsOldFirst)
3885 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3886 else
3887 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3889 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3890 DeleteAllItems();
3891 SetItemCountEx(ShownCountWithStopped());
3892 RedrawItems(0, ShownCountWithStopped());
3894 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3897 void CGitLogListBase::Clear()
3899 m_arShownList.SafeRemoveAll();
3900 DeleteAllItems();
3902 m_logEntries.ClearAll();
3905 void CGitLogListBase::OnDestroy()
3907 SafeTerminateThread();
3908 SafeTerminateAsyncDiffThread();
3910 int retry = 0;
3911 while(m_LogCache.SaveCache())
3913 if(retry > 5)
3914 break;
3915 Sleep(1000);
3917 ++retry;
3919 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3920 // MB_YESNO) == IDNO)
3921 // break;
3924 __super::OnDestroy();
3927 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3929 CRect rect;
3930 int i=(int)wParam;
3931 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3932 this->InvalidateRect(rect);
3934 return 0;
3938 * Save column widths to the registry
3940 void CGitLogListBase::SaveColumnWidths()
3942 // HACK that graph column is always shown
3943 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3945 __super::SaveColumnWidths();
3948 int CGitLogListBase::GetHeadIndex()
3950 if(m_HeadHash.IsEmpty())
3951 return -1;
3953 for (size_t i = 0; i < m_arShownList.size(); ++i)
3955 GitRev* pRev = m_arShownList.SafeGetAt(i);
3956 if(pRev)
3958 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3959 return (int)i;
3962 return -1;
3964 void CGitLogListBase::OnFind()
3966 if (!m_pFindDialog)
3968 m_pFindDialog = new CFindDlg(this);
3969 m_pFindDialog->Create(this);
3973 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3975 if (GetSelectedCount() != 0)
3976 return 0;
3978 CGitHash theSelectedHash = m_lastSelectedHash;
3979 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3980 m_lastSelectedHash = theSelectedHash;
3982 int countPerPage = GetCountPerPage();
3983 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3984 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3985 EnsureVisible((int)itemToSelect, FALSE);
3986 return 0;
3989 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3991 CString* ref = reinterpret_cast<CString*>(wParam);
3992 if (!ref || ref->IsEmpty())
3993 return 1;
3995 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
3997 CGitHash hash;
3998 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
3999 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4001 if (hash.IsEmpty())
4002 return 1;
4004 bool bFound = false;
4005 int cnt = (int)m_arShownList.size();
4006 int i;
4007 for (i = 0; i < cnt; ++i)
4009 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4010 if (pLogEntry && pLogEntry->m_CommitHash == hash)
4012 bFound = true;
4013 break;
4016 if (!bFound)
4017 return 1;
4019 EnsureVisible(i, FALSE);
4020 if (!bShift)
4022 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4023 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4024 SetSelectionMark(i);
4026 else
4028 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4029 if (pLogEntry)
4030 m_highlight = pLogEntry->m_CommitHash;
4032 Invalidate();
4033 UpdateData(FALSE);
4035 return 0;
4038 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4040 ASSERT(m_pFindDialog);
4041 bool bFound = false;
4042 int i=0;
4044 if (m_pFindDialog->IsTerminating())
4046 // invalidate the handle identifying the dialog box.
4047 m_pFindDialog = nullptr;
4048 return 0;
4051 int cnt = (int)m_arShownList.size();
4052 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4054 if(m_pFindDialog->IsRef())
4056 CString str;
4057 str=m_pFindDialog->GetFindString();
4059 CGitHash hash;
4061 if(!str.IsEmpty())
4063 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4064 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4067 if(!hash.IsEmpty())
4069 for (i = 0; i < cnt; ++i)
4071 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4072 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4074 bFound = true;
4075 break;
4079 if (!bFound)
4081 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4082 return 0;
4086 if (m_pFindDialog->FindNext() && !bFound)
4088 //read data from dialog
4089 CString findText = m_pFindDialog->GetFindString();
4090 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4092 std::tr1::wregex pat;
4093 bool bRegex = false;
4094 if (m_pFindDialog->Regex())
4095 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4097 std::tr1::regex_constants::match_flag_type flags = std::tr1::regex_constants::match_not_null;
4099 for (i = m_nSearchIndex + 1; ; ++i)
4101 if (i >= cnt)
4103 i = 0;
4104 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4106 if (m_nSearchIndex >= 0)
4108 if (i == m_nSearchIndex)
4110 ::MessageBeep(0xFFFFFFFF);
4111 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4112 break;
4116 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4118 CString str;
4119 str+=pLogEntry->m_CommitHash.ToString();
4120 str += L'\n';
4122 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4123 if (refList != m_HashMap.cend())
4125 for (const auto& ref : (*refList).second)
4127 str += ref;
4128 str += L'\n';
4132 str+=pLogEntry->GetAuthorEmail();
4133 str += L'\n';
4134 str+=pLogEntry->GetAuthorName();
4135 str += L'\n';
4136 str+=pLogEntry->GetBody();
4137 str += L'\n';
4138 str+=pLogEntry->GetCommitterEmail();
4139 str += L'\n';
4140 str+=pLogEntry->GetCommitterName();
4141 str += L'\n';
4142 str+=pLogEntry->GetSubject();
4143 str += L'\n';
4144 str+=pLogEntry->m_Notes;
4145 str += L'\n';
4146 str+=GetTagInfo(pLogEntry);
4147 str += L'\n';
4150 /*Because changed files list is loaded on demand when gui show,
4151 files will empty when files have not fetched.
4153 we can add it back by using one-way diff(with outnumber changed and rename detect.
4154 here just need changed filename list. one-way is much quicker.
4156 if(pLogEntry->m_IsFull)
4158 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4160 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4161 str += L'\n';
4162 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4163 str += L'\n';
4166 else
4168 if(!pLogEntry->m_IsSimpleListReady)
4169 pLogEntry->SafeGetSimpleList(&g_Git);
4171 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4173 str += pLogEntry->m_SimpleFileList[j];
4174 str += L'\n';
4178 if (bRegex)
4180 if (std::regex_search(std::wstring(str), pat, flags))
4182 bFound = true;
4183 break;
4186 else
4188 if (bMatchCase)
4190 if (str.Find(findText) >= 0)
4192 bFound = true;
4193 break;
4196 else
4198 CString msg = str;
4199 msg = msg.MakeLower();
4200 CString find = findText.MakeLower();
4201 if (msg.Find(find) >= 0)
4203 bFound = TRUE;
4204 break;
4208 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4210 } // if(m_pFindDialog->FindNext())
4211 //UpdateLogInfoLabel();
4213 if (bFound)
4215 m_nSearchIndex = i;
4216 EnsureVisible(i, FALSE);
4217 if (!bShift)
4219 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4220 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4221 SetSelectionMark(i);
4223 else
4225 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4226 if (pLogEntry)
4227 m_highlight = pLogEntry->m_CommitHash;
4229 Invalidate();
4230 //FillLogMessageCtrl();
4231 UpdateData(FALSE);
4234 return 0;
4237 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4239 LVHITTESTINFO lvhitTestInfo;
4241 lvhitTestInfo.pt = point;
4243 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4244 int nSubItem = lvhitTestInfo.iSubItem;
4246 UINT nFlags = lvhitTestInfo.flags;
4248 // nFlags is 0 if the SubItemHitTest fails
4249 // Therefore, 0 & <anything> will equal false
4250 if (nFlags & LVHT_ONITEM)
4252 // Get the client area occupied by this control
4253 RECT rcClient;
4254 GetClientRect(&rcClient);
4256 // Fill in the TOOLINFO structure
4257 pTI->hwnd = m_hWnd;
4258 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4259 pTI->lpszText = LPSTR_TEXTCALLBACK;
4260 pTI->rect = rcClient;
4262 return pTI->uId; // By returning a unique value per listItem,
4263 // we ensure that when the mouse moves over another list item,
4264 // the tooltip will change
4266 else
4268 // Otherwise, we aren't interested, so let the message propagate
4269 return -1;
4273 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4275 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4276 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4278 *pResult = 0;
4280 // Ignore messages from the built in tooltip, we are processing them internally
4281 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4282 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4283 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4284 return FALSE;
4286 // Get the mouse position
4287 const MSG* pMessage = GetCurrentMessage();
4289 CPoint pt;
4290 pt = pMessage->pt;
4291 ScreenToClient(&pt);
4293 // Check if the point falls onto a list item
4294 LVHITTESTINFO lvhitTestInfo;
4295 lvhitTestInfo.pt = pt;
4297 int nItem = SubItemHitTest(&lvhitTestInfo);
4299 if (lvhitTestInfo.flags & LVHT_ONITEM)
4301 // Get branch description first
4302 CString strTipText;
4303 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4305 CString branch;
4306 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4307 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4309 MAP_STRING_STRING descriptions;
4310 g_Git.GetBranchDescriptions(descriptions);
4311 if (descriptions.find(branch) != descriptions.cend())
4313 strTipText.LoadString(IDS_DESCRIPTION);
4314 strTipText += L":\n";
4315 strTipText += descriptions[branch];
4320 bool followMousePos = false;
4321 if (!strTipText.IsEmpty())
4322 followMousePos = true;
4323 else
4324 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4325 if (strTipText.IsEmpty())
4326 return FALSE;
4328 // we want multiline tooltips
4329 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4331 wcscpy_s(m_wszTip, strTipText);
4332 // handle Unicode as well as non-Unicode requests
4333 if (pNMHDR->code == TTN_NEEDTEXTA)
4335 pTTTA->hinst = nullptr;
4336 pTTTA->lpszText = m_szTip;
4337 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4339 else
4341 pTTTW->hinst = nullptr;
4342 pTTTW->lpszText = m_wszTip;
4345 CRect rect;
4346 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4347 if (followMousePos)
4348 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4349 ClientToScreen(rect);
4350 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4352 return TRUE; // We found a tool tip,
4353 // tell the framework this message has been handled
4356 return FALSE; // We didn't handle the message,
4357 // let the framework continue propagating the message
4360 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4362 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4364 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4365 if (pLogEntry == nullptr)
4366 return CString();
4367 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4368 return CString();
4369 return pLogEntry->GetSubject();
4371 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4373 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4374 if (pLogEntry == nullptr)
4375 return CString();
4376 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4378 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4380 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4381 if (pLogEntry == nullptr)
4382 return CString();
4383 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4385 else if (nSubItem == LOGLIST_ACTION)
4387 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4388 if (pLogEntry == nullptr)
4389 return CString();
4391 if (!pLogEntry->m_IsDiffFiles)
4392 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4394 int actions = pLogEntry->GetAction(this);
4395 CString sToolTipText;
4397 CString actionText;
4398 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4399 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4401 if (actions & CTGitPath::LOGACTIONS_ADDED)
4403 if (!actionText.IsEmpty())
4404 actionText += L"\r\n";
4405 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4408 if (actions & CTGitPath::LOGACTIONS_DELETED)
4410 if (!actionText.IsEmpty())
4411 actionText += L"\r\n";
4412 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4415 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4417 if (!actionText.IsEmpty())
4418 actionText += L"\r\n";
4419 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4422 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4424 if (!actionText.IsEmpty())
4425 actionText += L"\r\n";
4426 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4429 if (!actionText.IsEmpty())
4431 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4432 sToolTipText = sTitle + L":\r\n" + actionText;
4434 return sToolTipText;
4436 return CString();
4439 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4441 POINT pt = point;
4442 ScreenToClient(&pt);
4443 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4446 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4448 if (!pLogEntry)
4449 return false;
4451 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4452 if (refList == m_HashMap.cend())
4453 return false;
4455 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4457 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4458 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4459 continue;
4461 CGit::REF_TYPE foundType;
4462 if (pShortname)
4463 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4464 else
4465 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4466 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4467 return false;
4469 type = foundType;
4470 if (pIndex)
4471 *pIndex = i;
4472 return true;
4474 return false;
4477 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4479 *pResult = 0;
4481 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4482 return;
4484 m_bDragging = TRUE;
4485 m_nDropIndex = -1;
4486 m_nDropMarkerLast = -1;
4487 m_nDropMarkerLastHot = GetHotItem();
4488 SetCapture();
4491 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4493 __super::OnMouseMove(nFlags, point);
4495 if (!m_bDragging)
4496 return;
4498 CPoint dropPoint = point;
4499 ClientToScreen(&dropPoint);
4501 if (WindowFromPoint(dropPoint) != this)
4503 SetCursor(LoadCursor(nullptr, IDC_NO));
4504 m_nDropIndex = -1;
4505 DrawDropInsertMarker(m_nDropIndex);
4506 return;
4509 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4510 ScreenToClient(&dropPoint);
4512 dropPoint.y += 10;
4513 m_nDropIndex = HitTest(dropPoint);
4515 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4517 dropPoint.y -= 10;
4518 m_nDropIndex = HitTest(dropPoint);
4519 if (m_nDropIndex != -1)
4520 m_nDropIndex = GetItemCount();
4523 POSITION pos = GetFirstSelectedItemPosition();
4524 int first = GetNextSelectedItem(pos);
4525 int last = first;
4526 while (pos)
4527 last = GetNextSelectedItem(pos);
4528 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4530 SetCursor(LoadCursor(nullptr, IDC_NO));
4531 m_nDropIndex = -1;
4534 // handle auto scrolling
4535 int hotItem = GetHotItem();
4536 int topindex = GetTopIndex();
4537 if (hotItem == topindex && hotItem != 0)
4538 EnsureVisible(hotItem - 1, FALSE);
4539 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4540 EnsureVisible(hotItem + 1, FALSE);
4542 DrawDropInsertMarker(m_nDropIndex);
4545 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4547 if (m_bDragging)
4549 ::ReleaseCapture();
4550 SetCursor(LoadCursor(nullptr, IDC_HAND));
4551 m_bDragging = FALSE;
4553 CRect rect;
4554 GetItemRect(m_nDropMarkerLast, &rect, 0);
4555 rect.bottom = rect.top + 2;
4556 rect.top -= 2;
4557 InvalidateRect(&rect, 0);
4559 CPoint pt(point);
4560 ClientToScreen(&pt);
4561 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4562 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4565 __super::OnLButtonUp(nFlags, point);
4568 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4570 if (m_nDropMarkerLast != nIndex)
4572 CRect rect;
4573 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4575 rect.bottom = rect.top + 2;
4576 rect.top -= 2;
4577 InvalidateRect(&rect, 0);
4579 else if (m_nDropMarkerLast == GetItemCount())
4580 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4581 m_nDropMarkerLast = nIndex;
4583 if (nIndex < 0)
4584 return;
4586 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4588 else if (m_nDropMarkerLastHot != GetHotItem())
4590 m_nDropMarkerLastHot = GetHotItem();
4591 m_nDropMarkerLast = -1;
4595 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4597 CBrush* pBrush = CDC::GetHalftoneBrush();
4598 CDC* pDC = GetDC();
4600 CRect rect;
4601 if (nIndex < GetItemCount())
4603 GetItemRect(nIndex, &rect, 0);
4604 rect.bottom = rect.top + 2;
4605 rect.top -= 2;
4607 else
4609 GetItemRect(nIndex - 1, &rect, 0);
4610 rect.top = rect.bottom - 2;
4611 rect.bottom += 2;
4614 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4615 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4616 pDC->SelectObject(pBrushOld);
4618 ReleaseDC(pDC);
4621 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
4623 return 0;