Add note for new users that a merge conflict requires a commit
[TortoiseGit.git] / src / TortoiseProc / GitLogListBase.cpp
blob64e735c8d2714f01e0e962928bad2959613754fc
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - TortoiseGit
4 // Copyright (C) 2005-2007 Marco Costalba
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // GitLogList.cpp : implementation file
22 #include "stdafx.h"
23 #include "resource.h"
24 #include "GitLogListBase.h"
25 #include "IconMenu.h"
26 #include "GitProgressDlg.h"
27 #include "ProgressDlg.h"
28 #include "MessageBox.h"
29 #include "LoglistUtils.h"
30 #include "StringUtils.h"
31 #include "UnicodeUtils.h"
32 #include "IconMenu.h"
33 #include "../TortoiseShell/Resource.h"
35 const UINT CGitLogListBase::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
36 const UINT CGitLogListBase::m_ScrollToMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTO");
37 const UINT CGitLogListBase::m_ScrollToRef = RegisterWindowMessage(L"TORTOISEGIT_LOG_SCROLLTOREF");
38 const UINT CGitLogListBase::m_RebaseActionMessage = RegisterWindowMessage(L"TORTOISEGIT_LOG_REBASEACTION");
39 const UINT CGitLogListBase::LOGLIST_RESET_WCREV = RegisterWindowMessage(L"TORTOISEGIT_LOG_RESET_WCREV");
41 IMPLEMENT_DYNAMIC(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
43 CGitLogListBase::CGitLogListBase() : CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>()
44 ,m_regMaxBugIDColWidth(L"Software\\TortoiseGit\\MaxBugIDColWidth", 200)
45 ,m_nSearchIndex(0)
46 ,m_bNoDispUpdates(FALSE)
47 , m_bThreadRunning(FALSE)
48 , m_bStrictStopped(false)
49 , m_SelectedFilters(LOGFILTER_ALL)
50 , m_ShowFilter(FILTERSHOW_ALL)
51 , m_bShowWC(false)
52 , m_logEntries(&m_LogCache)
53 , m_pFindDialog(nullptr)
54 , m_dwDefaultColumns(0)
55 , m_arShownList(&m_critSec)
56 , m_hasWC(true)
57 , m_bNoHightlightHead(FALSE)
58 , m_ShowRefMask(LOGLIST_SHOWALLREFS)
59 , m_bFullCommitMessageOnLogLine(false)
60 , m_OldTopIndex(-1)
61 , m_AsyncThreadRunning(FALSE)
62 , m_AsyncThreadExit(FALSE)
63 , m_bIsCherryPick(false)
64 , m_pMailmap(nullptr)
65 , m_bShowBugtraqColumn(false)
66 , m_IsIDReplaceAction(FALSE)
67 , m_ShowMask(0)
68 , m_LoadingThread(nullptr)
69 , m_bExitThread(FALSE)
70 , m_IsOldFirst(FALSE)
71 , m_IsRebaseReplaceGraph(FALSE)
72 , m_ContextMenuMask(0xFFFFFFFFFFFFFFFF)
73 , m_bDragndropEnabled(false)
74 , m_bDragging(FALSE)
75 , m_nDropIndex(-1)
76 , m_nDropMarkerLast(-1)
77 , m_nDropMarkerLastHot(-1)
79 // use the default GUI font, create a copy of it and
80 // change the copy to BOLD (leave the rest of the font
81 // the same)
82 HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
83 LOGFONT lf = {0};
84 GetObject(hFont, sizeof(LOGFONT), &lf);
85 lf.lfWeight = FW_BOLD;
86 m_boldFont.CreateFontIndirect(&lf);
87 lf.lfWeight = FW_DONTCARE;
88 lf.lfItalic = TRUE;
89 m_FontItalics.CreateFontIndirect(&lf);
90 lf.lfWeight = FW_BOLD;
91 m_boldItalicsFont.CreateFontIndirect(&lf);
93 this->m_critSec.Init();
94 ResetWcRev(false);
96 int cx = GetSystemMetrics(SM_CXSMICON);
97 int cy = GetSystemMetrics(SM_CYSMICON);
98 m_hModifiedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONMODIFIED), IMAGE_ICON, cx, cy, 0);
99 m_hReplacedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONREPLACED), IMAGE_ICON, cx, cy, 0);
100 m_hConflictedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONCONFLICTED), IMAGE_ICON, cx, cy, 0);
101 m_hAddedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONADDED), IMAGE_ICON, cx, cy, 0);
102 m_hDeletedIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONDELETED), IMAGE_ICON, cx, cy, 0);
103 m_hFetchIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_ACTIONFETCHING), IMAGE_ICON, cx, cy, 0);
105 m_bFilterWithRegex = !!CRegDWORD(L"Software\\TortoiseGit\\UseRegexFilter", FALSE);
106 m_bFilterCaseSensitively = !!CRegDWORD(L"Software\\TortoiseGit\\FilterCaseSensitively", FALSE);
108 m_Filter.m_NumberOfLogsScale = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogsScale", CFilterData::SHOW_NO_LIMIT);
109 if (m_Filter.m_NumberOfLogsScale == CFilterData::SHOW_LAST_SEL_DATE)
111 CString key;
112 key.Format(L"Software\\TortoiseGit\\History\\LogDlg_Limits\\%s\\FromDate", (LPCTSTR)g_Git.m_CurrentDir);
113 key.Replace(L':', L'_');
114 CString lastSelFromDate = CRegString(key);
115 if (lastSelFromDate.GetLength() == 10)
117 CTime time = CTime(_wtoi((LPCTSTR)lastSelFromDate.Mid(0, 4)), _wtoi((LPCTSTR)lastSelFromDate.Mid(5, 2)), _wtoi((LPCTSTR)lastSelFromDate.Mid(8, 2)), 0, 0, 0);
118 m_Filter.m_From = (DWORD)time.GetTime();
121 m_Filter.m_NumberOfLogs = (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\NumberOfLogs", 1);
123 for (int i = 0; i < Lanes::COLORS_NUM; ++i)
125 m_LineColors[i] = m_Colors.GetColor((CColors::Colors)(CColors::BranchLine1+i));
127 // get short/long datetime setting from registry
128 DWORD RegUseShortDateFormat = CRegDWORD(L"Software\\TortoiseGit\\LogDateFormat", TRUE);
129 if ( RegUseShortDateFormat )
131 m_DateFormat = DATE_SHORTDATE;
133 else
135 m_DateFormat = DATE_LONGDATE;
137 // get relative time display setting from registry
138 DWORD regRelativeTimes = CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE);
139 m_bRelativeTimes = (regRelativeTimes != 0);
141 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_PICK);
142 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SQUASH);
143 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_EDIT);
144 m_ContextMenuMask &= ~GetContextMenuBit(ID_REBASE_SKIP);
145 m_ContextMenuMask &= ~GetContextMenuBit(ID_LOG);
146 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAME);
147 m_ContextMenuMask &= ~GetContextMenuBit(ID_BLAMEPREVIOUS);
149 m_ColumnRegKey = L"log";
151 m_bTagsBranchesOnRightSide = !!CRegDWORD(L"Software\\TortoiseGit\\DrawTagsBranchesOnRightSide", FALSE);
152 m_bSymbolizeRefNames = !!CRegDWORD(L"Software\\TortoiseGit\\SymbolizeRefNames", FALSE);
153 m_bIncludeBoundaryCommits = !!CRegDWORD(L"Software\\TortoiseGit\\LogIncludeBoundaryCommits", FALSE);
154 m_bFullCommitMessageOnLogLine = !!CRegDWORD(L"Software\\TortoiseGit\\FullCommitMessageOnLogLine", FALSE);
156 m_LineWidth = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogLineWidth", 2));
157 m_NodeSize = max(1, CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\Graph\\LogNodeSize", 10));
159 if (CRegDWORD(L"Software\\TortoiseGit\\LogDialog\\UseMailmap", FALSE) == TRUE)
160 git_read_mailmap(&m_pMailmap);
162 m_AsyncDiffEvent = ::CreateEvent(nullptr, FALSE, TRUE, nullptr);
163 m_AsynDiffListLock.Init();
164 StartAsyncDiffThread();
167 int CGitLogListBase::AsyncDiffThread()
169 while(!m_AsyncThreadExit)
171 ::WaitForSingleObject(m_AsyncDiffEvent, INFINITE);
173 GitRevLoglist* pRev = nullptr;
174 while(!m_AsyncThreadExit && !m_AsynDiffList.empty())
176 m_AsynDiffListLock.Lock();
177 pRev = m_AsynDiffList.back();
178 m_AsynDiffList.pop_back();
179 m_AsynDiffListLock.Unlock();
181 if( pRev->m_CommitHash.IsEmpty() )
183 if(pRev->m_IsDiffFiles)
184 continue;
186 CTGitPathList& files = pRev->GetFiles(this);
187 files.Clear();
188 pRev->m_ParentHash.clear();
189 pRev->m_ParentHash.push_back(m_HeadHash);
190 g_Git.RefreshGitIndex();
191 g_Git.GetWorkingTreeChanges(files);
192 auto& action = pRev->GetAction(this);
193 action = 0;
194 for (int j = 0; j < files.GetCount(); ++j)
195 action |= files[j].m_Action;
197 CString err;
198 if (pRev->GetUnRevFiles().FillUnRev(CTGitPath::LOGACTIONS_UNVER, nullptr, &err))
200 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
201 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
202 return -1;
205 InterlockedExchange(&pRev->m_IsDiffFiles, TRUE);
206 InterlockedExchange(&pRev->m_IsFull, TRUE);
208 CString body = L"\n";
209 body.AppendFormat(IDS_FILESCHANGES, files.GetCount());
210 pRev->GetBody() = body;
211 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)0,0);
212 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
215 if (!pRev->CheckAndDiff())
216 { // fetch change file list
217 for (int i = GetTopIndex(); !m_AsyncThreadExit && i <= GetTopIndex() + GetCountPerPage(); ++i)
219 if (i < (int)m_arShownList.size())
221 GitRevLoglist* data = m_arShownList.SafeGetAt(i);
222 if(data->m_CommitHash == pRev->m_CommitHash)
224 ::PostMessage(m_hWnd,MSG_LOADED,(WPARAM)i,0);
225 break;
230 if(!m_AsyncThreadExit && GetSelectedCount() == 1)
232 POSITION pos = GetFirstSelectedItemPosition();
233 int nItem = GetNextSelectedItem(pos);
235 if(nItem>=0)
237 GitRevLoglist* data = m_arShownList.SafeGetAt(nItem);
238 if(data)
239 if(data->m_CommitHash == pRev->m_CommitHash)
240 this->GetParent()->PostMessage(WM_COMMAND, MSG_FETCHED_DIFF, 0);
246 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
247 return 0;
249 void CGitLogListBase::hideFromContextMenu(unsigned __int64 hideMask, bool exclusivelyShow)
251 if (exclusivelyShow)
252 m_ContextMenuMask &= hideMask;
253 else
254 m_ContextMenuMask &= ~hideMask;
257 CGitLogListBase::~CGitLogListBase()
259 InterlockedExchange(&m_bNoDispUpdates, TRUE);
260 this->m_arShownList.SafeRemoveAll();
262 DestroyIcon(m_hModifiedIcon);
263 DestroyIcon(m_hReplacedIcon);
264 DestroyIcon(m_hConflictedIcon);
265 DestroyIcon(m_hAddedIcon);
266 DestroyIcon(m_hDeletedIcon);
267 m_logEntries.ClearAll();
269 git_free_mailmap(m_pMailmap);
271 SafeTerminateThread();
272 SafeTerminateAsyncDiffThread();
274 if(m_AsyncDiffEvent)
275 CloseHandle(m_AsyncDiffEvent);
279 BEGIN_MESSAGE_MAP(CGitLogListBase, CHintCtrl<CResizableColumnsListCtrl<CListCtrl>>)
280 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
281 ON_REGISTERED_MESSAGE(m_ScrollToMessage, OnScrollToMessage)
282 ON_REGISTERED_MESSAGE(m_ScrollToRef, OnScrollToRef)
283 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdrawLoglist)
284 ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetdispinfoLoglist)
285 ON_WM_CONTEXTMENU()
286 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclkLoglist)
287 ON_NOTIFY_REFLECT(LVN_ODFINDITEM,OnLvnOdfinditemLoglist)
288 ON_WM_CREATE()
289 ON_WM_DESTROY()
290 ON_MESSAGE(MSG_LOADED,OnLoad)
291 ON_WM_MEASUREITEM()
292 ON_WM_MEASUREITEM_REFLECT()
293 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &OnToolTipText)
294 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &OnToolTipText)
295 ON_WM_MOUSEMOVE()
296 ON_WM_LBUTTONUP()
297 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
298 END_MESSAGE_MAP()
300 void CGitLogListBase::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
302 //if (m_nRowHeight>0)
303 lpMeasureItemStruct->itemHeight = 50;
306 int CGitLogListBase:: OnCreate(LPCREATESTRUCT lpCreateStruct)
308 PreSubclassWindow();
309 return __super::OnCreate(lpCreateStruct);
312 void CGitLogListBase::SetStyle()
314 SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_DOUBLEBUFFER | LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT);
317 void CGitLogListBase::PreSubclassWindow()
319 SetStyle();
320 // load the icons for the action columns
321 // m_Theme.Open(m_hWnd, L"ListView");
322 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
323 __super::PreSubclassWindow();
326 CString CGitLogListBase::GetRebaseActionName(int action)
328 if (action & LOGACTIONS_REBASE_EDIT)
329 return MAKEINTRESOURCE(IDS_PATHACTIONS_EDIT);
330 if (action & LOGACTIONS_REBASE_SQUASH)
331 return MAKEINTRESOURCE(IDS_PATHACTIONS_SQUASH);
332 if (action & LOGACTIONS_REBASE_PICK)
333 return MAKEINTRESOURCE(IDS_PATHACTIONS_PICK);
334 if (action & LOGACTIONS_REBASE_SKIP)
335 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIP);
337 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
340 void CGitLogListBase::InsertGitColumn()
342 CString temp;
344 Init();
346 // only load properties if we have a repository
347 if (GitAdminDir::IsWorkingTreeOrBareRepo(g_Git.m_CurrentDir))
348 UpdateProjectProperties();
350 static UINT normal[] =
352 IDS_LOG_GRAPH,
353 IDS_LOG_REBASE,
354 IDS_LOG_ID,
355 IDS_LOG_HASH,
356 IDS_LOG_ACTIONS,
357 IDS_LOG_MESSAGE,
358 IDS_LOG_AUTHOR,
359 IDS_LOG_DATE,
360 IDS_LOG_EMAIL,
361 IDS_LOG_COMMIT_NAME,
362 IDS_LOG_COMMIT_EMAIL,
363 IDS_LOG_COMMIT_DATE,
364 IDS_LOG_BUGIDS,
365 IDS_LOG_SVNREV,
368 static int with[] =
370 ICONITEMBORDER+16*4,
371 ICONITEMBORDER+16*4,
372 ICONITEMBORDER+16*4,
373 ICONITEMBORDER+16*4,
374 2 * ICONITEMBORDER + GetSystemMetrics(SM_CXSMICON) * 5,
375 LOGLIST_MESSAGE_MIN,
376 ICONITEMBORDER+16*4,
377 ICONITEMBORDER+16*4,
378 ICONITEMBORDER+16*4,
379 ICONITEMBORDER+16*4,
380 ICONITEMBORDER+16*4,
381 ICONITEMBORDER+16*4,
382 ICONITEMBORDER+16*4,
383 ICONITEMBORDER+16*4,
385 m_dwDefaultColumns = GIT_LOG_GRAPH|GIT_LOG_ACTIONS|GIT_LOG_MESSAGE|GIT_LOG_AUTHOR|GIT_LOG_DATE;
387 DWORD hideColumns = 0;
388 if(this->m_IsRebaseReplaceGraph)
390 hideColumns |= GIT_LOG_GRAPH;
391 m_dwDefaultColumns |= GIT_LOG_REBASE;
393 else
394 hideColumns |= GIT_LOG_REBASE;
396 if(this->m_IsIDReplaceAction)
398 hideColumns |= GIT_LOG_ACTIONS;
399 m_dwDefaultColumns |= GIT_LOG_ID;
400 m_dwDefaultColumns |= GIT_LOG_HASH;
402 else
403 hideColumns |= GIT_LOG_ID;
404 if(this->m_bShowBugtraqColumn)
405 m_dwDefaultColumns |= GIT_LOGLIST_BUG;
406 else
407 hideColumns |= GIT_LOGLIST_BUG;
408 if (CTGitPath(g_Git.m_CurrentDir).HasGitSVNDir())
409 m_dwDefaultColumns |= GIT_LOGLIST_SVNREV;
410 else
411 hideColumns |= GIT_LOGLIST_SVNREV;
412 SetRedraw(false);
414 m_ColumnManager.SetNames(normal, _countof(normal));
415 m_ColumnManager.ReadSettings(m_dwDefaultColumns, hideColumns, m_ColumnRegKey + L"loglist", _countof(normal), with);
416 m_ColumnManager.SetRightAlign(LOGLIST_ID);
418 if (!(hideColumns & GIT_LOG_ACTIONS))
420 // Configure fake a imagelist for LogList with 1px width and height = GetSystemMetrics(SM_CYSMICON)
421 // to set the minimum item height: we draw icons in the actions column, but on High-DPI the
422 // display's font height may be less than small icon height.
423 ASSERT((GetStyle() & LVS_SHAREIMAGELISTS) == 0);
424 HIMAGELIST hImageList = ImageList_Create(1, GetSystemMetrics(SM_CYSMICON), 0, 1, 0);
425 ListView_SetImageList(GetSafeHwnd(), hImageList, LVSIL_SMALL);
428 SetRedraw(true);
431 void CGitLogListBase::FillBackGround(HDC hdc, DWORD_PTR Index, CRect &rect)
433 LVITEM rItem = { 0 };
434 rItem.mask = LVIF_STATE;
435 rItem.iItem = (int)Index;
436 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
437 GetItem(&rItem);
439 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(Index);
440 HBRUSH brush = nullptr;
442 if (!(rItem.state & LVIS_SELECTED))
444 int action = pLogEntry->GetRebaseAction();
445 if (action & LOGACTIONS_REBASE_SQUASH)
446 brush = ::CreateSolidBrush(RGB(156,156,156));
447 else if (action & LOGACTIONS_REBASE_EDIT)
448 brush = ::CreateSolidBrush(RGB(200,200,128));
450 else if (!IsAppThemed())
452 if (rItem.state & LVIS_SELECTED)
454 if (::GetFocus() == m_hWnd)
455 brush = ::CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
456 else
457 brush = ::CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
460 if (brush)
462 ::FillRect(hdc, &rect, brush);
463 ::DeleteObject(brush);
467 void DrawTrackingRoundRect(HDC hdc, CRect rect, HBRUSH brush, COLORREF darkColor)
469 POINT point = { 4, 4 };
470 CRect rt2 = rect;
471 rt2.DeflateRect(1, 1);
472 rt2.OffsetRect(2, 2);
474 HPEN nullPen = ::CreatePen(PS_NULL, 0, 0);
475 HPEN oldpen = (HPEN)::SelectObject(hdc, nullPen);
476 HBRUSH darkBrush = (HBRUSH)::CreateSolidBrush(darkColor);
477 HBRUSH oldbrush = (HBRUSH)::SelectObject(hdc, darkBrush);
478 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
480 ::SelectObject(hdc, brush);
481 rt2.OffsetRect(-2, -2);
482 ::RoundRect(hdc, rt2.left, rt2.top, rt2.right, rt2.bottom, point.x, point.y);
483 ::SelectObject(hdc, oldbrush);
484 ::SelectObject(hdc, oldpen);
485 ::DeleteObject(nullPen);
486 ::DeleteObject(darkBrush);
489 void DrawUpstream(HDC hdc, CRect rect, COLORREF color, int bold)
491 HPEN pen = ::CreatePen(PS_SOLID, bold, color);
492 HPEN oldpen = (HPEN)::SelectObject(hdc, pen);
493 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 2 - bold, nullptr);
494 ::LineTo(hdc, rect.left + 2 + bold, rect.bottom + 1 - bold);
495 ::MoveToEx(hdc, rect.left + 3, rect.top + 1, nullptr);
496 ::LineTo(hdc, rect.left, rect.top + 4);
497 ::MoveToEx(hdc, rect.left + 2 + bold, rect.top + 1, nullptr);
498 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 4);
499 ::MoveToEx(hdc, rect.left + 1, rect.top + 2 + bold, nullptr);
500 ::LineTo(hdc, rect.right + 1 + bold, rect.top + 2 + bold);
501 ::SelectObject(hdc, oldpen);
502 ::DeleteObject(pen);
505 void CGitLogListBase::DrawTagBranchMessage(HDC hdc, CRect &rect, INT_PTR index, std::vector<REFLABEL> &refList)
507 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
508 CRect rt=rect;
509 LVITEM rItem = { 0 };
510 rItem.mask = LVIF_STATE;
511 rItem.iItem = (int)index;
512 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
513 GetItem(&rItem);
515 CDC W_Dc;
516 W_Dc.Attach(hdc);
518 HTHEME hTheme = nullptr;
519 if (IsAppThemed())
520 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
522 SIZE oneSpaceSize;
523 if (m_bTagsBranchesOnRightSide)
525 HFONT oldFont = (HFONT)SelectObject(hdc, (HFONT)GetStockObject(DEFAULT_GUI_FONT));
526 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
527 SelectObject(hdc, oldFont);
528 rt.left += oneSpaceSize.cx * 2;
530 else
532 GetTextExtentPoint32(hdc, L" ", 1, &oneSpaceSize);
533 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
534 rt.left += oneSpaceSize.cx;
537 CString msg = MessageDisplayStr(data);
538 int action = data->GetRebaseAction();
539 bool skip = !!(action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP));
540 if (IsAppThemed())
542 int txtState = LISS_NORMAL;
543 if (rItem.state & LVIS_SELECTED)
544 txtState = LISS_SELECTED;
546 DTTOPTS opts = { 0 };
547 opts.dwSize = sizeof(opts);
548 opts.crText = skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT);
549 opts.dwFlags = DTT_TEXTCOLOR;
550 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, msg, -1, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS, &rt, &opts);
552 else
554 if ((rItem.state & LVIS_SELECTED) && (::GetFocus() == m_hWnd))
556 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_HIGHLIGHTTEXT));
557 ::DrawText(hdc,msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
558 ::SetTextColor(hdc, clrOld);
560 else
562 COLORREF clrOld = ::SetTextColor(hdc, skip ? RGB(128,128,128) : ::GetSysColor(COLOR_WINDOWTEXT));
563 ::DrawText(hdc, msg, msg.GetLength(), &rt, DT_NOPREFIX | DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
564 ::SetTextColor(hdc, clrOld);
568 if (m_bTagsBranchesOnRightSide)
570 SIZE size;
571 GetTextExtentPoint32(hdc, msg, msg.GetLength(), &size);
573 rt.left += oneSpaceSize.cx + size.cx;
575 DrawTagBranch(hdc, W_Dc, hTheme, rect, rt, rItem, data, refList);
578 if (hTheme)
579 CloseThemeData(hTheme);
581 W_Dc.Detach();
584 void CGitLogListBase::DrawTagBranch(HDC hdc, CDC& W_Dc, HTHEME hTheme, CRect& rect, CRect& rt, LVITEM& rItem, GitRevLoglist* data, std::vector<REFLABEL>& refList)
586 for (unsigned int i = 0; i < refList.size(); ++i)
588 CString shortname = !refList[i].simplifiedName.IsEmpty() ? refList[i].simplifiedName : refList[i].name;
589 HBRUSH brush = 0;
590 COLORREF colRef = refList[i].color;
591 bool singleRemote = refList[i].singleRemote;
592 bool hasTracking = refList[i].hasTracking;
593 CGit::REF_TYPE refType = refList[i].refType;
595 //When row selected, ajust label color
596 if (!IsAppThemed())
598 if (rItem.state & LVIS_SELECTED)
599 colRef = CColors::MixColors(colRef, ::GetSysColor(COLOR_HIGHLIGHT), 150);
602 brush = ::CreateSolidBrush(colRef);
604 if (!shortname.IsEmpty() && (rt.left < rect.right))
606 SIZE size = { 0 };
607 GetTextExtentPoint32(hdc, shortname, shortname.GetLength(), &size);
609 rt.SetRect(rt.left, rt.top, rt.left + size.cx, rt.bottom);
610 rt.right += 8;
612 int textpos = DT_CENTER;
614 if (rt.right > rect.right)
616 rt.right = rect.right;
617 textpos = 0;
620 CRect textRect = rt;
622 if (singleRemote)
624 rt.right += 5;
625 textRect.OffsetRect(5, 0);
628 if (hasTracking)
629 DrawTrackingRoundRect(hdc, rt, brush, m_Colors.Darken(colRef, 100));
630 else
632 //Fill interior of ref label
633 ::FillRect(hdc, &rt, brush);
636 //Draw edge of label
637 CRect rectEdge = rt;
639 if (!hasTracking)
641 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 100), m_Colors.Darken(colRef, 100));
642 rectEdge.DeflateRect(1, 1);
643 W_Dc.Draw3dRect(rectEdge, m_Colors.Lighten(colRef, 50), m_Colors.Darken(colRef, 50));
646 if (refType == CGit::REF_TYPE::ANNOTATED_TAG)
648 rt.right += 8;
649 POINT trianglept[3] = { { rt.right - 8, rt.top }, { rt.right, (rt.top + rt.bottom) / 2 }, { rt.right - 8, rt.bottom } };
650 HRGN hrgn = ::CreatePolygonRgn(trianglept, 3, ALTERNATE);
651 ::FillRgn(hdc, hrgn, brush);
652 ::DeleteObject(hrgn);
653 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[0].y, nullptr);
654 HPEN pen;
655 HPEN oldpen = (HPEN)SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Lighten(colRef, 50)));
656 ::LineTo(hdc, trianglept[1].x - 1, trianglept[1].y - 1);
657 ::DeleteObject(pen);
658 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, m_Colors.Darken(colRef, 50)));
659 ::LineTo(hdc, trianglept[2].x - 1, trianglept[2].y - 1);
660 ::DeleteObject(pen);
661 SelectObject(hdc, pen = ::CreatePen(PS_SOLID, 2, colRef));
662 ::MoveToEx(hdc, trianglept[0].x - 1, trianglept[2].y - 3, nullptr);
663 ::LineTo(hdc, trianglept[0].x - 1, trianglept[0].y);
664 ::DeleteObject(pen);
665 SelectObject(hdc, oldpen);
668 //Draw text inside label
669 bool customColor = (colRef & 0xff) * 30 + ((colRef >> 8) & 0xff) * 59 + ((colRef >> 16) & 0xff) * 11 <= 12800; // check if dark background
670 if (!customColor && IsAppThemed())
672 int txtState = LISS_NORMAL;
673 if (rItem.state & LVIS_SELECTED)
674 txtState = LISS_SELECTED;
676 DTTOPTS opts = { 0 };
677 opts.dwSize = sizeof(opts);
678 opts.crText = ::GetSysColor(COLOR_WINDOWTEXT);
679 opts.dwFlags = DTT_TEXTCOLOR;
680 DrawThemeTextEx(hTheme, hdc, LVP_LISTITEM, txtState, shortname, -1, textpos | DT_SINGLELINE | DT_VCENTER, &textRect, &opts);
682 else
684 W_Dc.SetBkMode(TRANSPARENT);
685 if (customColor || (rItem.state & LVIS_SELECTED))
687 COLORREF clrNew = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
688 COLORREF clrOld = ::SetTextColor(hdc,clrNew);
689 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
690 ::SetTextColor(hdc,clrOld);
692 else
694 COLORREF clrOld = ::SetTextColor(hdc, ::GetSysColor(COLOR_WINDOWTEXT));
695 ::DrawText(hdc, shortname, shortname.GetLength(), &textRect, textpos | DT_SINGLELINE | DT_VCENTER);
696 ::SetTextColor(hdc, clrOld);
700 if (singleRemote)
702 COLORREF color = ::GetSysColor(customColor ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
703 int bold = data->m_CommitHash == m_HeadHash ? 2 : 1;
704 CRect newRect;
705 newRect.SetRect(rt.left + 2, rt.top + 4, rt.left + 6, rt.bottom - 4);
706 DrawUpstream(hdc, newRect, color, bold);
709 if (!refList[i].fullName.IsEmpty())
710 m_RefLabelPosMap[refList[i].fullName] = rt;
712 rt.left = rt.right + 1;
714 if (brush)
715 ::DeleteObject(brush);
717 rt.right = rect.right;
720 static COLORREF blend(const COLORREF& col1, const COLORREF& col2, int amount = 128) {
721 // Returns ((256 - amount)*col1 + amount*col2) / 256;
722 return RGB(((256 - amount)*GetRValue(col1) + amount*GetRValue(col2) ) / 256,
723 ((256 - amount)*GetGValue(col1) + amount*GetGValue(col2) ) / 256,
724 ((256 - amount)*GetBValue(col1) + amount*GetBValue(col2) ) / 256);
727 Gdiplus::Color GetGdiColor(COLORREF col)
729 return Gdiplus::Color(GetRValue(col),GetGValue(col),GetBValue(col));
731 void CGitLogListBase::paintGraphLane(HDC hdc, int laneHeight,int type, int x1, int x2,
732 const COLORREF& col,const COLORREF& activeColor, int top
735 int h = laneHeight / 2;
736 int m = (x1 + x2) / 2;
737 int r = (x2 - x1) * m_NodeSize / 30;
738 int d = 2 * r;
740 #define P_CENTER m , h+top
741 #define P_0 x2, h+top
742 #define P_90 m , 0+top-1
743 #define P_180 x1, h+top
744 #define P_270 m , 2 * h+top +1
745 #define R_CENTER m - r, h - r+top, d, d
748 #define DELTA_UR_B 2*(x1 - m), 2*h +top
749 #define DELTA_UR_E 0*16, 90*16 +top // -,
751 #define DELTA_DR_B 2*(x1 - m), 2*-h +top
752 #define DELTA_DR_E 270*16, 90*16 +top // -'
754 #define DELTA_UL_B 2*(x2 - m), 2*h +top
755 #define DELTA_UL_E 90*16, 90*16 +top // ,-
757 #define DELTA_DL_B 2*(x2 - m),2*-h +top
758 #define DELTA_DL_E 180*16, 90*16 // '-
760 #define CENTER_UR x1, 2*h, 225
761 #define CENTER_DR x1, 0 , 135
762 #define CENTER_UL x2, 2*h, 315
763 #define CENTER_DL x2, 0 , 45
766 Gdiplus::Graphics graphics( hdc );
768 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
770 // arc
771 switch (type) {
772 case Lanes::JOIN:
773 case Lanes::JOIN_R:
774 case Lanes::HEAD:
775 case Lanes::HEAD_R:
777 Gdiplus::LinearGradientBrush gradient(
778 Gdiplus::Point(x1-2, h+top-2),
779 Gdiplus::Point(P_270),
780 GetGdiColor(activeColor),GetGdiColor(col));
783 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
784 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
786 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
787 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top+h-1, x2-x1,laneHeight,270,90);
788 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
790 break;
792 case Lanes::JOIN_L:
794 Gdiplus::LinearGradientBrush gradient(
795 Gdiplus::Point(P_270),
796 Gdiplus::Point(x2+1, h+top-1),
797 GetGdiColor(col),GetGdiColor(activeColor));
800 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
801 //Gdiplus::Pen mypen(Gdiplus::Color(0,0,0),2);
803 //graphics.DrawRectangle(&mypen,x1-(x2-x1)/2,top+h, x2-x1,laneHeight);
804 graphics.DrawArc(&mypen,x1+(x2-x1)/2,top+h-1, x2-x1,laneHeight,180,90);
805 //graphics.DrawLine(&mypen,x1-1,h+top,P_270);
808 break;
810 case Lanes::TAIL:
811 case Lanes::TAIL_R:
813 Gdiplus::LinearGradientBrush gradient(
814 Gdiplus::Point(x1-2, h+top-2),
815 Gdiplus::Point(P_90),
816 GetGdiColor(activeColor),GetGdiColor(col));
818 Gdiplus::Pen mypen(&gradient, (Gdiplus::REAL)m_LineWidth);
820 graphics.DrawArc(&mypen,x1-(x2-x1)/2-1,top-h-1, x2-x1,laneHeight,0,90);
822 #if 0
823 QConicalGradient gradient(CENTER_DR);
824 gradient.setColorAt(0.375, activeCol);
825 gradient.setColorAt(0.625, col);
826 myPen.setBrush(gradient);
827 p->setPen(myPen);
828 p->drawArc(P_CENTER, DELTA_DR);
829 #endif
830 break;
832 default:
833 break;
837 //static QPen myPen(Qt::black, 2); // fast path here
838 CPen pen;
839 pen.CreatePen(PS_SOLID,2,col);
840 //myPen.setColor(col);
841 HPEN oldpen=(HPEN)::SelectObject(hdc,(HPEN)pen);
843 Gdiplus::Pen myPen(GetGdiColor(col), (Gdiplus::REAL)m_LineWidth);
845 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
847 //p->setPen(myPen);
849 // vertical line
850 switch (type) {
851 case Lanes::ACTIVE:
852 case Lanes::NOT_ACTIVE:
853 case Lanes::MERGE_FORK:
854 case Lanes::MERGE_FORK_R:
855 case Lanes::MERGE_FORK_L:
856 case Lanes::JOIN:
857 case Lanes::JOIN_R:
858 case Lanes::JOIN_L:
859 case Lanes::CROSS:
860 //DrawLine(hdc,P_90,P_270);
861 graphics.DrawLine(&myPen,P_90,P_270);
862 //p->drawLine(P_90, P_270);
863 break;
864 case Lanes::HEAD_L:
865 case Lanes::BRANCH:
866 //DrawLine(hdc,P_CENTER,P_270);
867 graphics.DrawLine(&myPen,P_CENTER,P_270);
868 //p->drawLine(P_CENTER, P_270);
869 break;
870 case Lanes::TAIL_L:
871 case Lanes::INITIAL:
872 case Lanes::MERGE_FORK_L_INITIAL:
873 case Lanes::BOUNDARY:
874 case Lanes::BOUNDARY_C:
875 case Lanes::BOUNDARY_R:
876 case Lanes::BOUNDARY_L:
877 //DrawLine(hdc,P_90, P_CENTER);
878 graphics.DrawLine(&myPen,P_90,P_CENTER);
879 //p->drawLine(P_90, P_CENTER);
880 break;
881 default:
882 break;
885 myPen.SetColor(GetGdiColor(activeColor));
887 // horizontal line
888 switch (type) {
889 case Lanes::MERGE_FORK:
890 case Lanes::JOIN:
891 case Lanes::HEAD:
892 case Lanes::TAIL:
893 case Lanes::CROSS:
894 case Lanes::CROSS_EMPTY:
895 case Lanes::BOUNDARY_C:
896 //DrawLine(hdc,P_180,P_0);
897 graphics.DrawLine(&myPen,P_180,P_0);
898 //p->drawLine(P_180, P_0);
899 break;
900 case Lanes::MERGE_FORK_R:
901 case Lanes::BOUNDARY_R:
902 //DrawLine(hdc,P_180,P_CENTER);
903 graphics.DrawLine(&myPen,P_180,P_CENTER);
904 //p->drawLine(P_180, P_CENTER);
905 break;
906 case Lanes::MERGE_FORK_L:
907 case Lanes::MERGE_FORK_L_INITIAL:
908 case Lanes::HEAD_L:
909 case Lanes::TAIL_L:
910 case Lanes::BOUNDARY_L:
911 //DrawLine(hdc,P_CENTER,P_0);
912 graphics.DrawLine(&myPen,P_CENTER,P_0);
913 //p->drawLine(P_CENTER, P_0);
914 break;
915 default:
916 break;
919 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
921 CBrush brush;
922 brush.CreateSolidBrush(col);
923 HBRUSH oldbrush=(HBRUSH)::SelectObject(hdc,(HBRUSH)brush);
925 Gdiplus::SolidBrush myBrush(GetGdiColor(col));
926 // center symbol, e.g. rect or ellipse
927 switch (type) {
928 case Lanes::ACTIVE:
929 case Lanes::INITIAL:
930 case Lanes::BRANCH:
932 //p->setPen(Qt::NoPen);
933 //p->setBrush(col);
934 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
935 graphics.FillEllipse(&myBrush, R_CENTER);
936 //p->drawEllipse(R_CENTER);
937 break;
938 case Lanes::MERGE_FORK:
939 case Lanes::MERGE_FORK_R:
940 case Lanes::MERGE_FORK_L:
941 case Lanes::MERGE_FORK_L_INITIAL:
942 //p->setPen(Qt::NoPen);
943 //p->setBrush(col);
944 //p->drawRect(R_CENTER);
945 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
946 graphics.FillRectangle(&myBrush, R_CENTER);
947 break;
948 case Lanes::UNAPPLIED:
949 // Red minus sign
950 //p->setPen(Qt::NoPen);
951 //p->setBrush(Qt::red);
952 //p->drawRect(m - r, h - 1, d, 2);
953 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
954 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
955 break;
956 case Lanes::APPLIED:
957 // Green plus sign
958 //p->setPen(Qt::NoPen);
959 //p->setBrush(DARK_GREEN);
960 //p->drawRect(m - r, h - 1, d, 2);
961 //p->drawRect(m - 1, h - r, 2, d);
962 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
963 graphics.FillRectangle(&myBrush,m-r,h-1,d,2);
964 graphics.FillRectangle(&myBrush,m-1,h-r,2,d);
965 break;
966 case Lanes::BOUNDARY:
967 //p->setBrush(back);
968 //p->drawEllipse(R_CENTER);
969 graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
970 graphics.DrawEllipse(&myPen, R_CENTER);
971 break;
972 case Lanes::BOUNDARY_C:
973 case Lanes::BOUNDARY_R:
974 case Lanes::BOUNDARY_L:
975 //p->setBrush(back);
976 //p->drawRect(R_CENTER);
977 graphics.SetSmoothingMode(Gdiplus::SmoothingModeNone);
978 graphics.FillRectangle(&myBrush,R_CENTER);
979 break;
980 default:
981 break;
984 ::SelectObject(hdc,oldpen);
985 ::SelectObject(hdc,oldbrush);
986 #undef P_CENTER
987 #undef P_0
988 #undef P_90
989 #undef P_180
990 #undef P_270
991 #undef R_CENTER
994 void CGitLogListBase::DrawGraph(HDC hdc,CRect &rect,INT_PTR index)
996 // TODO: unfinished
997 // return;
998 GitRevLoglist* data = m_arShownList.SafeGetAt(index);
999 if(data->m_CommitHash.IsEmpty())
1000 return;
1002 CRect rt=rect;
1003 LVITEM rItem = { 0 };
1004 rItem.mask = LVIF_STATE;
1005 rItem.iItem = (int)index;
1006 rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
1007 GetItem(&rItem);
1009 // p->translate(QPoint(opt.rect.left(), opt.rect.top()));
1011 if (data->m_Lanes.empty())
1012 m_logEntries.setLane(data->m_CommitHash);
1014 std::vector<int>& lanes=data->m_Lanes;
1015 size_t laneNum = lanes.size();
1016 UINT activeLane = 0;
1017 for (UINT i = 0; i < laneNum; ++i)
1018 if (Lanes::isMerge(lanes[i])) {
1019 activeLane = i;
1020 break;
1023 int x2 = 0;
1024 int maxWidth = rect.Width();
1025 int lw = 3 * rect.Height() / 4; //laneWidth()
1027 COLORREF activeColor = m_LineColors[activeLane % Lanes::COLORS_NUM];
1028 //if (opt.state & QStyle::State_Selected)
1029 // activeColor = blend(activeColor, opt.palette.highlightedText().color(), 208);
1031 for (unsigned int i = 0; i < laneNum && x2 < maxWidth; ++i)
1033 int x1 = x2;
1034 x2 += lw;
1036 int ln = lanes[i];
1037 if (ln == Lanes::EMPTY)
1038 continue;
1040 COLORREF color = i == activeLane ? activeColor : m_LineColors[i % Lanes::COLORS_NUM];
1041 paintGraphLane(hdc, rect.Height(),ln, x1+rect.left, x2+rect.left, color,activeColor, rect.top);
1044 #if 0
1045 for (UINT i = 0; i < laneNum && x2 < maxWidth; ++i) {
1046 int x1 = x2;
1047 x2 += lw;
1049 int ln = lanes[i];
1050 if (ln == Lanes::EMPTY)
1051 continue;
1053 UINT col = ( Lanes:: isHead(ln) ||Lanes:: isTail(ln) || Lanes::isJoin(ln)
1054 || ln ==Lanes:: CROSS_EMPTY) ? activeLane : i;
1056 if (ln == Lanes::CROSS)
1058 paintGraphLane(hdc, rect.Height(),Lanes::NOT_ACTIVE, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1059 paintGraphLane(hdc, rect.Height(),Lanes::CROSS, x1, x2, m_LineColors[activeLane % Lanes::COLORS_NUM],rect.top);
1061 else
1062 paintGraphLane(hdc, rect.Height(),ln, x1, x2, m_LineColors[col % Lanes::COLORS_NUM],rect.top);
1064 #endif
1067 void CGitLogListBase::OnNMCustomdrawLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1069 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
1070 // Take the default processing unless we set this to something else below.
1071 *pResult = CDRF_DODEFAULT;
1073 if (m_bNoDispUpdates)
1074 return;
1076 switch (pLVCD->nmcd.dwDrawStage)
1078 case CDDS_PREPAINT:
1080 *pResult = CDRF_NOTIFYITEMDRAW;
1081 return;
1083 break;
1084 case CDDS_ITEMPREPAINT:
1086 // This is the prepaint stage for an item. Here's where we set the
1087 // item's text color.
1089 // Tell Windows to send draw notifications for each subitem.
1090 *pResult = CDRF_NOTIFYSUBITEMDRAW;
1092 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
1094 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1096 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1097 if (data)
1099 HGDIOBJ hGdiObj = nullptr;
1100 int action = data->GetRebaseAction();
1101 if (action & (LOGACTIONS_REBASE_DONE | LOGACTIONS_REBASE_SKIP))
1102 crText = RGB(128,128,128);
1104 if (action & LOGACTIONS_REBASE_SQUASH)
1105 pLVCD->clrTextBk = RGB(156,156,156);
1106 else if (action & LOGACTIONS_REBASE_EDIT)
1107 pLVCD->clrTextBk = RGB(200,200,128);
1108 else
1109 pLVCD->clrTextBk = ::GetSysColor(COLOR_WINDOW);
1111 if (action & LOGACTIONS_REBASE_CURRENT)
1112 hGdiObj = m_boldFont.GetSafeHandle();
1114 BOOL isHeadHash = data->m_CommitHash == m_HeadHash && m_bNoHightlightHead == FALSE;
1115 BOOL isHighlight = data->m_CommitHash == m_highlight && !m_highlight.IsEmpty();
1116 if (isHeadHash && isHighlight)
1117 hGdiObj = m_boldItalicsFont.GetSafeHandle();
1118 else if (isHeadHash)
1119 hGdiObj = m_boldFont.GetSafeHandle();
1120 else if (isHighlight)
1121 hGdiObj = m_FontItalics.GetSafeHandle();
1123 if (hGdiObj)
1125 SelectObject(pLVCD->nmcd.hdc, hGdiObj);
1126 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1129 // if ((data->childStackDepth)||(m_mergedRevs.find(data->Rev) != m_mergedRevs.end()))
1130 // crText = GetSysColor(COLOR_GRAYTEXT);
1132 if (data->m_CommitHash.IsEmpty())
1134 //crText = GetSysColor(RGB(200,200,0));
1135 //SelectObject(pLVCD->nmcd.hdc, m_boldFont);
1136 // We changed the font, so we're returning CDRF_NEWFONT. This
1137 // tells the control to recalculate the extent of the text.
1138 *pResult = CDRF_NOTIFYSUBITEMDRAW | CDRF_NEWFONT;
1142 if (m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1144 if (m_bStrictStopped)
1145 crText = GetSysColor(COLOR_GRAYTEXT);
1147 // Store the color back in the NMLVCUSTOMDRAW struct.
1148 pLVCD->clrText = crText;
1149 return;
1151 break;
1152 case CDDS_ITEMPREPAINT|CDDS_ITEM|CDDS_SUBITEM:
1154 if (m_bStrictStopped && m_arShownList.size() == pLVCD->nmcd.dwItemSpec)
1156 pLVCD->nmcd.uItemState &= ~(CDIS_SELECTED|CDIS_FOCUS);
1159 if (pLVCD->iSubItem == LOGLIST_GRAPH && !HasFilterText() && (m_ShowFilter & FILTERSHOW_MERGEPOINTS))
1161 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec && !this->m_IsRebaseReplaceGraph)
1163 CRect rect;
1164 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_LABEL, rect);
1166 //TRACE(L"A Graphic left %d right %d\r\n", rect.left, rect.right);
1167 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1169 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1170 if( !data ->m_CommitHash.IsEmpty())
1171 DrawGraph(pLVCD->nmcd.hdc,rect,pLVCD->nmcd.dwItemSpec);
1173 *pResult = CDRF_SKIPDEFAULT;
1174 return;
1178 if (pLVCD->iSubItem == LOGLIST_MESSAGE)
1180 // If the top index of list is changed, the position map of reference label is outdated.
1181 if (m_OldTopIndex != GetTopIndex())
1183 m_OldTopIndex = GetTopIndex();
1184 m_RefLabelPosMap.clear();
1187 if (m_arShownList.size() > pLVCD->nmcd.dwItemSpec)
1189 GitRevLoglist* data = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1191 if ((m_HashMap.find(data->m_CommitHash) != m_HashMap.cend() || (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)) && !(data->GetRebaseAction() & LOGACTIONS_REBASE_DONE))
1193 CRect rect;
1194 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1196 // BEGIN: extended redraw, HACK for issue #1618 and #2014
1197 // not in FillBackGround method, because this only affected the message subitem
1198 if (0 != pLVCD->iStateId) // don't know why, but this helps against loosing the focus rect
1199 return;
1201 int index = (int)pLVCD->nmcd.dwItemSpec;
1202 int state = GetItemState(index, LVIS_SELECTED);
1203 int txtState = LISS_NORMAL;
1204 if (IsAppThemed() && GetHotItem() == (int)index)
1206 if (state & LVIS_SELECTED)
1207 txtState = LISS_HOTSELECTED;
1208 else
1209 txtState = LISS_HOT;
1211 else if (state & LVIS_SELECTED)
1213 if (::GetFocus() == m_hWnd)
1214 txtState = LISS_SELECTED;
1215 else
1216 txtState = LISS_SELECTEDNOTFOCUS;
1219 HTHEME hTheme = nullptr;
1220 if (IsAppThemed())
1221 hTheme = OpenThemeData(m_hWnd, L"Explorer::ListView;ListView");
1223 if (hTheme && IsThemeBackgroundPartiallyTransparent(hTheme, LVP_LISTDETAIL, txtState))
1224 DrawThemeParentBackground(m_hWnd, pLVCD->nmcd.hdc, &rect);
1225 else
1227 HBRUSH brush = ::CreateSolidBrush(pLVCD->clrTextBk);
1228 ::FillRect(pLVCD->nmcd.hdc, rect, brush);
1229 ::DeleteObject(brush);
1231 if (hTheme && txtState != LISS_NORMAL)
1233 CRect rt;
1234 // get rect of whole line
1235 GetItemRect(index, rt, LVIR_BOUNDS);
1236 CRect rect2 = rect;
1238 // calculate background for rect of whole line, but limit redrawing to SubItem rect
1239 DrawThemeBackground(hTheme, pLVCD->nmcd.hdc, LVP_LISTITEM, txtState, rt, rect2);
1241 CloseThemeData(hTheme);
1243 // END: extended redraw
1245 FillBackGround(pLVCD->nmcd.hdc, pLVCD->nmcd.dwItemSpec,rect);
1247 std::vector<REFLABEL> refsToShow;
1248 STRING_VECTOR remoteTrackingList;
1249 const STRING_VECTOR& refList = m_HashMap[data->m_CommitHash];
1250 for (unsigned int i = 0; i < refList.size(); ++i)
1252 CString str = refList[i];
1254 REFLABEL refLabel;
1255 refLabel.color = RGB(255, 255, 255);
1256 refLabel.singleRemote = false;
1257 refLabel.hasTracking = false;
1258 refLabel.sameName = false;
1259 refLabel.name = CGit::GetShortName(str, &refLabel.refType);
1260 refLabel.fullName = str;
1262 switch (refLabel.refType)
1264 case CGit::REF_TYPE::LOCAL_BRANCH:
1266 if (!(m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES))
1267 continue;
1268 if (refLabel.name == m_CurrentBranch)
1269 refLabel.color = m_Colors.GetColor(CColors::CurrentBranch);
1270 else
1271 refLabel.color = m_Colors.GetColor(CColors::LocalBranch);
1273 std::pair<CString, CString> trackingEntry = m_TrackingMap[refLabel.name];
1274 CString pullRemote = trackingEntry.first;
1275 CString pullBranch = trackingEntry.second;
1276 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
1278 CString defaultUpstream;
1279 defaultUpstream.Format(L"refs/remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
1280 refLabel.hasTracking = true;
1281 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
1283 bool found = false;
1284 for (size_t j = i + 1; j < refList.size(); ++j)
1286 if (refList[j] == defaultUpstream)
1288 found = true;
1289 break;
1293 if (found)
1295 bool sameName = pullBranch == refLabel.name;
1296 refsToShow.push_back(refLabel);
1297 CGit::GetShortName(defaultUpstream, refLabel.name, L"refs/remotes/");
1298 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1299 if (m_bSymbolizeRefNames)
1301 if (!m_SingleRemote.IsEmpty() && m_SingleRemote == pullRemote)
1303 refLabel.simplifiedName = L'/';
1304 if (sameName)
1305 refLabel.simplifiedName += L'≡';
1306 else
1307 refLabel.simplifiedName += pullBranch;
1308 refLabel.singleRemote = true;
1310 else if (sameName)
1311 refLabel.simplifiedName = pullRemote + L"/≡";
1312 refLabel.sameName = sameName;
1314 refLabel.fullName = defaultUpstream;
1315 refsToShow.push_back(refLabel);
1316 remoteTrackingList.push_back(defaultUpstream);
1317 continue;
1321 break;
1323 case CGit::REF_TYPE::REMOTE_BRANCH:
1325 if (!(m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES))
1326 continue;
1327 bool found = false;
1328 for (size_t j = 0; j < remoteTrackingList.size(); ++j)
1330 if (remoteTrackingList[j] == str)
1332 found = true;
1333 break;
1336 if (found)
1337 continue;
1339 refLabel.color = m_Colors.GetColor(CColors::RemoteBranch);
1340 if (m_bSymbolizeRefNames)
1342 if (!m_SingleRemote.IsEmpty() && CStringUtils::StartsWith(refLabel.name, m_SingleRemote + L"/"))
1344 refLabel.simplifiedName = L'/' + refLabel.name.Mid(m_SingleRemote.GetLength() + 1);
1345 refLabel.singleRemote = true;
1348 break;
1350 case CGit::REF_TYPE::ANNOTATED_TAG:
1351 case CGit::REF_TYPE::TAG:
1352 if (!(m_ShowRefMask & LOGLIST_SHOWTAGS))
1353 continue;
1354 refLabel.color = m_Colors.GetColor(CColors::Tag);
1355 break;
1356 case CGit::REF_TYPE::STASH:
1357 if (!(m_ShowRefMask & LOGLIST_SHOWSTASH))
1358 continue;
1359 refLabel.color = m_Colors.GetColor(CColors::Stash);
1360 break;
1361 case CGit::REF_TYPE::BISECT_GOOD:
1362 case CGit::REF_TYPE::BISECT_BAD:
1363 case CGit::REF_TYPE::BISECT_SKIP:
1364 if (!(m_ShowRefMask & LOGLIST_SHOWBISECT))
1365 continue;
1366 refLabel.color = (refLabel.refType == CGit::REF_TYPE::BISECT_GOOD) ? m_Colors.GetColor(CColors::BisectGood) : ((refLabel.refType == CGit::REF_TYPE::BISECT_SKIP) ? m_Colors.GetColor(CColors::BisectSkip) : m_Colors.GetColor(CColors::BisectBad));
1367 break;
1368 case CGit::REF_TYPE::NOTES:
1369 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1370 continue;
1371 refLabel.color = m_Colors.GetColor(CColors::NoteNode);
1372 break;
1373 default:
1374 if (!(m_ShowRefMask & LOGLIST_SHOWOTHERREFS))
1375 continue;
1376 refLabel.color = m_Colors.GetColor(CColors::OtherRef);
1377 break;
1379 refsToShow.push_back(refLabel);
1381 if (!m_superProjectHash.IsEmpty() && data->m_CommitHash == m_superProjectHash)
1383 REFLABEL refLabel;
1384 refLabel.color = RGB(246, 153, 253);
1385 refLabel.singleRemote = false;
1386 refLabel.hasTracking = false;
1387 refLabel.sameName = false;
1388 refLabel.name = L"super-project-pointer";
1389 refLabel.fullName = "";
1390 refsToShow.push_back(refLabel);
1393 if (refsToShow.empty())
1395 *pResult = CDRF_DODEFAULT;
1396 return;
1399 DrawTagBranchMessage(pLVCD->nmcd.hdc, rect, pLVCD->nmcd.dwItemSpec, refsToShow);
1401 *pResult = CDRF_SKIPDEFAULT;
1402 return;
1409 if (pLVCD->iSubItem == LOGLIST_ACTION)
1411 if (m_IsIDReplaceAction || !m_ColumnManager.IsVisible(LOGLIST_ACTION))
1413 *pResult = CDRF_DODEFAULT;
1414 return;
1416 *pResult = CDRF_DODEFAULT;
1418 if (m_arShownList.size() <= pLVCD->nmcd.dwItemSpec)
1419 return;
1421 int nIcons = 0;
1422 int iconwidth = ::GetSystemMetrics(SM_CXSMICON);
1423 int iconheight = ::GetSystemMetrics(SM_CYSMICON);
1425 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pLVCD->nmcd.dwItemSpec);
1426 CRect rect;
1427 GetSubItemRect((int)pLVCD->nmcd.dwItemSpec, pLVCD->iSubItem, LVIR_BOUNDS, rect);
1428 //TRACE(L"Action left %d right %d\r\n", rect.left, rect.right);
1429 // Get the selected state of the
1430 // item being drawn.
1432 CMemDC myDC(*CDC::FromHandle(pLVCD->nmcd.hdc), rect);
1433 BitBlt(myDC.GetDC(), rect.left, rect.top, rect.Width(), rect.Height(), pLVCD->nmcd.hdc, rect.left, rect.top, SRCCOPY);
1435 // Fill the background if necessary
1436 FillBackGround(myDC.GetDC(), pLVCD->nmcd.dwItemSpec, rect);
1438 // Draw the icon(s) into the compatible DC
1439 int action = pLogEntry->GetAction(this);
1440 if (!pLogEntry->m_IsDiffFiles)
1442 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hFetchIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1443 *pResult = CDRF_SKIPDEFAULT;
1444 return;
1447 if (action & CTGitPath::LOGACTIONS_MODIFIED)
1448 ::DrawIconEx(myDC.GetDC(), rect.left + ICONITEMBORDER, rect.top, m_hModifiedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1449 ++nIcons;
1451 if (action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_COPY))
1452 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hAddedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1453 ++nIcons;
1455 if (action & CTGitPath::LOGACTIONS_DELETED)
1456 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hDeletedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1457 ++nIcons;
1459 if (action & CTGitPath::LOGACTIONS_REPLACED)
1460 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hReplacedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1461 ++nIcons;
1463 if (action & CTGitPath::LOGACTIONS_UNMERGED)
1464 ::DrawIconEx(myDC.GetDC(), rect.left + nIcons * iconwidth + ICONITEMBORDER, rect.top, m_hConflictedIcon, iconwidth, iconheight, 0, nullptr, DI_NORMAL);
1465 ++nIcons;
1467 *pResult = CDRF_SKIPDEFAULT;
1468 return;
1471 break;
1473 *pResult = CDRF_DODEFAULT;
1476 CString FindSVNRev(const CString& msg)
1480 const std::wsregex_iterator end;
1481 std::wstring s = msg;
1482 std::wregex regex1(L"^\\s*git-svn-id:\\s+(.*)\\@(\\d+)\\s([a-f\\d\\-]+)$");
1483 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex1); it != end; ++it)
1485 const std::wsmatch match = *it;
1486 if (match.size() == 4)
1488 ATLTRACE(L"matched rev: %s\n", std::wstring(match[2]).c_str());
1489 return std::wstring(match[2]).c_str();
1492 std::wregex regex2(L"^\\s*git-svn-id:\\s(\\d+)\\@([a-f\\d\\-]+)$");
1493 for (std::wsregex_iterator it(s.cbegin(), s.cend(), regex2); it != end; ++it)
1495 const std::wsmatch match = *it;
1496 if (match.size() == 3)
1498 ATLTRACE(L"matched rev: %s\n", std::wstring(match[1]).c_str());
1499 return std::wstring(match[1]).c_str();
1503 catch (std::exception&) {}
1505 return L"";
1508 CString CGitLogListBase::MessageDisplayStr(GitRev* pLogEntry)
1510 if (!m_bFullCommitMessageOnLogLine || pLogEntry->GetBody().IsEmpty())
1511 return pLogEntry->GetSubject();
1513 CString txt(pLogEntry->GetSubject());
1514 txt += L' ';
1515 txt += pLogEntry->GetBody();
1517 // Deal with CRLF
1518 txt.Replace(L'\n', L' ');
1519 txt.Replace(L'\r', L' ');
1521 return txt;
1524 // CGitLogListBase message handlers
1526 static const char* GetMailmapMapping(GIT_MAILMAP mailmap, const CString& email, const CString& name, bool returnEmail)
1528 struct payload_struct { const CString* name; const char* authorName; };
1529 payload_struct payload = { &name, nullptr };
1530 const char* author1 = nullptr;
1531 const char* email1 = nullptr;
1532 git_lookup_mailmap(mailmap, &email1, &author1, CUnicodeUtils::GetUTF8(email), &payload,
1533 [](void* payload) -> const char* { return reinterpret_cast<payload_struct*>(payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(*reinterpret_cast<payload_struct*>(payload)->name)); });
1534 free((void *)payload.authorName);
1535 if (returnEmail)
1536 return email1;
1537 return author1;
1540 static void CopyMailmapProcessedData(GIT_MAILMAP mailmap, LV_ITEM* pItem, const CString& email, const CString& name, bool returnEmail)
1542 if (mailmap)
1544 const char* translated = GetMailmapMapping(mailmap, email, name, returnEmail);
1545 if (translated)
1547 lstrcpyn(pItem->pszText, CUnicodeUtils::GetUnicode(translated), pItem->cchTextMax - 1);
1548 return;
1551 if (returnEmail)
1552 lstrcpyn(pItem->pszText, (LPCTSTR)email, pItem->cchTextMax - 1);
1553 else
1554 lstrcpyn(pItem->pszText, (LPCTSTR)name, pItem->cchTextMax - 1);
1557 void CGitLogListBase::OnLvnGetdispinfoLoglist(NMHDR *pNMHDR, LRESULT *pResult)
1559 NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
1561 // Create a pointer to the item
1562 LV_ITEM* pItem = &(pDispInfo)->item;
1564 // Do the list need text information?
1565 if (!(pItem->mask & LVIF_TEXT))
1566 return;
1568 // By default, clear text buffer.
1569 lstrcpyn(pItem->pszText, L"", pItem->cchTextMax - 1);
1571 bool bOutOfRange = pItem->iItem >= ShownCountWithStopped();
1573 *pResult = 0;
1574 if (m_bNoDispUpdates || bOutOfRange)
1575 return;
1577 // Which item number?
1578 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(pItem->iItem);
1580 CString temp;
1581 if(m_IsOldFirst)
1582 temp.Format(L"%d", pItem->iItem + 1);
1583 else
1584 temp.Format(L"%zu", m_arShownList.size() - pItem->iItem);
1586 if (!pLogEntry)
1587 return;
1589 // Which column?
1590 switch (pItem->iSubItem)
1592 case LOGLIST_GRAPH: //Graphic
1593 break;
1594 case LOGLIST_REBASE:
1595 if (m_IsRebaseReplaceGraph)
1596 lstrcpyn(pItem->pszText, GetRebaseActionName(pLogEntry->GetRebaseAction() & LOGACTIONS_REBASE_MODE_MASK), pItem->cchTextMax - 1);
1597 break;
1598 case LOGLIST_ACTION: //action -- no text in the column
1599 break;
1600 case LOGLIST_HASH:
1601 lstrcpyn(pItem->pszText, pLogEntry->m_CommitHash.ToString(), pItem->cchTextMax - 1);
1602 break;
1603 case LOGLIST_ID:
1604 if (this->m_IsIDReplaceAction)
1605 lstrcpyn(pItem->pszText, temp, pItem->cchTextMax - 1);
1606 break;
1607 case LOGLIST_MESSAGE: //Message
1608 lstrcpyn(pItem->pszText, (LPCTSTR)MessageDisplayStr(pLogEntry), pItem->cchTextMax - 1);
1609 break;
1610 case LOGLIST_AUTHOR: //Author
1611 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), false);
1612 break;
1613 case LOGLIST_DATE: //Date
1614 if (!pLogEntry->m_CommitHash.IsEmpty())
1615 lstrcpyn(pItem->pszText,
1616 CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
1617 pItem->cchTextMax - 1);
1618 break;
1620 case LOGLIST_EMAIL:
1621 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetAuthorEmail(), pLogEntry->GetAuthorName(), true);
1622 break;
1624 case LOGLIST_COMMIT_NAME: //Commit
1625 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), false);
1626 break;
1628 case LOGLIST_COMMIT_EMAIL: //Commit Email
1629 CopyMailmapProcessedData(m_pMailmap, pItem, pLogEntry->GetCommitterEmail(), pLogEntry->GetCommitterName(), true);
1630 break;
1632 case LOGLIST_COMMIT_DATE: //Commit Date
1633 if (!pLogEntry->m_CommitHash.IsEmpty())
1634 lstrcpyn(pItem->pszText,
1635 CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, m_bRelativeTimes),
1636 pItem->cchTextMax - 1);
1637 break;
1638 case LOGLIST_BUG: //Bug ID
1639 lstrcpyn(pItem->pszText, (LPCTSTR)this->m_ProjectProperties.FindBugID(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1640 break;
1641 case LOGLIST_SVNREV: //SVN revision
1642 lstrcpyn(pItem->pszText, (LPCTSTR)FindSVNRev(pLogEntry->GetSubjectBody()), pItem->cchTextMax - 1);
1643 break;
1645 default:
1646 ASSERT(false);
1650 bool CGitLogListBase::IsOnStash(int index)
1652 GitRevLoglist* rev = m_arShownList.SafeGetAt(index);
1653 if (IsStash(rev))
1654 return true;
1655 if (index > 0)
1657 GitRevLoglist* preRev = m_arShownList.SafeGetAt(index - 1);
1658 if (IsStash(preRev))
1659 return preRev->m_ParentHash.size() == 2 && preRev->m_ParentHash[1] == rev->m_CommitHash;
1661 return false;
1664 bool CGitLogListBase::IsStash(const GitRev * pSelLogEntry)
1666 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1667 if (refList == m_HashMap.cend())
1668 return false;
1669 return find_if((*refList).second, [](const auto& ref) { return ref == L"refs/stash"; }) != (*refList).second.cend();
1672 bool CGitLogListBase::IsBisect(const GitRev * pSelLogEntry)
1674 auto refList = m_HashMap.find(pSelLogEntry->m_CommitHash);
1675 if (refList == m_HashMap.cend())
1676 return false;
1677 return find_if((*refList).second, [](const auto& ref) { return CStringUtils::StartsWith(ref, L"refs/bisect/"); }) != (*refList).second.cend();
1680 void CGitLogListBase::GetParentHashes(GitRev *pRev, GIT_REV_LIST &parentHash)
1682 if (pRev->m_ParentHash.empty())
1684 if (pRev->GetParentFromHash(pRev->m_CommitHash))
1685 MessageBox(pRev->GetLastErr(), L"TortoiseGit", MB_ICONERROR);
1687 parentHash = pRev->m_ParentHash;
1690 void CGitLogListBase::OnContextMenu(CWnd* pWnd, CPoint point)
1692 __super::OnContextMenu(pWnd, point);
1694 if (pWnd != this)
1695 return;
1697 int selIndex = GetSelectionMark();
1698 if (selIndex < 0)
1699 return; // nothing selected, nothing to do with a context menu
1701 // if the user selected the info text telling about not all revisions shown due to
1702 // the "stop on copy/rename" option, we also don't show the context menu
1703 if (m_bStrictStopped && selIndex == (int)m_arShownList.size())
1704 return;
1706 // if the context menu is invoked through the keyboard, we have to use
1707 // a calculated position on where to anchor the menu on
1708 if ((point.x == -1) && (point.y == -1))
1710 CRect rect;
1711 GetItemRect(selIndex, &rect, LVIR_LABEL);
1712 ClientToScreen(&rect);
1713 point = rect.CenterPoint();
1715 m_nSearchIndex = selIndex;
1717 bool showExtendedMenu = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
1719 POSITION pos = GetFirstSelectedItemPosition();
1720 int FirstSelect = GetNextSelectedItem(pos);
1721 if (FirstSelect < 0)
1722 return;
1724 GitRevLoglist* pSelLogEntry = m_arShownList.SafeGetAt(FirstSelect);
1725 if (pSelLogEntry == nullptr)
1726 return;
1728 int LastSelect = -1;
1729 UINT selectedCount = 1;
1730 while (pos)
1732 LastSelect = GetNextSelectedItem(pos);
1733 ++selectedCount;
1736 ASSERT(GetSelectedCount() == selectedCount);
1738 #if 0
1739 GitRev revSelected = pSelLogEntry->Rev;
1740 GitRev revPrevious = git_revnum_t(revSelected)-1;
1741 if ((pSelLogEntry->pArChangedPaths)&&(pSelLogEntry->pArChangedPaths->GetCount() <= 2))
1743 for (int i=0; i<pSelLogEntry->pArChangedPaths->GetCount(); ++i)
1745 LogChangedPath * changedpath = (LogChangedPath *)pSelLogEntry->pArChangedPaths->SafeGetAt(i);
1746 if (changedpath->lCopyFromRev)
1747 revPrevious = changedpath->lCopyFromRev;
1750 GitRev revSelected2;
1751 if (pos)
1753 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1754 revSelected2 = pLogEntry->Rev;
1756 bool bAllFromTheSameAuthor = true;
1757 CString firstAuthor;
1758 CLogDataVector selEntries;
1759 GitRev revLowest, revHighest;
1760 GitRevRangeArray revisionRanges;
1762 POSITION pos = GetFirstSelectedItemPosition();
1763 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1764 revisionRanges.AddRevision(pLogEntry->Rev);
1765 selEntries.push_back(pLogEntry);
1766 firstAuthor = pLogEntry->sAuthor;
1767 revLowest = pLogEntry->Rev;
1768 revHighest = pLogEntry->Rev;
1769 while (pos)
1771 pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(GetNextSelectedItem(pos)));
1772 revisionRanges.AddRevision(pLogEntry->Rev);
1773 selEntries.push_back(pLogEntry);
1774 if (firstAuthor.Compare(pLogEntry->sAuthor))
1775 bAllFromTheSameAuthor = false;
1776 revLowest = (git_revnum_t(pLogEntry->Rev) > git_revnum_t(revLowest) ? revLowest : pLogEntry->Rev);
1777 revHighest = (git_revnum_t(pLogEntry->Rev) < git_revnum_t(revHighest) ? revHighest : pLogEntry->Rev);
1781 #endif
1783 //entry is selected, now show the popup menu
1784 CIconMenu popup;
1785 CIconMenu subbranchmenu, submenu, gnudiffmenu, diffmenu, blamemenu, revertmenu;
1787 if (popup.CreatePopupMenu())
1789 bool isHeadCommit = (pSelLogEntry->m_CommitHash == m_HeadHash);
1790 CString currentBranch = L"refs/heads/" + g_Git.GetCurrentBranch();
1791 CTGitPath workingTree(g_Git.m_CurrentDir);
1792 bool isMergeActive = workingTree.IsMergeActive();
1793 bool isBisectActive = workingTree.IsBisectActive();
1794 bool isStash = IsOnStash(FirstSelect);
1795 GIT_REV_LIST parentHash;
1796 GetParentHashes(pSelLogEntry, parentHash);
1798 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_PICK) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1799 popup.AppendMenuIcon(ID_REBASE_PICK, IDS_REBASE_PICK, IDI_PICK);
1801 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))
1802 popup.AppendMenuIcon(ID_REBASE_SQUASH, IDS_REBASE_SQUASH, IDI_SQUASH);
1804 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_EDIT) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1805 popup.AppendMenuIcon(ID_REBASE_EDIT, IDS_REBASE_EDIT, IDI_EDIT);
1807 if (m_ContextMenuMask & GetContextMenuBit(ID_REBASE_SKIP) && !(pSelLogEntry->GetRebaseAction() & (LOGACTIONS_REBASE_CURRENT | LOGACTIONS_REBASE_DONE)))
1808 popup.AppendMenuIcon(ID_REBASE_SKIP, IDS_REBASE_SKIP, IDI_SKIP);
1810 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)))
1811 popup.AppendMenu(MF_SEPARATOR, NULL);
1813 if (selectedCount == 1)
1816 bool requiresSeparator = false;
1817 if( !pSelLogEntry->m_CommitHash.IsEmpty())
1819 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPARE) && m_hasWC) // compare revision with WC
1821 popup.AppendMenuIcon(ID_COMPARE, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1822 requiresSeparator = true;
1825 else
1827 if(m_ContextMenuMask&GetContextMenuBit(ID_COMMIT))
1829 popup.AppendMenuIcon(ID_COMMIT, IDS_LOG_POPUP_COMMIT, IDI_COMMIT);
1830 requiresSeparator = true;
1832 if (isMergeActive && (m_ContextMenuMask & GetContextMenuBit(ID_MERGE_ABORT)))
1834 popup.AppendMenuIcon(ID_MERGE_ABORT, IDS_MENUMERGEABORT, IDI_MERGEABORT);
1835 requiresSeparator = true;
1839 if (m_ContextMenuMask & GetContextMenuBit(ID_BLAMEPREVIOUS))
1841 if (parentHash.size() == 1)
1843 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME);
1844 requiresSeparator = true;
1846 else if (parentHash.size() > 1)
1848 blamemenu.CreatePopupMenu();
1849 popup.AppendMenuIcon(ID_BLAMEPREVIOUS, IDS_LOG_POPUP_BLAMEPREVIOUS, IDI_BLAME, blamemenu.m_hMenu);
1850 for (size_t i = 0; i < parentHash.size(); ++i)
1852 CString str;
1853 str.Format(IDS_PARENT, i + 1);
1854 blamemenu.AppendMenuIcon(ID_BLAMEPREVIOUS +((i + 1) << 16), str);
1856 requiresSeparator = true;
1860 if(m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF1) && m_hasWC) // compare with WC, unified
1862 if (parentHash.size() == 1)
1864 popup.AppendMenuIcon(ID_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF_CH, IDI_DIFF);
1865 requiresSeparator = true;
1867 else if (parentHash.size() > 1)
1869 gnudiffmenu.CreatePopupMenu();
1870 popup.AppendMenuIcon(ID_GNUDIFF1,IDS_LOG_POPUP_GNUDIFF_PARENT, IDI_DIFF, gnudiffmenu.m_hMenu);
1872 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFF << 16)), CString(MAKEINTRESOURCE(IDS_ALLPARENTS)));
1873 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFE << 16)), CString(MAKEINTRESOURCE(IDS_ONLYMERGEDFILES)));
1874 gnudiffmenu.AppendMenuIcon((UINT_PTR)(ID_GNUDIFF1 + (0xFFFD << 16)), CString(MAKEINTRESOURCE(IDS_DIFFWITHMERGE)));
1876 for (size_t i = 0; i < parentHash.size(); ++i)
1878 CString str;
1879 str.Format(IDS_PARENT, i + 1);
1880 gnudiffmenu.AppendMenuIcon(ID_GNUDIFF1+((i+1)<<16),str);
1882 requiresSeparator = true;
1886 if(m_ContextMenuMask&GetContextMenuBit(ID_COMPAREWITHPREVIOUS))
1888 if (parentHash.size() == 1)
1890 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF);
1891 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1892 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1893 requiresSeparator = true;
1895 else if (parentHash.size() > 1)
1897 diffmenu.CreatePopupMenu();
1898 popup.AppendMenuIcon(ID_COMPAREWITHPREVIOUS, IDS_LOG_POPUP_COMPAREWITHPREVIOUS, IDI_DIFF, diffmenu.m_hMenu);
1899 for (size_t i = 0; i < parentHash.size(); ++i)
1901 CString str;
1902 str.Format(IDS_PARENT, i + 1);
1903 diffmenu.AppendMenuIcon(ID_COMPAREWITHPREVIOUS +((i+1)<<16),str);
1904 if (i == 0 && CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
1906 popup.SetDefaultItem(ID_COMPAREWITHPREVIOUS, FALSE);
1907 diffmenu.SetDefaultItem((UINT)(ID_COMPAREWITHPREVIOUS + ((i + 1) << 16)), FALSE);
1910 requiresSeparator = true;
1914 if(m_ContextMenuMask&GetContextMenuBit(ID_BLAME))
1916 popup.AppendMenuIcon(ID_BLAME, IDS_LOG_POPUP_BLAME, IDI_BLAME);
1917 requiresSeparator = true;
1920 if (requiresSeparator)
1922 popup.AppendMenu(MF_SEPARATOR, NULL);
1923 requiresSeparator = false;
1926 if (pSelLogEntry->m_CommitHash.IsEmpty() && !isMergeActive)
1928 if(m_ContextMenuMask&GetContextMenuBit(ID_STASH_SAVE))
1930 popup.AppendMenuIcon(ID_STASH_SAVE, IDS_MENUSTASHSAVE, IDI_COMMIT);
1931 requiresSeparator = true;
1935 if ((pSelLogEntry->m_CommitHash.IsEmpty() || isStash) && workingTree.HasStashDir())
1937 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_POP))
1939 popup.AppendMenuIcon(ID_STASH_POP, IDS_MENUSTASHPOP, IDI_RELOCATE);
1940 requiresSeparator = true;
1943 if (m_ContextMenuMask&GetContextMenuBit(ID_STASH_LIST))
1945 popup.AppendMenuIcon(ID_STASH_LIST, IDS_MENUSTASHLIST, IDI_LOG);
1946 requiresSeparator = true;
1950 if (requiresSeparator)
1952 popup.AppendMenu(MF_SEPARATOR, NULL);
1953 requiresSeparator = false;
1956 if (isBisectActive)
1958 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
1959 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTGOOD) && !IsBisect(pFirstEntry))
1961 popup.AppendMenuIcon(ID_BISECTGOOD, IDS_MENUBISECTGOOD, IDI_THUMB_UP);
1962 requiresSeparator = true;
1965 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTBAD) && !IsBisect(pFirstEntry))
1967 popup.AppendMenuIcon(ID_BISECTBAD, IDS_MENUBISECTBAD, IDI_THUMB_DOWN);
1968 requiresSeparator = true;
1970 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTSKIP) && !IsBisect(pFirstEntry))
1972 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
1973 requiresSeparator = true;
1977 if (pSelLogEntry->m_CommitHash.IsEmpty() && isBisectActive)
1979 if (m_ContextMenuMask&GetContextMenuBit(ID_BISECTRESET))
1981 popup.AppendMenuIcon(ID_BISECTRESET, IDS_MENUBISECTRESET, IDI_BISECT_RESET);
1982 requiresSeparator = true;
1986 if (requiresSeparator)
1988 popup.AppendMenu(MF_SEPARATOR, NULL);
1989 requiresSeparator = false;
1992 if (pSelLogEntry->m_CommitHash.IsEmpty())
1994 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && !isMergeActive)
1995 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
1997 if(m_ContextMenuMask&GetContextMenuBit(ID_FETCH))
1998 popup.AppendMenuIcon(ID_FETCH, IDS_MENUFETCH, IDI_PULL);
2000 if ((m_ContextMenuMask & GetContextMenuBit(ID_SUBMODULE_UPDATE)) && workingTree.HasSubmodules())
2001 popup.AppendMenuIcon(ID_SUBMODULE_UPDATE, IDS_PROC_SYNC_SUBKODULEUPDATE, IDI_UPDATE);
2003 popup.AppendMenu(MF_SEPARATOR, NULL);
2005 if (m_ContextMenuMask & GetContextMenuBit(ID_CLEANUP))
2006 popup.AppendMenuIcon(ID_CLEANUP, IDS_MENUCLEANUP, IDI_CLEANUP);
2008 popup.AppendMenu(MF_SEPARATOR, NULL);
2012 // if (!m_ProjectProperties.sWebViewerRev.IsEmpty())
2013 // {
2014 // popup.AppendMenuIcon(ID_VIEWREV, IDS_LOG_POPUP_VIEWREV);
2015 // }
2016 // if (!m_ProjectProperties.sWebViewerPathRev.IsEmpty())
2017 // {
2018 // popup.AppendMenuIcon(ID_VIEWPATHREV, IDS_LOG_POPUP_VIEWPATHREV);
2019 // }
2020 // if ((!m_ProjectProperties.sWebViewerPathRev.IsEmpty())||
2021 // (!m_ProjectProperties.sWebViewerRev.IsEmpty()))
2022 // {
2023 // popup.AppendMenu(MF_SEPARATOR, NULL);
2024 // }
2026 CString str;
2027 //if (m_hasWC)
2028 // popup.AppendMenuIcon(ID_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
2030 if(!pSelLogEntry->m_CommitHash.IsEmpty())
2032 if ((m_ContextMenuMask & GetContextMenuBit(ID_LOG)) && selectedCount == 1)
2033 popup.AppendMenuIcon(ID_LOG, IDS_LOG_POPUP_LOG, IDI_LOG);
2035 if (m_ContextMenuMask&GetContextMenuBit(ID_REPOBROWSE))
2036 popup.AppendMenuIcon(ID_REPOBROWSE, IDS_LOG_BROWSEREPO, IDI_REPOBROWSE);
2038 str.Format(IDS_LOG_POPUP_MERGEREV, (LPCTSTR)g_Git.GetCurrentBranch());
2040 if (m_ContextMenuMask&GetContextMenuBit(ID_MERGEREV) && !isHeadCommit && m_hasWC && !isMergeActive && !isStash)
2042 popup.AppendMenuIcon(ID_MERGEREV, str, IDI_MERGE);
2044 size_t index = (size_t)-1;
2045 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2046 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2047 popup.SetMenuItemData(ID_MERGEREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2050 str.Format(IDS_RESET_TO_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2052 if (m_ContextMenuMask&GetContextMenuBit(ID_RESET) && m_hasWC && !isStash)
2053 popup.AppendMenuIcon(ID_RESET,str,IDI_REVERT);
2056 // Add Switch Branch express Menu
2057 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end()
2058 && (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHBRANCH) && m_hasWC && !isStash)
2061 std::vector<const CString*> branchs;
2062 auto addCheck = [&](const CString& ref)
2064 if (!CStringUtils::StartsWith(ref, L"refs/heads/") || ref == currentBranch)
2065 return;
2066 branchs.push_back(&ref);
2068 size_t index = (size_t)-1;
2069 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2070 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2071 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2072 else
2073 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2075 CString str2;
2076 str2.LoadString(IDS_SWITCH_BRANCH);
2078 if(branchs.size() == 1)
2080 str2 += L' ';
2081 str2 += L'"' + branchs[0]->Mid((int)wcslen(L"refs/heads/")) + L'"';
2082 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH);
2084 popup.SetMenuItemData(ID_SWITCHBRANCH,(ULONG_PTR)branchs[0]);
2087 else if(branchs.size() > 1)
2089 subbranchmenu.CreatePopupMenu();
2090 for (size_t i = 0 ; i < branchs.size(); ++i)
2092 if (*branchs[i] != currentBranch)
2094 subbranchmenu.AppendMenuIcon(ID_SWITCHBRANCH+(i<<16), branchs[i]->Mid(11));
2095 subbranchmenu.SetMenuItemData(ID_SWITCHBRANCH+(i<<16), (ULONG_PTR) branchs[i]);
2099 popup.AppendMenuIcon(ID_SWITCHBRANCH, str2, IDI_SWITCH, subbranchmenu.m_hMenu);
2103 if (m_ContextMenuMask&GetContextMenuBit(ID_SWITCHTOREV) && !isHeadCommit && m_hasWC && !isStash)
2105 popup.AppendMenuIcon(ID_SWITCHTOREV, IDS_SWITCH_TO_THIS, IDI_SWITCH);
2106 size_t index = (size_t)-1;
2107 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2108 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2109 popup.SetMenuItemData(ID_SWITCHTOREV, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2112 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_BRANCH) && !isStash)
2114 popup.AppendMenuIcon(ID_CREATE_BRANCH, IDS_CREATE_BRANCH_AT_THIS, IDI_COPY);
2116 size_t index = (size_t)-1;
2117 CGit::REF_TYPE type = CGit::REF_TYPE::REMOTE_BRANCH;
2118 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2119 popup.SetMenuItemData(ID_CREATE_BRANCH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2122 if (m_ContextMenuMask&GetContextMenuBit(ID_CREATE_TAG) && !isStash)
2123 popup.AppendMenuIcon(ID_CREATE_TAG,IDS_CREATE_TAG_AT_THIS , IDI_TAG);
2125 str.Format(IDS_REBASE_THIS_FORMAT, (LPCTSTR)g_Git.GetCurrentBranch());
2127 if (pSelLogEntry->m_CommitHash != m_HeadHash && m_hasWC && !isMergeActive && !isStash)
2128 if(m_ContextMenuMask&GetContextMenuBit(ID_REBASE_TO_VERSION))
2129 popup.AppendMenuIcon(ID_REBASE_TO_VERSION, str , IDI_REBASE);
2131 if(m_ContextMenuMask&GetContextMenuBit(ID_EXPORT))
2132 popup.AppendMenuIcon(ID_EXPORT,IDS_EXPORT_TO_THIS, IDI_EXPORT);
2134 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive && !isStash)
2136 if (parentHash.size() == 1)
2137 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT);
2138 else if (parentHash.size() > 1)
2140 revertmenu.CreatePopupMenu();
2141 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREV, IDI_REVERT, revertmenu.m_hMenu);
2143 for (size_t i = 0; i < parentHash.size(); ++i)
2145 CString str2;
2146 str2.Format(IDS_PARENT, i + 1);
2147 revertmenu.AppendMenuIcon(ID_REVERTREV + ((i + 1) << 16), str2);
2152 if (m_ContextMenuMask&GetContextMenuBit(ID_EDITNOTE) && !isStash)
2153 popup.AppendMenuIcon(ID_EDITNOTE, IDS_EDIT_NOTES, IDI_EDIT);
2155 popup.AppendMenu(MF_SEPARATOR, NULL);
2159 if(!pSelLogEntry->m_Ref.IsEmpty())
2161 popup.AppendMenuIcon(ID_REFLOG_DEL, IDS_REFLOG_DEL, IDI_DELETE);
2162 if (selectedCount == 1 && CStringUtils::StartsWith(pSelLogEntry->m_Ref, L"refs/stash"))
2163 popup.AppendMenuIcon(ID_REFLOG_STASH_APPLY, IDS_MENUSTASHAPPLY, IDI_RELOCATE);
2164 if (selectedCount <= 2)
2165 popup.AppendMenu(MF_SEPARATOR, NULL);
2168 if (selectedCount >= 2)
2170 bool bAddSeparator = false;
2171 if ((selectedCount == 2) || IsSelectionContinuous())
2173 if (m_ContextMenuMask&GetContextMenuBit(ID_COMPARETWO)) // compare two revisions
2175 popup.AppendMenuIcon(ID_COMPARETWO, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
2176 bAddSeparator = true;
2180 if (selectedCount == 2)
2182 if (m_ContextMenuMask&GetContextMenuBit(ID_GNUDIFF2) && m_hasWC) // compare two revisions, unified
2184 popup.AppendMenuIcon(ID_GNUDIFF2, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
2185 bAddSeparator = true;
2188 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2190 CString firstSelHash = pSelLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2191 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2192 CString lastSelHash = pLastEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength());
2193 CString menu;
2194 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L".." + firstSelHash));
2195 popup.AppendMenuIcon(ID_LOG_VIEWRANGE, menu, IDI_LOG);
2196 menu.Format(IDS_SHOWLOG_OF, (LPCTSTR)(lastSelHash + L"..." + firstSelHash));
2197 popup.AppendMenuIcon(ID_LOG_VIEWRANGE_REACHABLEFROMONLYONE, menu, IDI_LOG);
2198 bAddSeparator = true;
2202 if ((m_ContextMenuMask & GetContextMenuBit(ID_COMPARETWOCOMMITCHANGES)) && selectedCount == 2 && !IsSelectionContinuous())
2204 bAddSeparator = true;
2205 popup.AppendMenuIcon(ID_COMPARETWOCOMMITCHANGES, IDS_LOG_POPUP_COMPARECHANGESET, IDI_DIFF);
2208 if (bAddSeparator)
2210 popup.AppendMenu(MF_SEPARATOR, NULL);
2211 bAddSeparator = false;
2214 if (m_ContextMenuMask&GetContextMenuBit(ID_REVERTREV) && m_hasWC && !isMergeActive)
2215 popup.AppendMenuIcon(ID_REVERTREV, IDS_LOG_POPUP_REVERTREVS, IDI_REVERT);
2217 if (bAddSeparator)
2218 popup.AppendMenu(MF_SEPARATOR, NULL);
2221 if (selectedCount > 1 && isBisectActive && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSKIP)) && !IsBisect(pSelLogEntry))
2223 popup.AppendMenuIcon(ID_BISECTSKIP, IDS_MENUBISECTSKIP, IDI_BISECT);
2224 popup.AppendMenu(MF_SEPARATOR, NULL);
2227 if (!pSelLogEntry->m_CommitHash.IsEmpty())
2229 bool bAddSeparator = false;
2230 if (selectedCount >= 2 && IsSelectionContinuous())
2232 if (m_ContextMenuMask&GetContextMenuBit(ID_COMBINE_COMMIT) && m_hasWC && !isMergeActive)
2234 CString head;
2235 int headindex;
2236 headindex = this->GetHeadIndex();
2237 if(headindex>=0 && LastSelect >= headindex && FirstSelect >= headindex)
2239 head.Format(L"HEAD~%d", FirstSelect - headindex);
2240 CGitHash hashFirst;
2241 int ret = g_Git.GetHash(hashFirst, head);
2242 head.Format(L"HEAD~%d",LastSelect-headindex);
2243 CGitHash hash;
2244 ret = ret || g_Git.GetHash(hash, head);
2245 GitRevLoglist* pFirstEntry = m_arShownList.SafeGetAt(FirstSelect);
2246 GitRevLoglist* pLastEntry = m_arShownList.SafeGetAt(LastSelect);
2247 if (!ret && pFirstEntry->m_CommitHash == hashFirst && pLastEntry->m_CommitHash == hash)
2249 popup.AppendMenuIcon(ID_COMBINE_COMMIT,IDS_COMBINE_TO_ONE,IDI_COMBINE);
2250 bAddSeparator = true;
2255 if (m_ContextMenuMask&GetContextMenuBit(ID_CHERRY_PICK) && !isHeadCommit && m_hasWC && !isMergeActive) {
2256 if (selectedCount >= 2)
2257 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSIONS, IDI_EXPORT);
2258 else
2259 popup.AppendMenuIcon(ID_CHERRY_PICK, IDS_CHERRY_PICK_VERSION, IDI_EXPORT);
2260 bAddSeparator = true;
2263 if (selectedCount <= 2 || (IsSelectionContinuous() && !isStash))
2264 if(m_ContextMenuMask&GetContextMenuBit(ID_CREATE_PATCH)) {
2265 popup.AppendMenuIcon(ID_CREATE_PATCH, IDS_CREATE_PATCH, IDI_PATCH);
2266 bAddSeparator = true;
2269 if (bAddSeparator)
2270 popup.AppendMenu(MF_SEPARATOR, NULL);
2273 if (m_hasWC && !isMergeActive && !isStash && (m_ContextMenuMask & GetContextMenuBit(ID_BISECTSTART)) && selectedCount == 2 && !m_arShownList.SafeGetAt(FirstSelect)->m_CommitHash.IsEmpty() && !isBisectActive)
2275 popup.AppendMenuIcon(ID_BISECTSTART, IDS_MENUBISECTSTART, IDI_BISECT);
2276 popup.AppendMenu(MF_SEPARATOR, NULL);
2279 if (selectedCount == 1)
2281 bool bAddSeparator = false;
2282 if ((m_ContextMenuMask & GetContextMenuBit(ID_PUSH)) && ((!isStash && m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend()) || showExtendedMenu))
2284 // show the push-option only if the log entry has an associated local branch
2285 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();
2286 if (isLocal || showExtendedMenu)
2288 CString str;
2289 str.LoadString(IDS_MENUPUSH);
2291 CString branch;
2292 size_t index = (size_t)-1;
2293 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2294 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, &branch, &index))
2295 if (type == CGit::REF_TYPE::LOCAL_BRANCH || type == CGit::REF_TYPE::ANNOTATED_TAG || type == CGit::REF_TYPE::TAG)
2296 str.Insert(str.Find(L'.'), L" \"" + branch + L'"');
2298 popup.AppendMenuIcon(ID_PUSH, str, IDI_PUSH);
2300 if (index != (size_t)-1 && index < m_HashMap[pSelLogEntry->m_CommitHash].size())
2301 popup.SetMenuItemData(ID_PUSH, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2303 if (m_ContextMenuMask & GetContextMenuBit(ID_SVNDCOMMIT) && workingTree.HasGitSVNDir())
2304 popup.AppendMenuIcon(ID_SVNDCOMMIT, IDS_MENUSVNDCOMMIT, IDI_COMMIT);
2306 bAddSeparator = true;
2309 if (m_ContextMenuMask & GetContextMenuBit(ID_PULL) && isHeadCommit && !isMergeActive && m_hasWC)
2311 popup.AppendMenuIcon(ID_PULL, IDS_MENUPULL, IDI_PULL);
2312 bAddSeparator = true;
2316 if(m_ContextMenuMask &GetContextMenuBit(ID_DELETE))
2318 if( this->m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.end() )
2320 std::vector<const CString*> branchs;
2321 auto addCheck = [&](const CString& ref)
2323 if (ref == currentBranch)
2324 return;
2325 branchs.push_back(&ref);
2327 size_t index = (size_t)-1;
2328 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2329 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2330 addCheck(m_HashMap[pSelLogEntry->m_CommitHash][index]);
2331 else
2332 for_each(m_HashMap[pSelLogEntry->m_CommitHash], addCheck);
2334 CString str;
2335 if (branchs.size() == 1)
2337 str.LoadString(IDS_DELETE_BRANCHTAG_SHORT);
2338 str += L' ';
2339 str += *branchs[0];
2340 popup.AppendMenuIcon(ID_DELETE, str, IDI_DELETE);
2341 popup.SetMenuItemData(ID_DELETE, (ULONG_PTR)branchs[0]);
2342 bAddSeparator = true;
2344 else if (branchs.size() > 1)
2346 str.LoadString(IDS_DELETE_BRANCHTAG);
2347 submenu.CreatePopupMenu();
2348 for (size_t i = 0; i < branchs.size(); ++i)
2350 submenu.AppendMenuIcon(ID_DELETE + (i << 16), *branchs[i]);
2351 submenu.SetMenuItemData(ID_DELETE + (i << 16), (ULONG_PTR)branchs[i]);
2353 submenu.AppendMenuIcon(ID_DELETE + (branchs.size() << 16), IDS_ALL);
2354 submenu.SetMenuItemData(ID_DELETE + (branchs.size() << 16), (ULONG_PTR)MAKEINTRESOURCE(IDS_ALL));
2356 popup.AppendMenuIcon(ID_DELETE,str, IDI_DELETE, submenu.m_hMenu);
2357 bAddSeparator = true;
2360 } // m_ContextMenuMask &GetContextMenuBit(ID_DELETE)
2361 if (bAddSeparator)
2362 popup.AppendMenu(MF_SEPARATOR, NULL);
2363 } // selectedCount == 1
2365 CIconMenu clipSubMenu;
2366 if (!clipSubMenu.CreatePopupMenu())
2367 return;
2368 if (m_ContextMenuMask & GetContextMenuBit(ID_COPYCLIPBOARD))
2370 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULL, IDS_LOG_POPUP_CLIPBOARD_FULL, IDI_COPYCLIP);
2371 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDFULLNOPATHS, IDS_LOG_POPUP_CLIPBOARD_FULLNOPATHS, IDI_COPYCLIP);
2372 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDHASH, IDS_LOG_HASH, IDI_COPYCLIP);
2373 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSFULL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSFULL, IDI_COPYCLIP);
2374 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSNAME, IDS_LOG_POPUP_CLIPBOARD_AUTHORSNAME, IDI_COPYCLIP);
2375 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDAUTHORSEMAIL, IDS_LOG_POPUP_CLIPBOARD_AUTHORSEMAIL, IDI_COPYCLIP);
2376 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDSUBJECTS, IDS_LOG_POPUP_CLIPBOARD_SUBJECTS, IDI_COPYCLIP);
2377 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDMESSAGES, IDS_LOG_POPUP_CLIPBOARD_MSGS, IDI_COPYCLIP);
2378 if (m_HashMap.find(pSelLogEntry->m_CommitHash) != m_HashMap.cend() && selectedCount == 1)
2380 clipSubMenu.AppendMenuIcon(ID_COPYCLIPBOARDBRANCHTAG, IDS_LOG_POPUP_CLIPBOARD_TAGBRANCHES, IDI_COPYCLIP);
2381 size_t index = (size_t)-1;
2382 CGit::REF_TYPE type = CGit::REF_TYPE::UNKNOWN;
2383 if (IsMouseOnRefLabelFromPopupMenu(pSelLogEntry, point, type, nullptr, &index))
2384 clipSubMenu.SetMenuItemData(ID_COPYCLIPBOARDBRANCHTAG, (ULONG_PTR)&m_HashMap[pSelLogEntry->m_CommitHash][index]);
2387 CString temp;
2388 temp.LoadString(IDS_LOG_POPUP_COPYTOCLIPBOARD);
2389 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)clipSubMenu.m_hMenu, temp);
2392 if(m_ContextMenuMask&GetContextMenuBit(ID_FINDENTRY))
2393 popup.AppendMenuIcon(ID_FINDENTRY, IDS_LOG_POPUP_FIND, IDI_FILTEREDIT);
2395 if (selectedCount == 1 && (m_ContextMenuMask & GetContextMenuBit(ID_SHOWBRANCHES)) && !pSelLogEntry->m_CommitHash.IsEmpty())
2396 popup.AppendMenuIcon(ID_SHOWBRANCHES, IDS_LOG_POPUP_SHOWBRANCHES, IDI_SHOWBRANCHES);
2398 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
2399 // DialogEnableWindow(IDOK, FALSE);
2400 // SetPromptApp(&theApp);
2402 this->ContextMenuAction(cmd, FirstSelect, LastSelect, &popup);
2404 // EnableOKButton();
2405 } // if (popup.CreatePopupMenu())
2408 bool CGitLogListBase::IsSelectionContinuous()
2410 if ( GetSelectedCount()==1 )
2412 // if only one revision is selected, the selection is of course
2413 // continuous
2414 return true;
2417 POSITION pos = GetFirstSelectedItemPosition();
2418 bool bContinuous = (m_arShownList.size() == m_logEntries.size());
2419 if (bContinuous)
2421 int itemindex = GetNextSelectedItem(pos);
2422 while (pos)
2424 int nextindex = GetNextSelectedItem(pos);
2425 if (nextindex - itemindex > 1)
2427 bContinuous = false;
2428 break;
2430 itemindex = nextindex;
2433 return bContinuous;
2436 void CGitLogListBase::CopySelectionToClipBoard(int toCopy)
2438 CString sClipdata;
2439 POSITION pos = GetFirstSelectedItemPosition();
2440 if (pos)
2442 CString sRev;
2443 sRev.LoadString(IDS_LOG_REVISION);
2444 CString sAuthor;
2445 sAuthor.LoadString(IDS_LOG_AUTHOR);
2446 CString sDate;
2447 sDate.LoadString(IDS_LOG_DATE);
2448 CString sMessage;
2449 sMessage.LoadString(IDS_LOG_MESSAGE);
2450 CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
2451 bool first = true;
2452 while (pos)
2454 CString sLogCopyText;
2455 CString sPaths;
2456 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(GetNextSelectedItem(pos));
2458 if (toCopy == ID_COPYCLIPBOARDFULL)
2460 sPaths = L"----\r\n";
2461 for (int cpPathIndex = 0; cpPathIndex<pLogEntry->GetFiles(this).GetCount(); ++cpPathIndex)
2463 sPaths += ((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetActionName() + L": " + pLogEntry->GetFiles(this)[cpPathIndex].GetGitPathString();
2464 if (((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).m_Action & (CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_COPY) && !((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString().IsEmpty())
2466 sPaths += L' ';
2467 sPaths.AppendFormat(from, (LPCTSTR)((CTGitPath&)pLogEntry->GetFiles(this)[cpPathIndex]).GetGitOldPathString());
2469 sPaths += L"\r\n";
2471 sPaths.Trim();
2472 sPaths += L"\r\n";
2475 if (toCopy == ID_COPYCLIPBOARDFULL || toCopy == ID_COPYCLIPBOARDFULLNOPATHS)
2477 CString sNotesTags;
2478 if (!pLogEntry->m_Notes.IsEmpty())
2480 sNotesTags = L"----\n" + CString(MAKEINTRESOURCE(IDS_NOTES));
2481 sNotesTags += L":\n";
2482 sNotesTags += pLogEntry->m_Notes;
2483 sNotesTags.Replace(L"\n", L"\r\n");
2485 CString tagInfo = GetTagInfo(pLogEntry);
2486 if (!tagInfo.IsEmpty())
2488 sNotesTags += L"----\r\n" + CString(MAKEINTRESOURCE(IDS_PROC_LOG_TAGINFO)) + L":\r\n";
2489 tagInfo.Replace(L"\n", L"\r\n");
2490 sNotesTags += tagInfo;
2493 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",
2494 (LPCTSTR)sRev, (LPCTSTR)pLogEntry->m_CommitHash.ToString(),
2495 (LPCTSTR)sAuthor, (LPCTSTR)pLogEntry->GetAuthorName(), (LPCTSTR)pLogEntry->GetAuthorEmail(),
2496 (LPCTSTR)sDate,
2497 (LPCTSTR)CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, m_bRelativeTimes),
2498 (LPCTSTR)sMessage, (LPCTSTR)pLogEntry->GetSubjectBody(true),
2499 (LPCTSTR)sNotesTags,
2500 (LPCTSTR)sPaths);
2501 sClipdata += sLogCopyText;
2503 else if (toCopy == ID_COPYCLIPBOARDAUTHORSFULL)
2505 if (!first)
2506 sClipdata += L"\r\n";
2507 sClipdata += pLogEntry->GetAuthorName();
2508 sClipdata += L" <";
2509 sClipdata += pLogEntry->GetAuthorEmail();
2510 sClipdata += L">";
2512 else if (toCopy == ID_COPYCLIPBOARDAUTHORSNAME)
2514 if (!first)
2515 sClipdata += L"\r\n";
2516 sClipdata += pLogEntry->GetAuthorName();
2518 else if (toCopy == ID_COPYCLIPBOARDAUTHORSEMAIL)
2520 if (!first)
2521 sClipdata += L"\r\n";
2522 sClipdata += pLogEntry->GetAuthorEmail();
2525 else if (toCopy == ID_COPYCLIPBOARDMESSAGES)
2527 sClipdata += L"* ";
2528 sClipdata += pLogEntry->GetSubjectBody(true);
2529 sClipdata += L"\r\n\r\n";
2531 else if (toCopy == ID_COPYCLIPBOARDSUBJECTS)
2533 sClipdata += L"* ";
2534 sClipdata += pLogEntry->GetSubject().Trim();
2535 sClipdata += L"\r\n\r\n";
2537 else
2539 if (!first)
2540 sClipdata += L"\r\n";
2541 sClipdata += pLogEntry->m_CommitHash;
2544 first = false;
2546 CStringUtils::WriteAsciiStringToClipboard(sClipdata, GetSafeHwnd());
2550 void CGitLogListBase::DiffSelectedRevWithPrevious()
2552 if (m_bThreadRunning)
2553 return;
2555 int FirstSelect=-1, LastSelect=-1;
2556 POSITION pos = GetFirstSelectedItemPosition();
2557 FirstSelect = GetNextSelectedItem(pos);
2558 while(pos)
2559 LastSelect = GetNextSelectedItem(pos);
2561 ContextMenuAction(ID_COMPAREWITHPREVIOUS, FirstSelect, LastSelect, nullptr);
2564 void CGitLogListBase::OnLvnOdfinditemLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2566 LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
2567 *pResult = -1;
2569 if (pFindInfo->lvfi.flags & LVFI_PARAM)
2570 return;
2571 if (pFindInfo->iStart < 0 || pFindInfo->iStart >= (int)m_arShownList.size())
2572 return;
2573 if (!pFindInfo->lvfi.psz)
2574 return;
2575 #if 0
2576 CString sCmp = pFindInfo->lvfi.psz;
2577 CString sRev;
2578 for (int i=pFindInfo->iStart; i<m_arShownList.GetCount(); ++i)
2580 GitRev * pLogEntry = reinterpret_cast<GitRev*>(m_arShownList.SafeGetAt(i));
2581 sRev.Format(L"%ld", pLogEntry->Rev);
2582 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2584 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2586 *pResult = i;
2587 return;
2590 else
2592 if (sCmp.Compare(sRev)==0)
2594 *pResult = i;
2595 return;
2599 if (pFindInfo->lvfi.flags & LVFI_WRAP)
2601 for (int i=0; i<pFindInfo->iStart; ++i)
2603 PLOGENTRYDATA pLogEntry = reinterpret_cast<PLOGENTRYDATA>(m_arShownList.SafeGetAt(i));
2604 sRev.Format(L"%ld", pLogEntry->Rev);
2605 if (pFindInfo->lvfi.flags & LVFI_PARTIAL)
2607 if (sCmp.Compare(sRev.Left(sCmp.GetLength()))==0)
2609 *pResult = i;
2610 return;
2613 else
2615 if (sCmp.Compare(sRev)==0)
2617 *pResult = i;
2618 return;
2623 #endif
2624 *pResult = -1;
2627 int CGitLogListBase::FillGitLog(CTGitPath *path, CString *range, int info)
2629 ClearText();
2631 this->m_arShownList.SafeRemoveAll();
2633 this->m_logEntries.ClearAll();
2634 if (this->m_logEntries.ParserFromLog(path, 0, info, range))
2635 return -1;
2637 SetItemCountEx((int)m_logEntries.size());
2639 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2641 if(m_IsOldFirst)
2643 m_logEntries.GetGitRevAt(m_logEntries.size()-i-1).m_IsFull=TRUE;
2644 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
2646 else
2648 m_logEntries.GetGitRevAt(i).m_IsFull=TRUE;
2649 this->m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2653 ReloadHashMap();
2655 if(path)
2656 m_Path=*path;
2657 return 0;
2660 int CGitLogListBase::FillGitLog(std::unordered_set<CGitHash>& hashes)
2662 ClearText();
2664 m_arShownList.SafeRemoveAll();
2666 m_logEntries.ClearAll();
2667 if (m_logEntries.Fill(hashes))
2668 return -1;
2670 SetItemCountEx((int)m_logEntries.size());
2672 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2674 if (m_IsOldFirst)
2676 m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1).m_IsFull = TRUE;
2677 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size() - i - 1));
2679 else
2681 m_logEntries.GetGitRevAt(i).m_IsFull = TRUE;
2682 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
2686 ReloadHashMap();
2688 return 0;
2691 int CGitLogListBase::BeginFetchLog()
2693 ClearText();
2695 this->m_arShownList.SafeRemoveAll();
2697 this->m_logEntries.ClearAll();
2699 this->m_LogCache.ClearAllParent();
2701 m_LogCache.FetchCacheIndex(g_Git.m_CurrentDir);
2703 CTGitPath *path;
2704 if(this->m_Path.IsEmpty())
2705 path = nullptr;
2706 else
2707 path=&this->m_Path;
2709 int mask;
2710 mask = CGit::LOG_INFO_ONLY_HASH;
2711 if (m_bIncludeBoundaryCommits)
2712 mask |= CGit::LOG_INFO_BOUNDARY;
2713 // if(this->m_bAllBranch)
2714 mask |= m_ShowMask ;
2716 if(m_bShowWC)
2718 this->m_logEntries.insert(m_logEntries.cbegin(), m_wcRev.m_CommitHash);
2719 ResetWcRev();
2720 this->m_LogCache.m_HashMap[m_wcRev.m_CommitHash]=m_wcRev;
2723 if (m_sRange.IsEmpty())
2724 m_sRange = L"HEAD";
2726 #if 0 /* use tortoiegit filter */
2727 if (this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_AUTHORS)
2728 data.m_Author = this->m_sFilterText;
2730 if(this->m_nSelectedFilter == LOGFILTER_ALL || m_nSelectedFilter == LOGFILTER_MESSAGES)
2731 data.m_MessageFilter = this->m_sFilterText;
2733 data.m_IsRegex = m_bFilterWithRegex;
2734 #endif
2736 // follow does not work for directories
2737 if (!path || path->IsDirectory())
2738 mask &= ~CGit::LOG_INFO_FOLLOW;
2739 // follow does not work with all branches 8at least in TGit)
2740 if (mask & CGit::LOG_INFO_FOLLOW)
2741 mask &= ~(CGit::LOG_INFO_ALL_BRANCH | CGit::LOG_INFO_BASIC_REFS | CGit::LOG_INFO_LOCAL_BRANCHES);
2743 CString cmd = g_Git.GetLogCmd(m_sRange, path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2745 //this->m_logEntries.ParserFromLog();
2746 if(IsInWorkingThread())
2748 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL);
2750 else
2752 SetItemCountEx((int)m_logEntries.size());
2757 [] { git_init(); } ();
2759 catch (char* msg)
2761 CString err(msg);
2762 MessageBox(L"Could not initialize libgit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2763 return -1;
2766 if (!g_Git.CanParseRev(m_sRange))
2768 if (!(mask & CGit::LOG_INFO_ALL_BRANCH) && !(mask & CGit::LOG_INFO_BASIC_REFS) && !(mask & CGit::LOG_INFO_LOCAL_BRANCHES))
2769 return 0;
2771 // if show all branches, pick any ref as dummy entry ref
2772 STRING_VECTOR list;
2773 if (g_Git.GetRefList(list))
2774 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2775 if (list.empty())
2776 return 0;
2778 cmd = g_Git.GetLogCmd(list[0], path, mask, &m_Filter, CRegDWORD(L"Software\\TortoiseGit\\LogOrderBy", CGit::LOG_ORDER_TOPOORDER));
2781 g_Git.m_critGitDllSec.Lock();
2782 try {
2783 if (git_open_log(&m_DllGitLog, CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2785 g_Git.m_critGitDllSec.Unlock();
2786 return -1;
2789 catch (char* msg)
2791 g_Git.m_critGitDllSec.Unlock();
2792 CString err(msg);
2793 MessageBox(L"Could not open log.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2794 return -1;
2796 g_Git.m_critGitDllSec.Unlock();
2798 return 0;
2801 BOOL CGitLogListBase::PreTranslateMessage(MSG* pMsg)
2803 if (pMsg->message == WM_KEYDOWN && pMsg->wParam=='\r')
2805 //if (GetFocus()==GetDlgItem(IDC_LOGLIST))
2807 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2809 DiffSelectedRevWithPrevious();
2810 return TRUE;
2813 #if 0
2814 if (GetFocus()==GetDlgItem(IDC_LOGMSG))
2816 DiffSelectedFile();
2817 return TRUE;
2819 #endif
2821 else if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetAsyncKeyState(VK_CONTROL)&0x8000)
2823 // select all entries
2824 for (int i=0; i<GetItemCount(); ++i)
2825 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2826 return TRUE;
2829 #if 0
2830 if (m_hAccel && !bSkipAccelerator)
2832 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
2833 if (ret)
2834 return TRUE;
2837 #endif
2838 //m_tooltips.RelayEvent(pMsg);
2839 return __super::PreTranslateMessage(pMsg);
2842 void CGitLogListBase::OnNMDblclkLoglist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2844 // a double click on an entry in the revision list has happened
2845 *pResult = 0;
2847 if (CRegDWORD(L"Software\\TortoiseGit\\DiffByDoubleClickInLog", FALSE))
2848 DiffSelectedRevWithPrevious();
2851 void CGitLogListBase::FetchLogAsync(void* data)
2853 ReloadHashMap();
2854 m_ProcData=data;
2855 StartLoadingThread();
2858 UINT CGitLogListBase::LogThreadEntry(LPVOID pVoid)
2860 return ((CGitLogListBase*)pVoid)->LogThread();
2863 void CGitLogListBase::GetTimeRange(CTime &oldest, CTime &latest)
2865 //CTime time;
2866 oldest=CTime::GetCurrentTime();
2867 latest=CTime(1971,1,2,0,0,0);
2868 for (unsigned int i = 0; i < m_logEntries.size(); ++i)
2870 if(m_logEntries[i].IsEmpty())
2871 continue;
2873 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() < oldest.GetTime())
2874 oldest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2876 if (m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime() > latest.GetTime())
2877 latest = m_logEntries.GetGitRevAt(i).GetCommitterDate().GetTime();
2881 if(latest<oldest)
2882 latest=oldest;
2885 UINT CGitLogListBase::LogThread()
2887 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_START,0);
2889 ULONGLONG t1,t2;
2891 if(BeginFetchLog())
2893 InterlockedExchange(&m_bThreadRunning, FALSE);
2894 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2896 return 1;
2899 std::wregex pat;//(L"Remove", regex_constants::icase);
2900 bool bRegex = false;
2901 if (m_bFilterWithRegex)
2902 bRegex = ValidateRegexp(m_sFilterText, pat, false);
2904 TRACE(L"\n===Begin===\n");
2905 //Update work copy item;
2907 if (!m_logEntries.empty())
2909 GitRevLoglist* pRev = &m_logEntries.GetGitRevAt(0);
2911 m_arShownList.SafeAdd(pRev);
2915 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2917 // store commit number of the last selected commit/line before the refresh or -1
2918 int lastSelectedHashNItem = -1;
2919 if (m_lastSelectedHash.IsEmpty())
2920 lastSelectedHashNItem = 0;
2922 int ret = 0;
2924 bool shouldWalk = true;
2925 if (!g_Git.CanParseRev(m_sRange))
2927 // walk revisions if show all branches and there exists any ref
2928 if (!(m_ShowMask & CGit::LOG_INFO_ALL_BRANCH) && !(m_ShowMask & CGit::LOG_INFO_BASIC_REFS) && !(m_ShowMask & CGit::LOG_INFO_LOCAL_BRANCHES))
2929 shouldWalk = false;
2930 else
2932 STRING_VECTOR list;
2933 if (g_Git.GetRefList(list))
2934 MessageBox(g_Git.GetGitLastErr(L"Could not get all refs."), L"TortoiseGit", MB_ICONERROR);
2935 if (list.empty())
2936 shouldWalk = false;
2940 if (shouldWalk)
2942 g_Git.m_critGitDllSec.Lock();
2943 if (!m_DllGitLog)
2945 MessageBox(L"Opening log failed.", L"TortoiseGit", MB_ICONERROR);
2946 g_Git.m_critGitDllSec.Unlock();
2947 InterlockedExchange(&m_bThreadRunning, FALSE);
2948 InterlockedExchange(&m_bNoDispUpdates, FALSE);
2949 return 1;
2951 int total = 0;
2954 [&] {git_get_log_firstcommit(m_DllGitLog);}();
2955 total = git_get_log_estimate_commit_count(m_DllGitLog);
2957 catch (char* msg)
2959 CString err(msg);
2960 MessageBox(L"Could not get first commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2961 ret = -1;
2963 g_Git.m_critGitDllSec.Unlock();
2965 GIT_COMMIT commit;
2966 t2 = t1 = GetTickCount64();
2967 int oldprecentage = 0;
2968 size_t oldsize = m_logEntries.size();
2969 std::unordered_map<CGitHash, std::unordered_set<CGitHash>> commitChildren;
2970 while (ret== 0 && !m_bExitThread)
2972 g_Git.m_critGitDllSec.Lock();
2975 [&] { ret = git_get_log_nextcommit(this->m_DllGitLog, &commit, m_ShowMask & CGit::LOG_INFO_FOLLOW); } ();
2977 catch (char* msg)
2979 g_Git.m_critGitDllSec.Unlock();
2980 CString err(msg);
2981 MessageBox(L"Could not get next commit.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
2982 break;
2984 g_Git.m_critGitDllSec.Unlock();
2986 if(ret)
2988 if (ret != -2) // other than end of revision walking
2989 MessageBox((L"Could not get next commit.\nlibgit returns:" + std::to_wstring(ret)).c_str(), L"TortoiseGit", MB_ICONERROR);
2990 break;
2993 if (commit.m_ignore == 1)
2995 git_free_commit(&commit);
2996 continue;
2999 //printf("%s\r\n",commit.GetSubject());
3000 if(m_bExitThread)
3001 break;
3003 CGitHash hash(commit.m_hash);
3005 GitRevLoglist* pRev = m_LogCache.GetCacheData(hash);
3006 pRev->m_GitCommit = commit;
3007 InterlockedExchange(&pRev->m_IsCommitParsed, FALSE);
3009 char* note = nullptr;
3010 g_Git.m_critGitDllSec.Lock();
3013 git_get_notes(commit.m_hash, &note);
3015 catch (char* msg)
3017 g_Git.m_critGitDllSec.Unlock();
3018 CString err(msg);
3019 MessageBox(L"Could not get commit notes.\nlibgit reports:\n" + err, L"TortoiseGit", MB_ICONERROR);
3020 break;
3022 g_Git.m_critGitDllSec.Unlock();
3024 if(note)
3026 pRev->m_Notes = CUnicodeUtils::GetUnicode(note);
3027 free(note);
3028 note = nullptr;
3031 if(!pRev->m_IsDiffFiles)
3033 pRev->m_CallDiffAsync = DiffAsync;
3036 pRev->ParserParentFromCommit(&commit);
3037 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS) // See also ShouldShowFilter()
3039 for (size_t i = 0; i < pRev->m_ParentHash.size(); ++i)
3041 const CGitHash &parentHash = pRev->m_ParentHash[i];
3042 auto it = commitChildren.find(parentHash);
3043 if (it == commitChildren.end())
3044 it = commitChildren.insert(make_pair(parentHash, std::unordered_set<CGitHash>())).first;
3045 it->second.insert(pRev->m_CommitHash);
3049 #ifdef DEBUG
3050 pRev->DbgPrint();
3051 TRACE(L"\n");
3052 #endif
3054 bool visible = true;
3055 if (HasFilterText())
3057 if(!IsMatchFilter(bRegex,pRev,pat))
3058 visible = false;
3060 if (visible && !ShouldShowFilter(pRev, commitChildren))
3061 visible = false;
3062 this->m_critSec.Lock();
3063 m_logEntries.append(hash, visible);
3064 if (visible)
3065 m_arShownList.SafeAdd(pRev);
3066 this->m_critSec.Unlock();
3068 if (!visible)
3069 continue;
3071 if (lastSelectedHashNItem == -1 && hash == m_lastSelectedHash)
3072 lastSelectedHashNItem = (int)m_arShownList.size() - 1;
3074 t2 = GetTickCount64();
3076 if (t2 - t1 > 500UL || (m_logEntries.size() - oldsize > 100))
3078 //update UI
3079 int percent = (int)m_logEntries.size() * 100 / total + GITLOG_START + 1;
3080 if(percent > 99)
3081 percent =99;
3082 if(percent < GITLOG_START)
3083 percent = GITLOG_START +1;
3085 oldsize = m_logEntries.size();
3086 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3088 //if( percent > oldprecentage )
3090 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) percent,0);
3091 oldprecentage = percent;
3094 if (lastSelectedHashNItem >= 0)
3095 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3097 t1 = t2;
3100 g_Git.m_critGitDllSec.Lock();
3101 git_close_log(m_DllGitLog);
3102 g_Git.m_critGitDllSec.Unlock();
3106 if (m_bExitThread)
3108 InterlockedExchange(&m_bThreadRunning, FALSE);
3109 return 0;
3112 //Update UI;
3113 PostMessage(LVM_SETITEMCOUNT, (WPARAM) this->m_logEntries.size(),(LPARAM) LVSICF_NOINVALIDATEALL|LVSICF_NOSCROLL);
3115 if (lastSelectedHashNItem >= 0)
3116 PostMessage(m_ScrollToMessage, lastSelectedHashNItem);
3118 if (this->m_hWnd)
3119 ::PostMessage(this->GetParent()->m_hWnd,MSG_LOAD_PERCENTAGE,(WPARAM) GITLOG_END,0);
3121 InterlockedExchange(&m_bThreadRunning, FALSE);
3123 return 0;
3126 void CGitLogListBase::FetchRemoteList()
3128 STRING_VECTOR remoteList;
3129 m_SingleRemote.Empty();
3130 if (!g_Git.GetRemoteList(remoteList) && remoteList.size() == 1)
3131 m_SingleRemote = remoteList[0];
3134 void CGitLogListBase::FetchTrackingBranchList()
3136 m_TrackingMap.clear();
3137 for (auto it = m_HashMap.cbegin(); it != m_HashMap.cend(); ++it)
3139 for (const auto& ref : it->second)
3141 CString branchName;
3142 if (CGit::GetShortName(ref, branchName, L"refs/heads/"))
3144 CString pullRemote, pullBranch;
3145 g_Git.GetRemoteTrackedBranch(branchName, pullRemote, pullBranch);
3146 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
3147 m_TrackingMap[branchName] = std::make_pair(pullRemote, pullBranch);
3153 void CGitLogListBase::Refresh(BOOL IsCleanFilter)
3155 SafeTerminateThread();
3157 this->SetItemCountEx(0);
3158 this->Clear();
3160 ResetWcRev();
3162 ShowGraphColumn((m_ShowMask & CGit::LOG_INFO_FOLLOW) ? false : true);
3164 if (m_pMailmap)
3166 git_free_mailmap(m_pMailmap);
3167 git_read_mailmap(&m_pMailmap);
3170 //Update branch and Tag info
3171 ReloadHashMap();
3172 if (m_pFindDialog)
3173 m_pFindDialog->RefreshList();
3174 //Assume Thread have exited
3175 //if(!m_bThreadRunning)
3177 m_logEntries.clear();
3179 if(IsCleanFilter)
3181 m_sFilterText.Empty();
3184 SafeTerminateAsyncDiffThread();
3185 m_AsynDiffListLock.Lock();
3186 m_AsynDiffList.clear();
3187 m_AsynDiffListLock.Unlock();
3188 StartAsyncDiffThread();
3190 StartLoadingThread();
3194 void CGitLogListBase::StartAsyncDiffThread()
3196 if (m_AsyncThreadExit)
3197 return;
3198 if (InterlockedExchange(&m_AsyncThreadRunning, TRUE) != FALSE)
3199 return;
3200 m_DiffingThread = AfxBeginThread(AsyncThread, this, THREAD_PRIORITY_BELOW_NORMAL);
3201 if (!m_DiffingThread)
3203 InterlockedExchange(&m_AsyncThreadRunning, FALSE);
3204 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3208 void CGitLogListBase::StartLoadingThread()
3210 if (InterlockedExchange(&m_bThreadRunning, TRUE) != FALSE)
3211 return;
3212 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3213 InterlockedExchange(&m_bExitThread, FALSE);
3214 m_LoadingThread = AfxBeginThread(LogThreadEntry, this, THREAD_PRIORITY_LOWEST);
3215 if (!m_LoadingThread)
3217 InterlockedExchange(&m_bThreadRunning, FALSE);
3218 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3219 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
3223 bool CGitLogListBase::ValidateRegexp(LPCTSTR regexp_str, std::wregex& pat, bool bMatchCase /* = false */)
3227 std::regex_constants::syntax_option_type type = std::regex_constants::ECMAScript;
3228 if (!bMatchCase)
3229 type |= std::regex_constants::icase;
3230 pat = std::wregex(regexp_str, type);
3231 return true;
3233 catch (std::exception&) {}
3234 return false;
3236 BOOL CGitLogListBase::IsMatchFilter(bool bRegex, GitRevLoglist* pRev, std::wregex& pat)
3238 BOOL result = TRUE;
3239 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3240 CString sRev;
3242 if ((bRegex)&&(m_bFilterWithRegex))
3244 if (m_SelectedFilters & LOGFILTER_BUGID)
3246 if(this->m_bShowBugtraqColumn)
3248 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3250 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)sBugIds);
3251 if (std::regex_search(std::wstring(sBugIds), pat, flags))
3252 return TRUE;
3256 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3258 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetSubject());
3259 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetSubject()), pat, flags))
3260 return TRUE;
3263 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3265 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)pRev->GetBody());
3266 if (std::regex_search(std::wstring((LPCTSTR)pRev->GetBody()), pat, flags))
3267 return TRUE;
3270 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3272 if (std::regex_search(std::wstring(pRev->GetAuthorName()), pat, flags))
3273 return TRUE;
3275 if (std::regex_search(std::wstring(pRev->GetCommitterName()), pat, flags))
3276 return TRUE;
3279 if (m_SelectedFilters & LOGFILTER_EMAILS)
3281 if (std::regex_search(std::wstring(pRev->GetAuthorEmail()), pat, flags))
3282 return TRUE;
3284 if (std::regex_search(std::wstring(pRev->GetCommitterEmail()), pat, flags))
3285 return TRUE;
3288 if (m_SelectedFilters & LOGFILTER_REVS)
3290 sRev = pRev->m_CommitHash.ToString();
3291 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags))
3293 return TRUE;
3297 if (m_SelectedFilters & LOGFILTER_NOTES)
3299 if (std::regex_search(std::wstring(pRev->m_Notes), pat, flags))
3300 return TRUE;
3303 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3305 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3306 for (const auto& ref : refs)
3308 if (std::regex_search(std::wstring(ref), pat, flags))
3309 return TRUE;
3313 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3315 if (std::regex_search(std::wstring(GetTagInfo(pRev)), pat, flags))
3316 return TRUE;
3319 if (m_SelectedFilters & LOGFILTER_PATHS)
3321 CTGitPathList* pathList = nullptr;
3322 if( pRev->m_IsDiffFiles)
3323 pathList = &pRev->GetFiles(this);
3324 else
3326 if(!pRev->m_IsSimpleListReady)
3327 pRev->SafeGetSimpleList(&g_Git);
3330 if(pathList)
3331 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount(); ++cpPathIndex)
3333 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitOldPathString()), pat, flags))
3334 return true;
3335 if (std::regex_search(std::wstring((LPCTSTR)pathList->m_paths[cpPathIndex].GetGitPathString()), pat, flags))
3336 return true;
3339 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3341 if (std::regex_search(std::wstring((LPCTSTR)pRev->m_SimpleFileList[i]), pat, flags))
3342 return true;
3346 else
3348 CString find = m_sFilterText;
3349 if (!m_bFilterCaseSensitively)
3350 find.MakeLower();
3351 result = find[0] == '!' ? FALSE : TRUE;
3352 if (!result)
3353 find = find.Mid(1);
3355 if (m_SelectedFilters & LOGFILTER_BUGID)
3357 if(this->m_bShowBugtraqColumn)
3359 CString sBugIds = m_ProjectProperties.FindBugID(pRev->GetSubjectBody());
3361 if (!m_bFilterCaseSensitively)
3362 sBugIds.MakeLower();
3363 if ((sBugIds.Find(find) >= 0))
3364 return result;
3368 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3370 CString msg = pRev->GetSubject();
3372 if (!m_bFilterCaseSensitively)
3373 msg = msg.MakeLower();
3374 if ((msg.Find(find) >= 0))
3375 return result;
3378 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3380 CString msg = pRev->GetBody();
3382 if (!m_bFilterCaseSensitively)
3383 msg = msg.MakeLower();
3384 if ((msg.Find(find) >= 0))
3385 return result;
3388 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3390 CString msg = pRev->GetAuthorName();
3391 if (!m_bFilterCaseSensitively)
3392 msg = msg.MakeLower();
3393 if ((msg.Find(find) >= 0))
3394 return result;
3397 if (m_SelectedFilters & LOGFILTER_EMAILS)
3399 CString msg = pRev->GetAuthorEmail();
3400 if (!m_bFilterCaseSensitively)
3401 msg = msg.MakeLower();
3402 if ((msg.Find(find) >= 0))
3403 return result;
3406 if (m_SelectedFilters & LOGFILTER_NOTES)
3408 CString msg = pRev->m_Notes;
3409 if (!m_bFilterCaseSensitively)
3410 msg = msg.MakeLower();
3411 if ((msg.Find(find) >= 0))
3412 return result;
3415 if (m_SelectedFilters & LOGFILTER_REVS)
3417 sRev = pRev->m_CommitHash.ToString();
3418 if ((sRev.Find(find) >= 0))
3419 return result;
3422 if (m_SelectedFilters & LOGFILTER_ANNOTATEDTAG)
3424 CString msg = GetTagInfo(pRev);
3425 if (!m_bFilterCaseSensitively)
3426 msg = msg.MakeLower();
3427 if ((msg.Find(find) >= 0))
3428 return result;
3431 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3433 const STRING_VECTOR& refs = m_HashMap[pRev->m_CommitHash];
3434 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3436 if (it->Find(find) >= 0)
3437 return result;
3441 if (m_SelectedFilters & LOGFILTER_PATHS)
3443 CTGitPathList* pathList = nullptr;
3444 if( pRev->m_IsDiffFiles)
3445 pathList = &pRev->GetFiles(this);
3446 else
3448 if(!pRev->m_IsSimpleListReady)
3449 pRev->SafeGetSimpleList(&g_Git);
3451 if(pathList)
3452 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList->GetCount() ; ++cpPathIndex)
3454 CTGitPath* cpath = &pathList->m_paths[cpPathIndex];
3455 CString path = cpath->GetGitOldPathString();
3456 if (!m_bFilterCaseSensitively)
3457 path.MakeLower();
3458 if ((path.Find(find)>=0))
3459 return result;
3460 path = cpath->GetGitPathString();
3461 if (!m_bFilterCaseSensitively)
3462 path.MakeLower();
3463 if ((path.Find(find)>=0))
3464 return result;
3467 for (size_t i = 0; i < pRev->m_SimpleFileList.size(); ++i)
3469 CString path = pRev->m_SimpleFileList[i];
3470 if (!m_bFilterCaseSensitively)
3471 path.MakeLower();
3472 if ((path.Find(find)>=0))
3473 return result;
3476 } // else (from if (bRegex))
3477 return !result;
3480 static bool CStringStartsWith(const CString &str, const CString &prefix)
3482 return str.Left(prefix.GetLength()) == prefix;
3484 bool CGitLogListBase::ShouldShowFilter(GitRevLoglist* pRev, const std::unordered_map<CGitHash, std::unordered_set<CGitHash>>& commitChildren)
3486 if (m_ShowFilter & FILTERSHOW_ANYCOMMIT)
3487 return true;
3489 if ((m_ShowFilter & FILTERSHOW_REFS) && m_HashMap.find(pRev->m_CommitHash) != m_HashMap.cend())
3491 // Keep all refs.
3492 const STRING_VECTOR &refList = m_HashMap[pRev->m_CommitHash];
3493 for (size_t i = 0; i < refList.size(); ++i)
3495 const CString &str = refList[i];
3496 if (CStringStartsWith(str, L"refs/heads/"))
3498 if (m_ShowRefMask & LOGLIST_SHOWLOCALBRANCHES)
3499 return true;
3501 else if (CStringStartsWith(str, L"refs/remotes/"))
3503 if (m_ShowRefMask & LOGLIST_SHOWREMOTEBRANCHES)
3504 return true;
3506 else if (CStringStartsWith(str, L"refs/tags/"))
3508 if (m_ShowRefMask & LOGLIST_SHOWTAGS)
3509 return true;
3511 else if (CStringStartsWith(str, L"refs/stash"))
3513 if (m_ShowRefMask & LOGLIST_SHOWSTASH)
3514 return true;
3516 else if (CStringStartsWith(str, L"refs/bisect/"))
3518 if (m_ShowRefMask & LOGLIST_SHOWBISECT)
3519 return true;
3522 // Keep the head too.
3523 if (pRev->m_CommitHash == m_HeadHash)
3524 return true;
3527 if (m_ShowFilter & FILTERSHOW_MERGEPOINTS)
3529 if (pRev->ParentsCount() > 1)
3530 return true;
3531 auto childrenIt = commitChildren.find(pRev->m_CommitHash);
3532 if (childrenIt != commitChildren.end())
3534 const std::unordered_set<CGitHash> &children = childrenIt->second;
3535 if (children.size() > 1)
3536 return true;
3539 return false;
3542 void CGitLogListBase::ShowGraphColumn(bool bShow)
3544 // HACK to hide graph column
3545 if (bShow)
3546 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3547 else
3548 SetColumnWidth(0, 0);
3551 CString CGitLogListBase::GetTagInfo(GitRev* pLogEntry)
3553 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.end())
3554 return L"";
3556 CString tagInfo;
3557 const STRING_VECTOR& vector = m_HashMap[pLogEntry->m_CommitHash];
3558 for (auto it = vector.cbegin(); it != vector.cend(); ++it)
3560 if (!CStringUtils::StartsWith((*it), L"refs/tags/"))
3561 continue;
3562 if (!CStringUtils::EndsWith((*it), L"^{}"))
3563 continue;
3565 CString cmd;
3566 cmd.Format(L"git.exe cat-file tag %s", (LPCTSTR)(*it).Left((*it).GetLength() - (int)wcslen(L"^{}")));
3567 CString output;
3568 if (g_Git.Run(cmd, &output, nullptr, CP_UTF8) != 0)
3569 continue;
3571 // parse tag date
3574 // this assumes that in the header of the tag there is no ">" before the "tagger " header entry
3575 int pos1 = output.Find(L'>');
3576 if (pos1 < 0)
3577 break;
3578 ++pos1;
3579 if (output[pos1] == L' ')
3580 ++pos1;
3581 int pos2 = output.Find(L'\n', pos1);
3582 if (pos2 < 0)
3583 break;
3585 CString str = output.Mid(pos1, pos2 - pos1);
3586 wchar_t* pEnd = nullptr;
3587 errno = 0;
3588 auto number = wcstoumax(str.GetBuffer(), &pEnd, 10);
3589 if (str.GetBuffer() == pEnd)
3590 break;
3591 if (errno == ERANGE)
3592 break;
3594 output.Delete(pos1, pos2 - pos1);
3595 output.Insert(pos1, (LPCWSTR)CLoglistUtils::FormatDateAndTime(CTime(number), m_DateFormat, true, m_bRelativeTimes));
3596 } while (0);
3597 output.Trim().AppendChar(L'\n');
3598 tagInfo += output;
3600 return tagInfo;
3603 void CGitLogListBase::RecalculateShownList(CThreadSafePtrArray * pShownlist)
3605 pShownlist->SafeRemoveAll();
3607 std::wregex pat;//(L"Remove", regex_constants::icase);
3608 bool bRegex = false;
3609 if (m_bFilterWithRegex)
3610 bRegex = ValidateRegexp(m_sFilterText, pat, false);
3612 std::regex_constants::match_flag_type flags = std::regex_constants::match_any;
3613 CString sRev;
3614 for (DWORD i=0; i<m_logEntries.size(); ++i)
3616 if ((bRegex)&&(m_bFilterWithRegex))
3618 #if 0
3619 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3621 ATLTRACE(L"bugID = \"%s\"\n", (LPCTSTR)m_logEntries[i]->sBugIDs);
3622 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries[i]->sBugIDs), pat, flags)&&IsEntryInDateRange(i))
3624 pShownlist->SafeAdd(m_logEntries[i]);
3625 continue;
3628 #endif
3629 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3631 ATLTRACE(L"messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject());
3632 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetSubject()), pat, flags)&&IsEntryInDateRange(i))
3634 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3635 continue;
3638 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3640 ATLTRACE("messge = \"%s\"\n", (LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody());
3641 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetBody()), pat, flags)&&IsEntryInDateRange(i))
3643 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3644 continue;
3647 if (m_SelectedFilters & LOGFILTER_PATHS)
3649 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3651 bool bGoing = true;
3652 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3654 CTGitPath cpath = pathList[cpPathIndex];
3655 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitOldPathString()), pat, flags)&&IsEntryInDateRange(i))
3657 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3658 bGoing = false;
3659 continue;
3661 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetGitPathString()), pat, flags)&&IsEntryInDateRange(i))
3663 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3664 bGoing = false;
3665 continue;
3667 if (std::regex_search(std::wstring((LPCTSTR)cpath.GetActionName()), pat, flags)&&IsEntryInDateRange(i))
3669 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3670 bGoing = false;
3671 continue;
3675 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3677 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorName()), pat, flags)&&IsEntryInDateRange(i))
3679 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3680 continue;
3683 if (m_SelectedFilters & LOGFILTER_EMAILS)
3685 if (std::regex_search(std::wstring((LPCTSTR)m_logEntries.GetGitRevAt(i).GetAuthorEmail()), pat, flags) && IsEntryInDateRange(i))
3687 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3688 continue;
3691 if (m_SelectedFilters & LOGFILTER_REVS)
3693 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3694 if (std::regex_search(std::wstring((LPCTSTR)sRev), pat, flags)&&IsEntryInDateRange(i))
3696 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3697 continue;
3700 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3702 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3703 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3705 if (std::regex_search(std::wstring((LPCTSTR)*it), pat, flags) && IsEntryInDateRange(i))
3707 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3708 continue;
3712 } // if (bRegex)
3713 else
3715 CString find = m_sFilterText;
3716 if (!m_bFilterCaseSensitively)
3717 find.MakeLower();
3718 #if 0
3719 if ((m_nSelectedFilter == LOGFILTER_ALL)||(m_nSelectedFilter == LOGFILTER_BUGID))
3721 CString sBugIDs = m_logEntries[i]->sBugIDs;
3723 if (!m_bFilterCaseSensitively)
3724 sBugIDs = sBugIDs.MakeLower();
3725 if ((sBugIDs.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3727 pShownlist->SafeAdd(m_logEntries[i]);
3728 continue;
3731 #endif
3732 if ((m_SelectedFilters & LOGFILTER_SUBJECT) || (m_SelectedFilters & LOGFILTER_MESSAGES))
3734 CString msg = m_logEntries.GetGitRevAt(i).GetSubject();
3736 if (!m_bFilterCaseSensitively)
3737 msg = msg.MakeLower();
3738 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3740 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3741 continue;
3744 if (m_SelectedFilters & LOGFILTER_MESSAGES)
3746 CString msg = m_logEntries.GetGitRevAt(i).GetBody();
3748 if (!m_bFilterCaseSensitively)
3749 msg = msg.MakeLower();
3750 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3752 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3753 continue;
3756 if (m_SelectedFilters & LOGFILTER_PATHS)
3758 CTGitPathList pathList = m_logEntries.GetGitRevAt(i).GetFiles(this);
3760 bool bGoing = true;
3761 for (INT_PTR cpPathIndex = 0; cpPathIndex < pathList.GetCount() && bGoing; ++cpPathIndex)
3763 CTGitPath cpath = pathList[cpPathIndex];
3764 CString path = cpath.GetGitOldPathString();
3765 if (!m_bFilterCaseSensitively)
3766 path.MakeLower();
3767 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3769 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3770 bGoing = false;
3771 continue;
3773 path = cpath.GetGitPathString();
3774 if (!m_bFilterCaseSensitively)
3775 path.MakeLower();
3776 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3778 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3779 bGoing = false;
3780 continue;
3782 path = cpath.GetActionName();
3783 if (!m_bFilterCaseSensitively)
3784 path.MakeLower();
3785 if ((path.Find(find)>=0)&&(IsEntryInDateRange(i)))
3787 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3788 bGoing = false;
3789 continue;
3793 if (m_SelectedFilters & LOGFILTER_AUTHORS)
3795 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorName();
3796 if (!m_bFilterCaseSensitively)
3797 msg = msg.MakeLower();
3798 if ((msg.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3800 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3801 continue;
3804 if (m_SelectedFilters & LOGFILTER_EMAILS)
3806 CString msg = m_logEntries.GetGitRevAt(i).GetAuthorEmail();
3807 if (!m_bFilterCaseSensitively)
3808 msg = msg.MakeLower();
3809 if ((msg.Find(find) >= 0) && (IsEntryInDateRange(i)))
3811 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3812 continue;
3815 if (m_SelectedFilters & LOGFILTER_REVS)
3817 sRev = m_logEntries.GetGitRevAt(i).m_CommitHash.ToString();
3818 if ((sRev.Find(find) >= 0)&&(IsEntryInDateRange(i)))
3820 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3821 continue;
3824 if ((m_SelectedFilters & LOGFILTER_REFNAME) && m_HashMap.find(m_logEntries.GetGitRevAt(i).m_CommitHash) != m_HashMap.cend())
3826 const STRING_VECTOR& refs = m_HashMap[m_logEntries.GetGitRevAt(i).m_CommitHash];
3827 for (auto it = refs.cbegin(); it != refs.cend(); ++it)
3829 if (it->Find(find) >= 0 && IsEntryInDateRange(i))
3831 pShownlist->SafeAdd(&m_logEntries.GetGitRevAt(i));
3832 continue;
3836 } // else (from if (bRegex))
3837 } // for (DWORD i=0; i<m_logEntries.size(); ++i)
3840 BOOL CGitLogListBase::IsEntryInDateRange(int /*i*/)
3843 __time64_t time = m_logEntries.GetGitRevAt(i).GetAuthorDate().GetTime();
3845 if(m_From == -1)
3846 if(m_To == -1)
3847 return true;
3848 else
3849 return time <= m_To;
3850 else
3851 if(m_To == -1)
3852 return time >= m_From;
3853 else
3854 return ((time >= m_From)&&(time <= m_To));
3856 return TRUE; /* git dll will filter time range */
3858 // return TRUE;
3861 void CGitLogListBase::StartFilter()
3863 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3864 RecalculateShownList(&m_arShownList);
3865 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3868 DeleteAllItems();
3869 SetItemCountEx(ShownCountWithStopped());
3870 RedrawItems(0, ShownCountWithStopped());
3871 Invalidate();
3874 void CGitLogListBase::RemoveFilter()
3876 InterlockedExchange(&m_bNoDispUpdates, TRUE);
3878 m_arShownList.SafeRemoveAll();
3880 // reset the time filter too
3881 #if 0
3882 m_timFrom = (__time64_t(m_tFrom));
3883 m_timTo = (__time64_t(m_tTo));
3884 m_DateFrom.SetTime(&m_timFrom);
3885 m_DateTo.SetTime(&m_timTo);
3886 m_DateFrom.SetRange(&m_timFrom, &m_timTo);
3887 m_DateTo.SetRange(&m_timFrom, &m_timTo);
3888 #endif
3890 for (DWORD i=0; i<m_logEntries.size(); ++i)
3892 if(this->m_IsOldFirst)
3893 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(m_logEntries.size()-i-1));
3894 else
3895 m_arShownList.SafeAdd(&m_logEntries.GetGitRevAt(i));
3897 // InterlockedExchange(&m_bNoDispUpdates, FALSE);
3898 DeleteAllItems();
3899 SetItemCountEx(ShownCountWithStopped());
3900 RedrawItems(0, ShownCountWithStopped());
3902 InterlockedExchange(&m_bNoDispUpdates, FALSE);
3905 void CGitLogListBase::Clear()
3907 m_arShownList.SafeRemoveAll();
3908 DeleteAllItems();
3910 m_logEntries.ClearAll();
3913 void CGitLogListBase::OnDestroy()
3915 SafeTerminateThread();
3916 SafeTerminateAsyncDiffThread();
3918 int retry = 0;
3919 while(m_LogCache.SaveCache())
3921 if(retry > 5)
3922 break;
3923 Sleep(1000);
3925 ++retry;
3927 //if(CMessageBox::Show(nullptr, L"Cannot Save Log Cache to Disk. To retry click yes. To give up click no.", L"TortoiseGit",
3928 // MB_YESNO) == IDNO)
3929 // break;
3932 __super::OnDestroy();
3935 LRESULT CGitLogListBase::OnLoad(WPARAM wParam,LPARAM /*lParam*/)
3937 CRect rect;
3938 int i=(int)wParam;
3939 this->GetItemRect(i,&rect,LVIR_BOUNDS);
3940 this->InvalidateRect(rect);
3942 return 0;
3946 * Save column widths to the registry
3948 void CGitLogListBase::SaveColumnWidths()
3950 // HACK that graph column is always shown
3951 SetColumnWidth(0, m_ColumnManager.GetWidth(0, false));
3953 __super::SaveColumnWidths();
3956 int CGitLogListBase::GetHeadIndex()
3958 if(m_HeadHash.IsEmpty())
3959 return -1;
3961 for (size_t i = 0; i < m_arShownList.size(); ++i)
3963 GitRev* pRev = m_arShownList.SafeGetAt(i);
3964 if(pRev)
3966 if(pRev->m_CommitHash.ToString() == m_HeadHash )
3967 return (int)i;
3970 return -1;
3972 void CGitLogListBase::OnFind()
3974 if (!m_pFindDialog)
3976 m_pFindDialog = new CFindDlg(this);
3977 m_pFindDialog->Create(this);
3981 LRESULT CGitLogListBase::OnScrollToMessage(WPARAM itemToSelect, LPARAM /*lParam*/)
3983 if (GetSelectedCount() != 0)
3984 return 0;
3986 CGitHash theSelectedHash = m_lastSelectedHash;
3987 SetItemState((int)itemToSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
3988 m_lastSelectedHash = theSelectedHash;
3990 int countPerPage = GetCountPerPage();
3991 EnsureVisible(max(0, (int)itemToSelect-countPerPage/2), FALSE);
3992 EnsureVisible(min(GetItemCount(), (int)itemToSelect+countPerPage/2), FALSE);
3993 EnsureVisible((int)itemToSelect, FALSE);
3994 return 0;
3997 LRESULT CGitLogListBase::OnScrollToRef(WPARAM wParam, LPARAM /*lParam*/)
3999 CString* ref = reinterpret_cast<CString*>(wParam);
4000 if (!ref || ref->IsEmpty())
4001 return 1;
4003 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4005 CGitHash hash;
4006 if (g_Git.GetHash(hash, *ref + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4007 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + *ref + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4009 if (hash.IsEmpty())
4010 return 1;
4012 bool bFound = false;
4013 int cnt = (int)m_arShownList.size();
4014 int i;
4015 for (i = 0; i < cnt; ++i)
4017 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4018 if (pLogEntry && pLogEntry->m_CommitHash == hash)
4020 bFound = true;
4021 break;
4024 if (!bFound)
4025 return 1;
4027 EnsureVisible(i, FALSE);
4028 if (!bShift)
4030 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4031 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4032 SetSelectionMark(i);
4034 else
4036 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4037 if (pLogEntry)
4038 m_highlight = pLogEntry->m_CommitHash;
4040 Invalidate();
4041 UpdateData(FALSE);
4043 return 0;
4046 LRESULT CGitLogListBase::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/)
4048 ASSERT(m_pFindDialog);
4049 bool bFound = false;
4050 int i=0;
4052 if (m_pFindDialog->IsTerminating())
4054 // invalidate the handle identifying the dialog box.
4055 m_pFindDialog = nullptr;
4056 return 0;
4059 int cnt = (int)m_arShownList.size();
4060 bool bShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
4062 if(m_pFindDialog->IsRef())
4064 CString str;
4065 str=m_pFindDialog->GetFindString();
4067 CGitHash hash;
4069 if(!str.IsEmpty())
4071 if (g_Git.GetHash(hash, str + L"^{}")) // add ^{} in order to get the correct SHA-1 (especially for signed tags)
4072 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + str + L"^{}\"."), L"TortoiseGit", MB_ICONERROR);
4075 if(!hash.IsEmpty())
4077 for (i = 0; i < cnt; ++i)
4079 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4080 if(pLogEntry && pLogEntry->m_CommitHash == hash)
4082 bFound = true;
4083 break;
4087 if (!bFound)
4089 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4090 return 0;
4094 if (m_pFindDialog->FindNext() && !bFound)
4096 //read data from dialog
4097 CString findText = m_pFindDialog->GetFindString();
4098 bool bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
4100 std::wregex pat;
4101 bool bRegex = false;
4102 if (m_pFindDialog->Regex())
4103 bRegex = ValidateRegexp(findText, pat, bMatchCase);
4105 std::regex_constants::match_flag_type flags = std::regex_constants::match_not_null;
4107 for (i = m_nSearchIndex + 1; ; ++i)
4109 if (i >= cnt)
4111 i = 0;
4112 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 2, 100);
4114 if (m_nSearchIndex >= 0)
4116 if (i == m_nSearchIndex)
4118 ::MessageBeep(0xFFFFFFFF);
4119 m_pFindDialog->FlashWindowEx(FLASHW_ALL, 3, 100);
4120 break;
4124 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(i);
4126 CString str;
4127 str+=pLogEntry->m_CommitHash.ToString();
4128 str += L'\n';
4130 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4131 if (refList != m_HashMap.cend())
4133 for (const auto& ref : (*refList).second)
4135 str += ref;
4136 str += L'\n';
4140 str+=pLogEntry->GetAuthorEmail();
4141 str += L'\n';
4142 str+=pLogEntry->GetAuthorName();
4143 str += L'\n';
4144 str+=pLogEntry->GetBody();
4145 str += L'\n';
4146 str+=pLogEntry->GetCommitterEmail();
4147 str += L'\n';
4148 str+=pLogEntry->GetCommitterName();
4149 str += L'\n';
4150 str+=pLogEntry->GetSubject();
4151 str += L'\n';
4152 str+=pLogEntry->m_Notes;
4153 str += L'\n';
4154 str+=GetTagInfo(pLogEntry);
4155 str += L'\n';
4158 /*Because changed files list is loaded on demand when gui show,
4159 files will empty when files have not fetched.
4161 we can add it back by using one-way diff(with outnumber changed and rename detect.
4162 here just need changed filename list. one-way is much quicker.
4164 if(pLogEntry->m_IsFull)
4166 for (int j = 0; j < pLogEntry->GetFiles(this).GetCount(); ++j)
4168 str += pLogEntry->GetFiles(this)[j].GetWinPath();
4169 str += L'\n';
4170 str += pLogEntry->GetFiles(this)[j].GetGitOldPathString();
4171 str += L'\n';
4174 else
4176 if(!pLogEntry->m_IsSimpleListReady)
4177 pLogEntry->SafeGetSimpleList(&g_Git);
4179 for (size_t j = 0; j < pLogEntry->m_SimpleFileList.size(); ++j)
4181 str += pLogEntry->m_SimpleFileList[j];
4182 str += L'\n';
4186 if (bRegex)
4188 if (std::regex_search(std::wstring(str), pat, flags))
4190 bFound = true;
4191 break;
4194 else
4196 if (bMatchCase)
4198 if (str.Find(findText) >= 0)
4200 bFound = true;
4201 break;
4204 else
4206 CString msg = str;
4207 msg = msg.MakeLower();
4208 CString find = findText.MakeLower();
4209 if (msg.Find(find) >= 0)
4211 bFound = TRUE;
4212 break;
4216 } // for (i = this->m_nSearchIndex; i<m_arShownList.GetItemCount()&&!bFound; ++i)
4218 } // if(m_pFindDialog->FindNext())
4219 //UpdateLogInfoLabel();
4221 if (bFound)
4223 m_nSearchIndex = i;
4224 EnsureVisible(i, FALSE);
4225 if (!bShift)
4227 SetItemState(GetSelectionMark(), 0, LVIS_SELECTED);
4228 SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
4229 SetSelectionMark(i);
4231 else
4233 GitRev* pLogEntry = m_arShownList.SafeGetAt(i);
4234 if (pLogEntry)
4235 m_highlight = pLogEntry->m_CommitHash;
4237 Invalidate();
4238 //FillLogMessageCtrl();
4239 UpdateData(FALSE);
4242 return 0;
4245 INT_PTR CGitLogListBase::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
4247 LVHITTESTINFO lvhitTestInfo;
4249 lvhitTestInfo.pt = point;
4251 int nItem = ListView_SubItemHitTest(m_hWnd, &lvhitTestInfo);
4252 int nSubItem = lvhitTestInfo.iSubItem;
4254 UINT nFlags = lvhitTestInfo.flags;
4256 // nFlags is 0 if the SubItemHitTest fails
4257 // Therefore, 0 & <anything> will equal false
4258 if (nFlags & LVHT_ONITEM)
4260 // Get the client area occupied by this control
4261 RECT rcClient;
4262 GetClientRect(&rcClient);
4264 // Fill in the TOOLINFO structure
4265 pTI->hwnd = m_hWnd;
4266 pTI->uId = (UINT)((nItem<<10)+(nSubItem&0x3ff)+1);
4267 pTI->lpszText = LPSTR_TEXTCALLBACK;
4268 pTI->rect = rcClient;
4270 return pTI->uId; // By returning a unique value per listItem,
4271 // we ensure that when the mouse moves over another list item,
4272 // the tooltip will change
4274 else
4276 // Otherwise, we aren't interested, so let the message propagate
4277 return -1;
4281 BOOL CGitLogListBase::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
4283 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
4284 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
4286 *pResult = 0;
4288 // Ignore messages from the built in tooltip, we are processing them internally
4289 if ((pNMHDR->idFrom == (UINT_PTR)m_hWnd) &&
4290 (((pNMHDR->code == TTN_NEEDTEXTA) && (pTTTA->uFlags & TTF_IDISHWND)) ||
4291 ((pNMHDR->code == TTN_NEEDTEXTW) && (pTTTW->uFlags & TTF_IDISHWND))))
4292 return FALSE;
4294 // Get the mouse position
4295 const MSG* pMessage = GetCurrentMessage();
4297 CPoint pt;
4298 pt = pMessage->pt;
4299 ScreenToClient(&pt);
4301 // Check if the point falls onto a list item
4302 LVHITTESTINFO lvhitTestInfo;
4303 lvhitTestInfo.pt = pt;
4305 int nItem = SubItemHitTest(&lvhitTestInfo);
4307 if (lvhitTestInfo.flags & LVHT_ONITEM)
4309 // Get branch description first
4310 CString strTipText;
4311 if (lvhitTestInfo.iSubItem == LOGLIST_MESSAGE)
4313 CString branch;
4314 CGit::REF_TYPE type = CGit::REF_TYPE::LOCAL_BRANCH;
4315 if (IsMouseOnRefLabel(m_arShownList.SafeGetAt(nItem), lvhitTestInfo.pt, type, &branch))
4317 MAP_STRING_STRING descriptions;
4318 g_Git.GetBranchDescriptions(descriptions);
4319 if (descriptions.find(branch) != descriptions.cend())
4321 strTipText.LoadString(IDS_DESCRIPTION);
4322 strTipText += L":\n";
4323 strTipText += descriptions[branch];
4328 bool followMousePos = false;
4329 if (!strTipText.IsEmpty())
4330 followMousePos = true;
4331 else
4332 strTipText = GetToolTipText(nItem, lvhitTestInfo.iSubItem);
4333 if (strTipText.IsEmpty())
4334 return FALSE;
4336 // we want multiline tooltips
4337 ::SendMessage(pNMHDR->hwndFrom, TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
4339 wcscpy_s(m_wszTip, strTipText);
4340 // handle Unicode as well as non-Unicode requests
4341 if (pNMHDR->code == TTN_NEEDTEXTA)
4343 pTTTA->hinst = nullptr;
4344 pTTTA->lpszText = m_szTip;
4345 ::WideCharToMultiByte(CP_ACP, 0, m_wszTip, -1, m_szTip, 8192, nullptr, nullptr);
4347 else
4349 pTTTW->hinst = nullptr;
4350 pTTTW->lpszText = m_wszTip;
4353 CRect rect;
4354 GetSubItemRect(nItem, lvhitTestInfo.iSubItem, LVIR_LABEL, rect);
4355 if (followMousePos)
4356 rect.MoveToXY(pt.x, pt.y + 18); // 18: to act like a normal tooltip
4357 ClientToScreen(rect);
4358 ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOOWNERZORDER);
4360 return TRUE; // We found a tool tip,
4361 // tell the framework this message has been handled
4364 return FALSE; // We didn't handle the message,
4365 // let the framework continue propagating the message
4368 CString CGitLogListBase::GetToolTipText(int nItem, int nSubItem)
4370 if (nSubItem == LOGLIST_MESSAGE && !m_bTagsBranchesOnRightSide)
4372 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4373 if (pLogEntry == nullptr)
4374 return CString();
4375 if (m_HashMap.find(pLogEntry->m_CommitHash) == m_HashMap.cend() && (m_superProjectHash.IsEmpty() || pLogEntry->m_CommitHash != m_superProjectHash))
4376 return CString();
4377 return pLogEntry->GetSubject();
4379 else if (nSubItem == LOGLIST_DATE && m_bRelativeTimes)
4381 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4382 if (pLogEntry == nullptr)
4383 return CString();
4384 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetAuthorDate(), m_DateFormat, true, false);
4386 else if (nSubItem == LOGLIST_COMMIT_DATE && m_bRelativeTimes)
4388 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4389 if (pLogEntry == nullptr)
4390 return CString();
4391 return CLoglistUtils::FormatDateAndTime(pLogEntry->GetCommitterDate(), m_DateFormat, true, false);
4393 else if (nSubItem == LOGLIST_ACTION)
4395 GitRevLoglist* pLogEntry = m_arShownList.SafeGetAt(nItem);
4396 if (pLogEntry == nullptr)
4397 return CString();
4399 if (!pLogEntry->m_IsDiffFiles)
4400 return CString(MAKEINTRESOURCE(IDS_PROC_LOG_FETCHINGFILES));
4402 int actions = pLogEntry->GetAction(this);
4403 CString sToolTipText;
4405 CString actionText;
4406 if (actions & CTGitPath::LOGACTIONS_MODIFIED)
4407 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_MODIFIED);
4409 if (actions & CTGitPath::LOGACTIONS_ADDED)
4411 if (!actionText.IsEmpty())
4412 actionText += L"\r\n";
4413 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_ADDED);
4416 if (actions & CTGitPath::LOGACTIONS_DELETED)
4418 if (!actionText.IsEmpty())
4419 actionText += L"\r\n";
4420 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_DELETED);
4423 if (actions & CTGitPath::LOGACTIONS_REPLACED)
4425 if (!actionText.IsEmpty())
4426 actionText += L"\r\n";
4427 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_REPLACED);
4430 if (actions & CTGitPath::LOGACTIONS_UNMERGED)
4432 if (!actionText.IsEmpty())
4433 actionText += L"\r\n";
4434 actionText += CTGitPath::GetActionName(CTGitPath::LOGACTIONS_UNMERGED);
4437 if (!actionText.IsEmpty())
4439 CString sTitle(MAKEINTRESOURCE(IDS_LOG_ACTIONS));
4440 sToolTipText = sTitle + L":\r\n" + actionText;
4442 return sToolTipText;
4444 return CString();
4447 bool CGitLogListBase::IsMouseOnRefLabelFromPopupMenu(const GitRevLoglist* pLogEntry, const CPoint& point, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4449 POINT pt = point;
4450 ScreenToClient(&pt);
4451 return IsMouseOnRefLabel(pLogEntry, pt, type, pShortname, pIndex);
4454 bool CGitLogListBase::IsMouseOnRefLabel(const GitRevLoglist* pLogEntry, const POINT& pt, CGit::REF_TYPE& type, CString* pShortname /*nullptr*/, size_t* pIndex /*nullptr*/)
4456 if (!pLogEntry)
4457 return false;
4459 auto refList = m_HashMap.find(pLogEntry->m_CommitHash);
4460 if (refList == m_HashMap.cend())
4461 return false;
4463 for (size_t i = 0; i < m_HashMap[pLogEntry->m_CommitHash].size(); ++i)
4465 const auto labelpos = m_RefLabelPosMap.find(m_HashMap[pLogEntry->m_CommitHash][i]);
4466 if (labelpos == m_RefLabelPosMap.cend() || !labelpos->second.PtInRect(pt))
4467 continue;
4469 CGit::REF_TYPE foundType;
4470 if (pShortname)
4471 *pShortname = CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4472 else
4473 CGit::GetShortName(m_HashMap[pLogEntry->m_CommitHash][i], &foundType);
4474 if (foundType != type && type != CGit::REF_TYPE::UNKNOWN)
4475 return false;
4477 type = foundType;
4478 if (pIndex)
4479 *pIndex = i;
4480 return true;
4482 return false;
4485 void CGitLogListBase::OnBeginDrag(NMHDR* /*pnmhdr*/, LRESULT* pResult)
4487 *pResult = 0;
4489 if (!m_bDragndropEnabled || GetSelectedCount() == 0 || !IsSelectionContinuous())
4490 return;
4492 m_bDragging = TRUE;
4493 m_nDropIndex = -1;
4494 m_nDropMarkerLast = -1;
4495 m_nDropMarkerLastHot = GetHotItem();
4496 SetCapture();
4499 void CGitLogListBase::OnMouseMove(UINT nFlags, CPoint point)
4501 __super::OnMouseMove(nFlags, point);
4503 if (!m_bDragging)
4504 return;
4506 CPoint dropPoint = point;
4507 ClientToScreen(&dropPoint);
4509 if (WindowFromPoint(dropPoint) != this)
4511 SetCursor(LoadCursor(nullptr, IDC_NO));
4512 m_nDropIndex = -1;
4513 DrawDropInsertMarker(m_nDropIndex);
4514 return;
4517 SetCursor(LoadCursor(nullptr, IDC_ARROW));
4518 ScreenToClient(&dropPoint);
4520 dropPoint.y += 10;
4521 m_nDropIndex = HitTest(dropPoint);
4523 if (m_nDropIndex == -1) // might be last item, allow to move past last item
4525 dropPoint.y -= 10;
4526 m_nDropIndex = HitTest(dropPoint);
4527 if (m_nDropIndex != -1)
4528 m_nDropIndex = GetItemCount();
4531 POSITION pos = GetFirstSelectedItemPosition();
4532 int first = GetNextSelectedItem(pos);
4533 int last = first;
4534 while (pos)
4535 last = GetNextSelectedItem(pos);
4536 if (m_nDropIndex == -1 || (m_nDropIndex >= first && m_nDropIndex - 1 <= last))
4538 SetCursor(LoadCursor(nullptr, IDC_NO));
4539 m_nDropIndex = -1;
4542 // handle auto scrolling
4543 int hotItem = GetHotItem();
4544 int topindex = GetTopIndex();
4545 if (hotItem == topindex && hotItem != 0)
4546 EnsureVisible(hotItem - 1, FALSE);
4547 else if (hotItem >= topindex + GetCountPerPage() - 1 && hotItem + 1 < GetItemCount())
4548 EnsureVisible(hotItem + 1, FALSE);
4550 DrawDropInsertMarker(m_nDropIndex);
4553 void CGitLogListBase::OnLButtonUp(UINT nFlags, CPoint point)
4555 if (m_bDragging)
4557 ::ReleaseCapture();
4558 SetCursor(LoadCursor(nullptr, IDC_HAND));
4559 m_bDragging = FALSE;
4561 CRect rect;
4562 GetItemRect(m_nDropMarkerLast, &rect, 0);
4563 rect.bottom = rect.top + 2;
4564 rect.top -= 2;
4565 InvalidateRect(&rect, 0);
4567 CPoint pt(point);
4568 ClientToScreen(&pt);
4569 if (WindowFromPoint(pt) == this && m_nDropIndex != -1)
4570 GetParent()->PostMessage(MSG_COMMITS_REORDERED, m_nDropIndex, 0);
4573 __super::OnLButtonUp(nFlags, point);
4576 void CGitLogListBase::DrawDropInsertMarker(int nIndex)
4578 if (m_nDropMarkerLast != nIndex)
4580 CRect rect;
4581 if (GetItemRect(m_nDropMarkerLast, &rect, 0))
4583 rect.bottom = rect.top + 2;
4584 rect.top -= 2;
4585 InvalidateRect(&rect, 0);
4587 else if (m_nDropMarkerLast == GetItemCount())
4588 DrawDropInsertMarkerLine(m_nDropMarkerLast); // double painting = removal
4589 m_nDropMarkerLast = nIndex;
4591 if (nIndex < 0)
4592 return;
4594 DrawDropInsertMarkerLine(m_nDropMarkerLast);
4596 else if (m_nDropMarkerLastHot != GetHotItem())
4598 m_nDropMarkerLastHot = GetHotItem();
4599 m_nDropMarkerLast = -1;
4603 void CGitLogListBase::DrawDropInsertMarkerLine(int nIndex)
4605 CBrush* pBrush = CDC::GetHalftoneBrush();
4606 CDC* pDC = GetDC();
4608 CRect rect;
4609 if (nIndex < GetItemCount())
4611 GetItemRect(nIndex, &rect, 0);
4612 rect.bottom = rect.top + 2;
4613 rect.top -= 2;
4615 else
4617 GetItemRect(nIndex - 1, &rect, 0);
4618 rect.top = rect.bottom - 2;
4619 rect.bottom += 2;
4622 CBrush* pBrushOld = pDC->SelectObject(pBrush);
4623 pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
4624 pDC->SelectObject(pBrushOld);
4626 ReleaseDC(pDC);
4629 ULONG CGitLogListBase::GetGestureStatus(CPoint /*ptTouch*/)
4631 return 0;