GitStatusListCtrl: Better locking
[TortoiseGit.git] / src / Git / GitStatusListCtrl.cpp
blobf752c5e038d308dea61c02e7938efb965cb40fe4
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - TortoiseGit
4 // Copyright (C) 2003-2008, 2013-2015 - TortoiseSVN
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.
21 #include "stdafx.h"
22 #include "resource.h"
23 #include "..\\TortoiseShell\resource.h"
24 #include "GitStatusListCtrl.h"
25 #include "MessageBox.h"
26 #include "MyMemDC.h"
27 #include "UnicodeUtils.h"
28 #include "AppUtils.h"
29 #include "PathUtils.h"
30 #include "TempFile.h"
31 #include "StringUtils.h"
32 #include "LoglistUtils.h"
33 #include "Git.h"
34 #include "GitRev.h"
35 #include "GitDiff.h"
36 #include "GitProgressDlg.h"
37 #include "SysImageList.h"
38 #include "TGitPath.h"
39 #include "registry.h"
40 #include "InputDlg.h"
41 #include "GitAdminDir.h"
42 #include "GitDataObject.h"
43 #include "ProgressCommands/AddProgressCommand.h"
44 #include "IconMenu.h"
45 #include "FormatMessageWrapper.h"
46 #include "BrowseFolder.h"
47 #include "SysInfo.h"
49 const UINT CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED
50 = ::RegisterWindowMessage(L"GITSLNM_ITEMCOUNTCHANGED");
51 const UINT CGitStatusListCtrl::GITSLNM_NEEDSREFRESH
52 = ::RegisterWindowMessage(L"GITSLNM_NEEDSREFRESH");
53 const UINT CGitStatusListCtrl::GITSLNM_ADDFILE
54 = ::RegisterWindowMessage(L"GITSLNM_ADDFILE");
55 const UINT CGitStatusListCtrl::GITSLNM_CHECKCHANGED
56 = ::RegisterWindowMessage(L"GITSLNM_CHECKCHANGED");
57 const UINT CGitStatusListCtrl::GITSLNM_ITEMCHANGED
58 = ::RegisterWindowMessage(L"GITSLNM_ITEMCHANGED");
60 struct icompare
62 bool operator() (const std::wstring& lhs, const std::wstring& rhs) const
64 // no logical comparison here: we need this sorted strictly
65 return _wcsicmp(lhs.c_str(), rhs.c_str()) < 0;
69 class CIShellFolderHook : public IShellFolder
71 public:
72 CIShellFolderHook(LPSHELLFOLDER sf, const CTGitPathList& pathlist)
74 sf->AddRef();
75 m_iSF = sf;
76 // it seems the paths in the HDROP need to be sorted, otherwise
77 // it might not work properly or even crash.
78 // to get the items sorted, we just add them to a set
79 for (int i = 0; i < pathlist.GetCount(); ++i)
80 sortedpaths.insert((LPCTSTR)g_Git.CombinePath(pathlist[i].GetWinPath()));
83 ~CIShellFolderHook() { m_iSF->Release(); }
85 // IUnknown methods --------
86 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject) { return m_iSF->QueryInterface(riid, ppvObject); }
87 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return m_iSF->AddRef(); }
88 virtual ULONG STDMETHODCALLTYPE Release(void) { return m_iSF->Release(); }
90 // IShellFolder methods ----
91 virtual HRESULT STDMETHODCALLTYPE GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv);
93 virtual HRESULT STDMETHODCALLTYPE CompareIDs(LPARAM lParam, __RPC__in PCUIDLIST_RELATIVE pidl1, __RPC__in PCUIDLIST_RELATIVE pidl2) { return m_iSF->CompareIDs(lParam, pidl1, pidl2); }
94 virtual HRESULT STDMETHODCALLTYPE GetDisplayNameOf(__RPC__in_opt PCUITEMID_CHILD pidl, SHGDNF uFlags, __RPC__out STRRET *pName) { return m_iSF->GetDisplayNameOf(pidl, uFlags, pName); }
95 virtual HRESULT STDMETHODCALLTYPE CreateViewObject(__RPC__in_opt HWND hwndOwner, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) { return m_iSF->CreateViewObject(hwndOwner, riid, ppv); }
96 virtual HRESULT STDMETHODCALLTYPE EnumObjects(__RPC__in_opt HWND hwndOwner, SHCONTF grfFlags, __RPC__deref_out_opt IEnumIDList **ppenumIDList) { return m_iSF->EnumObjects(hwndOwner, grfFlags, ppenumIDList); }
97 virtual HRESULT STDMETHODCALLTYPE BindToObject(__RPC__in PCUIDLIST_RELATIVE pidl, __RPC__in_opt IBindCtx *pbc, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) { return m_iSF->BindToObject(pidl, pbc, riid, ppv); }
98 virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(__RPC__in_opt HWND hwnd, __RPC__in_opt IBindCtx *pbc, __RPC__in_string LPWSTR pszDisplayName, __reserved ULONG *pchEaten, __RPC__deref_out_opt PIDLIST_RELATIVE *ppidl, __RPC__inout_opt ULONG *pdwAttributes) { return m_iSF->ParseDisplayName(hwnd, pbc, pszDisplayName, pchEaten, ppidl, pdwAttributes); }
99 virtual HRESULT STDMETHODCALLTYPE GetAttributesOf(UINT cidl, __RPC__in_ecount_full_opt(cidl) PCUITEMID_CHILD_ARRAY apidl, __RPC__inout SFGAOF *rgfInOut) { return m_iSF->GetAttributesOf(cidl, apidl, rgfInOut); }
100 virtual HRESULT STDMETHODCALLTYPE BindToStorage(__RPC__in PCUIDLIST_RELATIVE pidl, __RPC__in_opt IBindCtx *pbc, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) { return m_iSF->BindToStorage(pidl, pbc, riid, ppv); }
101 virtual HRESULT STDMETHODCALLTYPE SetNameOf(__in_opt HWND hwnd, __in PCUITEMID_CHILD pidl, __in LPCWSTR pszName, __in SHGDNF uFlags, __deref_opt_out PITEMID_CHILD *ppidlOut) { return m_iSF->SetNameOf(hwnd, pidl, pszName, uFlags, ppidlOut); }
103 protected:
104 LPSHELLFOLDER m_iSF;
105 std::set<std::wstring, icompare> sortedpaths;
108 HRESULT STDMETHODCALLTYPE CIShellFolderHook::GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv)
110 if (InlineIsEqualGUID(riid, IID_IDataObject))
112 HRESULT hres = m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, IID_IDataObject, nullptr, ppv);
113 if (FAILED(hres))
114 return hres;
116 IDataObject * idata = (LPDATAOBJECT)(*ppv);
117 // the IDataObject returned here doesn't have a HDROP, so we create one ourselves and add it to the IDataObject
118 // the HDROP is necessary for most context menu handlers
119 int nLength = 0;
120 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
122 nLength += (int)it->size();
123 nLength += 1; // '\0' separator
125 int nBufferSize = sizeof(DROPFILES) + ((nLength + 5)*sizeof(TCHAR));
126 auto pBuffer = std::make_unique<char[]>(nBufferSize);
127 SecureZeroMemory(pBuffer.get(), nBufferSize);
128 DROPFILES* df = (DROPFILES*)pBuffer.get();
129 df->pFiles = sizeof(DROPFILES);
130 df->fWide = 1;
131 TCHAR* pFilenames = (TCHAR*)((BYTE*)(pBuffer.get()) + sizeof(DROPFILES));
132 TCHAR* pCurrentFilename = pFilenames;
134 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
136 wcscpy_s(pCurrentFilename, it->size() + 1, it->c_str());
137 pCurrentFilename += it->size();
138 *pCurrentFilename = '\0'; // separator between file names
139 pCurrentFilename++;
141 *pCurrentFilename = '\0'; // terminate array
142 pCurrentFilename++;
143 *pCurrentFilename = '\0'; // terminate array
144 STGMEDIUM medium = { 0 };
145 medium.tymed = TYMED_HGLOBAL;
146 medium.hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE, nBufferSize + 20);
147 if (medium.hGlobal)
149 LPVOID pMem = ::GlobalLock(medium.hGlobal);
150 if (pMem)
152 memcpy(pMem, pBuffer.get(), nBufferSize);
153 GlobalUnlock(medium.hGlobal);
154 FORMATETC formatetc = { 0 };
155 formatetc.cfFormat = CF_HDROP;
156 formatetc.dwAspect = DVASPECT_CONTENT;
157 formatetc.lindex = -1;
158 formatetc.tymed = TYMED_HGLOBAL;
159 medium.pUnkForRelease = nullptr;
160 hres = idata->SetData(&formatetc, &medium, TRUE);
161 return hres;
164 return E_OUTOFMEMORY;
166 else
168 // just pass it on to the base object
169 return m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, riid, rgfReserved, ppv);
173 IContextMenu2 * g_IContext2 = nullptr;
174 IContextMenu3 * g_IContext3 = nullptr;
175 CIShellFolderHook * g_pFolderhook = nullptr;
176 IShellFolder * g_psfDesktopFolder = nullptr;
177 LPITEMIDLIST * g_pidlArray = nullptr;
178 int g_pidlArrayItems = 0;
180 #define SHELL_MIN_CMD 10000
181 #define SHELL_MAX_CMD 20000
183 HRESULT CALLBACK dfmCallback(IShellFolder * /*psf*/, HWND /*hwnd*/, IDataObject * /*pdtobj*/, UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/)
185 switch (uMsg)
187 case DFM_MERGECONTEXTMENU:
188 return S_OK;
189 case DFM_INVOKECOMMAND:
190 case DFM_INVOKECOMMANDEX:
191 case DFM_GETDEFSTATICID: // Required for Windows 7 to pick a default
192 return S_FALSE;
194 return E_NOTIMPL;
197 BEGIN_MESSAGE_MAP(CGitStatusListCtrl, CResizableColumnsListCtrl<CListCtrl>)
198 ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHdnItemclick)
199 ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHdnItemclick)
200 ON_NOTIFY_REFLECT_EX(LVN_ITEMCHANGED, OnLvnItemchanged)
201 ON_WM_CONTEXTMENU()
202 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclk)
203 ON_NOTIFY_REFLECT(LVN_GETINFOTIP, OnLvnGetInfoTip)
204 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw)
205 ON_WM_SETCURSOR()
206 ON_WM_GETDLGCODE()
207 ON_NOTIFY_REFLECT(NM_RETURN, OnNMReturn)
208 ON_WM_KEYDOWN()
209 ON_WM_PAINT()
210 ON_WM_SYSCOLORCHANGE()
211 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
212 END_MESSAGE_MAP()
214 CGitStatusListCtrl::CGitStatusListCtrl() : CResizableColumnsListCtrl<CListCtrl>()
215 , m_pbCanceled(nullptr)
216 , m_pStatLabel(nullptr)
217 , m_pSelectButton(nullptr)
218 , m_pConfirmButton(nullptr)
219 , m_bBusy(false)
220 , m_bWaitCursor(false)
221 , m_bEmpty(false)
222 , m_bShowIgnores(false)
223 , m_bIgnoreRemoveOnly(false)
224 , m_bCheckChildrenWithParent(false)
225 , m_bUnversionedLast(true)
226 , m_bHasChangeLists(false)
227 , m_bHasCheckboxes(false)
228 , m_bCheckIfGroupsExist(true)
229 , m_bFileDropsEnabled(false)
230 , m_bOwnDrag(false)
231 , m_dwDefaultColumns(0)
232 , m_bAscending(false)
233 , m_nSortedColumn(-1)
234 , m_bHasExternalsFromDifferentRepos(false)
235 , m_amend(false)
236 , m_bDoNotAutoselectSubmodules(false)
237 , m_bNoAutoselectMissing(false)
238 , m_bHasWC(true)
239 , m_hwndLogicalParent(nullptr)
240 , m_bHasUnversionedItems(FALSE)
241 , m_nTargetCount(0)
242 , m_bHasExternals(false)
243 , m_bHasIgnoreGroup(false)
244 , m_nUnversioned(0)
245 , m_nNormal(0)
246 , m_nModified(0)
247 , m_nAdded(0)
248 , m_nDeleted(0)
249 , m_nConflicted(0)
250 , m_nTotal(0)
251 , m_nSelected(0)
252 , m_nRenamed(0)
253 , m_nShownUnversioned(0)
254 , m_nShownModified(0)
255 , m_nShownAdded(0)
256 , m_nShownDeleted(0)
257 , m_nShownConflicted(0)
258 , m_nShownFiles(0)
259 , m_nShownSubmodules(0)
260 , m_dwShow(0)
261 , m_bShowFolders(false)
262 , m_bUpdate(false)
263 , m_dwContextMenus(0)
264 , m_nIconFolder(0)
265 , m_nRestoreOvl(0)
266 , m_pContextMenu(nullptr)
267 , m_hShellMenu(nullptr)
268 , m_nBackgroundImageID(0)
269 , m_FileLoaded(0)
270 , m_bIsRevertTheirMy(false)
271 , m_nLineAdded(0)
272 , m_nLineDeleted(0)
273 , m_nBlockItemChangeHandler(0)
275 m_critSec.Init();
276 m_bNoAutoselectMissing = CRegDWORD(L"Software\\TortoiseGit\\AutoselectMissingFiles", FALSE) == TRUE;
279 CGitStatusListCtrl::~CGitStatusListCtrl()
281 ClearStatusArray();
284 void CGitStatusListCtrl::ClearStatusArray()
286 #if 0
287 CAutoWriteLock locker(m_guard);
288 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
290 delete m_arStatusArray[i];
292 m_arStatusArray.clear();
293 #endif
296 void CGitStatusListCtrl::Init(DWORD dwColumns, const CString& sColumnInfoContainer, unsigned __int64 dwContextMenus /* = GitSLC_POPALL */, bool bHasCheckboxes /* = true */, bool bHasWC /* = true */, DWORD allowedColumns /* = 0xffffffff */)
298 CAutoWriteLock locker(m_guard);
300 m_dwDefaultColumns = dwColumns | 1;
301 m_dwContextMenus = dwContextMenus;
302 m_bHasCheckboxes = bHasCheckboxes;
303 m_bHasWC = bHasWC;
304 m_bWaitCursor = true;
306 // set the extended style of the listcontrol
307 DWORD exStyle = LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_SUBITEMIMAGES;
308 exStyle |= (bHasCheckboxes ? LVS_EX_CHECKBOXES : 0);
309 SetRedraw(false);
310 SetExtendedStyle(exStyle);
311 CResizableColumnsListCtrl::Init();
313 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
315 m_nIconFolder = SYS_IMAGE_LIST().GetDirIconIndex();
316 m_nRestoreOvl = SYS_IMAGE_LIST().AddIcon((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_RESTOREOVL), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));
317 SYS_IMAGE_LIST().SetOverlayImage(m_nRestoreOvl, OVL_RESTORE);
318 SetImageList(&SYS_IMAGE_LIST(), LVSIL_SMALL);
320 // keep CSorter::operator() in sync!!
321 static UINT standardColumnNames[GITSLC_NUMCOLUMNS]
322 = { IDS_STATUSLIST_COLFILE
323 , IDS_STATUSLIST_COLFILENAME
324 , IDS_STATUSLIST_COLEXT
325 , IDS_STATUSLIST_COLSTATUS
326 , IDS_STATUSLIST_COLADD
327 , IDS_STATUSLIST_COLDEL
328 , IDS_STATUSLIST_COLLASTMODIFIED
329 , IDS_STATUSLIST_COLSIZE
332 m_ColumnManager.SetNames(standardColumnNames,GITSLC_NUMCOLUMNS);
333 m_ColumnManager.ReadSettings(m_dwDefaultColumns, 0xffffffff & ~(allowedColumns | m_dwDefaultColumns), sColumnInfoContainer, GITSLC_NUMCOLUMNS);
334 m_ColumnManager.SetRightAlign(4);
335 m_ColumnManager.SetRightAlign(5);
336 m_ColumnManager.SetRightAlign(7);
338 // enable file drops
339 if (!m_pDropTarget)
341 m_pDropTarget = std::make_unique<CGitStatusListCtrlDropTarget>(this);
342 RegisterDragDrop(m_hWnd, m_pDropTarget.get());
343 // create the supported formats:
344 FORMATETC ftetc = { 0 };
345 ftetc.dwAspect = DVASPECT_CONTENT;
346 ftetc.lindex = -1;
347 ftetc.tymed = TYMED_HGLOBAL;
348 ftetc.cfFormat = CF_HDROP;
349 m_pDropTarget->AddSuportedFormat(ftetc);
352 SetRedraw(true);
353 m_bWaitCursor = false;
356 bool CGitStatusListCtrl::SetBackgroundImage(UINT nID)
358 m_nBackgroundImageID = nID;
359 return CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), nID);
362 BOOL CGitStatusListCtrl::GetStatus ( const CTGitPathList* pathList
363 , bool bUpdate /* = FALSE */
364 , bool bShowIgnores /* = false */
365 , bool bShowUnRev /* = false */
366 , bool bShowLocalChangesIgnored /* = false */)
368 CAutoWriteLock locker(m_guard);
370 m_bEmpty = false;
371 m_bBusy = true;
372 m_bWaitCursor = true;
373 Invalidate();
375 m_bIsRevertTheirMy = g_Git.IsRebaseRunning() > 0;
377 int mask= CGitStatusListCtrl::FILELIST_MODIFY;
378 if(bShowIgnores)
379 mask|= CGitStatusListCtrl::FILELIST_IGNORE;
380 if(bShowUnRev)
381 mask|= CGitStatusListCtrl::FILELIST_UNVER;
382 if (bShowLocalChangesIgnored)
383 mask |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
384 this->UpdateFileList(mask, bUpdate, pathList);
386 if (pathList && m_setDirectFiles.empty())
388 // remember files which are selected by users so that those can be preselected
389 for (int i = 0; i < pathList->GetCount(); ++i)
390 if (!(*pathList)[i].IsDirectory())
391 m_setDirectFiles.insert((*pathList)[i].GetGitPathString());
394 #if 0
395 int refetchcounter = 0;
396 BOOL bRet = TRUE;
397 Invalidate();
398 // force the cursor to change
399 POINT pt;
400 GetCursorPos(&pt);
401 SetCursorPos(pt.x, pt.y);
403 m_mapFilenameToChecked.clear();
404 //m_StatusUrlList.Clear();
405 bool bHasChangelists = (m_changelists.size() > 1 || (!m_changelists.empty() && !m_bHasIgnoreGroup));
406 m_changelists.clear();
407 for (size_t i=0; i < m_arStatusArray.size(); i++)
409 FileEntry * entry = m_arStatusArray[i];
410 if ( bHasChangelists && entry->checked)
412 // If change lists are present, remember all checked entries
413 CString path = entry->GetPath().GetGitPathString();
414 m_mapFilenameToChecked[path] = true;
416 if ( (entry->status==git_wc_status_unversioned || entry->status==git_wc_status_missing ) && entry->checked )
418 // The user manually selected an unversioned or missing file. We remember
419 // this so that the selection can be restored when refreshing.
420 CString path = entry->GetPath().GetGitPathString();
421 m_mapFilenameToChecked[path] = true;
423 else if ( entry->status > git_wc_status_normal && !entry->checked )
425 // The user manually deselected a versioned file. We remember
426 // this so that the deselection can be restored when refreshing.
427 CString path = entry->GetPath().GetGitPathString();
428 m_mapFilenameToChecked[path] = false;
432 // use a sorted path list to make sure we fetch the status of
433 // parent items first, *then* the child items (if any)
434 CTGitPathList sortedPathList = pathList;
435 sortedPathList.SortByPathname();
438 bRet = TRUE;
439 m_nTargetCount = 0;
440 m_bHasExternalsFromDifferentRepos = FALSE;
441 m_bHasExternals = FALSE;
442 m_bHasUnversionedItems = FALSE;
443 m_bHasChangeLists = false;
444 m_bShowIgnores = bShowIgnores;
445 m_nSortedColumn = 0;
446 m_bBlock = TRUE;
447 m_bBusy = true;
448 m_bEmpty = false;
449 Invalidate();
451 // first clear possible status data left from
452 // previous GetStatus() calls
453 ClearStatusArray();
455 m_StatusFileList = sortedPathList;
457 // Since Git_client_status() returns all files, even those in
458 // folders included with Git:externals we need to check if all
459 // files we get here belongs to the same repository.
460 // It is possible to commit changes in an external folder, as long
461 // as the folder belongs to the same repository (but another path),
462 // but it is not possible to commit all files if the externals are
463 // from a different repository.
465 // To check if all files belong to the same repository, we compare the
466 // UUID's - if they're identical then the files belong to the same
467 // repository and can be committed. But if they're different, then
468 // tell the user to commit all changes in the external folders
469 // first and exit.
470 CStringA sUUID; // holds the repo UUID
471 CTGitPathList arExtPaths; // list of Git:external paths
473 GitConfig config;
475 m_sURL.Empty();
477 m_nTargetCount = sortedPathList.GetCount();
479 GitStatus status(m_pbCanceled);
480 if(m_nTargetCount > 1 && sortedPathList.AreAllPathsFilesInOneDirectory())
482 // This is a special case, where we've been given a list of files
483 // all from one folder
484 // We handle them by setting a status filter, then requesting the Git status of
485 // all the files in the directory, filtering for the ones we're interested in
486 status.SetFilter(sortedPathList);
488 // if all selected entries are files, we don't do a recursive status
489 // fetching. But if only one is a directory, we have to recurse.
490 git_depth_t depth = git_depth_files;
491 // We have set a filter. If all selected items were files or we fetch
492 // the status not recursively, then we have to include
493 // ignored items too - the user has selected them
494 bool bShowIgnoresRight = true;
495 for (int fcindex=0; fcindex<sortedPathList.GetCount(); ++fcindex)
497 if (sortedPathList[fcindex].IsDirectory())
499 depth = git_depth_infinity;
500 bShowIgnoresRight = false;
501 break;
504 if(!FetchStatusForSingleTarget(config, status, sortedPathList.GetCommonDirectory(), bUpdate, sUUID, arExtPaths, true, depth, bShowIgnoresRight))
505 bRet = FALSE;
507 else
509 for(int nTarget = 0; nTarget < m_nTargetCount; nTarget++)
511 // check whether the path we want the status for is already fetched due to status-fetching
512 // of a parent path.
513 // this check is only done for file paths, because folder paths could be included already
514 // but not recursively
515 if (sortedPathList[nTarget].IsDirectory() || !GetListEntry(sortedPathList[nTarget]))
517 if(!FetchStatusForSingleTarget(config, status, sortedPathList[nTarget], bUpdate, sUUID,
518 arExtPaths, false, git_depth_infinity, bShowIgnores))
520 bRet = FALSE;
526 // remove the 'helper' files of conflicted items from the list.
527 // otherwise they would appear as unversioned files.
528 for (INT_PTR cind = 0; cind < m_ConflictFileList.GetCount(); ++cind)
530 for (size_t i=0; i < m_arStatusArray.size(); i++)
532 if (m_arStatusArray[i]->GetPath().IsEquivalentTo(m_ConflictFileList[cind]))
534 delete m_arStatusArray[i];
535 m_arStatusArray.erase(m_arStatusArray.cbegin() + i);
536 break;
540 refetchcounter++;
541 } while(!BuildStatistics() && (refetchcounter < 2) && (*m_pbCanceled==false));
543 m_bBlock = FALSE;
544 m_bBusy = false;
545 GetCursorPos(&pt);
546 SetCursorPos(pt.x, pt.y);
547 return bRet;
548 #endif
549 m_bBusy = false;
550 m_bWaitCursor = false;
551 BuildStatistics();
552 return TRUE;
555 // Get the show-flags bitmap value which corresponds to a particular Git status
556 DWORD CGitStatusListCtrl::GetShowFlagsFromGitStatus(git_wc_status_kind status)
558 switch (status)
560 case git_wc_status_none:
561 case git_wc_status_unversioned:
562 return GITSLC_SHOWUNVERSIONED;
563 case git_wc_status_ignored:
564 if (!m_bShowIgnores)
565 return GITSLC_SHOWDIRECTS;
566 return GITSLC_SHOWDIRECTS|GITSLC_SHOWIGNORED;
567 case git_wc_status_normal:
568 return GITSLC_SHOWNORMAL;
569 case git_wc_status_added:
570 return GITSLC_SHOWADDED;
571 case git_wc_status_deleted:
572 return GITSLC_SHOWREMOVED;
573 case git_wc_status_modified:
574 return GITSLC_SHOWMODIFIED;
575 case git_wc_status_conflicted:
576 return GITSLC_SHOWCONFLICTED;
577 default:
578 // we should NEVER get here!
579 ASSERT(FALSE);
580 break;
582 return 0;
585 void CGitStatusListCtrl::Show(unsigned int dwShow, unsigned int dwCheck /*=0*/, bool /*bShowFolders*/ /* = true */,BOOL UpdateStatusList,bool UseStoredCheckStatus)
587 m_bWaitCursor = true;
588 m_bBusy = true;
589 m_bEmpty = false;
590 Invalidate();
592 CAutoWriteLock locker(m_guard);
593 WORD langID = (WORD)CRegStdDWORD(L"Software\\TortoiseGit\\LanguageID", GetUserDefaultLangID());
595 //SetItemCount(listIndex);
596 SetRedraw(FALSE);
597 DeleteAllItems();
598 m_nSelected = 0;
600 m_nShownUnversioned = 0;
601 m_nShownModified = 0;
602 m_nShownAdded = 0;
603 m_nShownDeleted = 0;
604 m_nShownConflicted = 0;
605 m_nShownFiles = 0;
606 m_nShownSubmodules = 0;
608 m_dwShow = dwShow;
610 if(UpdateStatusList)
612 m_arStatusArray.clear();
613 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
614 m_arStatusArray.push_back(&m_StatusFileList[i]);
616 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
617 m_arStatusArray.push_back(&m_UnRevFileList[i]);
619 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
620 m_arStatusArray.push_back(&m_IgnoreFileList[i]);
622 PrepareGroups();
623 if (m_nSortedColumn >= 0)
625 CSorter predicate (&m_ColumnManager, m_nSortedColumn, m_bAscending);
626 std::stable_sort(m_arStatusArray.begin(), m_arStatusArray.end(), predicate);
629 int index =0;
630 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
632 //set default checkbox status
633 auto entry = const_cast<CTGitPath*>(m_arStatusArray[i]);
634 CString path = entry->GetGitPathString();
635 if (!m_mapFilenameToChecked.empty() && m_mapFilenameToChecked.find(path) != m_mapFilenameToChecked.end())
636 entry->m_Checked=m_mapFilenameToChecked[path];
637 else if (!UseStoredCheckStatus)
639 bool autoSelectSubmodules = !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules);
640 if (((entry->m_Action & dwCheck) && !(m_bNoAutoselectMissing && entry->m_Action & CTGitPath::LOGACTIONS_MISSING) || dwShow & GITSLC_SHOWDIRECTFILES && m_setDirectFiles.find(path) != m_setDirectFiles.end()) && autoSelectSubmodules)
641 entry->m_Checked=true;
642 else
643 entry->m_Checked=false;
644 m_mapFilenameToChecked[path] = entry->m_Checked;
647 if(entry->m_Action & dwShow)
649 AddEntry(entry,langID,index);
650 index++;
654 AdjustColumnWidths();
656 SetRedraw(TRUE);
657 GetStatisticsString();
659 CHeaderCtrl * pHeader = GetHeaderCtrl();
660 HDITEM HeaderItem = {0};
661 HeaderItem.mask = HDI_FORMAT;
662 for (int i=0; i<pHeader->GetItemCount(); ++i)
664 pHeader->GetItem(i, &HeaderItem);
665 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
666 pHeader->SetItem(i, &HeaderItem);
668 if (m_nSortedColumn >= 0)
670 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
671 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
672 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
675 RestoreScrollPos();
677 m_bWaitCursor = false;
678 m_bBusy = false;
679 m_bEmpty = (GetItemCount() == 0);
680 Invalidate();
682 this->BuildStatistics();
684 #if 0
686 m_bShowFolders = bShowFolders;
688 int nTopIndex = GetTopIndex();
689 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
690 int nSelectedEntry = 0;
691 if (posSelectedEntry)
692 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
693 SetRedraw(FALSE);
694 DeleteAllItems();
696 PrepareGroups();
698 m_arListArray.clear();
700 m_arListArray.reserve(m_arStatusArray.size());
701 SetItemCount (static_cast<int>(m_arStatusArray.size()));
703 int listIndex = 0;
704 for (size_t i=0; i < m_arStatusArray.size(); ++i)
706 FileEntry * entry = m_arStatusArray[i];
707 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
708 continue;
709 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
710 continue;
711 if (entry->IsFolder() && (!bShowFolders))
712 continue; // don't show folders if they're not wanted.
714 #if 0
715 git_wc_status_kind status = GitStatus::GetMoreImportant(entry->status, entry->remotestatus);
716 DWORD showFlags = GetShowFlagsFromGitStatus(status);
717 if (entry->switched)
718 showFlags |= SVNSLC_SHOWSWITCHED;
719 if (!entry->changelist.IsEmpty())
720 showFlags |= SVNSLC_SHOWINCHANGELIST;
721 #endif
722 bool bAllowCheck = ((entry->changelist.Compare(GITSLC_IGNORECHANGELIST) != 0)
723 && (m_bCheckIfGroupsExist || (m_changelists.empty() || (m_changelists.size() == 1 && m_bHasIgnoreGroup))));
725 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
726 #if 0
727 if (status != Git_wc_status_ignored || (entry->direct) || (dwShow & GitSLC_SHOWIGNORED))
729 if ((!entry->IsFolder()) && (status == Git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
731 if (PathFileExists(entry->GetPath().GetWinPath()))
733 m_arListArray.push_back(i);
734 if ((dwCheck & SVNSLC_SHOWREMOVEDANDPRESENT)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
736 if (bAllowCheck)
737 entry->checked = true;
739 AddEntry(entry, langID, listIndex++);
742 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
744 m_arListArray.push_back(i);
745 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
747 if (bAllowCheck)
748 entry->checked = true;
750 AddEntry(entry, langID, listIndex++);
752 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
754 m_arListArray.push_back(i);
755 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
757 if (bAllowCheck)
758 entry->checked = true;
760 AddEntry(entry, langID, listIndex++);
763 #endif
766 SetItemCount(listIndex);
768 m_ColumnManager.UpdateRelevance (m_arStatusArray, m_arListArray);
770 AdjustColumnWidths();
772 SetRedraw(TRUE);
773 GetStatisticsString();
775 CHeaderCtrl * pHeader = GetHeaderCtrl();
776 HDITEM HeaderItem = {0};
777 HeaderItem.mask = HDI_FORMAT;
778 for (int i=0; i<pHeader->GetItemCount(); ++i)
780 pHeader->GetItem(i, &HeaderItem);
781 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
782 pHeader->SetItem(i, &HeaderItem);
784 if (m_nSortedColumn)
786 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
787 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
788 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
791 if (nSelectedEntry)
793 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
794 EnsureVisible(nSelectedEntry, false);
796 else
798 // Restore the item at the top of the list.
799 for (int i=0;GetTopIndex() != nTopIndex;i++)
801 if ( !EnsureVisible(nTopIndex+i,false) )
802 break;
806 m_bEmpty = (GetItemCount() == 0);
807 Invalidate();
808 #endif
811 void CGitStatusListCtrl::Show(unsigned int /*dwShow*/, const CTGitPathList& checkedList, bool /*bShowFolders*/ /* = true */)
813 CAutoWriteLock locker(m_guard);
814 m_bWaitCursor = true;
815 m_bBusy = true;
816 m_dwShow = GITSLC_SHOWALL;
817 DeleteAllItems();
818 m_arStatusArray.clear();
819 for (int i = 0; i < checkedList.GetCount(); ++i)
821 this->AddEntry((CTGitPath *)&checkedList[i],0,i);
822 m_arStatusArray.push_back(&checkedList[i]);
825 AdjustColumnWidths();
827 RestoreScrollPos();
828 m_bWaitCursor = false;
829 m_bBusy = false;
830 return ;
831 #if 0
833 Locker lock(m_critSec);
834 WORD langID = (WORD)CRegStdDWORD(L"Software\\TortoiseGit\\LanguageID", GetUserDefaultLangID());
836 m_dwShow = dwShow;
837 m_bShowFolders = bShowFolders;
838 m_nSelected = 0;
839 int nTopIndex = GetTopIndex();
840 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
841 int nSelectedEntry = 0;
842 if (posSelectedEntry)
843 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
844 SetRedraw(FALSE);
845 DeleteAllItems();
847 PrepareGroups();
849 m_arListArray.clear();
851 m_arListArray.reserve(m_arStatusArray.size());
852 SetItemCount (static_cast<int>(m_arStatusArray.size()));
854 int listIndex = 0;
855 for (size_t i=0; i < m_arStatusArray.size(); ++i)
857 FileEntry * entry = m_arStatusArray[i];
858 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
859 continue;
860 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
861 continue;
862 if (entry->IsFolder() && (!bShowFolders))
863 continue; // don't show folders if they're not wanted.
864 #if 0
865 git_wc_status_kind status = SVNStatus::GetMoreImportant(entry->status, entry->remotestatus);
866 DWORD showFlags = GetShowFlagsFromSVNStatus(status);
867 if (!entry->changelist.IsEmpty())
868 showFlags |= SVNSLC_SHOWINCHANGELIST;
870 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
871 if (status != git_wc_status_ignored || (entry->direct) || (dwShow & SVNSLC_SHOWIGNORED))
873 for (int npath = 0; npath < checkedList.GetCount(); ++npath)
875 if (entry->GetPath().IsEquivalentTo(checkedList[npath]))
877 entry->checked = true;
878 break;
881 if ((!entry->IsFolder()) && (status == git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
883 if (PathFileExists(entry->GetPath().GetWinPath()))
885 m_arListArray.push_back(i);
886 AddEntry(entry, langID, listIndex++);
889 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
891 m_arListArray.push_back(i);
892 AddEntry(entry, langID, listIndex++);
894 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
896 m_arListArray.push_back(i);
897 AddEntry(entry, langID, listIndex++);
899 else if (entry->switched)
901 m_arListArray.push_back(i);
902 AddEntry(entry, langID, listIndex++);
905 #endif
908 SetItemCount(listIndex);
910 AdjustColumnWidths();
912 SetRedraw(TRUE);
913 GetStatisticsString();
915 CHeaderCtrl * pHeader = GetHeaderCtrl();
916 HDITEM HeaderItem = {0};
917 HeaderItem.mask = HDI_FORMAT;
918 for (int i=0; i<pHeader->GetItemCount(); ++i)
920 pHeader->GetItem(i, &HeaderItem);
921 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
922 pHeader->SetItem(i, &HeaderItem);
924 if (m_nSortedColumn)
926 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
927 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
928 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
931 if (nSelectedEntry)
933 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
934 EnsureVisible(nSelectedEntry, false);
936 else
938 // Restore the item at the top of the list.
939 for (int i=0;GetTopIndex() != nTopIndex;i++)
941 if ( !EnsureVisible(nTopIndex+i,false) )
942 break;
946 m_bEmpty = (GetItemCount() == 0);
947 Invalidate();
948 #endif
951 void CGitStatusListCtrl::StoreScrollPos()
953 m_sScrollPos.enabled = true;
954 m_sScrollPos.nTopIndex = GetTopIndex();
955 m_sScrollPos.selMark = GetSelectionMark();
956 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
957 m_sScrollPos.nSelectedEntry = 0;
958 if (posSelectedEntry)
959 m_sScrollPos.nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
962 void CGitStatusListCtrl::RestoreScrollPos()
964 if (!m_sScrollPos.enabled || CRegDWORD(L"Software\\TortoiseGit\\RememberFileListPosition", TRUE) != TRUE)
965 return;
967 if (m_sScrollPos.nSelectedEntry)
969 SetItemState(m_sScrollPos.nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
970 EnsureVisible(m_sScrollPos.nSelectedEntry, false);
972 else
974 // Restore the item at the top of the list.
975 for (int i = 0; GetTopIndex() != m_sScrollPos.nTopIndex; ++i)
977 if (!EnsureVisible(m_sScrollPos.nTopIndex + i, false))
978 break;
981 if (m_sScrollPos.selMark >= 0)
983 SetSelectionMark(m_sScrollPos.selMark);
984 SetItemState(m_sScrollPos.selMark, LVIS_FOCUSED, LVIS_FOCUSED);
986 m_sScrollPos.enabled = false;
989 int CGitStatusListCtrl::GetColumnIndex(int mask)
991 for (int i = 0; i < 32; ++i)
992 if(mask&0x1)
993 return i;
994 else
995 mask=mask>>1;
996 return -1;
998 void CGitStatusListCtrl::AddEntry(CTGitPath * GitPath, WORD /*langID*/, int listIndex)
1000 static CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
1001 static bool abbreviateRenamings(((DWORD)CRegDWORD(L"Software\\TortoiseGit\\AbbreviateRenamings", FALSE)) == TRUE);
1002 static bool relativeTimes = (CRegDWORD(L"Software\\TortoiseGit\\RelativeTimes", FALSE) != FALSE);
1004 CAutoWriteLock locker(m_guard);
1005 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
1006 CString path = GitPath->GetGitPathString();
1008 int index = listIndex;
1009 int nCol = 1;
1010 CString entryname = GitPath->GetGitPathString();
1011 int icon_idx = 0;
1012 if (GitPath->IsDirectory())
1014 icon_idx = m_nIconFolder;
1015 m_nShownSubmodules++;
1017 else
1019 icon_idx = SYS_IMAGE_LIST().GetPathIconIndex(*GitPath);
1020 m_nShownFiles++;
1022 switch (GitPath->m_Action)
1024 case CTGitPath::LOGACTIONS_ADDED:
1025 case CTGitPath::LOGACTIONS_COPY:
1026 m_nShownAdded++;
1027 break;
1028 case CTGitPath::LOGACTIONS_DELETED:
1029 case CTGitPath::LOGACTIONS_MISSING:
1030 case CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING:
1031 m_nShownDeleted++;
1032 break;
1033 case CTGitPath::LOGACTIONS_REPLACED:
1034 case CTGitPath::LOGACTIONS_MODIFIED:
1035 case CTGitPath::LOGACTIONS_MERGED:
1036 m_nShownModified++;
1037 break;
1038 case CTGitPath::LOGACTIONS_UNMERGED:
1039 case CTGitPath::LOGACTIONS_UNMERGED | CTGitPath::LOGACTIONS_ADDED:
1040 case CTGitPath::LOGACTIONS_UNMERGED | CTGitPath::LOGACTIONS_MODIFIED:
1041 m_nShownConflicted++;
1042 break;
1043 case CTGitPath::LOGACTIONS_UNVER:
1044 m_nShownUnversioned++;
1045 break;
1046 default:
1047 m_nShownUnversioned++;
1048 break;
1050 if(GitPath->m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !GitPath->GetGitOldPathString().IsEmpty())
1052 if (!abbreviateRenamings)
1054 entryname += L' ';
1055 // relative path
1056 entryname.AppendFormat(from, (LPCTSTR)GitPath->GetGitOldPathString());
1058 else
1059 entryname = GitPath->GetAbbreviatedRename();
1062 InsertItem(index, entryname, icon_idx);
1063 if (m_restorepaths.find(GitPath->GetWinPathString()) != m_restorepaths.end())
1064 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), TVIS_OVERLAYMASK);
1066 this->SetItemData(index, (DWORD_PTR)GitPath);
1067 // SVNSLC_COLFILENAME
1068 SetItemText(index, nCol++, GitPath->GetFileOrDirectoryName());
1069 // SVNSLC_COLEXT
1070 SetItemText(index, nCol++, GitPath->GetFileExtension());
1071 // SVNSLC_COLSTATUS
1072 SetItemText(index, nCol++, GitPath->GetActionName());
1074 SetItemText(index, GetColumnIndex(GITSLC_COLADD),GitPath->m_StatAdd);
1075 SetItemText(index, GetColumnIndex(GITSLC_COLDEL),GitPath->m_StatDel);
1077 if (!(GitPath->m_Action & CTGitPath::LOGACTIONS_DELETED) && m_ColumnManager.IsRelevant(GetColumnIndex(GITSLC_COLMODIFICATIONDATE)))
1079 CString modificationDate;
1080 __int64 filetime = GitPath->GetLastWriteTime();
1081 if (filetime)
1083 FILETIME* f = (FILETIME*)(__int64*)&filetime;
1084 modificationDate = CLoglistUtils::FormatDateAndTime(CTime(CGit::filetime_to_time_t(f)), DATE_SHORTDATE, true, relativeTimes);
1086 SetItemText(index, GetColumnIndex(GITSLC_COLMODIFICATIONDATE), modificationDate);
1088 // SVNSLC_COLSIZE
1089 if (GitPath->IsDirectory() || !m_ColumnManager.IsRelevant(GetColumnIndex(GITSLC_COLSIZE)))
1090 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), L"");
1091 else
1093 TCHAR buf[100] = { 0 };
1094 StrFormatByteSize64(GitPath->GetFileSize(), buf, 100);
1095 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), buf);
1098 SetCheck(index, GitPath->m_Checked);
1099 if (GitPath->m_Checked)
1100 m_nSelected++;
1102 if ((GitPath->m_Action & CTGitPath::LOGACTIONS_SKIPWORKTREE) || (GitPath->m_Action & CTGitPath::LOGACTIONS_ASSUMEVALID))
1103 SetItemGroup(index, 3);
1104 else if (GitPath->m_Action & CTGitPath::LOGACTIONS_IGNORE)
1105 SetItemGroup(index, 2);
1106 else if( GitPath->m_Action & CTGitPath::LOGACTIONS_UNVER)
1107 SetItemGroup(index,1);
1108 else
1109 SetItemGroup(index, GitPath->m_ParentNo&(PARENT_MASK|MERGE_MASK));
1112 bool CGitStatusListCtrl::SetItemGroup(int item, int groupindex)
1114 CAutoWriteLock locker(m_guard);
1115 // if (!(m_dwContextMenus & SVNSLC_POPCHANGELISTS))
1116 // return false;
1117 if (groupindex < 0)
1118 return false;
1119 LVITEM i = {0};
1120 i.mask = LVIF_GROUPID;
1121 i.iItem = item;
1122 i.iSubItem = 0;
1123 i.iGroupId = groupindex;
1125 return !!SetItem(&i);
1128 void CGitStatusListCtrl::OnHdnItemclick(NMHDR *pNMHDR, LRESULT *pResult)
1130 LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
1131 *pResult = 0;
1133 CAutoReadWeakLock lock(m_guard);
1134 if (!lock.IsAcquired())
1135 return;
1137 if (m_arStatusArray.empty())
1138 return;
1140 if (m_nSortedColumn == phdr->iItem)
1141 m_bAscending = !m_bAscending;
1142 else
1143 m_bAscending = TRUE;
1144 m_nSortedColumn = phdr->iItem;
1145 Show(m_dwShow, 0, m_bShowFolders,false,true);
1148 BOOL CGitStatusListCtrl::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
1150 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
1151 *pResult = 0;
1152 CWnd* pParent = GetLogicalParent();
1153 if (pParent && pParent->GetSafeHwnd())
1154 pParent->SendMessage(GITSLNM_ITEMCHANGED, pNMLV->iItem);
1156 if (m_nBlockItemChangeHandler)
1157 return FALSE;
1159 if ((pNMLV->uNewState==0)||(pNMLV->uNewState & LVIS_SELECTED)||(pNMLV->uNewState & LVIS_FOCUSED))
1160 return FALSE;
1162 CAutoWriteWeakLock writeLock(m_guard);
1163 if (!writeLock.IsAcquired())
1165 NotifyCheck();
1166 return FALSE;
1169 bool bSelected = !!(ListView_GetItemState(m_hWnd, pNMLV->iItem, LVIS_SELECTED) & LVIS_SELECTED);
1170 int nListItems = GetItemCount();
1172 // was the item checked?
1174 if (GetCheck(pNMLV->iItem))
1177 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
1178 CheckEntry(pNMLV->iItem, nListItems);
1180 if (bSelected)
1182 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
1183 POSITION pos = GetFirstSelectedItemPosition();
1184 int index;
1185 while ((index = GetNextSelectedItem(pos)) >= 0)
1187 if (index != pNMLV->iItem)
1188 CheckEntry(index, nListItems);
1192 else
1195 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
1196 UncheckEntry(pNMLV->iItem, nListItems);
1198 if (bSelected)
1200 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
1201 POSITION pos = GetFirstSelectedItemPosition();
1202 int index;
1203 while ((index = GetNextSelectedItem(pos)) >= 0)
1205 if (index != pNMLV->iItem)
1206 UncheckEntry(index, nListItems);
1211 GetStatisticsString();
1212 NotifyCheck();
1214 return FALSE;
1217 void CGitStatusListCtrl::CheckEntry(int index, int /*nListItems*/)
1219 CAutoWriteLock locker(m_guard);
1220 auto path = GetListEntry(index);
1221 if (!path)
1222 return;
1223 m_mapFilenameToChecked[path->GetGitPathString()] = true;
1224 SetCheck(index, TRUE);
1225 // if an unversioned item was checked, then we need to check if
1226 // the parent folders are unversioned too. If the parent folders actually
1227 // are unversioned, then check those too.
1228 #if 0
1229 if (entry->status == git_wc_status_unversioned)
1231 // we need to check the parent folder too
1232 const CTGitPath& folderpath = entry->path;
1233 for (int i=0; i< nListItems; ++i)
1235 FileEntry * testEntry = GetListEntry(i);
1236 ASSERT(testEntry);
1237 if (!testEntry)
1238 continue;
1239 if (!testEntry->checked)
1241 if (testEntry->path.IsAncestorOf(folderpath) && (!testEntry->path.IsEquivalentTo(folderpath)))
1243 SetEntryCheck(testEntry,i,true);
1244 m_nSelected++;
1249 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1250 if ( (entry->status == git_wc_status_deleted) || (m_bCheckChildrenWithParent) || (bShift) )
1252 // if a deleted folder gets checked, we have to check all
1253 // children of that folder too.
1254 if (entry->path.IsDirectory())
1255 SetCheckOnAllDescendentsOf(entry, true);
1257 // if a deleted file or folder gets checked, we have to
1258 // check all parents of this item too.
1259 for (int i=0; i<nListItems; ++i)
1261 FileEntry * testEntry = GetListEntry(i);
1262 ASSERT(testEntry);
1263 if (!testEntry)
1264 continue;
1265 if (!testEntry->checked)
1267 if (testEntry->path.IsAncestorOf(entry->path) && (!testEntry->path.IsEquivalentTo(entry->path)))
1269 if ((testEntry->status == git_wc_status_deleted)||(m_bCheckChildrenWithParent))
1271 SetEntryCheck(testEntry,i,true);
1272 m_nSelected++;
1273 // now we need to check all children of this parent folder
1274 SetCheckOnAllDescendentsOf(testEntry, true);
1280 #endif
1281 if ( !path->m_Checked )
1283 path->m_Checked = TRUE;
1284 m_nSelected++;
1288 void CGitStatusListCtrl::UncheckEntry(int index, int /*nListItems*/)
1290 CAutoWriteLock locker(m_guard);
1291 auto path = GetListEntry(index);
1292 if (!path)
1293 return;
1294 SetCheck(index, FALSE);
1295 m_mapFilenameToChecked[path->GetGitPathString()] = false;
1296 // item was unchecked
1297 #if 0
1298 if (entry->path.IsDirectory())
1300 // disable all files within an unselected folder, except when unchecking a folder with property changes
1301 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1302 if ( (entry->status != git_wc_status_modified) || (bShift) )
1304 SetCheckOnAllDescendentsOf(entry, false);
1307 else if (entry->status == git_wc_status_deleted)
1309 // a "deleted" file was unchecked, so uncheck all parent folders
1310 // and all children of those parents
1311 for (int i=0; i<nListItems; i++)
1313 FileEntry * testEntry = GetListEntry(i);
1314 ASSERT(testEntry);
1315 if (!testEntry)
1316 continue;
1317 if (testEntry->checked)
1319 if (testEntry->path.IsAncestorOf(entry->path))
1321 if (testEntry->status == git_wc_status_deleted)
1323 SetEntryCheck(testEntry,i,false);
1324 m_nSelected--;
1326 SetCheckOnAllDescendentsOf(testEntry, false);
1332 #endif
1333 if ( path->m_Checked )
1335 path->m_Checked = FALSE;
1336 m_nSelected--;
1339 bool CGitStatusListCtrl::BuildStatistics()
1341 CAutoReadLock locker(m_guard);
1342 bool bRefetchStatus = false;
1344 // now gather some statistics
1345 m_nUnversioned = 0;
1346 m_nNormal = 0;
1347 m_nModified = 0;
1348 m_nAdded = 0;
1349 m_nDeleted = 0;
1350 m_nConflicted = 0;
1351 m_nTotal = 0;
1352 m_nSelected = 0;
1353 m_nLineAdded = 0;
1354 m_nLineDeleted = 0;
1355 m_nRenamed = 0;
1357 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
1359 int status = m_arStatusArray[i]->m_Action;
1361 m_nLineAdded += _wtol(m_arStatusArray[i]->m_StatAdd);
1362 m_nLineDeleted += _wtol(m_arStatusArray[i]->m_StatDel);
1364 if(status&(CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
1365 m_nAdded++;
1367 if(status&CTGitPath::LOGACTIONS_DELETED)
1368 m_nDeleted++;
1370 if(status&(CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_MODIFIED))
1371 m_nModified++;
1373 if(status&CTGitPath::LOGACTIONS_UNMERGED)
1374 m_nConflicted++;
1376 if(status&(CTGitPath::LOGACTIONS_IGNORE|CTGitPath::LOGACTIONS_UNVER))
1377 m_nUnversioned++;
1379 if(status&(CTGitPath::LOGACTIONS_REPLACED))
1380 m_nRenamed++;
1382 if (m_arStatusArray[i]->m_Checked)
1383 m_nSelected++;
1385 return !bRefetchStatus;
1388 int CGitStatusListCtrl::GetGroupFromPoint(POINT * ppt)
1390 // the point must be relative to the upper left corner of the control
1392 if (!ppt)
1393 return -1;
1394 if (!IsGroupViewEnabled())
1395 return -1;
1397 POINT pt = *ppt;
1398 pt.x = 10;
1399 UINT flags = 0;
1400 int nItem = -1;
1401 RECT rc;
1402 GetWindowRect(&rc);
1403 while (((flags & LVHT_BELOW) == 0)&&(pt.y < rc.bottom))
1405 nItem = HitTest(pt, &flags);
1406 if ((flags & LVHT_ONITEM)||(flags & LVHT_EX_GROUP_HEADER))
1408 // the first item below the point
1410 // check if the point is too much right (i.e. if the point
1411 // is farther to the right than the width of the item)
1412 RECT r;
1413 GetItemRect(nItem, &r, LVIR_LABEL);
1414 if (ppt->x > r.right)
1415 return -1;
1417 LVITEM lv = {0};
1418 lv.mask = LVIF_GROUPID;
1419 lv.iItem = nItem;
1420 GetItem(&lv);
1421 int groupID = lv.iGroupId;
1422 // now we search upwards and check if the item above this one
1423 // belongs to another group. If it belongs to the same group,
1424 // we're not over a group header
1425 while (pt.y >= 0)
1427 pt.y -= 2;
1428 nItem = HitTest(pt, &flags);
1429 if ((flags & LVHT_ONITEM)&&(nItem >= 0))
1431 // the first item below the point
1432 LVITEM lv2 = {0};
1433 lv2.mask = LVIF_GROUPID;
1434 lv2.iItem = nItem;
1435 GetItem(&lv2);
1436 if (lv2.iGroupId != groupID)
1437 return groupID;
1438 else
1439 return -1;
1442 if (pt.y < 0)
1443 return groupID;
1444 return -1;
1446 pt.y += 2;
1448 return -1;
1451 void CGitStatusListCtrl::OnContextMenuGroup(CWnd * /*pWnd*/, CPoint point)
1453 POINT clientpoint = point;
1454 ScreenToClient(&clientpoint);
1455 if ((IsGroupViewEnabled())&&(GetGroupFromPoint(&clientpoint) >= 0))
1457 CAutoReadWeakLock readLock(m_guard);
1458 if (!readLock.IsAcquired())
1459 return;
1461 CMenu popup;
1462 if (popup.CreatePopupMenu())
1464 CString temp;
1465 temp.LoadString(IDS_STATUSLIST_CHECKGROUP);
1466 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_CHECKGROUP, temp);
1467 temp.LoadString(IDS_STATUSLIST_UNCHECKGROUP);
1468 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_UNCHECKGROUP, temp);
1469 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
1470 bool bCheck = false;
1471 switch (cmd)
1473 case IDGITLC_CHECKGROUP:
1474 bCheck = true;
1475 // fall through here
1476 case IDGITLC_UNCHECKGROUP:
1478 int group = GetGroupFromPoint(&clientpoint);
1479 // go through all items and check/uncheck those assigned to the group
1480 // but block the OnLvnItemChanged handler
1481 for (int i=0; i<GetItemCount(); ++i)
1483 LVITEM lv = { 0 };
1484 lv.mask = LVIF_GROUPID;
1485 lv.iItem = i;
1486 GetItem(&lv);
1488 if (lv.iGroupId == group)
1490 auto entry = GetListEntry(i);
1491 if (entry)
1493 bool bOldCheck = entry->m_Checked;
1494 SetEntryCheck(entry, i, bCheck);
1495 if (bCheck != bOldCheck)
1497 if (bCheck)
1498 m_nSelected++;
1499 else
1500 m_nSelected--;
1506 GetStatisticsString();
1507 NotifyCheck();
1509 break;
1515 void CGitStatusListCtrl::OnContextMenuList(CWnd * pWnd, CPoint point)
1517 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1519 CAutoReadWeakLock readLock(m_guard);
1520 if (!readLock.IsAcquired())
1521 return;
1523 auto selectedCount = GetSelectedCount();
1524 int selIndex = GetSelectionMark();
1525 if ((point.x == -1) && (point.y == -1))
1527 CRect rect;
1528 GetItemRect(selIndex, &rect, LVIR_LABEL);
1529 ClientToScreen(&rect);
1530 point = rect.CenterPoint();
1532 if (selectedCount == 0 && m_bHasCheckboxes)
1534 // nothing selected could mean the context menu is requested for
1535 // a group header
1536 OnContextMenuGroup(pWnd, point);
1538 else if (selIndex >= 0)
1540 CAutoWriteLock writeLock(m_guard);
1541 auto filepath = GetListEntry(selIndex);
1542 if (!filepath)
1543 return;
1545 //const CTGitPath& filepath = entry->path;
1546 int wcStatus = filepath->m_Action;
1547 // entry is selected, now show the popup menu
1548 CIconMenu popup;
1549 CMenu changelistSubMenu;
1550 CMenu ignoreSubMenu;
1551 CMenu shellMenu;
1552 if (popup.CreatePopupMenu())
1554 //Add Menu for version controlled file
1556 if (selectedCount > 0 && (wcStatus & CTGitPath::LOGACTIONS_UNMERGED))
1558 if (selectedCount == 1 && (m_dwContextMenus & GITSLC_POPCONFLICT))
1560 popup.AppendMenuIcon(IDGITLC_EDITCONFLICT, IDS_MENUCONFLICT, IDI_CONFLICT);
1561 popup.SetDefaultItem(IDGITLC_EDITCONFLICT, FALSE);
1563 if (m_dwContextMenus & GITSLC_POPRESOLVE)
1564 popup.AppendMenuIcon(IDGITLC_RESOLVECONFLICT, IDS_STATUSLIST_CONTEXT_RESOLVED, IDI_RESOLVE);
1565 if ((m_dwContextMenus & GITSLC_POPRESOLVE)/*&&(entry->textstatus == git_wc_status_conflicted)*/)
1567 popup.AppendMenuIcon(IDGITLC_RESOLVETHEIRS, IDS_SVNPROGRESS_MENUUSETHEIRS, IDI_RESOLVE);
1568 popup.AppendMenuIcon(IDGITLC_RESOLVEMINE, IDS_SVNPROGRESS_MENUUSEMINE, IDI_RESOLVE);
1570 if ((m_dwContextMenus & GITSLC_POPCONFLICT)||(m_dwContextMenus & GITSLC_POPRESOLVE))
1571 popup.AppendMenu(MF_SEPARATOR);
1574 if (selectedCount > 0)
1576 if (wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
1578 if (m_dwContextMenus & GITSLC_POPADD)
1580 //if ( entry->IsFolder() )
1582 // popup.AppendMenuIcon(IDSVNLC_ADD_RECURSIVE, IDS_STATUSLIST_CONTEXT_ADD_RECURSIVE, IDI_ADD);
1584 //else
1586 popup.AppendMenuIcon(IDGITLC_ADD, IDS_STATUSLIST_CONTEXT_ADD, IDI_ADD);
1589 if (m_dwContextMenus & GITSLC_POPCOMMIT)
1590 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1594 if (!(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) && !((wcStatus & CTGitPath::LOGACTIONS_MISSING) && wcStatus != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) && wcStatus != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MODIFIED)) && selectedCount > 0)
1596 bool bEntryAdded = false;
1597 if (m_dwContextMenus & GITSLC_POPCOMPAREWITHBASE)
1599 if(filepath->m_ParentNo & MERGE_MASK)
1600 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_TREE_DIFF, IDI_DIFF);
1601 else
1602 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_LOG_COMPAREWITHBASE, IDI_DIFF);
1604 if (!(wcStatus & (CTGitPath::LOGACTIONS_UNMERGED)) || selectedCount != 1)
1605 popup.SetDefaultItem(IDGITLC_COMPARE, FALSE);
1606 bEntryAdded = true;
1609 if (!g_Git.IsInitRepos() && (m_dwContextMenus & GITSLC_POPGNUDIFF))
1611 popup.AppendMenuIcon(IDGITLC_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1612 bEntryAdded = true;
1615 if ((m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPAREWC)) && m_bHasWC)
1617 if ((!m_CurrentVersion.IsEmpty()) && m_CurrentVersion != GIT_REV_ZERO)
1619 popup.AppendMenuIcon(IDGITLC_COMPAREWC, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1620 bEntryAdded = true;
1624 if (bEntryAdded)
1625 popup.AppendMenu(MF_SEPARATOR);
1628 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
1630 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPARETWOREVISIONS))
1632 popup.AppendMenuIcon(IDGITLC_COMPARETWOREVISIONS, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
1633 popup.SetDefaultItem(IDGITLC_COMPARETWOREVISIONS, FALSE);
1635 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_GNUDIFF2REVISIONS))
1636 popup.AppendMenuIcon(IDGITLC_GNUDIFF2REVISIONS, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1639 //Select Multi item
1640 if (selectedCount > 0)
1642 if (selectedCount == 2 && (m_dwContextMenus & GITSLC_POPCOMPARETWOFILES) && (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO))
1644 POSITION pos = GetFirstSelectedItemPosition();
1645 int index = GetNextSelectedItem(pos);
1646 if (index >= 0)
1648 auto entry2 = GetListEntry(index);
1649 bool firstEntryExistsAndIsFile = entry2 && !entry2->IsDirectory();
1650 index = GetNextSelectedItem(pos);
1651 if (index >= 0)
1653 entry2 = GetListEntry(index);
1654 if (firstEntryExistsAndIsFile && entry2 && !entry2->IsDirectory())
1655 popup.AppendMenuIcon(IDGITLC_COMPARETWOFILES, IDS_STATUSLIST_CONTEXT_COMPARETWOFILES, IDI_DIFF);
1661 if (selectedCount > 0 && (!(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))) && m_bHasWC)
1663 if ((m_dwContextMenus & GITSLC_POPCOMMIT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && !(wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1664 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1666 if ((m_dwContextMenus & GITSLC_POPREVERT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO))
1667 popup.AppendMenuIcon(IDGITLC_REVERT, IDS_MENUREVERT, IDI_REVERT);
1669 if ((m_dwContextMenus & GITSLC_POPSKIPWORKTREE) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && !(wcStatus & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_UNMERGED | CTGitPath::LOGACTIONS_SKIPWORKTREE)))
1670 popup.AppendMenuIcon(IDGITLC_SKIPWORKTREE, IDS_STATUSLIST_SKIPWORKTREE);
1672 if ((m_dwContextMenus & GITSLC_POPASSUMEVALID) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && !(wcStatus & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_UNMERGED | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1673 popup.AppendMenuIcon(IDGITLC_ASSUMEVALID, IDS_MENUASSUMEVALID);
1675 if ((m_dwContextMenus & GITLC_POPUNSETIGNORELOCALCHANGES) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && (wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1676 popup.AppendMenuIcon(IDGITLC_UNSETIGNORELOCALCHANGES, IDS_STATUSLIST_UNSETIGNORELOCALCHANGES);
1678 if (m_dwContextMenus & GITSLC_POPRESTORE && !filepath->IsDirectory())
1680 if (m_restorepaths.find(filepath->GetWinPathString()) == m_restorepaths.end())
1681 popup.AppendMenuIcon(IDGITLC_CREATERESTORE, IDS_MENUCREATERESTORE, IDI_RESTORE);
1682 else
1683 popup.AppendMenuIcon(IDGITLC_RESTOREPATH, IDS_MENURESTORE, IDI_RESTORE);
1686 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOREV)) && ( !this->m_CurrentVersion.IsEmpty() )
1687 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1689 popup.AppendMenuIcon(IDGITLC_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
1692 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOPARENT)) && ( !this->m_CurrentVersion.IsEmpty() )
1693 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_ADDED))
1695 popup.AppendMenuIcon(IDGITLC_REVERTTOPARENT, IDS_LOG_POPUP_REVERTTOPARENT, IDI_REVERT);
1699 if (selectedCount == 1 && !(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)))
1701 if (m_dwContextMenus & GITSLC_POPSHOWLOG)
1702 popup.AppendMenuIcon(IDGITLC_LOG, IDS_REPOBROWSE_SHOWLOG, IDI_LOG);
1703 if (m_dwContextMenus & GITSLC_POPSHOWLOGSUBMODULE && filepath->IsDirectory())
1704 popup.AppendMenuIcon(IDGITLC_LOGSUBMODULE, IDS_LOG_SUBMODULE, IDI_LOG);
1705 if (m_dwContextMenus & GITSLC_POPSHOWLOGOLDNAME && (wcStatus & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !filepath->GetGitOldPathString().IsEmpty()))
1706 popup.AppendMenuIcon(IDGITLC_LOGOLDNAME, IDS_STATUSLIST_SHOWLOGOLDNAME, IDI_LOG);
1707 if ((m_dwContextMenus & GITSLC_POPBLAME) && !filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && !((wcStatus & CTGitPath::LOGACTIONS_ADDED) && (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)) && m_bHasWC)
1708 popup.AppendMenuIcon(IDGITLC_BLAME, IDS_MENUBLAME, IDI_BLAME);
1711 if (selectedCount > 0)
1713 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_EXPORT)) && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)))
1714 popup.AppendMenuIcon(IDGITLC_EXPORT, IDS_LOG_POPUP_EXPORT, IDI_EXPORT);
1717 if (selectedCount == 1)
1719 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_SAVEAS) && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1720 popup.AppendMenuIcon(IDGITLC_SAVEAS, IDS_LOG_POPUP_SAVE, IDI_SAVEAS);
1722 if (m_dwContextMenus & GITSLC_POPOPEN && !filepath->IsDirectory() && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)))
1724 popup.AppendMenuIcon(IDGITLC_VIEWREV, IDS_LOG_POPUP_VIEWREV);
1725 popup.AppendMenuIcon(IDGITLC_OPEN, IDS_REPOBROWSE_OPEN, IDI_OPEN);
1726 popup.AppendMenuIcon(IDGITLC_OPENWITH, IDS_LOG_POPUP_OPENWITH, IDI_OPEN);
1729 if (m_dwContextMenus & GITSLC_POPEXPLORE && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC)
1730 popup.AppendMenuIcon(IDGITLC_EXPLORE, IDS_STATUSLIST_CONTEXT_EXPLORE, IDI_EXPLORER);
1732 if (m_dwContextMenus & GITSLC_PREPAREDIFF && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1734 popup.AppendMenu(MF_SEPARATOR);
1735 popup.AppendMenuIcon(IDGITLC_PREPAREDIFF, IDS_PREPAREDIFF, IDI_DIFF);
1736 if (!m_sMarkForDiffFilename.IsEmpty())
1738 CString diffWith;
1739 if (filepath->GetGitPathString() == m_sMarkForDiffFilename)
1740 diffWith = m_sMarkForDiffVersion;
1741 else
1743 PathCompactPathEx(CStrBuf(diffWith, 2 * GIT_HASH_SIZE), m_sMarkForDiffFilename, 2 * GIT_HASH_SIZE, 0);
1744 diffWith += L':' + m_sMarkForDiffVersion.Left(g_Git.GetShortHASHLength());
1746 CString menuEntry;
1747 menuEntry.Format(IDS_MENUDIFFNOW, (LPCTSTR)diffWith);
1748 popup.AppendMenuIcon(IDGITLC_PREPAREDIFF_COMPARE, menuEntry, IDI_DIFF);
1752 if (selectedCount > 0)
1754 // if (((wcStatus == git_wc_status_unversioned)||(wcStatus == git_wc_status_ignored))&&(m_dwContextMenus & SVNSLC_POPDELETE))
1755 // popup.AppendMenuIcon(IDSVNLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1756 // if ((wcStatus != Git_wc_status_unversioned)&&(wcStatus != git_wc_status_ignored)&&(wcStatus != Git_wc_status_deleted)&&(wcStatus != Git_wc_status_added)&&(m_dwContextMenus & GitSLC_POPDELETE))
1757 // {
1758 // if (bShift)
1759 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVEKEEP, IDI_DELETE);
1760 // else
1761 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVE, IDI_DELETE);
1762 // }
1763 if ((wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE | CTGitPath::LOGACTIONS_MISSING))/*||(wcStatus == git_wc_status_deleted)*/)
1765 if (m_dwContextMenus & GITSLC_POPDELETE)
1766 popup.AppendMenuIcon(IDGITLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1768 if ( (wcStatus & CTGitPath::LOGACTIONS_UNVER || wcStatus & CTGitPath::LOGACTIONS_DELETED) )
1770 if (m_dwContextMenus & GITSLC_POPIGNORE)
1772 CTGitPathList ignorelist;
1773 FillListOfSelectedItemPaths(ignorelist);
1774 //check if all selected entries have the same extension
1775 bool bSameExt = true;
1776 CString sExt;
1777 for (int i=0; i<ignorelist.GetCount(); ++i)
1779 if (sExt.IsEmpty() && (i==0))
1780 sExt = ignorelist[i].GetFileExtension();
1781 else if (sExt.CompareNoCase(ignorelist[i].GetFileExtension())!=0)
1782 bSameExt = false;
1784 if (bSameExt)
1786 if (ignoreSubMenu.CreateMenu())
1788 CString ignorepath;
1789 if (ignorelist.GetCount()==1)
1790 ignorepath = ignorelist[0].GetFileOrDirectoryName();
1791 else
1792 ignorepath.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1793 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNORE, ignorepath);
1794 ignorepath = L'*' + sExt;
1795 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREMASK, ignorepath);
1796 if (ignorelist.GetCount() == 1 && !ignorelist[0].GetContainingDirectory().GetGitPathString().IsEmpty())
1797 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREFOLDER, ignorelist[0].GetContainingDirectory().GetGitPathString());
1798 CString temp;
1799 temp.LoadString(IDS_MENUIGNORE);
1800 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)ignoreSubMenu.m_hMenu, temp);
1803 else
1805 CString temp;
1806 if (ignorelist.GetCount()==1)
1807 temp.LoadString(IDS_MENUIGNORE);
1808 else
1809 temp.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1810 popup.AppendMenuIcon(IDGITLC_IGNORE, temp, IDI_IGNORE);
1811 temp.Format(IDS_MENUIGNOREMULTIPLEMASK, ignorelist.GetCount());
1812 popup.AppendMenuIcon(IDGITLC_IGNOREMASK, temp, IDI_IGNORE);
1820 if (selectedCount > 0)
1822 popup.AppendMenu(MF_SEPARATOR);
1823 popup.AppendMenuIcon(IDGITLC_COPY, IDS_STATUSLIST_CONTEXT_COPY, IDI_COPYCLIP);
1824 popup.AppendMenuIcon(IDGITLC_COPYEXT, IDS_STATUSLIST_CONTEXT_COPYEXT, IDI_COPYCLIP);
1825 #if 0
1826 if ((m_dwContextMenus & SVNSLC_POPCHANGELISTS))
1827 &&(wcStatus != git_wc_status_unversioned)&&(wcStatus != git_wc_status_none))
1829 popup.AppendMenu(MF_SEPARATOR);
1830 // changelist commands
1831 size_t numChangelists = GetNumberOfChangelistsInSelection();
1832 if (numChangelists > 0)
1833 popup.AppendMenuIcon(IDSVNLC_REMOVEFROMCS, IDS_STATUSLIST_CONTEXT_REMOVEFROMCS);
1834 if ((!entry->IsFolder())&&(changelistSubMenu.CreateMenu()))
1836 CString temp;
1837 temp.LoadString(IDS_STATUSLIST_CONTEXT_CREATECS);
1838 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATECS, temp);
1840 if (entry->changelist.Compare(SVNSLC_IGNORECHANGELIST))
1842 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1843 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATEIGNORECS, SVNSLC_IGNORECHANGELIST);
1846 if (!m_changelists.empty())
1848 // find the changelist names
1849 bool bNeedSeparator = true;
1850 int cmdID = IDSVNLC_MOVETOCS;
1851 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
1853 if ((entry->changelist.Compare(it->first))&&(it->first.Compare(SVNSLC_IGNORECHANGELIST)))
1855 if (bNeedSeparator)
1857 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1858 bNeedSeparator = false;
1860 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, cmdID, it->first);
1861 cmdID++;
1865 temp.LoadString(IDS_STATUSLIST_CONTEXT_MOVETOCS);
1866 popup.AppendMenu(MF_POPUP|MF_STRING, (UINT_PTR)changelistSubMenu.GetSafeHmenu(), temp);
1869 #endif
1872 m_hShellMenu = nullptr;
1873 if (selectedCount > 0 && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)) && m_bHasWC && (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO) && shellMenu.CreatePopupMenu())
1875 // insert the shell context menu
1876 popup.AppendMenu(MF_SEPARATOR);
1877 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)shellMenu.m_hMenu, CString(MAKEINTRESOURCE(IDS_STATUSLIST_CONTEXT_SHELL)));
1878 m_hShellMenu = shellMenu.m_hMenu;
1881 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
1882 g_IContext2 = nullptr;
1883 g_IContext3 = nullptr;
1884 if (m_pContextMenu)
1886 if (cmd >= SHELL_MIN_CMD && cmd <= SHELL_MAX_CMD) // see if returned idCommand belongs to shell menu entries)
1888 CMINVOKECOMMANDINFOEX cmi = { 0 };
1889 cmi.cbSize = sizeof(CMINVOKECOMMANDINFOEX);
1890 cmi.fMask = CMIC_MASK_UNICODE | CMIC_MASK_PTINVOKE;
1891 if (GetKeyState(VK_CONTROL) < 0)
1892 cmi.fMask |= CMIC_MASK_CONTROL_DOWN;
1893 if (bShift)
1894 cmi.fMask |= CMIC_MASK_SHIFT_DOWN;
1895 cmi.hwnd = m_hWnd;
1896 cmi.lpVerb = MAKEINTRESOURCEA(cmd - SHELL_MIN_CMD);
1897 cmi.lpVerbW = MAKEINTRESOURCEW(cmd - SHELL_MIN_CMD);
1898 cmi.nShow = SW_SHOWNORMAL;
1899 cmi.ptInvoke = point;
1901 m_pContextMenu->InvokeCommand((LPCMINVOKECOMMANDINFO)&cmi);
1903 cmd = 0;
1905 m_pContextMenu->Release();
1906 m_pContextMenu = nullptr;
1908 if (g_pFolderhook)
1910 delete g_pFolderhook;
1911 g_pFolderhook = nullptr;
1913 if (g_psfDesktopFolder)
1915 g_psfDesktopFolder->Release();
1916 g_psfDesktopFolder = nullptr;
1918 for (int i = 0; i < g_pidlArrayItems; i++)
1920 if (g_pidlArray[i])
1921 CoTaskMemFree(g_pidlArray[i]);
1923 if (g_pidlArray)
1924 CoTaskMemFree(g_pidlArray);
1925 g_pidlArray = nullptr;
1926 g_pidlArrayItems = 0;
1928 m_bWaitCursor = true;
1929 bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1930 //int iItemCountBeforeMenuCmd = GetItemCount();
1931 //bool bForce = false;
1932 switch (cmd)
1934 case IDGITLC_VIEWREV:
1935 OpenFile(filepath, ALTERNATIVEEDITOR);
1936 break;
1938 case IDGITLC_OPEN:
1939 OpenFile(filepath,OPEN);
1940 break;
1942 case IDGITLC_OPENWITH:
1943 OpenFile(filepath,OPEN_WITH);
1944 break;
1946 case IDGITLC_EXPLORE:
1947 CAppUtils::ExploreTo(GetSafeHwnd(), g_Git.CombinePath(filepath));
1948 break;
1950 case IDGITLC_PREPAREDIFF:
1951 m_sMarkForDiffFilename = filepath->GetGitPathString();
1952 m_sMarkForDiffVersion = m_CurrentVersion;
1953 break;
1955 case IDGITLC_PREPAREDIFF_COMPARE:
1957 CTGitPath savedFile(m_sMarkForDiffFilename);
1958 CGitDiff::Diff(filepath, &savedFile, m_CurrentVersion, m_sMarkForDiffVersion, false, false, 0, bShift);
1960 break;
1962 case IDGITLC_CREATERESTORE:
1964 POSITION pos = GetFirstSelectedItemPosition();
1965 while (pos)
1967 int index = GetNextSelectedItem(pos);
1968 auto entry2 = GetListEntry(index);
1969 if (!entry2 || entry2->IsDirectory())
1970 continue;
1971 if (m_restorepaths.find(entry2->GetWinPathString()) != m_restorepaths.end())
1972 continue;
1973 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
1974 // delete the temp file: the temp file has the FILE_ATTRIBUTE_TEMPORARY flag set
1975 // and copying the real file over it would leave that temp flag.
1976 DeleteFile(tempFile.GetWinPath());
1977 if (CopyFile(g_Git.CombinePath(entry2), tempFile.GetWinPath(), FALSE))
1979 m_restorepaths[entry2->GetWinPathString()] = tempFile.GetWinPathString();
1980 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), LVIS_OVERLAYMASK);
1983 Invalidate();
1985 break;
1987 case IDGITLC_RESTOREPATH:
1989 if (CMessageBox::Show(m_hWnd, IDS_STATUSLIST_RESTOREPATH, IDS_APPNAME, 2, IDI_QUESTION, IDS_RESTOREBUTTON, IDS_ABORTBUTTON) == 2)
1990 break;
1991 POSITION pos = GetFirstSelectedItemPosition();
1992 while (pos)
1994 int index = GetNextSelectedItem(pos);
1995 auto entry2 = GetListEntry(index);
1996 if (!entry2)
1997 continue;
1998 if (m_restorepaths.find(entry2->GetWinPathString()) == m_restorepaths.end())
1999 continue;
2000 if (CopyFile(m_restorepaths[entry2->GetWinPathString()], g_Git.CombinePath(entry2), FALSE))
2002 m_restorepaths.erase(entry2->GetWinPathString());
2003 SetItemState(index, 0, LVIS_OVERLAYMASK);
2006 Invalidate();
2008 break;
2010 // Compare current version and work copy.
2011 case IDGITLC_COMPAREWC:
2013 if (!CheckMultipleDiffs())
2014 break;
2015 POSITION pos = GetFirstSelectedItemPosition();
2016 while ( pos )
2018 int index = GetNextSelectedItem(pos);
2019 StartDiffWC(index);
2022 break;
2024 // Compare with base version. when current version is zero, compare workcopy and HEAD.
2025 case IDGITLC_COMPARE:
2027 if (!CheckMultipleDiffs())
2028 break;
2029 POSITION pos = GetFirstSelectedItemPosition();
2030 while ( pos )
2032 int index = GetNextSelectedItem(pos);
2033 StartDiff(index);
2036 break;
2038 case IDGITLC_COMPARETWOREVISIONS:
2040 if (!CheckMultipleDiffs())
2041 break;
2042 POSITION pos = GetFirstSelectedItemPosition();
2043 while ( pos )
2045 int index = GetNextSelectedItem(pos);
2046 StartDiffTwo(index);
2049 break;
2051 case IDGITLC_COMPARETWOFILES:
2053 POSITION pos = GetFirstSelectedItemPosition();
2054 if (pos)
2056 auto firstfilepath = GetListEntry(GetNextSelectedItem(pos));
2057 if (!firstfilepath)
2058 break;
2060 auto secondfilepath = GetListEntry(GetNextSelectedItem(pos));
2061 if (!secondfilepath)
2062 break;
2064 CString sCmd;
2065 sCmd.Format(L"/command:diff /path:\"%s\" /endrev:%s /path2:\"%s\" /startrev:%s /hwnd:%p", firstfilepath->GetWinPath(), firstfilepath->Exists() ? GIT_REV_ZERO : L"HEAD", secondfilepath->GetWinPath(), secondfilepath->Exists() ? GIT_REV_ZERO : L"HEAD", (void*)m_hWnd);
2066 if (bShift)
2067 sCmd += L" /alternative";
2068 CAppUtils::RunTortoiseGitProc(sCmd);
2071 break;
2073 case IDGITLC_GNUDIFF1:
2075 if (!CheckMultipleDiffs())
2076 break;
2077 POSITION pos = GetFirstSelectedItemPosition();
2078 while (pos)
2080 auto selectedFilepath = GetListEntry(GetNextSelectedItem(pos));
2081 if (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
2083 CString fromwhere;
2084 if (m_amend)
2085 fromwhere = L"~1";
2086 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, GitRev::GetHead() + fromwhere, *selectedFilepath, GitRev::GetWorkingCopy(), bShift);
2088 else
2090 if ((selectedFilepath->m_ParentNo & (PARENT_MASK | MERGE_MASK)) == 0)
2091 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, m_CurrentVersion + L"~1", *selectedFilepath, m_CurrentVersion, bShift);
2092 else
2094 CString str;
2095 if (!(selectedFilepath->m_ParentNo & MERGE_MASK))
2096 str.Format(L"%s^%d", (LPCTSTR)m_CurrentVersion, (selectedFilepath->m_ParentNo & PARENT_MASK) + 1);
2098 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, str, *selectedFilepath, m_CurrentVersion, bShift, false, false, false, !!(selectedFilepath->m_ParentNo & MERGE_MASK));
2103 break;
2105 case IDGITLC_GNUDIFF2REVISIONS:
2107 if (!CheckMultipleDiffs())
2108 break;
2109 POSITION pos = GetFirstSelectedItemPosition();
2110 while (pos)
2112 auto entry = GetListEntry(GetNextSelectedItem(pos));
2113 CAppUtils::StartShowUnifiedDiff(m_hWnd, *entry, m_Rev2, *entry, m_Rev1, bShift);
2116 break;
2118 case IDGITLC_ADD:
2120 CTGitPathList paths;
2121 FillListOfSelectedItemPaths(paths, true);
2123 CGitProgressDlg progDlg;
2124 AddProgressCommand addCommand;
2125 progDlg.SetCommand(&addCommand);
2126 addCommand.SetShowCommitButtonAfterAdd((m_dwContextMenus & GITSLC_POPCOMMIT) != 0);
2127 addCommand.SetPathList(paths);
2128 progDlg.SetItemCount(paths.GetCount());
2129 progDlg.DoModal();
2131 // reset unchecked status
2132 POSITION pos = GetFirstSelectedItemPosition();
2133 int index;
2134 while ((index = GetNextSelectedItem(pos)) >= 0)
2135 m_mapFilenameToChecked.erase(GetListEntry(index)->GetGitPathString());
2137 if (GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2138 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2140 SetRedraw(TRUE);
2142 break;
2144 case IDGITLC_DELETE:
2145 DeleteSelectedFiles();
2146 break;
2148 case IDGITLC_BLAME:
2150 CAppUtils::LaunchTortoiseBlame(g_Git.CombinePath(filepath), m_CurrentVersion);
2152 break;
2154 case IDGITLC_LOG:
2155 case IDGITLC_LOGSUBMODULE:
2157 CString sCmd;
2158 sCmd.Format(L"/command:log /path:\"%s\"", (LPCTSTR)g_Git.CombinePath(filepath));
2159 if (cmd == IDGITLC_LOG && filepath->IsDirectory())
2160 sCmd += L" /submodule";
2161 if (!m_sDisplayedBranch.IsEmpty())
2162 sCmd += L" /range:\"" + m_sDisplayedBranch + L'"';
2163 CAppUtils::RunTortoiseGitProc(sCmd, false, !(cmd == IDGITLC_LOGSUBMODULE));
2165 break;
2167 case IDGITLC_LOGOLDNAME:
2169 CTGitPath oldName(filepath->GetGitOldPathString());
2170 CString sCmd;
2171 sCmd.Format(L"/command:log /path:\"%s\"", (LPCTSTR)g_Git.CombinePath(oldName));
2172 if (!m_sDisplayedBranch.IsEmpty())
2173 sCmd += L" /range:\"" + m_sDisplayedBranch + L'"';
2174 CAppUtils::RunTortoiseGitProc(sCmd);
2176 break;
2178 case IDGITLC_EDITCONFLICT:
2180 if (CAppUtils::ConflictEdit(*filepath, bShift, m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2182 CString conflictedFile = g_Git.CombinePath(filepath);
2183 if (!PathFileExists(conflictedFile) && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2185 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2186 break;
2188 StoreScrollPos();
2189 Show(m_dwShow, 0, m_bShowFolders, 0, true);
2192 break;
2194 case IDGITLC_RESOLVETHEIRS: //follow up
2195 case IDGITLC_RESOLVEMINE: //follow up
2196 case IDGITLC_RESOLVECONFLICT:
2198 if (CMessageBox::Show(m_hWnd, IDS_PROC_RESOLVE, IDS_APPNAME, MB_ICONQUESTION | MB_YESNO)==IDYES)
2200 bool needsFullRefresh = false;
2201 POSITION pos = GetFirstSelectedItemPosition();
2202 while (pos != 0)
2204 int index;
2205 index = GetNextSelectedItem(pos);
2206 auto fentry = GetListEntry(index);
2207 if (!fentry)
2208 continue;
2210 CAppUtils::resolve_with resolveWith = CAppUtils::RESOLVE_WITH_CURRENT;
2211 if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE))
2212 resolveWith = CAppUtils::RESOLVE_WITH_THEIRS;
2213 else if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS))
2214 resolveWith = CAppUtils::RESOLVE_WITH_MINE;
2215 if (CAppUtils::ResolveConflict(*fentry, resolveWith) == 0 && fentry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
2216 needsFullRefresh = true;
2218 if (needsFullRefresh && CRegDWORD(L"Software\\TortoiseGit\\RefreshFileListAfterResolvingConflict", TRUE) == TRUE)
2220 CWnd* pParent = GetLogicalParent();
2221 if (pParent && pParent->GetSafeHwnd())
2222 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2223 SetRedraw(TRUE);
2224 break;
2226 StoreScrollPos();
2227 Show(m_dwShow, 0, m_bShowFolders,0,true);
2230 break;
2232 case IDGITLC_IGNORE:
2234 CTGitPathList ignorelist;
2235 //std::vector<CString> toremove;
2236 FillListOfSelectedItemPaths(ignorelist, true);
2238 if(!CAppUtils::IgnoreFile(ignorelist,false))
2239 break;
2241 SetRedraw(FALSE);
2242 CWnd* pParent = GetLogicalParent();
2243 if (pParent && pParent->GetSafeHwnd())
2245 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2247 SetRedraw(TRUE);
2249 break;
2251 case IDGITLC_IGNOREMASK:
2253 CString common;
2254 CString ext=filepath->GetFileExtension();
2255 CTGitPathList ignorelist;
2256 FillListOfSelectedItemPaths(ignorelist, true);
2258 if (!CAppUtils::IgnoreFile(ignorelist,true))
2259 break;
2261 SetRedraw(FALSE);
2262 CWnd* pParent = GetLogicalParent();
2263 if (pParent && pParent->GetSafeHwnd())
2265 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2268 SetRedraw(TRUE);
2270 break;
2272 case IDGITLC_IGNOREFOLDER:
2274 CTGitPathList ignorelist;
2275 ignorelist.AddPath(filepath->GetContainingDirectory());
2277 if (!CAppUtils::IgnoreFile(ignorelist, false))
2278 break;
2280 SetRedraw(FALSE);
2281 CWnd *pParent = GetLogicalParent();
2282 if (pParent && pParent->GetSafeHwnd())
2283 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2285 SetRedraw(TRUE);
2287 break;
2288 case IDGITLC_COMMIT:
2290 CTGitPathList targetList;
2291 FillListOfSelectedItemPaths(targetList);
2292 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2293 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2294 CString commandline = L"/command:commit /pathfile:\"";
2295 commandline += tempFile.GetWinPathString();
2296 commandline += L'"';
2297 commandline += L" /deletepathfile";
2298 CAppUtils::RunTortoiseGitProc(commandline);
2300 break;
2301 case IDGITLC_REVERT:
2303 // If at least one item is not in the status "added"
2304 // we ask for a confirmation
2305 BOOL bConfirm = FALSE;
2306 POSITION pos = GetFirstSelectedItemPosition();
2307 int index;
2308 while ((index = GetNextSelectedItem(pos)) >= 0)
2310 auto fentry = GetListEntry(index);
2311 if(fentry && fentry->m_Action &CTGitPath::LOGACTIONS_MODIFIED && !fentry->IsDirectory())
2313 bConfirm = TRUE;
2314 break;
2318 CString str;
2319 str.Format(IDS_PROC_WARNREVERT, selectedCount);
2321 if (!bConfirm || MessageBox(str, L"TortoiseGit", MB_YESNO | MB_ICONQUESTION) == IDYES)
2323 CTGitPathList targetList;
2324 FillListOfSelectedItemPaths(targetList);
2326 // make sure that the list is reverse sorted, so that
2327 // children are removed before any parents
2328 targetList.SortByPathname(true);
2330 // put all reverted files in the trashbin, except the ones with 'added'
2331 // status because they are not restored by the revert.
2332 CTGitPathList delList;
2333 POSITION pos2 = GetFirstSelectedItemPosition();
2334 int index2;
2335 while ((index2 = GetNextSelectedItem(pos2)) >= 0)
2337 auto entry = GetListEntry(index2);
2338 if (entry&&(!(entry->m_Action& CTGitPath::LOGACTIONS_ADDED))
2339 && (!(entry->m_Action& CTGitPath::LOGACTIONS_REPLACED)) && !entry->IsDirectory())
2341 CTGitPath fullpath;
2342 fullpath.SetFromWin(g_Git.CombinePath(entry));
2343 delList.AddPath(fullpath);
2346 if (DWORD(CRegDWORD(L"Software\\TortoiseGit\\RevertWithRecycleBin", TRUE)))
2347 delList.DeleteAllFiles(true);
2349 CString revertToCommit = L"HEAD";
2350 if (m_amend)
2351 revertToCommit = L"HEAD~1";
2352 CString err;
2353 if (g_Git.Revert(revertToCommit, targetList, err))
2354 MessageBox(L"Revert failed:\n" + err, L"TortoiseGit", MB_ICONERROR);
2355 else
2357 bool updateStatusList = false;
2358 for (int i = 0 ; i < targetList.GetCount(); ++i)
2360 int nListboxEntries = GetItemCount();
2361 for (int nItem=0; nItem<nListboxEntries; ++nItem)
2363 auto path = GetListEntry(nItem);
2364 if (path->GetGitPathString()==targetList[i].GetGitPathString() && !path->IsDirectory())
2366 if(path->m_Action & CTGitPath::LOGACTIONS_ADDED)
2368 path->m_Action = CTGitPath::LOGACTIONS_UNVER;
2369 SetEntryCheck(path,nItem,false);
2370 updateStatusList = true;
2371 #if 0 // revert an added file and some entry will be cloned (part 1/2)
2372 SetItemGroup(nItem,1);
2373 this->m_StatusFileList.RemoveItem(*path);
2374 this->m_UnRevFileList.AddPath(*path);
2375 //this->m_IgnoreFileList.RemoveItem(*path);
2376 #endif
2378 else
2380 if (GetCheck(nItem))
2381 m_nSelected--;
2382 RemoveListEntry(nItem);
2384 break;
2386 else if (path->GetGitPathString()==targetList[i].GetGitPathString() && path->IsDirectory() && path->IsWCRoot())
2388 CString sCmd;
2389 sCmd.Format(L"/command:revert /path:\"%s\"", (LPCTSTR)path->GetGitPathString());
2390 CCommonAppUtils::RunTortoiseGitProc(sCmd);
2394 SetRedraw(TRUE);
2395 #if 0 // revert an added file and some entry will be cloned (part 2/2)
2396 Show(m_dwShow, 0, m_bShowFolders,updateStatusList,true);
2397 NotifyCheck();
2398 #else
2399 if (updateStatusList && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2400 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2401 #endif
2405 break;
2407 case IDGITLC_ASSUMEVALID:
2408 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_ASSUMEVALID, BST_CHECKED, BST_INDETERMINATE);
2409 break;
2410 case IDGITLC_SKIPWORKTREE:
2411 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_SKIPWORKTREE, BST_INDETERMINATE, BST_CHECKED);
2412 break;
2413 case IDGITLC_UNSETIGNORELOCALCHANGES:
2414 SetGitIndexFlagsForSelectedFiles(IDS_PROC_UNSET_IGNORELOCALCHANGES, BST_UNCHECKED, BST_UNCHECKED);
2415 break;
2416 case IDGITLC_COPY:
2417 CopySelectedEntriesToClipboard(0);
2418 break;
2419 case IDGITLC_COPYEXT:
2420 CopySelectedEntriesToClipboard((DWORD)-1);
2421 break;
2422 case IDGITLC_EXPORT:
2423 FilesExport();
2424 break;
2425 case IDGITLC_SAVEAS:
2426 FileSaveAs(filepath);
2427 break;
2429 case IDGITLC_REVERTTOREV:
2430 RevertSelectedItemToVersion();
2431 break;
2432 case IDGITLC_REVERTTOPARENT:
2433 RevertSelectedItemToVersion(true);
2434 break;
2435 #if 0
2436 case IDSVNLC_COMMIT:
2438 CTSVNPathList targetList;
2439 FillListOfSelectedItemPaths(targetList);
2440 CTSVNPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2441 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2442 CString commandline = CPathUtils::GetAppDirectory();
2443 commandline += L"TortoiseGitProc.exe /command:commit /pathfile:\"";
2444 commandline += tempFile.GetWinPathString();
2445 commandline += L'"';
2446 commandline += L" /deletepathfile";
2447 CAppUtils::LaunchApplication(commandline, nullptr, false);
2449 break;
2450 case IDSVNLC_CREATEIGNORECS:
2451 CreateChangeList(SVNSLC_IGNORECHANGELIST);
2452 break;
2453 case IDSVNLC_CREATECS:
2455 CCreateChangelistDlg dlg;
2456 if (dlg.DoModal() == IDOK)
2457 CreateChangeList(dlg.m_sName);
2459 break;
2460 default:
2462 if (cmd < IDSVNLC_MOVETOCS)
2463 break;
2464 CTSVNPathList changelistItems;
2465 FillListOfSelectedItemPaths(changelistItems);
2467 // find the changelist name
2468 CString sChangelist;
2469 int cmdID = IDSVNLC_MOVETOCS;
2470 SetRedraw(FALSE);
2471 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
2473 if ((it->first.Compare(SVNSLC_IGNORECHANGELIST))&&(entry->changelist.Compare(it->first)))
2475 if (cmd == cmdID)
2476 sChangelist = it->first;
2477 cmdID++;
2480 if (!sChangelist.IsEmpty())
2482 SVN git;
2483 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
2485 // The changelists were moved, but we now need to run through the selected items again
2486 // and update their changelist
2487 POSITION pos = GetFirstSelectedItemPosition();
2488 int index;
2489 while ((index = GetNextSelectedItem(pos)) >= 0)
2491 FileEntry * e = GetListEntry(index);
2492 e->changelist = sChangelist;
2493 if (!e->IsFolder())
2495 if (m_changelists.find(e->changelist)!=m_changelists.end())
2496 SetItemGroup(index, m_changelists[e->changelist]);
2497 else
2498 SetItemGroup(index, 0);
2502 else
2503 MessageBox(git.GetLastErrorMessage(), L"TortoiseGit", MB_ICONERROR);
2505 SetRedraw(TRUE);
2507 break;
2508 #endif
2510 } // switch (cmd)
2511 m_bWaitCursor = false;
2512 GetStatisticsString();
2513 //int iItemCountAfterMenuCmd = GetItemCount();
2514 //if (iItemCountAfterMenuCmd != iItemCountBeforeMenuCmd)
2516 // CWnd* pParent = GetParent();
2517 // if (pParent && pParent->GetSafeHwnd())
2518 // {
2519 // pParent->SendMessage(SVNSLNM_ITEMCOUNTCHANGED);
2520 // }
2522 } // if (popup.CreatePopupMenu())
2523 } // if (selIndex >= 0)
2526 void CGitStatusListCtrl::SetGitIndexFlagsForSelectedFiles(UINT message, BOOL assumevalid, BOOL skipworktree)
2528 if (CMessageBox::Show(GetSafeHwnd(), message, IDS_APPNAME, MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
2529 return;
2531 CAutoReadLock locker(m_guard);
2533 CAutoRepository repository(g_Git.GetGitRepository());
2534 if (!repository)
2536 MessageBox(g_Git.GetLibGit2LastErr(), L"TortoiseGit", MB_ICONERROR);
2537 return;
2540 CAutoIndex gitindex;
2541 if (git_repository_index(gitindex.GetPointer(), repository))
2543 MessageBox(g_Git.GetLibGit2LastErr(), L"TortoiseGit", MB_ICONERROR);
2544 return;
2547 POSITION pos = GetFirstSelectedItemPosition();
2548 int index = -1;
2549 while ((index = GetNextSelectedItem(pos)) >= 0)
2551 auto path = GetListEntry(index);
2552 if (path == nullptr)
2553 continue;
2555 size_t idx;
2556 if (!git_index_find(&idx, gitindex, CUnicodeUtils::GetMulti(path->GetGitPathString(), CP_UTF8)))
2558 git_index_entry *e = const_cast<git_index_entry *>(git_index_get_byindex(gitindex, idx)); // HACK
2559 if (assumevalid == BST_UNCHECKED)
2560 e->flags &= ~GIT_IDXENTRY_VALID;
2561 else if (assumevalid == BST_CHECKED)
2562 e->flags |= GIT_IDXENTRY_VALID;
2563 if (skipworktree == BST_UNCHECKED)
2564 e->flags_extended &= ~GIT_IDXENTRY_SKIP_WORKTREE;
2565 else if (skipworktree == BST_CHECKED)
2566 e->flags_extended |= GIT_IDXENTRY_SKIP_WORKTREE;
2567 git_index_add(gitindex, e);
2569 else
2570 MessageBox(g_Git.GetLibGit2LastErr(), L"TortoiseGit", MB_ICONERROR);
2573 if (git_index_write(gitindex))
2575 MessageBox(g_Git.GetLibGit2LastErr(), L"TortoiseGit", MB_ICONERROR);
2576 return;
2579 if (nullptr != GetLogicalParent() && nullptr != GetLogicalParent()->GetSafeHwnd())
2580 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2582 SetRedraw(TRUE);
2585 void CGitStatusListCtrl::OnContextMenu(CWnd* pWnd, CPoint point)
2587 __super::OnContextMenu(pWnd, point);
2588 if (pWnd == this)
2589 OnContextMenuList(pWnd, point);
2592 void CGitStatusListCtrl::OnNMDblclk(NMHDR *pNMHDR, LRESULT *pResult)
2594 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
2595 *pResult = 0;
2597 CAutoReadWeakLock readLock(m_guard);
2598 if (!readLock.IsAcquired())
2599 return;
2601 if (pNMLV->iItem < 0)
2602 return;
2604 auto file = GetListEntry(pNMLV->iItem);
2606 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) {
2607 StartDiffWC(pNMLV->iItem);
2608 return;
2610 if( file->m_Action&CTGitPath::LOGACTIONS_UNMERGED )
2612 if (CAppUtils::ConflictEdit(*file, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000), m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2614 CString conflictedFile = g_Git.CombinePath(file);
2615 if (!PathFileExists(conflictedFile) && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2617 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2618 return;
2620 StoreScrollPos();
2621 Show(m_dwShow, 0, m_bShowFolders, 0, true);
2624 else if ((file->m_Action & CTGitPath::LOGACTIONS_MISSING) && file->m_Action != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) && file->m_Action != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MODIFIED))
2625 return;
2626 else
2628 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
2629 StartDiffTwo(pNMLV->iItem);
2630 else
2631 StartDiff(pNMLV->iItem);
2634 void CGitStatusListCtrl::StartDiffTwo(int fileindex)
2636 if(fileindex<0)
2637 return;
2639 CAutoReadLock locker(m_guard);
2640 auto ptr = GetListEntry(fileindex);
2641 if (!ptr)
2642 return;
2643 CTGitPath file1 = *ptr;
2645 if (file1.m_Action & CTGitPath::LOGACTIONS_ADDED)
2646 CGitDiff::DiffNull(&file1, m_Rev1, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2647 else if (file1.m_Action & CTGitPath::LOGACTIONS_DELETED)
2648 CGitDiff::DiffNull(&file1, m_Rev2, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2649 else
2650 CGitDiff::Diff(&file1, &file1, m_Rev1, m_Rev2, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2653 void CGitStatusListCtrl::StartDiffWC(int fileindex)
2655 if(fileindex<0)
2656 return;
2658 CAutoReadLock locker(m_guard);
2659 if (m_CurrentVersion.IsEmpty())
2660 m_CurrentVersion == GIT_REV_ZERO;
2662 auto ptr = GetListEntry(fileindex);
2663 if (!ptr)
2664 return;
2665 CTGitPath file1 = *ptr;
2666 file1.m_Action = 0; // reset action, so that diff is not started as added/deleted file; see issue #1757
2668 CGitDiff::Diff(&file1, &file1, GIT_REV_ZERO, m_CurrentVersion, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2671 void CGitStatusListCtrl::StartDiff(int fileindex)
2673 if(fileindex<0)
2674 return;
2676 CAutoReadLock locker(m_guard);
2677 auto ptr = GetListEntry(fileindex);
2678 if (!ptr)
2679 return;
2680 CTGitPath file1 = *ptr;
2681 CTGitPath file2;
2682 if(file1.m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY))
2683 file2.SetFromGit(file1.GetGitOldPathString());
2684 else
2685 file2=file1;
2687 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion== GIT_REV_ZERO)
2689 CString fromwhere;
2690 if(m_amend && (file1.m_Action & CTGitPath::LOGACTIONS_ADDED) == 0)
2691 fromwhere = L"~1";
2692 if( g_Git.IsInitRepos())
2693 CGitDiff::DiffNull(GetListEntry(fileindex),
2694 GIT_REV_ZERO, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2695 else if( file1.m_Action&CTGitPath::LOGACTIONS_ADDED )
2696 CGitDiff::DiffNull(GetListEntry(fileindex),
2697 m_CurrentVersion + fromwhere, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2698 else if( file1.m_Action&CTGitPath::LOGACTIONS_DELETED )
2699 CGitDiff::DiffNull(GetListEntry(fileindex),
2700 GitRev::GetHead() + fromwhere, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2701 else
2702 CGitDiff::Diff(&file1,&file2,
2703 CString(GIT_REV_ZERO),
2704 GitRev::GetHead() + fromwhere, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2706 else
2708 CGitHash hash;
2709 CString fromwhere = m_CurrentVersion + L"~1";
2710 if(m_amend)
2711 fromwhere = m_CurrentVersion + L"~2";
2712 bool revfail = !!g_Git.GetHash(hash, fromwhere);
2713 if (revfail || (file1.m_Action & file1.LOGACTIONS_ADDED))
2714 CGitDiff::DiffNull(&file1, m_CurrentVersion, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2715 else if (file1.m_Action & file1.LOGACTIONS_DELETED)
2717 if (file1.m_ParentNo > 0)
2718 fromwhere.Format(L"%s^%d", (LPCTSTR)m_CurrentVersion, file1.m_ParentNo + 1);
2720 CGitDiff::DiffNull(&file1, fromwhere, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2722 else
2724 if( file1.m_ParentNo & MERGE_MASK)
2726 CTGitPath base, theirs, mine, merge;
2728 CString temppath;
2729 GetTempPath(temppath);
2730 temppath.TrimRight(L'\\');
2732 mine.SetFromGit(temppath + L'\\' + file1.GetFileOrDirectoryName() + L".LOCAL" + file1.GetFileExtension());
2733 theirs.SetFromGit(temppath + L'\\' + file1.GetFileOrDirectoryName() + L".REMOTE" + file1.GetFileExtension());
2734 base.SetFromGit(temppath + L'\\' + file1.GetFileOrDirectoryName() + L".BASE" + file1.GetFileExtension());
2736 CFile tempfile;
2737 //create a empty file, incase stage is not three
2738 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2739 tempfile.Close();
2740 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2741 tempfile.Close();
2742 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2743 tempfile.Close();
2745 merge.SetFromGit(temppath + L'\\' + file1.GetFileOrDirectoryName() + L".Merged" + file1.GetFileExtension());
2747 int parent1=-1, parent2 =-1;
2748 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
2750 if(m_arStatusArray[i]->GetGitPathString() == file1.GetGitPathString())
2752 if(m_arStatusArray[i]->m_ParentNo & MERGE_MASK)
2755 else
2757 if(parent1<0)
2758 parent1 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2759 else if (parent2 <0)
2760 parent2 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2765 if(g_Git.GetOneFile(m_CurrentVersion, file1, (CString&)merge.GetWinPathString()))
2766 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2768 if(parent1>=0)
2770 CString str;
2771 str.Format(L"%s^%d", (LPCTSTR)this->m_CurrentVersion, parent1 + 1);
2773 if(g_Git.GetOneFile(str, file1, (CString&)mine.GetWinPathString()))
2774 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2777 if(parent2>=0)
2779 CString str;
2780 str.Format(L"%s^%d", (LPCTSTR)this->m_CurrentVersion, parent2 + 1);
2782 if(g_Git.GetOneFile(str, file1, (CString&)theirs.GetWinPathString()))
2783 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2786 if(parent1>=0 && parent2>=0)
2788 CString cmd, output;
2789 cmd.Format(L"git.exe merge-base %s^%d %s^%d", (LPCTSTR)this->m_CurrentVersion, parent1 + 1,
2790 (LPCTSTR)m_CurrentVersion, parent2 + 1);
2792 if (!g_Git.Run(cmd, &output, nullptr, CP_UTF8))
2794 if (g_Git.GetOneFile(output.Left(2 * GIT_HASH_SIZE), file1, (CString&)base.GetWinPathString()))
2795 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETBASEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2798 CAppUtils::StartExtMerge(!!(GetAsyncKeyState(VK_SHIFT) & 0x8000), base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL");
2800 else
2802 CString str;
2803 if( (file1.m_ParentNo&PARENT_MASK) == 0)
2804 str = L"~1";
2805 else
2806 str.Format(L"^%d", (file1.m_ParentNo & PARENT_MASK) + 1);
2807 CGitDiff::Diff(&file1,&file2,
2808 m_CurrentVersion,
2809 m_CurrentVersion + str, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2815 CString CGitStatusListCtrl::GetStatisticsString(bool simple)
2817 CString sNormal = CString(MAKEINTRESOURCE(IDS_STATUSNORMAL));
2818 CString sAdded = CString(MAKEINTRESOURCE(IDS_STATUSADDED));
2819 CString sDeleted = CString(MAKEINTRESOURCE(IDS_STATUSDELETED));
2820 CString sModified = CString(MAKEINTRESOURCE(IDS_STATUSMODIFIED));
2821 CString sConflicted = CString(MAKEINTRESOURCE(IDS_STATUSCONFLICTED));
2822 CString sUnversioned = CString(MAKEINTRESOURCE(IDS_STATUSUNVERSIONED));
2823 CString sRenamed = CString(MAKEINTRESOURCE(IDS_STATUSREPLACED));
2824 CString sToolTip;
2825 if(simple)
2827 sToolTip.Format(IDS_STATUSLIST_STATUSLINE1,
2828 this->m_nLineAdded,this->m_nLineDeleted,
2829 (LPCTSTR)sModified, m_nModified,
2830 (LPCTSTR)sAdded, m_nAdded,
2831 (LPCTSTR)sDeleted, m_nDeleted,
2832 (LPCTSTR)sRenamed, m_nRenamed
2835 else
2837 sToolTip.Format(IDS_STATUSLIST_STATUSLINE2,
2838 this->m_nLineAdded,this->m_nLineDeleted,
2839 (LPCTSTR)sNormal, m_nNormal,
2840 (LPCTSTR)sUnversioned, m_nUnversioned,
2841 (LPCTSTR)sModified, m_nModified,
2842 (LPCTSTR)sAdded, m_nAdded,
2843 (LPCTSTR)sDeleted, m_nDeleted,
2844 (LPCTSTR)sConflicted, m_nConflicted
2847 CString sStats;
2848 sStats.Format(IDS_COMMITDLG_STATISTICSFORMAT, m_nSelected, GetItemCount());
2849 if (m_pStatLabel)
2850 m_pStatLabel->SetWindowText(sStats);
2852 if (m_pSelectButton)
2854 if (m_nSelected == 0)
2855 m_pSelectButton->SetCheck(BST_UNCHECKED);
2856 else if (m_nSelected != GetItemCount())
2857 m_pSelectButton->SetCheck(BST_INDETERMINATE);
2858 else
2859 m_pSelectButton->SetCheck(BST_CHECKED);
2862 if (m_pConfirmButton)
2863 m_pConfirmButton->EnableWindow(m_nSelected>0);
2865 return sToolTip;
2868 CString CGitStatusListCtrl::GetCommonDirectory(bool bStrict)
2870 CAutoReadLock locker(m_guard);
2871 if (!bStrict)
2873 // not strict means that the selected folder has priority
2874 if (!m_StatusFileList.GetCommonDirectory().IsEmpty())
2875 return m_StatusFileList.GetCommonDirectory().GetWinPath();
2878 CTGitPathList list;
2879 int nListItems = GetItemCount();
2880 for (int i=0; i<nListItems; ++i)
2882 auto* entry = GetListEntry(i);
2883 if (entry->IsEmpty())
2884 continue;
2885 list.AddPath(*entry);
2887 return list.GetCommonRoot().GetWinPath();
2890 void CGitStatusListCtrl::SelectAll(bool bSelect, bool /*bIncludeNoCommits*/)
2892 CWaitCursor waitCursor;
2893 // block here so the LVN_ITEMCHANGED messages
2894 // get ignored
2895 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
2898 CAutoWriteLock locker(m_guard);
2899 SetRedraw(FALSE);
2901 int nListItems = GetItemCount();
2902 if (bSelect)
2903 m_nSelected = nListItems;
2904 else
2905 m_nSelected = 0;
2907 for (int i=0; i<nListItems; ++i)
2909 auto path = GetListEntry(i);
2910 if (!path)
2911 continue;
2912 //if ((bIncludeNoCommits)||(entry->GetChangeList().Compare(SVNSLC_IGNORECHANGELIST)))
2913 SetEntryCheck(path,i,bSelect);
2916 SetRedraw(TRUE);
2917 GetStatisticsString();
2918 NotifyCheck();
2921 void CGitStatusListCtrl::Check(DWORD dwCheck, bool check)
2923 CWaitCursor waitCursor;
2924 // block here so the LVN_ITEMCHANGED messages
2925 // get ignored
2927 CAutoWriteLock locker(m_guard);
2928 SetRedraw(FALSE);
2929 ScopedInDecrement blocker(m_nBlockItemChangeHandler);
2931 int nListItems = GetItemCount();
2933 for (int i = 0; i < nListItems; ++i)
2935 auto entry = GetListEntry(i);
2936 if (!entry)
2937 continue;
2939 DWORD showFlags = entry->m_Action;
2940 if (entry->IsDirectory())
2941 showFlags |= GITSLC_SHOWSUBMODULES;
2942 else
2943 showFlags |= GITSLC_SHOWFILES;
2945 if (check && (showFlags & dwCheck) && !GetCheck(i) && !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules && !(dwCheck & GITSLC_SHOWSUBMODULES)))
2947 SetEntryCheck(entry, i, true);
2948 m_nSelected++;
2950 else if (!check && (showFlags & dwCheck) && GetCheck(i))
2952 SetEntryCheck(entry, i, false);
2953 m_nSelected--;
2957 SetRedraw(TRUE);
2958 GetStatisticsString();
2959 NotifyCheck();
2962 void CGitStatusListCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
2964 LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR);
2965 *pResult = 0;
2966 if (CRegDWORD(L"Software\\TortoiseGit\\ShowListFullPathTooltip", TRUE) != TRUE)
2967 return;
2969 CAutoReadWeakLock readLock(m_guard);
2970 if (!readLock.IsAcquired())
2971 return;
2973 auto entry = GetListEntry(pGetInfoTip->iItem);
2975 if (entry)
2976 if (pGetInfoTip->cchTextMax > entry->GetGitPathString().GetLength() + g_Git.m_CurrentDir.GetLength())
2978 CString str = g_Git.CombinePath(entry->GetWinPathString());
2979 wcsncpy_s(pGetInfoTip->pszText, pGetInfoTip->cchTextMax, str.GetBuffer(), pGetInfoTip->cchTextMax - 1);
2983 void CGitStatusListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
2985 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
2987 // Take the default processing unless we set this to something else below.
2988 *pResult = CDRF_DODEFAULT;
2990 // First thing - check the draw stage. If it's the control's prepaint
2991 // stage, then tell Windows we want messages for every item.
2993 switch (pLVCD->nmcd.dwDrawStage)
2995 case CDDS_PREPAINT:
2996 *pResult = CDRF_NOTIFYITEMDRAW;
2997 break;
2998 case CDDS_ITEMPREPAINT:
3000 // This is the prepaint stage for an item. Here's where we set the
3001 // item's text color. Our return value will tell Windows to draw the
3002 // item itself, but it will use the new color we set here.
3004 // Tell Windows to paint the control itself.
3005 *pResult = CDRF_DODEFAULT;
3006 CAutoReadWeakLock readLock(m_guard, 0);
3007 if (!readLock.IsAcquired())
3008 return;
3010 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
3012 if (m_arStatusArray.size() > (DWORD_PTR)pLVCD->nmcd.dwItemSpec)
3014 auto entry = GetListEntry((int)pLVCD->nmcd.dwItemSpec);
3015 if (!entry)
3016 return;
3018 // coloring
3019 // ========
3020 // black : unversioned, normal
3021 // purple : added
3022 // blue : modified
3023 // brown : missing, deleted, replaced
3024 // green : merged (or potential merges)
3025 // red : conflicts or sure conflicts
3026 if(entry->m_Action & CTGitPath::LOGACTIONS_GRAY)
3027 crText = RGB(128,128,128);
3028 else if(entry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3029 crText = m_Colors.GetColor(CColors::Conflict);
3030 else if(entry->m_Action & (CTGitPath::LOGACTIONS_MODIFIED))
3031 crText = m_Colors.GetColor(CColors::Modified);
3032 else if(entry->m_Action & (CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
3033 crText = m_Colors.GetColor(CColors::Added);
3034 else if(entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
3035 crText = m_Colors.GetColor(CColors::Deleted);
3036 else if(entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
3037 crText = m_Colors.GetColor(CColors::Renamed);
3038 else if(entry->m_Action & CTGitPath::LOGACTIONS_MERGED)
3039 crText = m_Colors.GetColor(CColors::Merged);
3040 else
3041 crText = GetSysColor(COLOR_WINDOWTEXT);
3042 // Store the color back in the NMLVCUSTOMDRAW struct.
3043 pLVCD->clrText = crText;
3046 break;
3050 BOOL CGitStatusListCtrl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
3052 if (pWnd != this)
3053 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3054 if (!m_bWaitCursor && !m_bBusy)
3056 HCURSOR hCur = LoadCursor(nullptr, IDC_ARROW);
3057 SetCursor(hCur);
3058 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3060 HCURSOR hCur = LoadCursor(nullptr, IDC_WAIT);
3061 SetCursor(hCur);
3062 return TRUE;
3065 void CGitStatusListCtrl::RemoveListEntry(int index)
3067 CAutoWriteLock locker(m_guard);
3068 DeleteItem(index);
3070 m_arStatusArray.erase(m_arStatusArray.cbegin() + index);
3072 #if 0
3073 delete m_arStatusArray[m_arListArray[index]];
3074 m_arStatusArray.erase(m_arStatusArray.begin()+m_arListArray[index]);
3075 m_arListArray.erase(m_arListArray.begin()+index);
3076 for (int i=index; i< (int)m_arListArray.size(); ++i)
3078 m_arListArray[i]--;
3080 #endif
3083 ///< Set a checkbox on an entry in the listbox
3084 // NEVER, EVER call SetCheck directly, because you'll end-up with the checkboxes and the 'checked' flag getting out of sync
3085 void CGitStatusListCtrl::SetEntryCheck(CTGitPath* pEntry, int listboxIndex, bool bCheck)
3087 CAutoWriteLock locker(m_guard);
3088 pEntry->m_Checked = bCheck;
3089 m_mapFilenameToChecked[pEntry->GetGitPathString()] = bCheck;
3090 SetCheck(listboxIndex, bCheck);
3093 void CGitStatusListCtrl::ResetChecked(const CTGitPath& entry)
3095 CAutoWriteLock locker(m_guard);
3096 CTGitPath adjustedEntry;
3097 if (g_Git.m_CurrentDir[g_Git.m_CurrentDir.GetLength() - 1] == L'\\')
3098 adjustedEntry.SetFromWin(entry.GetWinPathString().Right(entry.GetWinPathString().GetLength() - g_Git.m_CurrentDir.GetLength()));
3099 else
3100 adjustedEntry.SetFromWin(entry.GetWinPathString().Right(entry.GetWinPathString().GetLength() - g_Git.m_CurrentDir.GetLength() - 1));
3101 if (entry.IsDirectory())
3103 STRING_VECTOR toDelete;
3104 for (auto it = m_mapFilenameToChecked.begin(); it != m_mapFilenameToChecked.end(); ++it)
3106 if (adjustedEntry.IsAncestorOf(it->first))
3107 toDelete.emplace_back(it->first);
3109 for (const auto& file : toDelete)
3110 m_mapFilenameToChecked.erase(file);
3111 return;
3113 m_mapFilenameToChecked.erase(adjustedEntry.GetGitPathString());
3116 #if 0
3117 void CGitStatusListCtrl::SetCheckOnAllDescendentsOf(const FileEntry* parentEntry, bool bCheck)
3119 CAutoWriteLock locker(m_guard);
3120 int nListItems = GetItemCount();
3121 for (int j=0; j< nListItems ; ++j)
3123 FileEntry * childEntry = GetListEntry(j);
3124 ASSERT(childEntry);
3125 if (!childEntry || childEntry == parentEntry)
3126 continue;
3127 if (childEntry->checked != bCheck)
3129 if (parentEntry->path.IsAncestorOf(childEntry->path))
3131 SetEntryCheck(childEntry,j,bCheck);
3132 if(bCheck)
3133 m_nSelected++;
3134 else
3135 m_nSelected--;
3140 #endif
3142 void CGitStatusListCtrl::WriteCheckedNamesToPathList(CTGitPathList& pathList)
3144 pathList.Clear();
3145 CAutoReadLock locker(m_guard);
3146 int nListItems = GetItemCount();
3147 for (int i = 0; i< nListItems; ++i)
3149 auto entry = GetListEntry(i);
3150 if (entry->m_Checked)
3151 pathList.AddPath(*entry);
3153 pathList.SortByPathname();
3157 /// Build a path list of all the selected items in the list (NOTE - SELECTED, not CHECKED)
3158 void CGitStatusListCtrl::FillListOfSelectedItemPaths(CTGitPathList& pathList, bool /*bNoIgnored*/)
3160 pathList.Clear();
3162 CAutoReadLock locker(m_guard);
3163 POSITION pos = GetFirstSelectedItemPosition();
3164 int index;
3165 while ((index = GetNextSelectedItem(pos)) >= 0)
3167 auto entry = GetListEntry(index);
3168 //if ((bNoIgnored)&&(entry->status == git_wc_status_ignored))
3169 // continue;
3170 pathList.AddPath(*entry);
3174 UINT CGitStatusListCtrl::OnGetDlgCode()
3176 // we want to process the return key and not have that one
3177 // routed to the default pushbutton
3178 return CListCtrl::OnGetDlgCode() | DLGC_WANTALLKEYS;
3181 void CGitStatusListCtrl::OnNMReturn(NMHDR * /*pNMHDR*/, LRESULT *pResult)
3183 *pResult = 0;
3184 CAutoReadWeakLock readLock(m_guard);
3185 if (!readLock.IsAcquired())
3186 return;
3187 if (!CheckMultipleDiffs())
3188 return;
3189 bool needsRefresh = false;
3190 bool resolvedTreeConfict = false;
3191 POSITION pos = GetFirstSelectedItemPosition();
3192 while ( pos )
3194 int index = GetNextSelectedItem(pos);
3195 if (index < 0)
3196 return;
3197 auto file = GetListEntry(index);
3198 if (file == nullptr)
3199 return;
3200 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
3201 StartDiffWC(index);
3202 else if ((file->m_Action & CTGitPath::LOGACTIONS_UNMERGED))
3204 if (CAppUtils::ConflictEdit(*file, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000), m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
3206 CString conflictedFile = g_Git.CombinePath(file);
3207 needsRefresh = needsRefresh || !PathFileExists(conflictedFile);
3208 resolvedTreeConfict = resolvedTreeConfict || (file->m_Action & CTGitPath::LOGACTIONS_UNMERGED) == 0;
3211 else if ((file->m_Action & CTGitPath::LOGACTIONS_MISSING) && file->m_Action != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) && file->m_Action != (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MODIFIED))
3212 continue;
3213 else
3215 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
3216 StartDiffTwo(index);
3217 else
3218 StartDiff(index);
3221 if (needsRefresh && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
3222 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
3223 else if (resolvedTreeConfict)
3225 StoreScrollPos();
3226 Show(m_dwShow, 0, m_bShowFolders, 0, true);
3230 void CGitStatusListCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
3232 // Since we catch all keystrokes (to have the enter key processed here instead
3233 // of routed to the default pushbutton) we have to make sure that other
3234 // keys like Tab and Esc still do what they're supposed to do
3235 // Tab = change focus to next/previous control
3236 // Esc = quit the dialog
3237 switch (nChar)
3239 case (VK_TAB):
3241 ::PostMessage(GetLogicalParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
3242 return;
3244 break;
3245 case (VK_ESCAPE):
3247 ::SendMessage(GetLogicalParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
3249 break;
3252 CListCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
3255 void CGitStatusListCtrl::PreSubclassWindow()
3257 __super::PreSubclassWindow();
3258 EnableToolTips(TRUE);
3259 SetWindowTheme(GetSafeHwnd(), L"Explorer", nullptr);
3262 void CGitStatusListCtrl::OnPaint()
3264 LRESULT defres = Default();
3265 if ((m_bBusy) || (m_bEmpty))
3267 CString str;
3268 if (m_bBusy)
3270 if (m_sBusy.IsEmpty())
3271 str.LoadString(IDS_STATUSLIST_BUSYMSG);
3272 else
3273 str = m_sBusy;
3275 else
3277 if (m_sEmpty.IsEmpty())
3278 str.LoadString(IDS_STATUSLIST_EMPTYMSG);
3279 else
3280 str = m_sEmpty;
3282 COLORREF clrText = ::GetSysColor(COLOR_WINDOWTEXT);
3283 COLORREF clrTextBk;
3284 if (IsWindowEnabled())
3285 clrTextBk = ::GetSysColor(COLOR_WINDOW);
3286 else
3287 clrTextBk = ::GetSysColor(COLOR_3DFACE);
3289 CRect rc;
3290 GetClientRect(&rc);
3291 CHeaderCtrl* pHC = GetHeaderCtrl();
3292 if (pHC)
3294 CRect rcH;
3295 pHC->GetItemRect(0, &rcH);
3296 rc.top += rcH.bottom;
3298 CDC* pDC = GetDC();
3300 CMyMemDC memDC(pDC, &rc);
3302 memDC.SetTextColor(clrText);
3303 memDC.SetBkColor(clrTextBk);
3304 memDC.BitBlt(rc.left, rc.top, rc.Width(), rc.Height(), pDC, rc.left, rc.top, SRCCOPY);
3305 rc.top += 10;
3306 CGdiObject * oldfont = memDC.SelectStockObject(DEFAULT_GUI_FONT);
3307 memDC.DrawText(str, rc, DT_CENTER | DT_VCENTER |
3308 DT_WORDBREAK | DT_NOPREFIX | DT_NOCLIP);
3309 memDC.SelectObject(oldfont);
3311 ReleaseDC(pDC);
3313 if (defres)
3315 // the Default() call did not process the WM_PAINT message!
3316 // Validate the update region ourselves to avoid
3317 // an endless loop repainting
3318 CRect rc;
3319 GetUpdateRect(&rc, FALSE);
3320 if (!rc.IsRectEmpty())
3321 ValidateRect(rc);
3325 void CGitStatusListCtrl::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
3327 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
3329 CAutoReadLock locker(m_guard);
3331 CTGitPathList pathList;
3332 FillListOfSelectedItemPaths(pathList);
3333 if (pathList.IsEmpty())
3334 return;
3336 auto pdsrc = std::make_unique<CIDropSource>();
3337 if (!pdsrc)
3338 return;
3339 pdsrc->AddRef();
3341 GitDataObject* pdobj = new GitDataObject(pathList, m_Rev2.IsEmpty() ? m_CurrentVersion : m_Rev2);
3342 if (!pdobj)
3343 return;
3344 pdobj->AddRef();
3346 CDragSourceHelper dragsrchelper;
3348 SetRedraw(false);
3349 dragsrchelper.InitializeFromWindow(m_hWnd, pNMLV->ptAction, pdobj);
3350 SetRedraw(true);
3351 //dragsrchelper.InitializeFromBitmap()
3352 pdsrc->m_pIDataObj = pdobj;
3353 pdsrc->m_pIDataObj->AddRef();
3355 // Initiate the Drag & Drop
3356 DWORD dwEffect;
3357 m_bOwnDrag = true;
3358 ::DoDragDrop(pdobj, pdsrc.get(), DROPEFFECT_MOVE | DROPEFFECT_COPY, &dwEffect);
3359 m_bOwnDrag = false;
3360 pdsrc->Release();
3361 pdsrc.release();
3362 pdobj->Release();
3364 *pResult = 0;
3367 bool CGitStatusListCtrl::EnableFileDrop()
3369 m_bFileDropsEnabled = true;
3370 return true;
3373 bool CGitStatusListCtrl::HasPath(const CTGitPath& path)
3375 CAutoReadLock locker(m_guard);
3376 CTGitPath adjustedEntry;
3377 if (g_Git.m_CurrentDir[g_Git.m_CurrentDir.GetLength() - 1] == L'\\')
3378 adjustedEntry.SetFromWin(path.GetWinPathString().Right(path.GetWinPathString().GetLength() - g_Git.m_CurrentDir.GetLength()));
3379 else
3380 adjustedEntry.SetFromWin(path.GetWinPathString().Right(path.GetWinPathString().GetLength() - g_Git.m_CurrentDir.GetLength() - 1));
3381 for (size_t i=0; i < m_arStatusArray.size(); ++i)
3383 if (m_arStatusArray[i]->IsEquivalentTo(adjustedEntry))
3384 return true;
3387 return false;
3390 BOOL CGitStatusListCtrl::PreTranslateMessage(MSG* pMsg)
3392 if (pMsg->message == WM_KEYDOWN)
3394 switch (pMsg->wParam)
3396 case 'A':
3398 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3400 // select all entries
3401 for (int i=0; i<GetItemCount(); ++i)
3402 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3403 return TRUE;
3406 break;
3407 case 'C':
3408 case VK_INSERT:
3410 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3412 // copy all selected paths to the clipboard
3413 if (GetAsyncKeyState(VK_SHIFT)&0x8000)
3414 CopySelectedEntriesToClipboard(GITSLC_COLSTATUS);
3415 else
3416 CopySelectedEntriesToClipboard(0);
3417 return TRUE;
3420 break;
3421 case VK_DELETE:
3423 if ((GetSelectedCount() > 0) && (m_dwContextMenus & GITSLC_POPDELETE))
3425 CAutoReadLock locker(m_guard);
3426 auto filepath = GetListEntry(GetSelectionMark());
3427 if (filepath != nullptr && (filepath->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)))
3428 DeleteSelectedFiles();
3431 break;
3435 return __super::PreTranslateMessage(pMsg);
3438 bool CGitStatusListCtrl::CopySelectedEntriesToClipboard(DWORD dwCols)
3440 static HINSTANCE hResourceHandle(AfxGetResourceHandle());
3441 // WORD langID = (WORD)CRegStdDWORD(L"Software\\TortoiseGit\\LanguageID", GetUserDefaultLangID());
3443 CString sClipboard;
3444 CString temp;
3445 //TCHAR buf[100];
3446 if (GetSelectedCount() == 0)
3447 return false;
3449 // first add the column titles as the first line
3450 // We needn't head when only path copy
3451 //temp.LoadString(IDS_STATUSLIST_COLFILE);
3452 //sClipboard = temp;
3454 DWORD selection = 0;
3455 for (int i = 0, count = m_ColumnManager.GetColumnCount(); i < count; ++i)
3456 if ( ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3457 || ((dwCols != 1) && (i < 32) && ((dwCols & (1 << i)) != 0)))
3459 sClipboard += L'\t' + m_ColumnManager.GetName(i);
3461 if (i < 32)
3462 selection += 1 << i;
3465 if(dwCols)
3466 sClipboard += L"\r\n";
3468 CAutoReadLock locker(m_guard);
3470 POSITION pos = GetFirstSelectedItemPosition();
3471 int index;
3472 while ((index = GetNextSelectedItem(pos)) >= 0)
3474 auto entry = GetListEntry(index);
3475 if (!entry)
3476 continue;
3478 sClipboard += entry->GetWinPathString();
3479 if (selection & GITSLC_COLFILENAME)
3480 sClipboard += L'\t' + entry->GetFileOrDirectoryName();
3481 if (selection & GITSLC_COLEXT)
3482 sClipboard += L'\t' + entry->GetFileExtension();
3484 if (selection & GITSLC_COLSTATUS)
3485 sClipboard += L'\t' + entry->GetActionName();
3486 #if 0
3487 if (selection & SVNSLC_COLDATE)
3489 TCHAR datebuf[SVN_DATE_BUFFER];
3490 apr_time_t date = entry->last_commit_date;
3491 SVN::formatDate(datebuf, date, true);
3492 if (date)
3493 temp = datebuf;
3494 else
3495 temp.Empty();
3496 sClipboard += L'\t' + temp;
3498 for ( int i = SVNSLC_NUMCOLUMNS, count = m_ColumnManager.GetColumnCount()
3499 ; i < count
3500 ; ++i)
3502 if ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3504 CString value
3505 = entry->present_props[m_ColumnManager.GetName(i)];
3506 sClipboard += L'\t' + value;
3509 #endif
3510 if (selection & GITSLC_COLADD)
3511 sClipboard += L'\t' + entry->m_StatAdd;
3512 if (selection & GITSLC_COLDEL)
3513 sClipboard += L'\t' + entry->m_StatDel;
3515 sClipboard += L"\r\n";
3518 return CStringUtils::WriteAsciiStringToClipboard(sClipboard);
3521 size_t CGitStatusListCtrl::GetNumberOfChangelistsInSelection()
3523 #if 0
3524 CAutoReadLock locker(m_guard);
3525 std::set<CString> changelists;
3526 POSITION pos = GetFirstSelectedItemPosition();
3527 int index;
3528 while ((index = GetNextSelectedItem(pos)) >= 0)
3530 FileEntry * entry = GetListEntry(index);
3531 if (!entry->changelist.IsEmpty())
3532 changelists.insert(entry->changelist);
3534 return changelists.size();
3535 #endif
3536 return 0;
3539 bool CGitStatusListCtrl::PrepareGroups(bool bForce /* = false */)
3541 CAutoWriteLock locker(m_guard);
3542 bool bHasGroups=false;
3543 int max =0;
3545 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
3547 int ParentNo = m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3548 if( ParentNo > max)
3549 max=m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3552 if (((m_dwShow & GITSLC_SHOWUNVERSIONED) && !m_UnRevFileList.IsEmpty()) ||
3553 ((m_dwShow & GITSLC_SHOWIGNORED) && !m_IgnoreFileList.IsEmpty()) ||
3554 (m_dwShow & (GITSLC_SHOWASSUMEVALID | GITSLC_SHOWSKIPWORKTREE) && !m_LocalChangesIgnoredFileList.IsEmpty()) ||
3555 max>0 || bForce)
3557 bHasGroups = true;
3560 RemoveAllGroups();
3561 EnableGroupView(bHasGroups);
3563 TCHAR groupname[1024] = { 0 };
3564 int groupindex = 0;
3566 if(bHasGroups)
3568 LVGROUP grp = {0};
3569 grp.cbSize = sizeof(LVGROUP);
3570 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3571 groupindex=0;
3573 //if(m_UnRevFileList.GetCount()>0)
3574 if(max >0)
3576 wcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MERGEDFILES)), 1023);
3577 grp.pszHeader = groupname;
3578 grp.iGroupId = MERGE_MASK;
3579 grp.uAlign = LVGA_HEADER_LEFT;
3580 InsertGroup(0, &grp);
3582 CAutoRepository repository(g_Git.GetGitRepository());
3583 if (!repository)
3584 MessageBox(CGit::GetLibGit2LastErr(L"Could not open repository."), L"TortoiseGit", MB_OK | MB_ICONERROR);
3585 for (int i = 0; i <= max; ++i)
3587 CString str;
3588 str.Format(IDS_STATUSLIST_GROUP_DIFFWITHPARENT, i+1);
3589 if (repository)
3591 CString rev;
3592 rev.Format(L"%s^%d", (LPCTSTR)m_CurrentVersion, i + 1);
3593 CGitHash hash;
3594 if (!CGit::GetHash(repository, hash, rev))
3595 str += L": " + hash.ToString().Left(g_Git.GetShortHASHLength());
3597 grp.pszHeader = str.GetBuffer();
3598 str.ReleaseBuffer();
3599 grp.iGroupId = i;
3600 grp.uAlign = LVGA_HEADER_LEFT;
3601 InsertGroup(i+1, &grp);
3604 else
3606 wcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MODIFIEDFILES)), 1023);
3607 grp.pszHeader = groupname;
3608 grp.iGroupId = groupindex;
3609 grp.uAlign = LVGA_HEADER_LEFT;
3610 InsertGroup(groupindex++, &grp);
3613 wcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_NOTVERSIONEDFILES)), 1023);
3614 grp.pszHeader = groupname;
3615 grp.iGroupId = groupindex;
3616 grp.uAlign = LVGA_HEADER_LEFT;
3617 InsertGroup(groupindex++, &grp);
3620 //if(m_IgnoreFileList.GetCount()>0)
3622 wcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNOREDFILES)), 1023);
3623 grp.pszHeader = groupname;
3624 grp.iGroupId = groupindex;
3625 grp.uAlign = LVGA_HEADER_LEFT;
3626 InsertGroup(groupindex++, &grp);
3630 wcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNORELOCALCHANGES)), 1023);
3631 grp.pszHeader = groupname;
3632 grp.iGroupId = groupindex;
3633 grp.uAlign = LVGA_HEADER_LEFT;
3634 InsertGroup(groupindex++, &grp);
3639 #if 0
3640 m_bHasIgnoreGroup = false;
3642 // now add the items which don't belong to a group
3643 LVGROUP grp = {0};
3644 grp.cbSize = sizeof(LVGROUP);
3645 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3646 CString sUnassignedName(MAKEINTRESOURCE(IDS_STATUSLIST_UNASSIGNED_CHANGESET));
3647 wcsncpy_s(groupname, 1024, (LPCTSTR)sUnassignedName, 1023);
3648 grp.pszHeader = groupname;
3649 grp.iGroupId = groupindex;
3650 grp.uAlign = LVGA_HEADER_LEFT;
3651 InsertGroup(groupindex++, &grp);
3653 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
3655 if (it->first.Compare(SVNSLC_IGNORECHANGELIST)!=0)
3657 LVGROUP grp = {0};
3658 grp.cbSize = sizeof(LVGROUP);
3659 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3660 wcsncpy_s(groupname, 1024, it->first, 1023);
3661 grp.pszHeader = groupname;
3662 grp.iGroupId = groupindex;
3663 grp.uAlign = LVGA_HEADER_LEFT;
3664 it->second = InsertGroup(groupindex++, &grp);
3666 else
3667 m_bHasIgnoreGroup = true;
3670 if (m_bHasIgnoreGroup)
3672 // and now add the group 'ignore-on-commit'
3673 std::map<CString,int>::iterator it = m_changelists.find(SVNSLC_IGNORECHANGELIST);
3674 if (it != m_changelists.end())
3676 grp.cbSize = sizeof(LVGROUP);
3677 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3678 wcsncpy_s(groupname, 1024, SVNSLC_IGNORECHANGELIST, 1023);
3679 grp.pszHeader = groupname;
3680 grp.iGroupId = groupindex;
3681 grp.uAlign = LVGA_HEADER_LEFT;
3682 it->second = InsertGroup(groupindex, &grp);
3685 #endif
3686 return bHasGroups;
3689 void CGitStatusListCtrl::NotifyCheck()
3691 CWnd* pParent = GetLogicalParent();
3692 if (pParent && pParent->GetSafeHwnd())
3694 pParent->SendMessage(GITSLNM_CHECKCHANGED, m_nSelected);
3698 int CGitStatusListCtrl::UpdateFileList(const CTGitPathList* list)
3700 CAutoWriteLock locker(m_guard);
3701 m_CurrentVersion = GIT_REV_ZERO;
3703 g_Git.GetWorkingTreeChanges(m_StatusFileList, m_amend, list);
3705 BOOL bDeleteChecked = FALSE;
3706 int deleteFromIndex = 0;
3707 bool needsRefresh = false;
3708 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
3710 auto gitpatch = const_cast<CTGitPath*>(&m_StatusFileList[i]);
3711 gitpatch->m_Checked = TRUE;
3713 if ((gitpatch->m_Action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_MODIFIED)) && !gitpatch->Exists())
3715 if (!bDeleteChecked)
3717 CString message;
3718 message.Format(IDS_ASK_REMOVE_FROM_INDEX, gitpatch->GetWinPath());
3719 deleteFromIndex = CMessageBox::ShowCheck(GetSafeHwnd(), message, L"TortoiseGit", 1, IDI_EXCLAMATION, CString(MAKEINTRESOURCE(IDS_RESTORE_FROM_INDEX)), CString(MAKEINTRESOURCE(IDS_REMOVE_FROM_INDEX)), CString(MAKEINTRESOURCE(IDS_IGNOREBUTTON)), nullptr, CString(MAKEINTRESOURCE(IDS_DO_SAME_FOR_REST)), &bDeleteChecked);
3721 if (deleteFromIndex == 1)
3723 CString err;
3724 if (g_Git.Run(L"git.exe checkout -- \"" + gitpatch->GetWinPathString() + L'"', &err, CP_UTF8))
3725 MessageBox(L"Restoring from index failed:\n" + err, L"TortoiseGit", MB_ICONERROR);
3726 else
3727 needsRefresh = true;
3729 else if (deleteFromIndex == 2)
3731 CString err;
3732 if (g_Git.Run(L"git.exe rm -f --cache -- \"" + gitpatch->GetWinPathString() + L'"', &err, CP_UTF8))
3733 MessageBox(L"Removing from index failed:\n" + err, L"TortoiseGit", MB_ICONERROR);
3734 else
3735 needsRefresh = true;
3739 m_arStatusArray.push_back(&m_StatusFileList[i]);
3742 if (needsRefresh)
3743 MessageBox(L"Due to changes to the index, please refresh the dialog (e.g., by pressing F5).", L"TortoiseGit", MB_ICONINFORMATION);
3745 return 0;
3748 int CGitStatusListCtrl::UpdateWithGitPathList(CTGitPathList &list)
3750 CAutoWriteLock locker(m_guard);
3751 m_arStatusArray.clear();
3752 for (int i = 0; i < list.GetCount(); ++i)
3754 auto gitpath = const_cast<CTGitPath*>(&list[i]);
3756 if(gitpath ->m_Action & CTGitPath::LOGACTIONS_HIDE)
3757 continue;
3759 gitpath->m_Checked = TRUE;
3760 m_arStatusArray.push_back(&list[i]);
3762 return 0;
3765 int CGitStatusListCtrl::UpdateUnRevFileList(CTGitPathList &list)
3767 CAutoWriteLock locker(m_guard);
3768 m_UnRevFileList = list;
3769 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
3771 auto gitpatch = const_cast<CTGitPath*>(&m_UnRevFileList[i]);
3772 gitpatch->m_Checked = FALSE;
3773 m_arStatusArray.push_back(&m_UnRevFileList[i]);
3775 return 0;
3778 int CGitStatusListCtrl::UpdateUnRevFileList(const CTGitPathList* List)
3780 CAutoWriteLock locker(m_guard);
3781 CString err;
3782 if (m_UnRevFileList.FillUnRev(CTGitPath::LOGACTIONS_UNVER, List, &err))
3784 MessageBox(L"Failed to get UnRev file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
3785 return -1;
3788 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
3790 auto gitpatch = const_cast<CTGitPath*>(&m_UnRevFileList[i]);
3791 gitpatch->m_Checked = FALSE;
3792 m_arStatusArray.push_back(&m_UnRevFileList[i]);
3794 return 0;
3797 int CGitStatusListCtrl::UpdateIgnoreFileList(const CTGitPathList* List)
3799 CAutoWriteLock locker(m_guard);
3800 CString err;
3801 if (m_IgnoreFileList.FillUnRev(CTGitPath::LOGACTIONS_IGNORE, List, &err))
3803 MessageBox(L"Failed to get Ignore file list\n" + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
3804 return -1;
3807 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
3809 auto gitpatch = const_cast<CTGitPath*>(&m_IgnoreFileList[i]);
3810 gitpatch->m_Checked = FALSE;
3811 m_arStatusArray.push_back(&m_IgnoreFileList[i]);
3813 return 0;
3816 int CGitStatusListCtrl::UpdateLocalChangesIgnoredFileList(const CTGitPathList* list)
3818 CAutoWriteLock locker(m_guard);
3819 m_LocalChangesIgnoredFileList.FillBasedOnIndexFlags(GIT_IDXENTRY_VALID, GIT_IDXENTRY_SKIP_WORKTREE, list);
3820 for (int i = 0; i < m_LocalChangesIgnoredFileList.GetCount(); ++i)
3822 auto gitpatch = const_cast<CTGitPath*>(&m_LocalChangesIgnoredFileList[i]);
3823 gitpatch->m_Checked = FALSE;
3824 m_arStatusArray.push_back(&m_LocalChangesIgnoredFileList[i]);
3826 return 0;
3829 int CGitStatusListCtrl::UpdateFileList(int mask, bool once, const CTGitPathList* List)
3831 CAutoWriteLock locker(m_guard);
3832 if(mask&CGitStatusListCtrl::FILELIST_MODIFY)
3834 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_MODIFY)))
3836 UpdateFileList(List);
3837 m_FileLoaded|=CGitStatusListCtrl::FILELIST_MODIFY;
3840 if (mask & CGitStatusListCtrl::FILELIST_UNVER || mask & CGitStatusListCtrl::FILELIST_IGNORE)
3842 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_UNVER)))
3844 UpdateUnRevFileList(List);
3845 m_FileLoaded|=CGitStatusListCtrl::FILELIST_UNVER;
3847 if(mask&CGitStatusListCtrl::FILELIST_IGNORE && (once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_IGNORE))))
3849 UpdateIgnoreFileList(List);
3850 m_FileLoaded |= CGitStatusListCtrl::FILELIST_IGNORE;
3853 if (mask & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED && (once || (!(m_FileLoaded & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED))))
3855 UpdateLocalChangesIgnoredFileList(List);
3856 m_FileLoaded |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
3858 return 0;
3861 void CGitStatusListCtrl::Clear()
3863 CAutoWriteLock locker(m_guard);
3864 m_FileLoaded=0;
3865 this->DeleteAllItems();
3866 this->m_arListArray.clear();
3867 this->m_arStatusArray.clear();
3868 this->m_changelists.clear();
3871 bool CGitStatusListCtrl::CheckMultipleDiffs()
3873 UINT selCount = GetSelectedCount();
3874 if (selCount > max(3, (DWORD)CRegDWORD(L"Software\\TortoiseGit\\NumDiffWarning", 10)))
3876 CString message;
3877 message.Format(IDS_STATUSLIST_WARN_MAXDIFF, selCount);
3878 return MessageBox(message, L"TortoiseGit", MB_YESNO | MB_ICONQUESTION) == IDYES;
3880 return true;
3883 //////////////////////////////////////////////////////////////////////////
3884 bool CGitStatusListCtrlDropTarget::OnDrop(FORMATETC* pFmtEtc, STGMEDIUM& medium, DWORD* /*pdwEffect*/, POINTL pt)
3886 if (pFmtEtc->cfFormat == CF_HDROP && medium.tymed == TYMED_HGLOBAL)
3888 HDROP hDrop = (HDROP)GlobalLock(medium.hGlobal);
3889 if (hDrop)
3891 TCHAR szFileName[MAX_PATH] = {0};
3893 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, nullptr, 0);
3895 POINT clientpoint;
3896 clientpoint.x = pt.x;
3897 clientpoint.y = pt.y;
3898 ScreenToClient(m_hTargetWnd, &clientpoint);
3899 if ((m_pGitStatusListCtrl->IsGroupViewEnabled()) && (m_pGitStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
3901 #if 0
3902 CTGitPathList changelistItems;
3903 for (UINT i = 0; i < cFiles; ++i)
3905 if (DragQueryFile(hDrop, i, szFileName, _countof(szFileName)))
3906 changelistItems.AddPath(CTGitPath(szFileName));
3908 // find the changelist name
3909 CString sChangelist;
3910 LONG_PTR nGroup = m_pGitStatusListCtrl->GetGroupFromPoint(&clientpoint);
3911 for (std::map<CString, int>::iterator it = m_pGitStatusListCtrl->m_changelists.begin(); it != m_pGitStatusListCtrl->m_changelists.end(); ++it)
3912 if (it->second == nGroup)
3913 sChangelist = it->first;
3915 if (!sChangelist.IsEmpty())
3917 CGit git;
3918 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
3920 for (int l=0; l<changelistItems.GetCount(); ++l)
3922 int index = m_pGitStatusListCtrl->GetIndex(changelistItems[l]);
3923 if (index >= 0)
3925 auto e = m_pGitStatusListCtrl->GetListEntry(index);
3926 if (e)
3928 e->changelist = sChangelist;
3929 if (!e->IsFolder())
3931 if (m_pGitStatusListCtrl->m_changelists.find(e->changelist) != m_pGitStatusListCtrl->m_changelists.end())
3932 m_pGitStatusListCtrl->SetItemGroup(index, m_pGitStatusListCtrl->m_changelists[e->changelist]);
3933 else
3934 m_pGitStatusListCtrl->SetItemGroup(index, 0);
3938 else
3940 HWND hParentWnd = GetParent(m_hTargetWnd);
3941 if (hParentWnd)
3942 ::SendMessage(hParentWnd, CGitStatusListCtrl::GITSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
3946 else
3947 CMessageBox::Show(m_pGitStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), L"TortoiseGit", MB_ICONERROR);
3949 else
3951 SVN git;
3952 if (git.RemoveFromChangeList(changelistItems, CStringArray(), git_depth_empty))
3954 for (int l=0; l<changelistItems.GetCount(); ++l)
3956 int index = m_pGitStatusListCtrl->GetIndex(changelistItems[l]);
3957 if (index >= 0)
3959 auto e = m_pGitStatusListCtrl->GetListEntry(index);
3960 if (e)
3962 e->changelist = sChangelist;
3963 m_pGitStatusListCtrl->SetItemGroup(index, 0);
3966 else
3968 HWND hParentWnd = GetParent(m_hTargetWnd);
3969 if (hParentWnd)
3970 ::SendMessage(hParentWnd, CGitStatusListCtrl::GITSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
3974 else
3975 CMessageBox::Show(m_pGitStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), L"TortoiseGit", MB_ICONERROR);
3977 #endif
3979 else
3981 for (UINT i = 0; i < cFiles; ++i)
3983 if (!DragQueryFile(hDrop, i, szFileName, _countof(szFileName)))
3984 continue;
3986 HWND hParentWnd = GetParent(m_hTargetWnd);
3987 if (hParentWnd)
3988 ::SendMessage(hParentWnd, CGitStatusListCtrl::GITSLNM_ADDFILE, 0, (LPARAM)szFileName);
3992 GlobalUnlock(medium.hGlobal);
3994 return true; //let base free the medium
3997 HRESULT STDMETHODCALLTYPE CGitStatusListCtrlDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD __RPC_FAR* pdwEffect)
3999 CIDropTarget::DragOver(grfKeyState, pt, pdwEffect);
4000 *pdwEffect = DROPEFFECT_COPY;
4001 if (m_pGitStatusListCtrl)
4003 POINT clientpoint;
4004 clientpoint.x = pt.x;
4005 clientpoint.y = pt.y;
4006 ScreenToClient(m_hTargetWnd, &clientpoint);
4007 if ((m_pGitStatusListCtrl->IsGroupViewEnabled()) && (m_pGitStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
4008 *pdwEffect = DROPEFFECT_NONE;
4009 else if ((!m_pGitStatusListCtrl->m_bFileDropsEnabled) || (m_pGitStatusListCtrl->m_bOwnDrag))
4010 *pdwEffect = DROPEFFECT_NONE;
4012 return S_OK;
4015 void CGitStatusListCtrl::FilesExport()
4017 CAutoReadLock locker(m_guard);
4018 CString exportDir;
4019 // export all changed files to a folder
4020 CBrowseFolder browseFolder;
4021 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
4022 if (browseFolder.Show(GetSafeHwnd(), exportDir) != CBrowseFolder::OK)
4023 return;
4025 POSITION pos = GetFirstSelectedItemPosition();
4026 int index;
4027 while ((index = GetNextSelectedItem(pos)) >= 0)
4029 auto fd = GetListEntry(index);
4030 // we cannot export directories or folders
4031 if ((fd->m_Action & CTGitPath::LOGACTIONS_DELETED) || fd->IsDirectory())
4032 continue;
4034 CPathUtils::MakeSureDirectoryPathExists(exportDir + L'\\' + fd->GetContainingDirectory().GetWinPathString());
4035 CString filename = exportDir + L'\\' + fd->GetWinPathString();
4036 if (m_CurrentVersion == GIT_REV_ZERO)
4038 if (!CopyFile(g_Git.CombinePath(fd), filename, false))
4040 MessageBox(CFormatMessageWrapper(), L"TortoiseGit", MB_OK | MB_ICONERROR);
4041 return;
4044 else
4046 if (g_Git.GetOneFile(m_CurrentVersion, *fd, filename))
4048 CString out;
4049 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)fd->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)filename);
4050 if (CMessageBox::Show(GetSafeHwnd(), g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), L"TortoiseGit", 2, IDI_WARNING, CString(MAKEINTRESOURCE(IDS_IGNOREBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 2)
4051 return;
4057 void CGitStatusListCtrl::FileSaveAs(CTGitPath *path)
4059 CAutoReadLock locker(m_guard);
4060 CString filename;
4061 filename.Format(L"%s\\%s-%s%s", (LPCTSTR)g_Git.CombinePath(path->GetContainingDirectory()), (LPCTSTR)path->GetBaseFilename(), (LPCTSTR)m_CurrentVersion.Left(g_Git.GetShortHASHLength()), (LPCTSTR)path->GetFileExtension());
4062 if (!CAppUtils::FileOpenSave(filename, nullptr, 0, 0, false, GetSafeHwnd()))
4063 return;
4064 if (m_CurrentVersion == GIT_REV_ZERO)
4066 if (!CopyFile(g_Git.CombinePath(path), filename, false))
4068 MessageBox(CFormatMessageWrapper(), L"TortoiseGit", MB_OK | MB_ICONERROR);
4069 return;
4072 else
4074 if (g_Git.GetOneFile(m_CurrentVersion, *path, filename))
4076 CString out;
4077 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)path->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)filename);
4078 CMessageBox::Show(GetSafeHwnd(), g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), L"TortoiseGit", MB_OK);
4079 return;
4084 int CGitStatusListCtrl::RevertSelectedItemToVersion(bool parent)
4086 CAutoReadLock locker(m_guard);
4087 if(this->m_CurrentVersion.IsEmpty())
4088 return 0;
4089 if(this->m_CurrentVersion == GIT_REV_ZERO)
4090 return 0;
4092 POSITION pos = GetFirstSelectedItemPosition();
4093 int index;
4094 CString cmd,out;
4095 std::map<CString, int> versionMap;
4096 while ((index = GetNextSelectedItem(pos)) >= 0)
4098 auto fentry = GetListEntry(index);
4099 CString version;
4100 if (parent)
4102 int parentNo = fentry->m_ParentNo & PARENT_MASK;
4103 CString ref;
4104 ref.Format(L"%s^%d", (LPCTSTR)m_CurrentVersion, parentNo + 1);
4105 CGitHash hash;
4106 if (g_Git.GetHash(hash, ref))
4108 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of ref \"" + ref + L"\"."), L"TortoiseGit", MB_ICONERROR);
4109 continue;
4112 version = hash.ToString();
4114 else
4115 version = m_CurrentVersion;
4117 CString filename = fentry->GetGitPathString();
4118 if (!fentry->GetGitOldPathString().IsEmpty())
4119 filename = fentry->GetGitOldPathString();
4120 cmd.Format(L"git.exe checkout %s -- \"%s\"", (LPCTSTR)version, (LPCTSTR)filename);
4121 out.Empty();
4122 if (g_Git.Run(cmd, &out, CP_UTF8))
4124 if (MessageBox(out, L"TortoiseGit", MB_ICONEXCLAMATION | MB_OKCANCEL) == IDCANCEL)
4125 continue;
4127 else
4128 versionMap[version]++;
4131 out.Empty();
4132 for (auto it = versionMap.cbegin(); it != versionMap.cend(); ++it)
4134 CString versionEntry;
4135 versionEntry.Format(IDS_STATUSLIST_FILESREVERTED, it->second, (LPCTSTR)it->first);
4136 out += versionEntry + L"\r\n";
4138 if (!out.IsEmpty())
4140 if (GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
4141 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
4142 CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", MB_OK);
4144 return 0;
4147 void CGitStatusListCtrl::OpenFile(CTGitPath*filepath,int mode)
4149 CString file;
4150 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
4151 file = g_Git.CombinePath(filepath);
4152 else
4154 file = CTempFiles::Instance().GetTempFilePath(false, *filepath, m_CurrentVersion).GetWinPathString();
4155 CString cmd,out;
4156 if(g_Git.GetOneFile(m_CurrentVersion, *filepath, file))
4158 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)filepath->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)file);
4159 CMessageBox::Show(GetSafeHwnd(), g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), L"TortoiseGit", MB_OK);
4160 return;
4162 SetFileAttributes(file, FILE_ATTRIBUTE_READONLY);
4164 if(mode == ALTERNATIVEEDITOR)
4166 CAppUtils::LaunchAlternativeEditor(file);
4167 return;
4170 if (mode == OPEN)
4171 CAppUtils::ShellOpen(file, GetSafeHwnd());
4172 else
4173 CAppUtils::ShowOpenWithDialog(file, GetSafeHwnd());
4176 void CGitStatusListCtrl::DeleteSelectedFiles()
4178 CAutoWriteLock locker(m_guard);
4179 //Collect paths
4180 std::vector<int> selectIndex;
4182 POSITION pos = GetFirstSelectedItemPosition();
4183 int index;
4184 while ((index = GetNextSelectedItem(pos)) >= 0)
4185 selectIndex.push_back(index);
4187 CAutoRepository repo = g_Git.GetGitRepository();
4188 if (!repo)
4190 MessageBox(g_Git.GetLibGit2LastErr(L"Could not open repository."), L"TortoiseGit", MB_OK);
4191 return;
4193 CAutoIndex gitIndex;
4194 if (git_repository_index(gitIndex.GetPointer(), repo))
4196 g_Git.GetLibGit2LastErr(L"Could not open index.");
4197 return;
4199 int needWriteIndex = 0;
4201 //Create file-list ('\0' separated) for SHFileOperation
4202 CString filelist;
4203 for (size_t i = 0; i < selectIndex.size(); ++i)
4205 index = selectIndex[i];
4207 auto path = GetListEntry(index);
4208 if (path == nullptr)
4209 continue;
4211 // do not report errors as we could remove an unversioned file
4212 needWriteIndex += git_index_remove_bypath(gitIndex, CUnicodeUtils::GetUTF8(path->GetGitPathString())) == 0 ? 1 : 0;
4214 if (!path->Exists())
4215 continue;
4217 filelist += path->GetWinPathString();
4218 filelist += L'|';
4220 filelist += L'|';
4221 int len = filelist.GetLength();
4222 auto buf = std::make_unique<TCHAR[]>(len + 2);
4223 wcscpy_s(buf.get(), len + 2, filelist);
4224 CStringUtils::PipesToNulls(buf.get(), len + 2);
4225 SHFILEOPSTRUCT fileop;
4226 fileop.hwnd = this->m_hWnd;
4227 fileop.wFunc = FO_DELETE;
4228 fileop.pFrom = buf.get();
4229 fileop.pTo = nullptr;
4230 fileop.fFlags = FOF_NO_CONNECTED_ELEMENTS | ((GetAsyncKeyState(VK_SHIFT) & 0x8000) ? 0 : FOF_ALLOWUNDO);
4231 fileop.lpszProgressTitle = L"deleting file";
4232 int result = SHFileOperation(&fileop);
4234 if ((result == 0 || len == 1) && (!fileop.fAnyOperationsAborted))
4236 if (needWriteIndex && git_index_write(gitIndex))
4237 MessageBox(g_Git.GetLibGit2LastErr(L"Could not write index."), L"TortoiseGit", MB_OK);
4239 if (needWriteIndex)
4241 CWnd* pParent = GetLogicalParent();
4242 if (pParent && pParent->GetSafeHwnd())
4243 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
4244 SetRedraw(TRUE);
4245 return;
4248 SetRedraw(FALSE);
4249 POSITION pos2 = nullptr;
4250 while ((pos2 = GetFirstSelectedItemPosition()) != nullptr)
4252 int index2 = GetNextSelectedItem(pos2);
4253 if (GetCheck(index2))
4254 m_nSelected--;
4255 m_nTotal--;
4257 RemoveListEntry(index2);
4259 SetRedraw(TRUE);
4263 BOOL CGitStatusListCtrl::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
4265 switch (message)
4267 case WM_MENUCHAR: // only supported by IContextMenu3
4268 if (g_IContext3)
4270 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4271 return TRUE;
4273 break;
4275 case WM_DRAWITEM:
4276 case WM_MEASUREITEM:
4277 if (wParam)
4278 break; // if wParam != 0 then the message is not menu-related
4280 case WM_INITMENU:
4281 case WM_INITMENUPOPUP:
4283 HMENU hMenu = (HMENU)wParam;
4284 if ((hMenu == m_hShellMenu) && (GetMenuItemCount(hMenu) == 0))
4286 // the shell submenu is populated only on request, i.e. right
4287 // before the submenu is shown
4288 if (g_pFolderhook)
4290 delete g_pFolderhook;
4291 g_pFolderhook = nullptr;
4293 CTGitPathList targetList;
4294 FillListOfSelectedItemPaths(targetList);
4295 if (!targetList.IsEmpty())
4297 // get IShellFolder interface of Desktop (root of shell namespace)
4298 if (g_psfDesktopFolder)
4299 g_psfDesktopFolder->Release();
4300 SHGetDesktopFolder(&g_psfDesktopFolder); // needed to obtain full qualified pidl
4302 // ParseDisplayName creates a PIDL from a file system path relative to the IShellFolder interface
4303 // but since we use the Desktop as our interface and the Desktop is the namespace root
4304 // that means that it's a fully qualified PIDL, which is what we need
4306 if (g_pidlArray)
4308 for (int i = 0; i < g_pidlArrayItems; i++)
4310 if (g_pidlArray[i])
4311 CoTaskMemFree(g_pidlArray[i]);
4313 CoTaskMemFree(g_pidlArray);
4314 g_pidlArray = nullptr;
4315 g_pidlArrayItems = 0;
4317 int nItems = targetList.GetCount();
4318 g_pidlArray = (LPITEMIDLIST *)CoTaskMemAlloc((nItems + 10) * sizeof(LPITEMIDLIST));
4319 SecureZeroMemory(g_pidlArray, (nItems + 10) * sizeof(LPITEMIDLIST));
4320 int succeededItems = 0;
4321 PIDLIST_RELATIVE pidl = nullptr;
4323 int bufsize = 1024;
4324 auto filepath = std::make_unique<WCHAR[]>(bufsize);
4325 for (int i = 0; i < nItems; i++)
4327 CString fullPath = g_Git.CombinePath(targetList[i].GetWinPath());
4328 if (bufsize < fullPath.GetLength())
4330 bufsize = fullPath.GetLength() + 3;
4331 filepath = std::make_unique<WCHAR[]>(bufsize);
4333 wcscpy_s(filepath.get(), bufsize, fullPath);
4334 if (SUCCEEDED(g_psfDesktopFolder->ParseDisplayName(nullptr, 0, filepath.get(), nullptr, &pidl, nullptr)))
4335 g_pidlArray[succeededItems++] = pidl; // copy pidl to pidlArray
4337 if (succeededItems == 0)
4339 CoTaskMemFree(g_pidlArray);
4340 g_pidlArray = nullptr;
4343 g_pidlArrayItems = succeededItems;
4345 if (g_pidlArrayItems)
4347 CString ext = targetList[0].GetFileExtension();
4349 ASSOCIATIONELEMENT const rgAssocItem[] =
4351 { ASSOCCLASS_PROGID_STR, nullptr, ext },
4352 { ASSOCCLASS_SYSTEM_STR, nullptr, ext },
4353 { ASSOCCLASS_APP_STR, nullptr, ext },
4354 { ASSOCCLASS_STAR, nullptr, nullptr },
4355 { ASSOCCLASS_FOLDER, nullptr, nullptr },
4357 IQueryAssociations* pIQueryAssociations = nullptr;
4358 if (FAILED(AssocCreateForClasses(rgAssocItem, ARRAYSIZE(rgAssocItem), IID_IQueryAssociations, (void**)&pIQueryAssociations)))
4359 pIQueryAssociations = nullptr; // not a problem, it works without this
4361 g_pFolderhook = new CIShellFolderHook(g_psfDesktopFolder, targetList);
4362 LPCONTEXTMENU icm1 = nullptr;
4364 DEFCONTEXTMENU dcm = { 0 };
4365 dcm.hwnd = m_hWnd;
4366 dcm.psf = g_pFolderhook;
4367 dcm.cidl = g_pidlArrayItems;
4368 dcm.apidl = (PCUITEMID_CHILD_ARRAY)g_pidlArray;
4369 dcm.punkAssociationInfo = pIQueryAssociations;
4370 if (SUCCEEDED(SHCreateDefaultContextMenu(&dcm, IID_IContextMenu, (void**)&icm1)))
4372 int iMenuType = 0; // to know which version of IContextMenu is supported
4373 if (icm1)
4374 { // since we got an IContextMenu interface we can now obtain the higher version interfaces via that
4375 if (icm1->QueryInterface(IID_IContextMenu3, (void**)&m_pContextMenu) == S_OK)
4376 iMenuType = 3;
4377 else if (icm1->QueryInterface(IID_IContextMenu2, (void**)&m_pContextMenu) == S_OK)
4378 iMenuType = 2;
4380 if (m_pContextMenu)
4381 icm1->Release(); // we can now release version 1 interface, cause we got a higher one
4382 else
4384 // since no higher versions were found
4385 // redirect ppContextMenu to version 1 interface
4386 iMenuType = 1;
4387 m_pContextMenu = icm1;
4390 if (m_pContextMenu)
4392 // lets fill the our popup menu
4393 UINT flags = CMF_NORMAL;
4394 flags |= (GetKeyState(VK_SHIFT) & 0x8000) != 0 ? CMF_EXTENDEDVERBS : 0;
4395 m_pContextMenu->QueryContextMenu(hMenu, 0, SHELL_MIN_CMD, SHELL_MAX_CMD, flags);
4398 // subclass window to handle menu related messages in CShellContextMenu
4399 if (iMenuType > 1) // only subclass if its version 2 or 3
4401 if (iMenuType == 2)
4402 g_IContext2 = (LPCONTEXTMENU2)m_pContextMenu;
4403 else // version 3
4404 g_IContext3 = (LPCONTEXTMENU3)m_pContextMenu;
4408 if (pIQueryAssociations)
4409 pIQueryAssociations->Release();
4412 if (g_IContext3)
4413 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4414 else if (g_IContext2)
4415 g_IContext2->HandleMenuMsg(message, wParam, lParam);
4416 return TRUE;
4420 break;
4421 default:
4422 break;
4425 return __super::OnWndMsg(message, wParam, lParam, pResult);
4428 CTGitPath* CGitStatusListCtrl::GetListEntry(int index)
4430 ATLASSERT(m_guard.GetCurrentThreadStatus());
4431 auto entry = const_cast<CTGitPath*>(m_arStatusArray[index]);
4432 ASSERT(entry);
4433 return entry;
4436 void CGitStatusListCtrl::OnSysColorChange()
4438 __super::OnSysColorChange();
4439 if (m_nBackgroundImageID)
4440 CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), m_nBackgroundImageID);