Optimize variable scopes
[TortoiseGit.git] / src / Git / GitStatusListCtrl.cpp
blob5c0d6e36c804ab6a54eb7c16589588cc094b40a9
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - 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 "GitDiff.h"
35 #include "GitProgressDlg.h"
36 #include "SysImageList.h"
37 #include "TGitPath.h"
38 #include "registry.h"
39 #include "InputDlg.h"
40 #include "GitAdminDir.h"
41 #include "DragDropImpl.h"
42 #include "GitDataObject.h"
43 #include "ProgressCommands/AddProgressCommand.h"
44 #include "IconMenu.h"
45 #include "FormatMessageWrapper.h"
46 #include "BrowseFolder.h"
48 const UINT CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED
49 = ::RegisterWindowMessage(_T("GITSLNM_ITEMCOUNTCHANGED"));
50 const UINT CGitStatusListCtrl::GITSLNM_NEEDSREFRESH
51 = ::RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
52 const UINT CGitStatusListCtrl::GITSLNM_ADDFILE
53 = ::RegisterWindowMessage(_T("GITSLNM_ADDFILE"));
54 const UINT CGitStatusListCtrl::GITSLNM_CHECKCHANGED
55 = ::RegisterWindowMessage(_T("GITSLNM_CHECKCHANGED"));
56 const UINT CGitStatusListCtrl::GITSLNM_ITEMCHANGED
57 = ::RegisterWindowMessage(_T("GITSLNM_ITEMCHANGED"));
59 struct icompare
61 bool operator() (const std::wstring& lhs, const std::wstring& rhs) const
63 // no logical comparison here: we need this sorted strictly
64 return _wcsicmp(lhs.c_str(), rhs.c_str()) < 0;
68 class CIShellFolderHook : public IShellFolder
70 public:
71 CIShellFolderHook(LPSHELLFOLDER sf, const CTGitPathList& pathlist)
73 sf->AddRef();
74 m_iSF = sf;
75 // it seems the paths in the HDROP need to be sorted, otherwise
76 // it might not work properly or even crash.
77 // to get the items sorted, we just add them to a set
78 for (int i = 0; i < pathlist.GetCount(); ++i)
79 sortedpaths.insert((LPCTSTR)g_Git.CombinePath(pathlist[i].GetWinPath()));
82 ~CIShellFolderHook() { m_iSF->Release(); }
84 // IUnknown methods --------
85 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject) { return m_iSF->QueryInterface(riid, ppvObject); }
86 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return m_iSF->AddRef(); }
87 virtual ULONG STDMETHODCALLTYPE Release(void) { return m_iSF->Release(); }
89 // IShellFolder methods ----
90 virtual HRESULT STDMETHODCALLTYPE GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv);
92 virtual HRESULT STDMETHODCALLTYPE CompareIDs(LPARAM lParam, __RPC__in PCUIDLIST_RELATIVE pidl1, __RPC__in PCUIDLIST_RELATIVE pidl2) { return m_iSF->CompareIDs(lParam, pidl1, pidl2); }
93 virtual HRESULT STDMETHODCALLTYPE GetDisplayNameOf(__RPC__in_opt PCUITEMID_CHILD pidl, SHGDNF uFlags, __RPC__out STRRET *pName) { return m_iSF->GetDisplayNameOf(pidl, uFlags, pName); }
94 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); }
95 virtual HRESULT STDMETHODCALLTYPE EnumObjects(__RPC__in_opt HWND hwndOwner, SHCONTF grfFlags, __RPC__deref_out_opt IEnumIDList **ppenumIDList) { return m_iSF->EnumObjects(hwndOwner, grfFlags, ppenumIDList); }
96 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); }
97 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); }
98 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); }
99 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); }
100 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); }
102 protected:
103 LPSHELLFOLDER m_iSF;
104 std::set<std::wstring, icompare> sortedpaths;
107 HRESULT STDMETHODCALLTYPE CIShellFolderHook::GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv)
109 if (InlineIsEqualGUID(riid, IID_IDataObject))
111 HRESULT hres = m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, IID_IDataObject, nullptr, ppv);
112 if (FAILED(hres))
113 return hres;
115 IDataObject * idata = (LPDATAOBJECT)(*ppv);
116 // the IDataObject returned here doesn't have a HDROP, so we create one ourselves and add it to the IDataObject
117 // the HDROP is necessary for most context menu handlers
118 int nLength = 0;
119 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
121 nLength += (int)it->size();
122 nLength += 1; // '\0' separator
124 int nBufferSize = sizeof(DROPFILES) + ((nLength + 5)*sizeof(TCHAR));
125 auto pBuffer = std::make_unique<char[]>(nBufferSize);
126 SecureZeroMemory(pBuffer.get(), nBufferSize);
127 DROPFILES* df = (DROPFILES*)pBuffer.get();
128 df->pFiles = sizeof(DROPFILES);
129 df->fWide = 1;
130 TCHAR* pFilenames = (TCHAR*)((BYTE*)(pBuffer.get()) + sizeof(DROPFILES));
131 TCHAR* pCurrentFilename = pFilenames;
133 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
135 wcscpy_s(pCurrentFilename, it->size() + 1, it->c_str());
136 pCurrentFilename += it->size();
137 *pCurrentFilename = '\0'; // separator between file names
138 pCurrentFilename++;
140 *pCurrentFilename = '\0'; // terminate array
141 pCurrentFilename++;
142 *pCurrentFilename = '\0'; // terminate array
143 STGMEDIUM medium = { 0 };
144 medium.tymed = TYMED_HGLOBAL;
145 medium.hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE, nBufferSize + 20);
146 if (medium.hGlobal)
148 LPVOID pMem = ::GlobalLock(medium.hGlobal);
149 if (pMem)
151 memcpy(pMem, pBuffer.get(), nBufferSize);
152 GlobalUnlock(medium.hGlobal);
153 FORMATETC formatetc = { 0 };
154 formatetc.cfFormat = CF_HDROP;
155 formatetc.dwAspect = DVASPECT_CONTENT;
156 formatetc.lindex = -1;
157 formatetc.tymed = TYMED_HGLOBAL;
158 medium.pUnkForRelease = nullptr;
159 hres = idata->SetData(&formatetc, &medium, TRUE);
160 return hres;
163 return E_OUTOFMEMORY;
165 else
167 // just pass it on to the base object
168 return m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, riid, rgfReserved, ppv);
172 IContextMenu2 * g_IContext2 = nullptr;
173 IContextMenu3 * g_IContext3 = nullptr;
174 CIShellFolderHook * g_pFolderhook = nullptr;
175 IShellFolder * g_psfDesktopFolder = nullptr;
176 LPITEMIDLIST * g_pidlArray = nullptr;
177 int g_pidlArrayItems = 0;
179 #define SHELL_MIN_CMD 10000
180 #define SHELL_MAX_CMD 20000
182 HRESULT CALLBACK dfmCallback(IShellFolder * /*psf*/, HWND /*hwnd*/, IDataObject * /*pdtobj*/, UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/)
184 switch (uMsg)
186 case DFM_MERGECONTEXTMENU:
187 return S_OK;
188 case DFM_INVOKECOMMAND:
189 case DFM_INVOKECOMMANDEX:
190 case DFM_GETDEFSTATICID: // Required for Windows 7 to pick a default
191 return S_FALSE;
193 return E_NOTIMPL;
196 BEGIN_MESSAGE_MAP(CGitStatusListCtrl, CResizableColumnsListCtrl<CListCtrl>)
197 ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHdnItemclick)
198 ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHdnItemclick)
199 ON_NOTIFY_REFLECT_EX(LVN_ITEMCHANGED, OnLvnItemchanged)
200 ON_WM_CONTEXTMENU()
201 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclk)
202 ON_NOTIFY_REFLECT(LVN_GETINFOTIP, OnLvnGetInfoTip)
203 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw)
204 ON_WM_SETCURSOR()
205 ON_WM_GETDLGCODE()
206 ON_NOTIFY_REFLECT(NM_RETURN, OnNMReturn)
207 ON_WM_KEYDOWN()
208 ON_WM_PAINT()
209 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
210 ON_NOTIFY_REFLECT(LVN_ITEMCHANGING, &CGitStatusListCtrl::OnLvnItemchanging)
211 END_MESSAGE_MAP()
213 CGitStatusListCtrl::CGitStatusListCtrl() : CResizableColumnsListCtrl<CListCtrl>()
214 //, m_HeadRev(GitRev::REV_HEAD)
215 , m_pbCanceled(nullptr)
216 , m_pStatLabel(nullptr)
217 , m_pSelectButton(nullptr)
218 , m_pConfirmButton(nullptr)
219 , m_bBusy(false)
220 , m_bEmpty(false)
221 , m_bShowIgnores(false)
222 , m_pDropTarget(nullptr)
223 , m_bIgnoreRemoveOnly(false)
224 , m_bCheckChildrenWithParent(false)
225 , m_bUnversionedLast(true)
226 , m_bHasChangeLists(false)
227 , m_bHasLocks(false)
228 , m_bBlock(false)
229 , m_bBlockUI(false)
230 , m_bHasCheckboxes(false)
231 , m_bCheckIfGroupsExist(true)
232 , m_bFileDropsEnabled(false)
233 , m_bOwnDrag(false)
234 , m_dwDefaultColumns(0)
235 , m_bAscending(false)
236 , m_nSortedColumn(-1)
237 , m_bHasExternalsFromDifferentRepos(false)
238 , m_sNoPropValueText(MAKEINTRESOURCE(IDS_STATUSLIST_NOPROPVALUE))
239 , m_amend(false)
240 , m_bDoNotAutoselectSubmodules(false)
241 , m_bNoAutoselectMissing(false)
242 , m_bHasWC(true)
243 , m_hwndLogicalParent(nullptr)
244 , m_bHasUnversionedItems(FALSE)
245 , m_nTargetCount(0)
246 , m_bHasExternals(false)
247 , m_bHasIgnoreGroup(false)
248 , m_nUnversioned(0)
249 , m_nNormal(0)
250 , m_nModified(0)
251 , m_nAdded(0)
252 , m_nDeleted(0)
253 , m_nConflicted(0)
254 , m_nTotal(0)
255 , m_nSelected(0)
256 , m_nRenamed(0)
257 , m_nShownUnversioned(0)
258 , m_nShownModified(0)
259 , m_nShownAdded(0)
260 , m_nShownDeleted(0)
261 , m_nShownConflicted(0)
262 , m_nShownFiles(0)
263 , m_nShownSubmodules(0)
264 , m_dwShow(0)
265 , m_bShowFolders(false)
266 , m_bUpdate(false)
267 , m_dwContextMenus(0)
268 , m_nIconFolder(0)
269 , m_nRestoreOvl(0)
270 , m_pContextMenu(nullptr)
271 , m_hShellMenu(nullptr)
273 m_FileLoaded=0;
274 m_dwDefaultColumns = 0;
275 m_critSec.Init();
276 m_bIsRevertTheirMy = false;
277 m_bNoAutoselectMissing = CRegDWORD(L"Software\\TortoiseGit\\AutoselectMissingFiles", FALSE) == TRUE;
278 this->m_nLineAdded =this->m_nLineDeleted =0;
281 CGitStatusListCtrl::~CGitStatusListCtrl()
283 // if (m_pDropTarget)
284 // delete m_pDropTarget;
285 ClearStatusArray();
288 void CGitStatusListCtrl::ClearStatusArray()
290 #if 0
291 Locker lock(m_critSec);
292 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
294 delete m_arStatusArray[i];
296 m_arStatusArray.clear();
297 #endif
300 void CGitStatusListCtrl::Init(DWORD dwColumns, const CString& sColumnInfoContainer, unsigned __int64 dwContextMenus /* = GitSLC_POPALL */, bool bHasCheckboxes /* = true */, bool bHasWC /* = true */, DWORD allowedColumns /* = 0xffffffff */)
302 Locker lock(m_critSec);
304 m_dwDefaultColumns = dwColumns | 1;
305 m_dwContextMenus = dwContextMenus;
306 m_bHasCheckboxes = bHasCheckboxes;
307 m_bHasWC = bHasWC;
309 // set the extended style of the listcontrol
310 DWORD exStyle = LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_SUBITEMIMAGES;
311 exStyle |= (bHasCheckboxes ? LVS_EX_CHECKBOXES : 0);
312 SetRedraw(false);
313 SetExtendedStyle(exStyle);
314 CResizableColumnsListCtrl::Init();
316 SetWindowTheme(m_hWnd, L"Explorer", nullptr);
318 m_nIconFolder = SYS_IMAGE_LIST().GetDirIconIndex();
319 m_nRestoreOvl = SYS_IMAGE_LIST().AddIcon((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_RESTOREOVL), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));
320 SYS_IMAGE_LIST().SetOverlayImage(m_nRestoreOvl, OVL_RESTORE);
321 SetImageList(&SYS_IMAGE_LIST(), LVSIL_SMALL);
323 // keep CSorter::operator() in sync!!
324 static UINT standardColumnNames[GITSLC_NUMCOLUMNS]
325 = { IDS_STATUSLIST_COLFILE
326 , IDS_STATUSLIST_COLFILENAME
327 , IDS_STATUSLIST_COLEXT
328 , IDS_STATUSLIST_COLSTATUS
329 , IDS_STATUSLIST_COLADD
330 , IDS_STATUSLIST_COLDEL
331 , IDS_STATUSLIST_COLLASTMODIFIED
332 , IDS_STATUSLIST_COLSIZE
335 m_ColumnManager.SetNames(standardColumnNames,GITSLC_NUMCOLUMNS);
336 m_ColumnManager.ReadSettings(m_dwDefaultColumns, 0xffffffff & ~(allowedColumns | m_dwDefaultColumns), sColumnInfoContainer, GITSLC_NUMCOLUMNS);
337 m_ColumnManager.SetRightAlign(4);
338 m_ColumnManager.SetRightAlign(5);
339 m_ColumnManager.SetRightAlign(7);
341 // enable file drops
342 #if 0
343 if (!m_pDropTarget)
345 m_pDropTarget = new CGitStatusListCtrlDropTarget(this);
346 RegisterDragDrop(m_hWnd,m_pDropTarget);
347 // create the supported formats:
348 FORMATETC ftetc={0};
349 ftetc.dwAspect = DVASPECT_CONTENT;
350 ftetc.lindex = -1;
351 ftetc.tymed = TYMED_HGLOBAL;
352 ftetc.cfFormat=CF_HDROP;
353 m_pDropTarget->AddSuportedFormat(ftetc);
355 #endif
357 SetRedraw(true);
360 bool CGitStatusListCtrl::SetBackgroundImage(UINT nID)
362 return CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), nID);
365 BOOL CGitStatusListCtrl::GetStatus ( const CTGitPathList* pathList
366 , bool bUpdate /* = FALSE */
367 , bool bShowIgnores /* = false */
368 , bool bShowUnRev /* = false */
369 , bool bShowLocalChangesIgnored /* = false */)
371 m_bBusy = true;
372 m_bEmpty = false;
373 Invalidate();
375 m_bIsRevertTheirMy = g_Git.IsRebaseRunning() > 0;
377 Locker lock(m_critSec);
378 int mask= CGitStatusListCtrl::FILELIST_MODIFY;
379 if(bShowIgnores)
380 mask|= CGitStatusListCtrl::FILELIST_IGNORE;
381 if(bShowUnRev)
382 mask|= CGitStatusListCtrl::FILELIST_UNVER;
383 if (bShowLocalChangesIgnored)
384 mask |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
385 this->UpdateFileList(mask,bUpdate,(CTGitPathList*)pathList);
387 if (pathList && m_mapDirectFiles.empty())
389 // remember files which are selected by users so that those can be preselected
390 for (int i = 0; i < pathList->GetCount(); ++i)
391 if (!(*pathList)[i].IsDirectory())
392 m_mapDirectFiles[(*pathList)[i].GetGitPathString()] = true;
395 #if 0
396 int refetchcounter = 0;
397 BOOL bRet = TRUE;
398 Invalidate();
399 // force the cursor to change
400 POINT pt;
401 GetCursorPos(&pt);
402 SetCursorPos(pt.x, pt.y);
404 m_mapFilenameToChecked.clear();
405 //m_StatusUrlList.Clear();
406 bool bHasChangelists = (m_changelists.size() > 1 || (!m_changelists.empty() && !m_bHasIgnoreGroup));
407 m_changelists.clear();
408 for (size_t i=0; i < m_arStatusArray.size(); i++)
410 FileEntry * entry = m_arStatusArray[i];
411 if ( bHasChangelists && entry->checked)
413 // If change lists are present, remember all checked entries
414 CString path = entry->GetPath().GetGitPathString();
415 m_mapFilenameToChecked[path] = true;
417 if ( (entry->status==git_wc_status_unversioned || entry->status==git_wc_status_missing ) && entry->checked )
419 // The user manually selected an unversioned or missing file. We remember
420 // this so that the selection can be restored when refreshing.
421 CString path = entry->GetPath().GetGitPathString();
422 m_mapFilenameToChecked[path] = true;
424 else if ( entry->status > git_wc_status_normal && !entry->checked )
426 // The user manually deselected a versioned file. We remember
427 // this so that the deselection can be restored when refreshing.
428 CString path = entry->GetPath().GetGitPathString();
429 m_mapFilenameToChecked[path] = false;
433 // use a sorted path list to make sure we fetch the status of
434 // parent items first, *then* the child items (if any)
435 CTGitPathList sortedPathList = pathList;
436 sortedPathList.SortByPathname();
439 bRet = TRUE;
440 m_nTargetCount = 0;
441 m_bHasExternalsFromDifferentRepos = FALSE;
442 m_bHasExternals = FALSE;
443 m_bHasUnversionedItems = FALSE;
444 m_bHasLocks = false;
445 m_bHasChangeLists = false;
446 m_bShowIgnores = bShowIgnores;
447 m_nSortedColumn = 0;
448 m_bBlock = TRUE;
449 m_bBusy = true;
450 m_bEmpty = false;
451 Invalidate();
453 // first clear possible status data left from
454 // previous GetStatus() calls
455 ClearStatusArray();
457 m_StatusFileList = sortedPathList;
459 // Since Git_client_status() returns all files, even those in
460 // folders included with Git:externals we need to check if all
461 // files we get here belongs to the same repository.
462 // It is possible to commit changes in an external folder, as long
463 // as the folder belongs to the same repository (but another path),
464 // but it is not possible to commit all files if the externals are
465 // from a different repository.
467 // To check if all files belong to the same repository, we compare the
468 // UUID's - if they're identical then the files belong to the same
469 // repository and can be committed. But if they're different, then
470 // tell the user to commit all changes in the external folders
471 // first and exit.
472 CStringA sUUID; // holds the repo UUID
473 CTGitPathList arExtPaths; // list of Git:external paths
475 GitConfig config;
477 m_sURL.Empty();
479 m_nTargetCount = sortedPathList.GetCount();
481 GitStatus status(m_pbCanceled);
482 if(m_nTargetCount > 1 && sortedPathList.AreAllPathsFilesInOneDirectory())
484 // This is a special case, where we've been given a list of files
485 // all from one folder
486 // We handle them by setting a status filter, then requesting the Git status of
487 // all the files in the directory, filtering for the ones we're interested in
488 status.SetFilter(sortedPathList);
490 // if all selected entries are files, we don't do a recursive status
491 // fetching. But if only one is a directory, we have to recurse.
492 git_depth_t depth = git_depth_files;
493 // We have set a filter. If all selected items were files or we fetch
494 // the status not recursively, then we have to include
495 // ignored items too - the user has selected them
496 bool bShowIgnoresRight = true;
497 for (int fcindex=0; fcindex<sortedPathList.GetCount(); ++fcindex)
499 if (sortedPathList[fcindex].IsDirectory())
501 depth = git_depth_infinity;
502 bShowIgnoresRight = false;
503 break;
506 if(!FetchStatusForSingleTarget(config, status, sortedPathList.GetCommonDirectory(), bUpdate, sUUID, arExtPaths, true, depth, bShowIgnoresRight))
507 bRet = FALSE;
509 else
511 for(int nTarget = 0; nTarget < m_nTargetCount; nTarget++)
513 // check whether the path we want the status for is already fetched due to status-fetching
514 // of a parent path.
515 // this check is only done for file paths, because folder paths could be included already
516 // but not recursively
517 if (sortedPathList[nTarget].IsDirectory() || !GetListEntry(sortedPathList[nTarget]))
519 if(!FetchStatusForSingleTarget(config, status, sortedPathList[nTarget], bUpdate, sUUID,
520 arExtPaths, false, git_depth_infinity, bShowIgnores))
522 bRet = FALSE;
528 // remove the 'helper' files of conflicted items from the list.
529 // otherwise they would appear as unversioned files.
530 for (INT_PTR cind = 0; cind < m_ConflictFileList.GetCount(); ++cind)
532 for (size_t i=0; i < m_arStatusArray.size(); i++)
534 if (m_arStatusArray[i]->GetPath().IsEquivalentTo(m_ConflictFileList[cind]))
536 delete m_arStatusArray[i];
537 m_arStatusArray.erase(m_arStatusArray.cbegin() + i);
538 break;
542 refetchcounter++;
543 } while(!BuildStatistics() && (refetchcounter < 2) && (*m_pbCanceled==false));
545 m_bBlock = FALSE;
546 m_bBusy = false;
547 GetCursorPos(&pt);
548 SetCursorPos(pt.x, pt.y);
549 return bRet;
550 #endif
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_incomplete:
568 return GITSLC_SHOWINCOMPLETE;
569 case git_wc_status_normal:
570 return GITSLC_SHOWNORMAL;
571 case git_wc_status_external:
572 return GITSLC_SHOWEXTERNAL;
573 case git_wc_status_added:
574 return GITSLC_SHOWADDED;
575 case git_wc_status_missing:
576 return GITSLC_SHOWMISSING;
577 case git_wc_status_deleted:
578 return GITSLC_SHOWREMOVED;
579 case git_wc_status_replaced:
580 return GITSLC_SHOWREPLACED;
581 case git_wc_status_modified:
582 return GITSLC_SHOWMODIFIED;
583 case git_wc_status_merged:
584 return GITSLC_SHOWMERGED;
585 case git_wc_status_conflicted:
586 return GITSLC_SHOWCONFLICTED;
587 case git_wc_status_obstructed:
588 return GITSLC_SHOWOBSTRUCTED;
589 default:
590 // we should NEVER get here!
591 ASSERT(FALSE);
592 break;
594 return 0;
597 void CGitStatusListCtrl::Show(unsigned int dwShow, unsigned int dwCheck /*=0*/, bool /*bShowFolders*/ /* = true */,BOOL UpdateStatusList,bool UseStoredCheckStatus)
599 m_bBusy = true;
600 m_bEmpty = false;
601 Invalidate();
603 CWinApp * pApp = AfxGetApp();
604 if (pApp)
605 pApp->DoWaitCursor(1);
607 Locker lock(m_critSec);
608 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
610 //SetItemCount(listIndex);
611 SetRedraw(FALSE);
612 DeleteAllItems();
613 m_nSelected = 0;
615 m_nShownUnversioned = 0;
616 m_nShownModified = 0;
617 m_nShownAdded = 0;
618 m_nShownDeleted = 0;
619 m_nShownConflicted = 0;
620 m_nShownFiles = 0;
621 m_nShownSubmodules = 0;
623 m_dwShow = dwShow;
625 if(UpdateStatusList)
627 m_arStatusArray.clear();
628 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
629 m_arStatusArray.push_back((CTGitPath*)&m_StatusFileList[i]);
631 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
632 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
634 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
635 m_arStatusArray.push_back((CTGitPath*)&m_IgnoreFileList[i]);
637 PrepareGroups();
638 if (m_nSortedColumn >= 0)
640 CSorter predicate (&m_ColumnManager, m_nSortedColumn, m_bAscending);
641 std::sort(m_arStatusArray.begin(), m_arStatusArray.end(), predicate);
644 int index =0;
645 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
647 //set default checkbox status
648 CTGitPath* entry = ((CTGitPath*)m_arStatusArray[i]);
649 CString path = entry->GetGitPathString();
650 if (!m_mapFilenameToChecked.empty() && m_mapFilenameToChecked.find(path) != m_mapFilenameToChecked.end())
651 entry->m_Checked=m_mapFilenameToChecked[path];
652 else if (!UseStoredCheckStatus)
654 bool autoSelectSubmodules = !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules);
655 if (((entry->m_Action & dwCheck) && !(m_bNoAutoselectMissing && entry->m_Action & CTGitPath::LOGACTIONS_MISSING) || dwShow & GITSLC_SHOWDIRECTFILES && m_mapDirectFiles.find(path) != m_mapDirectFiles.end()) && autoSelectSubmodules)
656 entry->m_Checked=true;
657 else
658 entry->m_Checked=false;
659 m_mapFilenameToChecked[path] = entry->m_Checked;
662 if(entry->m_Action & dwShow)
664 AddEntry(entry,langID,index);
665 index++;
669 AdjustColumnWidths();
671 SetRedraw(TRUE);
672 GetStatisticsString();
674 CHeaderCtrl * pHeader = GetHeaderCtrl();
675 HDITEM HeaderItem = {0};
676 HeaderItem.mask = HDI_FORMAT;
677 for (int i=0; i<pHeader->GetItemCount(); ++i)
679 pHeader->GetItem(i, &HeaderItem);
680 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
681 pHeader->SetItem(i, &HeaderItem);
683 if (m_nSortedColumn >= 0)
685 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
686 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
687 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
690 #if 0
691 if (nSelectedEntry)
693 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
694 EnsureVisible(nSelectedEntry, false);
696 else
698 // Restore the item at the top of the list.
699 for (int i=0;GetTopIndex() != nTopIndex;i++)
701 if ( !EnsureVisible(nTopIndex+i,false) )
702 break;
705 #endif
706 if (pApp)
707 pApp->DoWaitCursor(-1);
709 m_bBusy = false;
710 m_bEmpty = (GetItemCount() == 0);
711 Invalidate();
713 this->BuildStatistics();
715 #if 0
717 CWinApp * pApp = AfxGetApp();
718 if (pApp)
719 pApp->DoWaitCursor(1);
721 m_bShowFolders = bShowFolders;
723 int nTopIndex = GetTopIndex();
724 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
725 int nSelectedEntry = 0;
726 if (posSelectedEntry)
727 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
728 SetRedraw(FALSE);
729 DeleteAllItems();
731 PrepareGroups();
733 m_arListArray.clear();
735 m_arListArray.reserve(m_arStatusArray.size());
736 SetItemCount (static_cast<int>(m_arStatusArray.size()));
738 int listIndex = 0;
739 for (size_t i=0; i < m_arStatusArray.size(); ++i)
741 FileEntry * entry = m_arStatusArray[i];
742 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
743 continue;
744 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
745 continue;
746 if (entry->IsFolder() && (!bShowFolders))
747 continue; // don't show folders if they're not wanted.
749 #if 0
750 git_wc_status_kind status = GitStatus::GetMoreImportant(entry->status, entry->remotestatus);
751 DWORD showFlags = GetShowFlagsFromGitStatus(status);
752 if (entry->IsLocked())
753 showFlags |= SVNSLC_SHOWLOCKS;
754 if (entry->switched)
755 showFlags |= SVNSLC_SHOWSWITCHED;
756 if (!entry->changelist.IsEmpty())
757 showFlags |= SVNSLC_SHOWINCHANGELIST;
758 #endif
759 bool bAllowCheck = ((entry->changelist.Compare(GITSLC_IGNORECHANGELIST) != 0)
760 && (m_bCheckIfGroupsExist || (m_changelists.empty() || (m_changelists.size() == 1 && m_bHasIgnoreGroup))));
762 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
763 #if 0
764 if (status != Git_wc_status_ignored || (entry->direct) || (dwShow & GitSLC_SHOWIGNORED))
766 if ((!entry->IsFolder()) && (status == Git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
768 if (PathFileExists(entry->GetPath().GetWinPath()))
770 m_arListArray.push_back(i);
771 if ((dwCheck & SVNSLC_SHOWREMOVEDANDPRESENT)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
773 if (bAllowCheck)
774 entry->checked = true;
776 AddEntry(entry, langID, listIndex++);
779 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
781 m_arListArray.push_back(i);
782 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
784 if (bAllowCheck)
785 entry->checked = true;
787 AddEntry(entry, langID, listIndex++);
789 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
791 m_arListArray.push_back(i);
792 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
794 if (bAllowCheck)
795 entry->checked = true;
797 AddEntry(entry, langID, listIndex++);
800 #endif
803 SetItemCount(listIndex);
805 m_ColumnManager.UpdateRelevance (m_arStatusArray, m_arListArray);
807 AdjustColumnWidths();
809 SetRedraw(TRUE);
810 GetStatisticsString();
812 CHeaderCtrl * pHeader = GetHeaderCtrl();
813 HDITEM HeaderItem = {0};
814 HeaderItem.mask = HDI_FORMAT;
815 for (int i=0; i<pHeader->GetItemCount(); ++i)
817 pHeader->GetItem(i, &HeaderItem);
818 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
819 pHeader->SetItem(i, &HeaderItem);
821 if (m_nSortedColumn)
823 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
824 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
825 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
828 if (nSelectedEntry)
830 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
831 EnsureVisible(nSelectedEntry, false);
833 else
835 // Restore the item at the top of the list.
836 for (int i=0;GetTopIndex() != nTopIndex;i++)
838 if ( !EnsureVisible(nTopIndex+i,false) )
839 break;
843 if (pApp)
844 pApp->DoWaitCursor(-1);
846 m_bEmpty = (GetItemCount() == 0);
847 Invalidate();
848 #endif
851 void CGitStatusListCtrl::Show(unsigned int /*dwShow*/, const CTGitPathList& checkedList, bool /*bShowFolders*/ /* = true */)
853 DeleteAllItems();
854 for (int i = 0; i < checkedList.GetCount(); ++i)
855 this->AddEntry((CTGitPath *)&checkedList[i],0,i);
857 AdjustColumnWidths();
858 return ;
859 #if 0
861 Locker lock(m_critSec);
862 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
864 CWinApp * pApp = AfxGetApp();
865 if (pApp)
866 pApp->DoWaitCursor(1);
867 m_dwShow = dwShow;
868 m_bShowFolders = bShowFolders;
869 m_nSelected = 0;
870 int nTopIndex = GetTopIndex();
871 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
872 int nSelectedEntry = 0;
873 if (posSelectedEntry)
874 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
875 SetRedraw(FALSE);
876 DeleteAllItems();
878 PrepareGroups();
880 m_arListArray.clear();
882 m_arListArray.reserve(m_arStatusArray.size());
883 SetItemCount (static_cast<int>(m_arStatusArray.size()));
885 int listIndex = 0;
886 for (size_t i=0; i < m_arStatusArray.size(); ++i)
888 FileEntry * entry = m_arStatusArray[i];
889 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
890 continue;
891 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
892 continue;
893 if (entry->IsFolder() && (!bShowFolders))
894 continue; // don't show folders if they're not wanted.
895 #if 0
896 git_wc_status_kind status = SVNStatus::GetMoreImportant(entry->status, entry->remotestatus);
897 DWORD showFlags = GetShowFlagsFromSVNStatus(status);
898 if (entry->IsLocked())
899 showFlags |= SVNSLC_SHOWLOCKS;
900 if (!entry->changelist.IsEmpty())
901 showFlags |= SVNSLC_SHOWINCHANGELIST;
903 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
904 if (status != git_wc_status_ignored || (entry->direct) || (dwShow & SVNSLC_SHOWIGNORED))
906 for (int npath = 0; npath < checkedList.GetCount(); ++npath)
908 if (entry->GetPath().IsEquivalentTo(checkedList[npath]))
910 entry->checked = true;
911 break;
914 if ((!entry->IsFolder()) && (status == git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
916 if (PathFileExists(entry->GetPath().GetWinPath()))
918 m_arListArray.push_back(i);
919 AddEntry(entry, langID, listIndex++);
922 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
924 m_arListArray.push_back(i);
925 AddEntry(entry, langID, listIndex++);
927 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
929 m_arListArray.push_back(i);
930 AddEntry(entry, langID, listIndex++);
932 else if (entry->switched)
934 m_arListArray.push_back(i);
935 AddEntry(entry, langID, listIndex++);
938 #endif
941 SetItemCount(listIndex);
943 AdjustColumnWidths();
945 SetRedraw(TRUE);
946 GetStatisticsString();
948 CHeaderCtrl * pHeader = GetHeaderCtrl();
949 HDITEM HeaderItem = {0};
950 HeaderItem.mask = HDI_FORMAT;
951 for (int i=0; i<pHeader->GetItemCount(); ++i)
953 pHeader->GetItem(i, &HeaderItem);
954 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
955 pHeader->SetItem(i, &HeaderItem);
957 if (m_nSortedColumn)
959 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
960 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
961 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
964 if (nSelectedEntry)
966 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
967 EnsureVisible(nSelectedEntry, false);
969 else
971 // Restore the item at the top of the list.
972 for (int i=0;GetTopIndex() != nTopIndex;i++)
974 if ( !EnsureVisible(nTopIndex+i,false) )
975 break;
979 if (pApp)
980 pApp->DoWaitCursor(-1);
982 m_bEmpty = (GetItemCount() == 0);
983 Invalidate();
984 #endif
986 int CGitStatusListCtrl::GetColumnIndex(int mask)
988 for (int i = 0; i < 32; ++i)
989 if(mask&0x1)
990 return i;
991 else
992 mask=mask>>1;
993 return -1;
995 void CGitStatusListCtrl::AddEntry(CTGitPath * GitPath, WORD /*langID*/, int listIndex)
997 static CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
998 static HINSTANCE hResourceHandle(AfxGetResourceHandle());
999 static bool abbreviateRenamings(((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\AbbreviateRenamings"), FALSE)) == TRUE);
1000 static bool relativeTimes = (CRegDWORD(_T("Software\\TortoiseGit\\RelativeTimes"), FALSE) != FALSE);
1002 CString path = GitPath->GetGitPathString();
1004 m_bBlock = TRUE;
1005 int index = listIndex;
1006 int nCol = 1;
1007 CString entryname = GitPath->GetGitPathString();
1008 int icon_idx = 0;
1009 if (GitPath->IsDirectory())
1011 icon_idx = m_nIconFolder;
1012 m_nShownSubmodules++;
1014 else
1016 icon_idx = SYS_IMAGE_LIST().GetPathIconIndex(*GitPath);
1017 m_nShownFiles++;
1019 switch (GitPath->m_Action)
1021 case CTGitPath::LOGACTIONS_ADDED:
1022 case CTGitPath::LOGACTIONS_COPY:
1023 m_nShownAdded++;
1024 break;
1025 case CTGitPath::LOGACTIONS_DELETED:
1026 case CTGitPath::LOGACTIONS_MISSING:
1027 case CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING:
1028 m_nShownDeleted++;
1029 break;
1030 case CTGitPath::LOGACTIONS_REPLACED:
1031 case CTGitPath::LOGACTIONS_MODIFIED:
1032 case CTGitPath::LOGACTIONS_MERGED:
1033 m_nShownModified++;
1034 break;
1035 case CTGitPath::LOGACTIONS_UNMERGED:
1036 m_nShownConflicted++;
1037 break;
1038 case CTGitPath::LOGACTIONS_UNVER:
1039 m_nShownUnversioned++;
1040 break;
1041 default:
1042 m_nShownUnversioned++;
1043 break;
1045 if(GitPath->m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !GitPath->GetGitOldPathString().IsEmpty())
1047 if (!abbreviateRenamings)
1049 entryname += L' ';
1050 // relative path
1051 entryname.AppendFormat(from, (LPCTSTR)GitPath->GetGitOldPathString());
1053 else
1054 entryname = GitPath->GetAbbreviatedRename();
1057 InsertItem(index, entryname, icon_idx);
1058 if (m_restorepaths.find(GitPath->GetWinPathString()) != m_restorepaths.end())
1059 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), TVIS_OVERLAYMASK);
1061 this->SetItemData(index, (DWORD_PTR)GitPath);
1062 // SVNSLC_COLFILENAME
1063 SetItemText(index, nCol++, GitPath->GetFileOrDirectoryName());
1064 // SVNSLC_COLEXT
1065 SetItemText(index, nCol++, GitPath->GetFileExtension());
1066 // SVNSLC_COLSTATUS
1067 SetItemText(index, nCol++, GitPath->GetActionName());
1069 SetItemText(index, GetColumnIndex(GITSLC_COLADD),GitPath->m_StatAdd);
1070 SetItemText(index, GetColumnIndex(GITSLC_COLDEL),GitPath->m_StatDel);
1073 CString modificationDate;
1074 __int64 filetime = GitPath->GetLastWriteTime();
1075 if (filetime && !(GitPath->m_Action & CTGitPath::LOGACTIONS_DELETED))
1077 FILETIME* f = (FILETIME*)(__int64*)&filetime;
1078 modificationDate = CLoglistUtils::FormatDateAndTime(CTime(CGit::filetime_to_time_t(f)), DATE_SHORTDATE, true, relativeTimes);
1080 SetItemText(index, GetColumnIndex(GITSLC_COLMODIFICATIONDATE), modificationDate);
1082 // SVNSLC_COLSIZE
1083 if (GitPath->IsDirectory())
1084 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), _T(""));
1085 else
1087 TCHAR buf[100] = { 0 };
1088 StrFormatByteSize64(GitPath->GetFileSize(), buf, 100);
1089 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), buf);
1092 SetCheck(index, GitPath->m_Checked);
1093 if (GitPath->m_Checked)
1094 m_nSelected++;
1096 if ((GitPath->m_Action & CTGitPath::LOGACTIONS_SKIPWORKTREE) || (GitPath->m_Action & CTGitPath::LOGACTIONS_ASSUMEVALID))
1097 SetItemGroup(index, 3);
1098 else if (GitPath->m_Action & CTGitPath::LOGACTIONS_IGNORE)
1099 SetItemGroup(index, 2);
1100 else if( GitPath->m_Action & CTGitPath::LOGACTIONS_UNVER)
1101 SetItemGroup(index,1);
1102 else
1103 SetItemGroup(index, GitPath->m_ParentNo&(PARENT_MASK|MERGE_MASK));
1105 m_bBlock = FALSE;
1108 bool CGitStatusListCtrl::SetItemGroup(int item, int groupindex)
1110 // if (!(m_dwContextMenus & SVNSLC_POPCHANGELISTS))
1111 // return false;
1112 if (groupindex < 0)
1113 return false;
1114 LVITEM i = {0};
1115 i.mask = LVIF_GROUPID;
1116 i.iItem = item;
1117 i.iSubItem = 0;
1118 i.iGroupId = groupindex;
1120 return !!SetItem(&i);
1123 void CGitStatusListCtrl::OnHdnItemclick(NMHDR *pNMHDR, LRESULT *pResult)
1125 LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
1126 *pResult = 0;
1127 if (m_bBlock || m_arStatusArray.empty())
1128 return;
1129 m_bBlock = TRUE;
1130 if (m_nSortedColumn == phdr->iItem)
1131 m_bAscending = !m_bAscending;
1132 else
1133 m_bAscending = TRUE;
1134 m_nSortedColumn = phdr->iItem;
1135 Show(m_dwShow, 0, m_bShowFolders,false,true);
1137 m_bBlock = FALSE;
1140 void CGitStatusListCtrl::OnLvnItemchanging(NMHDR *pNMHDR, LRESULT *pResult)
1142 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
1143 *pResult = 0;
1145 #define ISCHECKED(x) ((x) ? ((((x)&LVIS_STATEIMAGEMASK)>>12)-1) : FALSE)
1146 if ((m_bBlock)&&(m_bBlockUI))
1148 // if we're blocked, prevent changing of the check state
1149 if ((!ISCHECKED(pNMLV->uOldState) && ISCHECKED(pNMLV->uNewState))||
1150 (ISCHECKED(pNMLV->uOldState) && !ISCHECKED(pNMLV->uNewState)))
1151 *pResult = TRUE;
1155 BOOL CGitStatusListCtrl::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
1157 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
1158 *pResult = 0;
1159 CWnd* pParent = GetLogicalParent();
1160 if (pParent && pParent->GetSafeHwnd())
1161 pParent->SendMessage(GITSLNM_ITEMCHANGED, pNMLV->iItem);
1163 if ((pNMLV->uNewState==0)||(pNMLV->uNewState & LVIS_SELECTED)||(pNMLV->uNewState & LVIS_FOCUSED))
1164 return FALSE;
1166 if (m_bBlock)
1167 return FALSE;
1169 bool bSelected = !!(ListView_GetItemState(m_hWnd, pNMLV->iItem, LVIS_SELECTED) & LVIS_SELECTED);
1170 int nListItems = GetItemCount();
1172 m_bBlock = TRUE;
1173 // was the item checked?
1175 //CTGitPath *gitpath=(CTGitPath*)GetItemData(pNMLV->iItem);
1176 //gitpath->m_Checked=GetCheck(pNMLV->iItem);
1178 if (GetCheck(pNMLV->iItem))
1180 CheckEntry(pNMLV->iItem, nListItems);
1181 if (bSelected)
1183 POSITION pos = GetFirstSelectedItemPosition();
1184 int index;
1185 while ((index = GetNextSelectedItem(pos)) >= 0)
1187 if (index != pNMLV->iItem)
1188 CheckEntry(index, nListItems);
1192 else
1194 UncheckEntry(pNMLV->iItem, nListItems);
1195 if (bSelected)
1197 POSITION pos = GetFirstSelectedItemPosition();
1198 int index;
1199 while ((index = GetNextSelectedItem(pos)) >= 0)
1201 if (index != pNMLV->iItem)
1202 UncheckEntry(index, nListItems);
1207 GetStatisticsString();
1208 m_bBlock = FALSE;
1209 NotifyCheck();
1211 return FALSE;
1214 void CGitStatusListCtrl::CheckEntry(int index, int /*nListItems*/)
1216 Locker lock(m_critSec);
1217 //FileEntry * entry = GetListEntry(index);
1218 CTGitPath *path=(CTGitPath*)GetItemData(index);
1219 ASSERT(path);
1220 if (!path)
1221 return;
1222 m_mapFilenameToChecked[path->GetGitPathString()] = true;
1223 SetCheck(index, TRUE);
1224 //entry = GetListEntry(index);
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 Locker lock(m_critSec);
1291 CTGitPath *path=(CTGitPath*)GetItemData(index);
1292 ASSERT(path);
1293 if (!path)
1294 return;
1295 SetCheck(index, FALSE);
1296 m_mapFilenameToChecked[path->GetGitPathString()] = false;
1297 //entry = GetListEntry(index);
1298 // item was unchecked
1299 #if 0
1300 if (entry->path.IsDirectory())
1302 // disable all files within an unselected folder, except when unchecking a folder with property changes
1303 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1304 if ( (entry->status != git_wc_status_modified) || (bShift) )
1306 SetCheckOnAllDescendentsOf(entry, false);
1309 else if (entry->status == git_wc_status_deleted)
1311 // a "deleted" file was unchecked, so uncheck all parent folders
1312 // and all children of those parents
1313 for (int i=0; i<nListItems; i++)
1315 FileEntry * testEntry = GetListEntry(i);
1316 ASSERT(testEntry);
1317 if (!testEntry)
1318 continue;
1319 if (testEntry->checked)
1321 if (testEntry->path.IsAncestorOf(entry->path))
1323 if (testEntry->status == git_wc_status_deleted)
1325 SetEntryCheck(testEntry,i,false);
1326 m_nSelected--;
1328 SetCheckOnAllDescendentsOf(testEntry, false);
1334 #endif
1335 if ( path->m_Checked )
1337 path->m_Checked = FALSE;
1338 m_nSelected--;
1341 bool CGitStatusListCtrl::BuildStatistics()
1343 bool bRefetchStatus = false;
1345 // now gather some statistics
1346 m_nUnversioned = 0;
1347 m_nNormal = 0;
1348 m_nModified = 0;
1349 m_nAdded = 0;
1350 m_nDeleted = 0;
1351 m_nConflicted = 0;
1352 m_nTotal = 0;
1353 m_nSelected = 0;
1354 m_nLineAdded = 0;
1355 m_nLineDeleted = 0;
1356 m_nRenamed = 0;
1358 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
1360 int status=((CTGitPath*)m_arStatusArray[i])->m_Action;
1362 m_nLineAdded += _tstol(((CTGitPath*)m_arStatusArray[i])->m_StatAdd);
1363 m_nLineDeleted += _tstol(((CTGitPath*)m_arStatusArray[i])->m_StatDel);
1365 if(status&(CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
1366 m_nAdded++;
1368 if(status&CTGitPath::LOGACTIONS_DELETED)
1369 m_nDeleted++;
1371 if(status&(CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_MODIFIED))
1372 m_nModified++;
1374 if(status&CTGitPath::LOGACTIONS_UNMERGED)
1375 m_nConflicted++;
1377 if(status&(CTGitPath::LOGACTIONS_IGNORE|CTGitPath::LOGACTIONS_UNVER))
1378 m_nUnversioned++;
1380 if(status&(CTGitPath::LOGACTIONS_REPLACED))
1381 m_nRenamed++;
1383 if(((CTGitPath*)m_arStatusArray[i])->m_Checked)
1384 m_nSelected++;
1386 return !bRefetchStatus;
1390 int CGitStatusListCtrl::GetGroupFromPoint(POINT * ppt)
1392 // the point must be relative to the upper left corner of the control
1394 if (!ppt)
1395 return -1;
1396 if (!IsGroupViewEnabled())
1397 return -1;
1399 POINT pt = *ppt;
1400 pt.x = 10;
1401 UINT flags = 0;
1402 int nItem = -1;
1403 RECT rc;
1404 GetWindowRect(&rc);
1405 while (((flags & LVHT_BELOW) == 0)&&(pt.y < rc.bottom))
1407 nItem = HitTest(pt, &flags);
1408 if ((flags & LVHT_ONITEM)||(flags & LVHT_EX_GROUP_HEADER))
1410 // the first item below the point
1412 // check if the point is too much right (i.e. if the point
1413 // is farther to the right than the width of the item)
1414 RECT r;
1415 GetItemRect(nItem, &r, LVIR_LABEL);
1416 if (ppt->x > r.right)
1417 return -1;
1419 LVITEM lv = {0};
1420 lv.mask = LVIF_GROUPID;
1421 lv.iItem = nItem;
1422 GetItem(&lv);
1423 int groupID = lv.iGroupId;
1424 // now we search upwards and check if the item above this one
1425 // belongs to another group. If it belongs to the same group,
1426 // we're not over a group header
1427 while (pt.y >= 0)
1429 pt.y -= 2;
1430 nItem = HitTest(pt, &flags);
1431 if ((flags & LVHT_ONITEM)&&(nItem >= 0))
1433 // the first item below the point
1434 LVITEM lv2 = {0};
1435 lv2.mask = LVIF_GROUPID;
1436 lv2.iItem = nItem;
1437 GetItem(&lv2);
1438 if (lv2.iGroupId != groupID)
1439 return groupID;
1440 else
1441 return -1;
1444 if (pt.y < 0)
1445 return groupID;
1446 return -1;
1448 pt.y += 2;
1450 return -1;
1453 void CGitStatusListCtrl::OnContextMenuGroup(CWnd * /*pWnd*/, CPoint point)
1455 POINT clientpoint = point;
1456 ScreenToClient(&clientpoint);
1457 if ((IsGroupViewEnabled())&&(GetGroupFromPoint(&clientpoint) >= 0))
1459 CMenu popup;
1460 if (popup.CreatePopupMenu())
1462 CString temp;
1463 temp.LoadString(IDS_STATUSLIST_CHECKGROUP);
1464 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_CHECKGROUP, temp);
1465 temp.LoadString(IDS_STATUSLIST_UNCHECKGROUP);
1466 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_UNCHECKGROUP, temp);
1467 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this, 0);
1468 bool bCheck = false;
1469 switch (cmd)
1471 case IDGITLC_CHECKGROUP:
1472 bCheck = true;
1473 // fall through here
1474 case IDGITLC_UNCHECKGROUP:
1476 int group = GetGroupFromPoint(&clientpoint);
1477 // go through all items and check/uncheck those assigned to the group
1478 // but block the OnLvnItemChanged handler
1479 m_bBlock = true;
1480 for (int i=0; i<GetItemCount(); ++i)
1482 LVITEM lv = { 0 };
1483 lv.mask = LVIF_GROUPID;
1484 lv.iItem = i;
1485 GetItem(&lv);
1487 if (lv.iGroupId == group)
1489 CTGitPath * entry = (CTGitPath*)GetItemData(i);
1490 if (entry)
1492 bool bOldCheck = entry->m_Checked;
1493 SetEntryCheck(entry, i, bCheck);
1494 if (bCheck != bOldCheck)
1496 if (bCheck)
1497 m_nSelected++;
1498 else
1499 m_nSelected--;
1505 GetStatisticsString();
1506 NotifyCheck();
1507 m_bBlock = false;
1509 break;
1515 void CGitStatusListCtrl::OnContextMenuList(CWnd * pWnd, CPoint point)
1517 //WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1519 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1520 CTGitPath * filepath;
1522 int selIndex = GetSelectionMark();
1523 if ((point.x == -1) && (point.y == -1))
1525 CRect rect;
1526 GetItemRect(selIndex, &rect, LVIR_LABEL);
1527 ClientToScreen(&rect);
1528 point = rect.CenterPoint();
1530 if ((GetSelectedCount() == 0) && (m_bHasCheckboxes))
1532 // nothing selected could mean the context menu is requested for
1533 // a group header
1534 OnContextMenuGroup(pWnd, point);
1536 else if (selIndex >= 0)
1538 //FileEntry * entry = GetListEntry(selIndex);
1540 filepath = (CTGitPath * )GetItemData(selIndex);
1542 ASSERT(filepath);
1543 if (!filepath)
1544 return;
1546 //const CTGitPath& filepath = entry->path;
1547 int wcStatus = filepath->m_Action;
1548 // entry is selected, now show the popup menu
1549 Locker lock(m_critSec);
1550 CIconMenu popup;
1551 CMenu changelistSubMenu;
1552 CMenu ignoreSubMenu;
1553 CMenu shellMenu;
1554 if (popup.CreatePopupMenu())
1556 //Add Menu for version controlled file
1558 if (GetSelectedCount() > 0 && wcStatus & CTGitPath::LOGACTIONS_UNMERGED)
1560 if (GetSelectedCount() == 1 && (m_dwContextMenus & GITSLC_POPCONFLICT)/*&&(entry->textstatus == git_wc_status_conflicted)*/)
1562 popup.AppendMenuIcon(IDGITLC_EDITCONFLICT, IDS_MENUCONFLICT, IDI_CONFLICT);
1563 popup.SetDefaultItem(IDGITLC_EDITCONFLICT, FALSE);
1565 if (m_dwContextMenus & GITSLC_POPRESOLVE)
1566 popup.AppendMenuIcon(IDGITLC_RESOLVECONFLICT, IDS_STATUSLIST_CONTEXT_RESOLVED, IDI_RESOLVE);
1567 if ((m_dwContextMenus & GITSLC_POPRESOLVE)/*&&(entry->textstatus == git_wc_status_conflicted)*/)
1569 popup.AppendMenuIcon(IDGITLC_RESOLVETHEIRS, IDS_SVNPROGRESS_MENUUSETHEIRS, IDI_RESOLVE);
1570 popup.AppendMenuIcon(IDGITLC_RESOLVEMINE, IDS_SVNPROGRESS_MENUUSEMINE, IDI_RESOLVE);
1572 if ((m_dwContextMenus & GITSLC_POPCONFLICT)||(m_dwContextMenus & GITSLC_POPRESOLVE))
1573 popup.AppendMenu(MF_SEPARATOR);
1576 if (GetSelectedCount() > 0)
1578 if (wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
1580 if (m_dwContextMenus & GITSLC_POPADD)
1582 //if ( entry->IsFolder() )
1584 // popup.AppendMenuIcon(IDSVNLC_ADD_RECURSIVE, IDS_STATUSLIST_CONTEXT_ADD_RECURSIVE, IDI_ADD);
1586 //else
1588 popup.AppendMenuIcon(IDGITLC_ADD, IDS_STATUSLIST_CONTEXT_ADD, IDI_ADD);
1591 if (m_dwContextMenus & GITSLC_POPCOMMIT)
1592 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1596 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)) && GetSelectedCount() > 0)
1598 bool bEntryAdded = false;
1599 if (m_dwContextMenus & GITSLC_POPCOMPAREWITHBASE)
1601 if(filepath->m_ParentNo & MERGE_MASK)
1602 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_TREE_DIFF, IDI_DIFF);
1603 else
1604 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_LOG_COMPAREWITHBASE, IDI_DIFF);
1606 if (!(wcStatus & (CTGitPath::LOGACTIONS_UNMERGED)) || GetSelectedCount() != 1)
1607 popup.SetDefaultItem(IDGITLC_COMPARE, FALSE);
1608 bEntryAdded = true;
1611 if (!g_Git.IsInitRepos() && (m_dwContextMenus & GITSLC_POPGNUDIFF))
1613 popup.AppendMenuIcon(IDGITLC_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1614 bEntryAdded = true;
1617 if ((m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPAREWC)) && m_bHasWC)
1619 if ((!m_CurrentVersion.IsEmpty()) && m_CurrentVersion != GIT_REV_ZERO)
1621 popup.AppendMenuIcon(IDGITLC_COMPAREWC, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1622 bEntryAdded = true;
1626 if (bEntryAdded)
1627 popup.AppendMenu(MF_SEPARATOR);
1630 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
1632 if(GetSelectedCount() == 1)
1634 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPARETWOREVISIONS))
1636 popup.AppendMenuIcon(IDGITLC_COMPARETWOREVISIONS, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
1637 popup.SetDefaultItem(IDGITLC_COMPARETWOREVISIONS, FALSE);
1639 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_GNUDIFF2REVISIONS))
1640 popup.AppendMenuIcon(IDGITLC_GNUDIFF2REVISIONS, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1644 //Select Multi item
1645 if (GetSelectedCount() > 0)
1647 if ((GetSelectedCount() == 2) && (m_dwContextMenus & GITSLC_POPCOMPARETWOFILES) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO))
1649 POSITION pos = GetFirstSelectedItemPosition();
1650 int index = GetNextSelectedItem(pos);
1651 if (index >= 0)
1653 CTGitPath* entry2 = nullptr;
1654 entry2 = (CTGitPath*)GetItemData(index);
1655 bool firstEntryExistsAndIsFile = entry2 && !entry2->IsDirectory();
1656 index = GetNextSelectedItem(pos);
1657 if (index >= 0)
1659 entry2 = (CTGitPath * )GetItemData(index);
1660 if (firstEntryExistsAndIsFile && entry2 && !entry2->IsDirectory())
1661 popup.AppendMenuIcon(IDGITLC_COMPARETWOFILES, IDS_STATUSLIST_CONTEXT_COMPARETWOFILES, IDI_DIFF);
1667 if ( (GetSelectedCount() >0 ) && (!(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))) && m_bHasWC)
1669 if ((m_dwContextMenus & GITSLC_POPCOMMIT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && !(wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1670 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1672 if ((m_dwContextMenus & GITSLC_POPREVERT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO))
1673 popup.AppendMenuIcon(IDGITLC_REVERT, IDS_MENUREVERT, IDI_REVERT);
1675 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)))
1676 popup.AppendMenuIcon(IDGITLC_SKIPWORKTREE, IDS_STATUSLIST_SKIPWORKTREE);
1678 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)))
1679 popup.AppendMenuIcon(IDGITLC_ASSUMEVALID, IDS_MENUASSUMEVALID);
1681 if ((m_dwContextMenus & GITLC_POPUNSETIGNORELOCALCHANGES) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && (wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1682 popup.AppendMenuIcon(IDGITLC_UNSETIGNORELOCALCHANGES, IDS_STATUSLIST_UNSETIGNORELOCALCHANGES);
1684 if (m_dwContextMenus & GITSLC_POPRESTORE && !filepath->IsDirectory())
1686 if (m_restorepaths.find(filepath->GetWinPathString()) == m_restorepaths.end())
1687 popup.AppendMenuIcon(IDGITLC_CREATERESTORE, IDS_MENUCREATERESTORE, IDI_RESTORE);
1688 else
1689 popup.AppendMenuIcon(IDGITLC_RESTOREPATH, IDS_MENURESTORE, IDI_RESTORE);
1692 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOREV)) && ( !this->m_CurrentVersion.IsEmpty() )
1693 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1695 popup.AppendMenuIcon(IDGITLC_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
1698 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOPARENT)) && ( !this->m_CurrentVersion.IsEmpty() )
1699 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_ADDED))
1701 popup.AppendMenuIcon(IDGITLC_REVERTTOPARENT, IDS_LOG_POPUP_REVERTTOPARENT, IDI_REVERT);
1705 if ((GetSelectedCount() == 1)&&(!(wcStatus & CTGitPath::LOGACTIONS_UNVER))
1706 &&(!(wcStatus & CTGitPath::LOGACTIONS_IGNORE)))
1708 if (m_dwContextMenus & GITSLC_POPSHOWLOG)
1709 popup.AppendMenuIcon(IDGITLC_LOG, IDS_REPOBROWSE_SHOWLOG, IDI_LOG);
1710 if (m_dwContextMenus & GITSLC_POPSHOWLOGSUBMODULE && filepath->IsDirectory())
1711 popup.AppendMenuIcon(IDGITLC_LOGSUBMODULE, IDS_LOG_SUBMODULE, IDI_LOG);
1712 if (m_dwContextMenus & GITSLC_POPSHOWLOGOLDNAME && (wcStatus & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !filepath->GetGitOldPathString().IsEmpty()))
1713 popup.AppendMenuIcon(IDGITLC_LOGOLDNAME, IDS_STATUSLIST_SHOWLOGOLDNAME, IDI_LOG);
1714 if (m_dwContextMenus & GITSLC_POPBLAME && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC)
1715 popup.AppendMenuIcon(IDGITLC_BLAME, IDS_MENUBLAME, IDI_BLAME);
1718 if (GetSelectedCount() > 0)
1720 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_EXPORT)) && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)))
1721 popup.AppendMenuIcon(IDGITLC_EXPORT, IDS_LOG_POPUP_EXPORT, IDI_EXPORT);
1724 // if ((wcStatus != git_wc_status_deleted)&&(wcStatus != git_wc_status_missing) && (GetSelectedCount() == 1))
1725 if ( (GetSelectedCount() == 1) )
1727 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_SAVEAS) && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1728 popup.AppendMenuIcon(IDGITLC_SAVEAS, IDS_LOG_POPUP_SAVE, IDI_SAVEAS);
1730 if (m_dwContextMenus & GITSLC_POPOPEN && !filepath->IsDirectory() && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)))
1732 popup.AppendMenuIcon(IDGITLC_VIEWREV, IDS_LOG_POPUP_VIEWREV);
1733 popup.AppendMenuIcon(IDGITLC_OPEN, IDS_REPOBROWSE_OPEN, IDI_OPEN);
1734 popup.AppendMenuIcon(IDGITLC_OPENWITH, IDS_LOG_POPUP_OPENWITH, IDI_OPEN);
1735 if (wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) {
1736 popup.SetDefaultItem(IDGITLC_OPEN, FALSE);
1740 if (m_dwContextMenus & GITSLC_POPEXPLORE && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC)
1741 popup.AppendMenuIcon(IDGITLC_EXPLORE, IDS_STATUSLIST_CONTEXT_EXPLORE, IDI_EXPLORER);
1743 if (m_dwContextMenus & GITSLC_PREPAREDIFF && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1745 popup.AppendMenu(MF_SEPARATOR);
1746 popup.AppendMenuIcon(IDGITLC_PREPAREDIFF, IDS_PREPAREDIFF, IDI_DIFF);
1747 if (!m_sMarkForDiffFilename.IsEmpty())
1749 CString diffWith;
1750 if (filepath->GetGitPathString() == m_sMarkForDiffFilename)
1751 diffWith = m_sMarkForDiffVersion;
1752 else
1754 PathCompactPathEx(CStrBuf(diffWith, 40), m_sMarkForDiffFilename, 40, 0);
1755 diffWith += _T(":") + m_sMarkForDiffVersion.Left(g_Git.GetShortHASHLength());
1757 CString menuEntry;
1758 menuEntry.Format(IDS_MENUDIFFNOW, (LPCTSTR)diffWith);
1759 popup.AppendMenuIcon(IDGITLC_PREPAREDIFF_COMPARE, menuEntry, IDI_DIFF);
1763 if (GetSelectedCount() > 0)
1765 // if (((wcStatus == git_wc_status_unversioned)||(wcStatus == git_wc_status_ignored))&&(m_dwContextMenus & SVNSLC_POPDELETE))
1766 // popup.AppendMenuIcon(IDSVNLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1767 // 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))
1768 // {
1769 // if (bShift)
1770 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVEKEEP, IDI_DELETE);
1771 // else
1772 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVE, IDI_DELETE);
1773 // }
1774 if ((wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE | CTGitPath::LOGACTIONS_MISSING))/*||(wcStatus == git_wc_status_deleted)*/)
1776 if (m_dwContextMenus & GITSLC_POPDELETE)
1777 popup.AppendMenuIcon(IDGITLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1779 if ( (wcStatus & CTGitPath::LOGACTIONS_UNVER || wcStatus & CTGitPath::LOGACTIONS_DELETED) )
1781 if (m_dwContextMenus & GITSLC_POPIGNORE)
1783 CTGitPathList ignorelist;
1784 FillListOfSelectedItemPaths(ignorelist);
1785 //check if all selected entries have the same extension
1786 bool bSameExt = true;
1787 CString sExt;
1788 for (int i=0; i<ignorelist.GetCount(); ++i)
1790 if (sExt.IsEmpty() && (i==0))
1791 sExt = ignorelist[i].GetFileExtension();
1792 else if (sExt.CompareNoCase(ignorelist[i].GetFileExtension())!=0)
1793 bSameExt = false;
1795 if (bSameExt)
1797 if (ignoreSubMenu.CreateMenu())
1799 CString ignorepath;
1800 if (ignorelist.GetCount()==1)
1801 ignorepath = ignorelist[0].GetFileOrDirectoryName();
1802 else
1803 ignorepath.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1804 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNORE, ignorepath);
1805 ignorepath = _T("*")+sExt;
1806 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREMASK, ignorepath);
1807 if (ignorelist.GetCount() == 1 && !ignorelist[0].GetContainingDirectory().GetGitPathString().IsEmpty())
1808 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREFOLDER, ignorelist[0].GetContainingDirectory().GetGitPathString());
1809 CString temp;
1810 temp.LoadString(IDS_MENUIGNORE);
1811 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)ignoreSubMenu.m_hMenu, temp);
1814 else
1816 CString temp;
1817 if (ignorelist.GetCount()==1)
1818 temp.LoadString(IDS_MENUIGNORE);
1819 else
1820 temp.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1821 popup.AppendMenuIcon(IDGITLC_IGNORE, temp, IDI_IGNORE);
1822 temp.Format(IDS_MENUIGNOREMULTIPLEMASK, ignorelist.GetCount());
1823 popup.AppendMenuIcon(IDGITLC_IGNOREMASK, temp, IDI_IGNORE);
1831 if (GetSelectedCount() > 0)
1833 popup.AppendMenu(MF_SEPARATOR);
1834 popup.AppendMenuIcon(IDGITLC_COPY, IDS_STATUSLIST_CONTEXT_COPY, IDI_COPYCLIP);
1835 popup.AppendMenuIcon(IDGITLC_COPYEXT, IDS_STATUSLIST_CONTEXT_COPYEXT, IDI_COPYCLIP);
1836 #if 0
1837 if ((m_dwContextMenus & SVNSLC_POPCHANGELISTS))
1838 &&(wcStatus != git_wc_status_unversioned)&&(wcStatus != git_wc_status_none))
1840 popup.AppendMenu(MF_SEPARATOR);
1841 // changelist commands
1842 size_t numChangelists = GetNumberOfChangelistsInSelection();
1843 if (numChangelists > 0)
1844 popup.AppendMenuIcon(IDSVNLC_REMOVEFROMCS, IDS_STATUSLIST_CONTEXT_REMOVEFROMCS);
1845 if ((!entry->IsFolder())&&(changelistSubMenu.CreateMenu()))
1847 CString temp;
1848 temp.LoadString(IDS_STATUSLIST_CONTEXT_CREATECS);
1849 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATECS, temp);
1851 if (entry->changelist.Compare(SVNSLC_IGNORECHANGELIST))
1853 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1854 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATEIGNORECS, SVNSLC_IGNORECHANGELIST);
1857 if (!m_changelists.empty())
1859 // find the changelist names
1860 bool bNeedSeparator = true;
1861 int cmdID = IDSVNLC_MOVETOCS;
1862 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
1864 if ((entry->changelist.Compare(it->first))&&(it->first.Compare(SVNSLC_IGNORECHANGELIST)))
1866 if (bNeedSeparator)
1868 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1869 bNeedSeparator = false;
1871 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, cmdID, it->first);
1872 cmdID++;
1876 temp.LoadString(IDS_STATUSLIST_CONTEXT_MOVETOCS);
1877 popup.AppendMenu(MF_POPUP|MF_STRING, (UINT_PTR)changelistSubMenu.GetSafeHmenu(), temp);
1880 #endif
1883 m_hShellMenu = nullptr;
1884 if (GetSelectedCount() > 0 && !(wcStatus & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING)) && m_bHasWC && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && shellMenu.CreatePopupMenu())
1886 // insert the shell context menu
1887 popup.AppendMenu(MF_SEPARATOR);
1888 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)shellMenu.m_hMenu, CString(MAKEINTRESOURCE(IDS_STATUSLIST_CONTEXT_SHELL)));
1889 m_hShellMenu = shellMenu.m_hMenu;
1892 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this, 0);
1893 g_IContext2 = nullptr;
1894 g_IContext3 = nullptr;
1895 if (m_pContextMenu)
1897 if (cmd >= SHELL_MIN_CMD && cmd <= SHELL_MAX_CMD) // see if returned idCommand belongs to shell menu entries)
1899 CMINVOKECOMMANDINFOEX cmi = { 0 };
1900 cmi.cbSize = sizeof(CMINVOKECOMMANDINFOEX);
1901 cmi.fMask = CMIC_MASK_UNICODE | CMIC_MASK_PTINVOKE;
1902 if (GetKeyState(VK_CONTROL) < 0)
1903 cmi.fMask |= CMIC_MASK_CONTROL_DOWN;
1904 if (bShift)
1905 cmi.fMask |= CMIC_MASK_SHIFT_DOWN;
1906 cmi.hwnd = m_hWnd;
1907 cmi.lpVerb = MAKEINTRESOURCEA(cmd - SHELL_MIN_CMD);
1908 cmi.lpVerbW = MAKEINTRESOURCEW(cmd - SHELL_MIN_CMD);
1909 cmi.nShow = SW_SHOWNORMAL;
1910 cmi.ptInvoke = point;
1912 m_pContextMenu->InvokeCommand((LPCMINVOKECOMMANDINFO)&cmi);
1914 cmd = 0;
1916 m_pContextMenu->Release();
1917 m_pContextMenu = nullptr;
1919 if (g_pFolderhook)
1921 delete g_pFolderhook;
1922 g_pFolderhook = nullptr;
1924 if (g_psfDesktopFolder)
1926 g_psfDesktopFolder->Release();
1927 g_psfDesktopFolder = nullptr;
1929 for (int i = 0; i < g_pidlArrayItems; i++)
1931 if (g_pidlArray[i])
1932 CoTaskMemFree(g_pidlArray[i]);
1934 if (g_pidlArray)
1935 CoTaskMemFree(g_pidlArray);
1936 g_pidlArray = nullptr;
1937 g_pidlArrayItems = 0;
1939 m_bBlock = TRUE;
1940 AfxGetApp()->DoWaitCursor(1);
1941 bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1942 //int iItemCountBeforeMenuCmd = GetItemCount();
1943 //bool bForce = false;
1944 switch (cmd)
1946 case IDGITLC_VIEWREV:
1947 OpenFile(filepath, ALTERNATIVEEDITOR);
1948 break;
1950 case IDGITLC_OPEN:
1951 OpenFile(filepath,OPEN);
1952 break;
1954 case IDGITLC_OPENWITH:
1955 OpenFile(filepath,OPEN_WITH);
1956 break;
1958 case IDGITLC_EXPLORE:
1959 CAppUtils::ExploreTo(GetSafeHwnd(), g_Git.CombinePath(filepath));
1960 break;
1962 case IDGITLC_PREPAREDIFF:
1963 m_sMarkForDiffFilename = filepath->GetGitPathString();
1964 m_sMarkForDiffVersion = m_CurrentVersion;
1965 break;
1967 case IDGITLC_PREPAREDIFF_COMPARE:
1969 CTGitPath savedFile(m_sMarkForDiffFilename);
1970 CGitDiff::Diff(filepath, &savedFile, m_CurrentVersion, m_sMarkForDiffVersion, false, false, 0, bShift);
1972 break;
1974 case IDGITLC_CREATERESTORE:
1976 POSITION pos = GetFirstSelectedItemPosition();
1977 while (pos)
1979 int index = GetNextSelectedItem(pos);
1980 CTGitPath * entry2 = (CTGitPath * )GetItemData(index);
1981 ASSERT(entry2);
1982 if (!entry2 || entry2->IsDirectory())
1983 continue;
1984 if (m_restorepaths.find(entry2->GetWinPathString()) != m_restorepaths.end())
1985 continue;
1986 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
1987 // delete the temp file: the temp file has the FILE_ATTRIBUTE_TEMPORARY flag set
1988 // and copying the real file over it would leave that temp flag.
1989 DeleteFile(tempFile.GetWinPath());
1990 if (CopyFile(g_Git.CombinePath(entry2), tempFile.GetWinPath(), FALSE))
1992 m_restorepaths[entry2->GetWinPathString()] = tempFile.GetWinPathString();
1993 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), LVIS_OVERLAYMASK);
1996 Invalidate();
1998 break;
2000 case IDGITLC_RESTOREPATH:
2002 if (CMessageBox::Show(m_hWnd, IDS_STATUSLIST_RESTOREPATH, IDS_APPNAME, 2, IDI_QUESTION, IDS_RESTOREBUTTON, IDS_ABORTBUTTON) == 2)
2003 break;
2004 POSITION pos = GetFirstSelectedItemPosition();
2005 while (pos)
2007 int index = GetNextSelectedItem(pos);
2008 CTGitPath * entry2 = (CTGitPath * )GetItemData(index);
2009 ASSERT(entry2);
2010 if (!entry2)
2011 continue;
2012 if (m_restorepaths.find(entry2->GetWinPathString()) == m_restorepaths.end())
2013 continue;
2014 if (CopyFile(m_restorepaths[entry2->GetWinPathString()], g_Git.CombinePath(entry2), FALSE))
2016 m_restorepaths.erase(entry2->GetWinPathString());
2017 SetItemState(index, 0, LVIS_OVERLAYMASK);
2020 Invalidate();
2022 break;
2024 // Compare current version and work copy.
2025 case IDGITLC_COMPAREWC:
2027 if (!CheckMultipleDiffs())
2028 break;
2029 POSITION pos = GetFirstSelectedItemPosition();
2030 while ( pos )
2032 int index = GetNextSelectedItem(pos);
2033 StartDiffWC(index);
2036 break;
2038 // Compare with base version. when current version is zero, compare workcopy and HEAD.
2039 case IDGITLC_COMPARE:
2041 if (!CheckMultipleDiffs())
2042 break;
2043 POSITION pos = GetFirstSelectedItemPosition();
2044 while ( pos )
2046 int index = GetNextSelectedItem(pos);
2047 StartDiff(index);
2050 break;
2052 case IDGITLC_COMPARETWOREVISIONS:
2054 if (!CheckMultipleDiffs())
2055 break;
2056 POSITION pos = GetFirstSelectedItemPosition();
2057 while ( pos )
2059 int index = GetNextSelectedItem(pos);
2060 StartDiffTwo(index);
2063 break;
2065 case IDGITLC_COMPARETWOFILES:
2067 POSITION pos = GetFirstSelectedItemPosition();
2068 if (pos)
2070 CTGitPath* firstfilepath = (CTGitPath*)GetItemData(GetNextSelectedItem(pos));
2071 ASSERT(firstfilepath);
2072 if (!firstfilepath)
2073 break;
2075 CTGitPath* secondfilepath = (CTGitPath*)GetItemData(GetNextSelectedItem(pos));
2076 ASSERT(secondfilepath);
2077 if (!secondfilepath)
2078 break;
2080 CString sCmd;
2081 sCmd.Format(_T("/command:diff /path:\"%s\" /endrev:%s /path2:\"%s\" /startrev:%s /hwnd:%p"), firstfilepath->GetWinPath(), firstfilepath->Exists() ? GIT_REV_ZERO : _T("HEAD"), secondfilepath->GetWinPath(), secondfilepath->Exists() ? GIT_REV_ZERO : _T("HEAD"), (void*)m_hWnd);
2082 if (bShift)
2083 sCmd += L" /alternative";
2084 CAppUtils::RunTortoiseGitProc(sCmd);
2087 break;
2089 case IDGITLC_GNUDIFF1:
2091 if (!CheckMultipleDiffs())
2092 break;
2093 POSITION pos = GetFirstSelectedItemPosition();
2094 while (pos)
2096 CTGitPath * selectedFilepath = (CTGitPath * )GetItemData(GetNextSelectedItem(pos));
2097 if (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
2099 CString fromwhere;
2100 if (m_amend)
2101 fromwhere = _T("~1");
2102 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, GitRev::GetHead() + fromwhere, *selectedFilepath, GitRev::GetWorkingCopy(), bShift);
2104 else
2106 if ((selectedFilepath->m_ParentNo & (PARENT_MASK | MERGE_MASK)) == 0)
2107 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, m_CurrentVersion + _T("~1"), *selectedFilepath, m_CurrentVersion, bShift);
2108 else
2110 CString str;
2111 if (!(selectedFilepath->m_ParentNo & MERGE_MASK))
2112 str.Format(_T("%s^%d"), (LPCTSTR)m_CurrentVersion, (selectedFilepath->m_ParentNo & PARENT_MASK) + 1);
2114 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, str, *selectedFilepath, m_CurrentVersion, bShift, false, false, false, !!(selectedFilepath->m_ParentNo & MERGE_MASK));
2119 break;
2121 case IDGITLC_GNUDIFF2REVISIONS:
2123 CAppUtils::StartShowUnifiedDiff(m_hWnd, *filepath, m_Rev2, *filepath, m_Rev1, bShift);
2125 break;
2127 case IDGITLC_ADD:
2129 CTGitPathList paths;
2130 FillListOfSelectedItemPaths(paths, true);
2132 CGitProgressDlg progDlg;
2133 AddProgressCommand addCommand;
2134 progDlg.SetCommand(&addCommand);
2135 addCommand.SetShowCommitButtonAfterAdd((m_dwContextMenus & GITSLC_POPCOMMIT) != 0);
2136 addCommand.SetPathList(paths);
2137 progDlg.SetItemCount(paths.GetCount());
2138 progDlg.DoModal();
2140 // reset unchecked status
2141 POSITION pos = GetFirstSelectedItemPosition();
2142 int index;
2143 while ((index = GetNextSelectedItem(pos)) >= 0)
2144 m_mapFilenameToChecked.erase(((CTGitPath*)GetItemData(index))->GetGitPathString());
2146 if (GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2147 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2149 SetRedraw(TRUE);
2151 break;
2153 case IDGITLC_DELETE:
2154 DeleteSelectedFiles();
2155 break;
2157 case IDGITLC_BLAME:
2159 CAppUtils::LaunchTortoiseBlame(g_Git.CombinePath(filepath), m_CurrentVersion);
2161 break;
2163 case IDGITLC_LOG:
2164 case IDGITLC_LOGSUBMODULE:
2166 CString sCmd;
2167 sCmd.Format(_T("/command:log /path:\"%s\""), (LPCTSTR)g_Git.CombinePath(filepath));
2168 if (cmd == IDGITLC_LOG && filepath->IsDirectory())
2169 sCmd += _T(" /submodule");
2170 if (!m_sDisplayedBranch.IsEmpty())
2171 sCmd += _T(" /range:\"") + m_sDisplayedBranch + _T("\"");
2172 CAppUtils::RunTortoiseGitProc(sCmd, false, !(cmd == IDGITLC_LOGSUBMODULE));
2174 break;
2176 case IDGITLC_LOGOLDNAME:
2178 CTGitPath oldName(filepath->GetGitOldPathString());
2179 CString sCmd;
2180 sCmd.Format(_T("/command:log /path:\"%s\""), (LPCTSTR)g_Git.CombinePath(oldName));
2181 if (!m_sDisplayedBranch.IsEmpty())
2182 sCmd += _T(" /range:\"") + m_sDisplayedBranch + _T("\"");
2183 CAppUtils::RunTortoiseGitProc(sCmd);
2185 break;
2187 case IDGITLC_EDITCONFLICT:
2189 if (CAppUtils::ConflictEdit(*filepath, bShift, m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2191 CString conflictedFile = g_Git.CombinePath(filepath);
2192 if (!PathFileExists(conflictedFile) && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2193 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2196 break;
2198 case IDGITLC_RESOLVETHEIRS: //follow up
2199 case IDGITLC_RESOLVEMINE: //follow up
2200 case IDGITLC_RESOLVECONFLICT:
2202 if (CMessageBox::Show(m_hWnd, IDS_PROC_RESOLVE, IDS_APPNAME, MB_ICONQUESTION | MB_YESNO)==IDYES)
2204 bool needsFullRefresh = false;
2205 POSITION pos = GetFirstSelectedItemPosition();
2206 while (pos != 0)
2208 int index;
2209 index = GetNextSelectedItem(pos);
2210 CTGitPath * fentry =(CTGitPath*) this->GetItemData(index);
2211 if (!fentry)
2212 continue;
2214 CAppUtils::resolve_with resolveWith = CAppUtils::RESOLVE_WITH_CURRENT;
2215 if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE))
2216 resolveWith = CAppUtils::RESOLVE_WITH_THEIRS;
2217 else if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS))
2218 resolveWith = CAppUtils::RESOLVE_WITH_MINE;
2219 if (CAppUtils::ResolveConflict(*fentry, resolveWith) == 0 && fentry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
2220 needsFullRefresh = true;
2222 if (needsFullRefresh && CRegDWORD(_T("Software\\TortoiseGit\\RefreshFileListAfterResolvingConflict"), TRUE) == TRUE)
2224 CWnd* pParent = GetLogicalParent();
2225 if (pParent && pParent->GetSafeHwnd())
2226 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2227 SetRedraw(TRUE);
2228 break;
2230 Show(m_dwShow, 0, m_bShowFolders,0,true);
2233 break;
2235 case IDGITLC_IGNORE:
2237 CTGitPathList ignorelist;
2238 //std::vector<CString> toremove;
2239 FillListOfSelectedItemPaths(ignorelist, true);
2241 if(!CAppUtils::IgnoreFile(ignorelist,false))
2242 break;
2244 SetRedraw(FALSE);
2245 CWnd* pParent = GetLogicalParent();
2246 if (pParent && pParent->GetSafeHwnd())
2248 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2250 SetRedraw(TRUE);
2252 break;
2254 case IDGITLC_IGNOREMASK:
2256 CString common;
2257 CString ext=filepath->GetFileExtension();
2258 CTGitPathList ignorelist;
2259 FillListOfSelectedItemPaths(ignorelist, true);
2261 if (!CAppUtils::IgnoreFile(ignorelist,true))
2262 break;
2264 SetRedraw(FALSE);
2265 CWnd* pParent = GetLogicalParent();
2266 if (pParent && pParent->GetSafeHwnd())
2268 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2271 SetRedraw(TRUE);
2273 break;
2275 case IDGITLC_IGNOREFOLDER:
2277 CTGitPathList ignorelist;
2278 ignorelist.AddPath(filepath->GetContainingDirectory());
2280 if (!CAppUtils::IgnoreFile(ignorelist, false))
2281 break;
2283 SetRedraw(FALSE);
2284 CWnd *pParent = GetLogicalParent();
2285 if (pParent && pParent->GetSafeHwnd())
2286 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2288 SetRedraw(TRUE);
2290 break;
2291 case IDGITLC_COMMIT:
2293 CTGitPathList targetList;
2294 FillListOfSelectedItemPaths(targetList);
2295 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2296 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2297 CString commandline = _T("/command:commit /pathfile:\"");
2298 commandline += tempFile.GetWinPathString();
2299 commandline += _T("\"");
2300 commandline += _T(" /deletepathfile");
2301 CAppUtils::RunTortoiseGitProc(commandline);
2303 break;
2304 case IDGITLC_REVERT:
2306 // If at least one item is not in the status "added"
2307 // we ask for a confirmation
2308 BOOL bConfirm = FALSE;
2309 POSITION pos = GetFirstSelectedItemPosition();
2310 int index;
2311 while ((index = GetNextSelectedItem(pos)) >= 0)
2313 //FileEntry * fentry = GetListEntry(index);
2314 CTGitPath *fentry=(CTGitPath*)GetItemData(index);
2315 if(fentry && fentry->m_Action &CTGitPath::LOGACTIONS_MODIFIED && !fentry->IsDirectory())
2317 bConfirm = TRUE;
2318 break;
2322 CString str;
2323 str.Format(IDS_PROC_WARNREVERT,GetSelectedCount());
2325 if (!bConfirm || CMessageBox::Show(this->m_hWnd, str, _T("TortoiseGit"), MB_YESNO | MB_ICONQUESTION)==IDYES)
2327 CTGitPathList targetList;
2328 FillListOfSelectedItemPaths(targetList);
2330 // make sure that the list is reverse sorted, so that
2331 // children are removed before any parents
2332 targetList.SortByPathname(true);
2334 // put all reverted files in the trashbin, except the ones with 'added'
2335 // status because they are not restored by the revert.
2336 CTGitPathList delList;
2337 POSITION pos2 = GetFirstSelectedItemPosition();
2338 int index2;
2339 while ((index2 = GetNextSelectedItem(pos2)) >= 0)
2341 CTGitPath *entry=(CTGitPath *)GetItemData(index2);
2342 if (entry&&(!(entry->m_Action& CTGitPath::LOGACTIONS_ADDED))
2343 && (!(entry->m_Action& CTGitPath::LOGACTIONS_REPLACED)) && !entry->IsDirectory())
2345 CTGitPath fullpath;
2346 fullpath.SetFromWin(g_Git.CombinePath(entry));
2347 delList.AddPath(fullpath);
2350 if (DWORD(CRegDWORD(_T("Software\\TortoiseGit\\RevertWithRecycleBin"), TRUE)))
2351 delList.DeleteAllFiles(true);
2353 CString revertToCommit = _T("HEAD");
2354 if (m_amend)
2355 revertToCommit = _T("HEAD~1");
2356 CString err;
2357 if (g_Git.Revert(revertToCommit, targetList, err))
2358 CMessageBox::Show(this->m_hWnd, _T("Revert failed:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
2359 else
2361 bool updateStatusList = false;
2362 for (int i = 0 ; i < targetList.GetCount(); ++i)
2364 int nListboxEntries = GetItemCount();
2365 for (int nItem=0; nItem<nListboxEntries; ++nItem)
2367 CTGitPath *path=(CTGitPath*)GetItemData(nItem);
2368 if (path->GetGitPathString()==targetList[i].GetGitPathString() && !path->IsDirectory())
2370 if(path->m_Action & CTGitPath::LOGACTIONS_ADDED)
2372 path->m_Action = CTGitPath::LOGACTIONS_UNVER;
2373 SetEntryCheck(path,nItem,false);
2374 updateStatusList = true;
2375 #if 0 // revert an added file and some entry will be cloned (part 1/2)
2376 SetItemGroup(nItem,1);
2377 this->m_StatusFileList.RemoveItem(*path);
2378 this->m_UnRevFileList.AddPath(*path);
2379 //this->m_IgnoreFileList.RemoveItem(*path);
2380 #endif
2382 else
2384 if (GetCheck(nItem))
2385 m_nSelected--;
2386 RemoveListEntry(nItem);
2388 break;
2390 else if (path->GetGitPathString()==targetList[i].GetGitPathString() && path->IsDirectory() && path->IsWCRoot())
2392 CString sCmd;
2393 sCmd.Format(_T("/command:revert /path:\"%s\""), (LPCTSTR)path->GetGitPathString());
2394 CCommonAppUtils::RunTortoiseGitProc(sCmd);
2398 SetRedraw(TRUE);
2399 #if 0 // revert an added file and some entry will be cloned (part 2/2)
2400 Show(m_dwShow, 0, m_bShowFolders,updateStatusList,true);
2401 NotifyCheck();
2402 #else
2403 if (updateStatusList && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2404 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2405 #endif
2409 break;
2411 case IDGITLC_ASSUMEVALID:
2412 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_ASSUMEVALID, BST_CHECKED, BST_INDETERMINATE);
2413 break;
2414 case IDGITLC_SKIPWORKTREE:
2415 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_SKIPWORKTREE, BST_INDETERMINATE, BST_CHECKED);
2416 break;
2417 case IDGITLC_UNSETIGNORELOCALCHANGES:
2418 SetGitIndexFlagsForSelectedFiles(IDS_PROC_UNSET_IGNORELOCALCHANGES, BST_UNCHECKED, BST_UNCHECKED);
2419 break;
2420 case IDGITLC_COPY:
2421 CopySelectedEntriesToClipboard(0);
2422 break;
2423 case IDGITLC_COPYEXT:
2424 CopySelectedEntriesToClipboard((DWORD)-1);
2425 break;
2426 case IDGITLC_EXPORT:
2427 FilesExport();
2428 break;
2429 case IDGITLC_SAVEAS:
2430 FileSaveAs(filepath);
2431 break;
2433 case IDGITLC_REVERTTOREV:
2434 RevertSelectedItemToVersion();
2435 break;
2436 case IDGITLC_REVERTTOPARENT:
2437 RevertSelectedItemToVersion(true);
2438 break;
2439 #if 0
2440 case IDSVNLC_COMMIT:
2442 CTSVNPathList targetList;
2443 FillListOfSelectedItemPaths(targetList);
2444 CTSVNPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2445 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2446 CString commandline = CPathUtils::GetAppDirectory();
2447 commandline += _T("TortoiseGitProc.exe /command:commit /pathfile:\"");
2448 commandline += tempFile.GetWinPathString();
2449 commandline += _T("\"");
2450 commandline += _T(" /deletepathfile");
2451 CAppUtils::LaunchApplication(commandline, nullptr, false);
2453 break;
2454 case IDSVNLC_CREATEIGNORECS:
2455 CreateChangeList(SVNSLC_IGNORECHANGELIST);
2456 break;
2457 case IDSVNLC_CREATECS:
2459 CCreateChangelistDlg dlg;
2460 if (dlg.DoModal() == IDOK)
2461 CreateChangeList(dlg.m_sName);
2463 break;
2464 default:
2466 if (cmd < IDSVNLC_MOVETOCS)
2467 break;
2468 CTSVNPathList changelistItems;
2469 FillListOfSelectedItemPaths(changelistItems);
2471 // find the changelist name
2472 CString sChangelist;
2473 int cmdID = IDSVNLC_MOVETOCS;
2474 SetRedraw(FALSE);
2475 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
2477 if ((it->first.Compare(SVNSLC_IGNORECHANGELIST))&&(entry->changelist.Compare(it->first)))
2479 if (cmd == cmdID)
2480 sChangelist = it->first;
2481 cmdID++;
2484 if (!sChangelist.IsEmpty())
2486 SVN git;
2487 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
2489 // The changelists were moved, but we now need to run through the selected items again
2490 // and update their changelist
2491 POSITION pos = GetFirstSelectedItemPosition();
2492 int index;
2493 while ((index = GetNextSelectedItem(pos)) >= 0)
2495 FileEntry * e = GetListEntry(index);
2496 e->changelist = sChangelist;
2497 if (!e->IsFolder())
2499 if (m_changelists.find(e->changelist)!=m_changelists.end())
2500 SetItemGroup(index, m_changelists[e->changelist]);
2501 else
2502 SetItemGroup(index, 0);
2506 else
2507 CMessageBox::Show(m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
2509 SetRedraw(TRUE);
2511 break;
2512 #endif
2514 } // switch (cmd)
2515 m_bBlock = FALSE;
2516 AfxGetApp()->DoWaitCursor(-1);
2517 GetStatisticsString();
2518 //int iItemCountAfterMenuCmd = GetItemCount();
2519 //if (iItemCountAfterMenuCmd != iItemCountBeforeMenuCmd)
2521 // CWnd* pParent = GetParent();
2522 // if (pParent && pParent->GetSafeHwnd())
2523 // {
2524 // pParent->SendMessage(SVNSLNM_ITEMCOUNTCHANGED);
2525 // }
2527 } // if (popup.CreatePopupMenu())
2528 } // if (selIndex >= 0)
2531 void CGitStatusListCtrl::SetGitIndexFlagsForSelectedFiles(UINT message, BOOL assumevalid, BOOL skipworktree)
2533 if (CMessageBox::Show(GetSafeHwnd(), message, IDS_APPNAME, MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
2534 return;
2536 CAutoRepository repository(g_Git.GetGitRepository());
2537 if (!repository)
2539 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2540 return;
2543 CAutoIndex gitindex;
2544 if (git_repository_index(gitindex.GetPointer(), repository))
2546 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2547 return;
2550 POSITION pos = GetFirstSelectedItemPosition();
2551 int index = -1;
2552 while ((index = GetNextSelectedItem(pos)) >= 0)
2554 CTGitPath * path = (CTGitPath *)GetItemData(index);
2555 ASSERT(path);
2556 if (path == nullptr)
2557 continue;
2559 size_t idx;
2560 if (!git_index_find(&idx, gitindex, CUnicodeUtils::GetMulti(path->GetGitPathString(), CP_UTF8)))
2562 git_index_entry *e = const_cast<git_index_entry *>(git_index_get_byindex(gitindex, idx)); // HACK
2563 if (assumevalid == BST_UNCHECKED)
2564 e->flags &= ~GIT_IDXENTRY_VALID;
2565 else if (assumevalid == BST_CHECKED)
2566 e->flags |= GIT_IDXENTRY_VALID;
2567 if (skipworktree == BST_UNCHECKED)
2568 e->flags_extended &= ~GIT_IDXENTRY_SKIP_WORKTREE;
2569 else if (skipworktree == BST_CHECKED)
2570 e->flags_extended |= GIT_IDXENTRY_SKIP_WORKTREE;
2571 git_index_add(gitindex, e);
2573 else
2574 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2577 if (git_index_write(gitindex))
2579 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2580 return;
2583 if (nullptr != GetLogicalParent() && nullptr != GetLogicalParent()->GetSafeHwnd())
2584 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2586 SetRedraw(TRUE);
2589 void CGitStatusListCtrl::OnContextMenu(CWnd* pWnd, CPoint point)
2591 __super::OnContextMenu(pWnd, point);
2592 if (pWnd == this)
2593 OnContextMenuList(pWnd, point);
2596 void CGitStatusListCtrl::OnNMDblclk(NMHDR *pNMHDR, LRESULT *pResult)
2598 Locker lock(m_critSec);
2599 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
2600 *pResult = 0;
2601 if (m_bBlock)
2602 return;
2604 if (pNMLV->iItem < 0)
2605 return;
2607 CTGitPath *file=(CTGitPath*)GetItemData(pNMLV->iItem);
2609 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) {
2610 OpenFile(file, OPEN);
2611 return;
2613 if( file->m_Action&CTGitPath::LOGACTIONS_UNMERGED )
2615 if (CAppUtils::ConflictEdit(*file, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000), m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2617 CString conflictedFile = g_Git.CombinePath(file);
2618 if (!PathFileExists(conflictedFile) && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
2619 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2622 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))
2623 return;
2624 else
2626 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
2627 StartDiffTwo(pNMLV->iItem);
2628 else
2629 StartDiff(pNMLV->iItem);
2632 void CGitStatusListCtrl::StartDiffTwo(int fileindex)
2634 if(fileindex<0)
2635 return;
2637 auto ptr = (CTGitPath*)GetItemData(fileindex);
2638 if (!ptr)
2639 return;
2640 CTGitPath file1 = *ptr;
2642 if (file1.m_Action & CTGitPath::LOGACTIONS_ADDED)
2643 CGitDiff::DiffNull(&file1, m_Rev1, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2644 else if (file1.m_Action & CTGitPath::LOGACTIONS_DELETED)
2645 CGitDiff::DiffNull(&file1, m_Rev2, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2646 else
2647 CGitDiff::Diff(&file1, &file1, m_Rev1, m_Rev2, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2650 void CGitStatusListCtrl::StartDiffWC(int fileindex)
2652 if(fileindex<0)
2653 return;
2655 CString Ver;
2656 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion== GIT_REV_ZERO)
2657 return;
2659 auto ptr = (CTGitPath*)GetItemData(fileindex);
2660 if (!ptr)
2661 return;
2662 CTGitPath file1 = *ptr;
2663 file1.m_Action = 0; // reset action, so that diff is not started as added/deleted file; see issue #1757
2665 CGitDiff::Diff(&file1, &file1, GIT_REV_ZERO, m_CurrentVersion, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2668 void CGitStatusListCtrl::StartDiff(int fileindex)
2670 if(fileindex<0)
2671 return;
2673 auto ptr = (CTGitPath*)GetItemData(fileindex);
2674 if (!ptr)
2675 return;
2676 CTGitPath file1 = *ptr;
2677 CTGitPath file2;
2678 if(file1.m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY))
2679 file2.SetFromGit(file1.GetGitOldPathString());
2680 else
2681 file2=file1;
2683 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion== GIT_REV_ZERO)
2685 CString fromwhere;
2686 if(m_amend && (file1.m_Action & CTGitPath::LOGACTIONS_ADDED) == 0)
2687 fromwhere = _T("~1");
2688 if( g_Git.IsInitRepos())
2689 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2690 GIT_REV_ZERO, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2691 else if( file1.m_Action&CTGitPath::LOGACTIONS_ADDED )
2692 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2693 m_CurrentVersion + fromwhere, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2694 else if( file1.m_Action&CTGitPath::LOGACTIONS_DELETED )
2695 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2696 GitRev::GetHead() + fromwhere, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2697 else
2698 CGitDiff::Diff(&file1,&file2,
2699 CString(GIT_REV_ZERO),
2700 GitRev::GetHead() + fromwhere, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2702 else
2704 CGitHash hash;
2705 CString fromwhere = m_CurrentVersion+_T("~1");
2706 if(m_amend)
2707 fromwhere = m_CurrentVersion+_T("~2");
2708 bool revfail = !!g_Git.GetHash(hash, fromwhere);
2709 if (revfail || (file1.m_Action & file1.LOGACTIONS_ADDED))
2710 CGitDiff::DiffNull(&file1, m_CurrentVersion, true, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2711 else if (file1.m_Action & file1.LOGACTIONS_DELETED)
2713 if (file1.m_ParentNo > 0)
2714 fromwhere.Format(_T("%s^%d"), (LPCTSTR)m_CurrentVersion, file1.m_ParentNo + 1);
2716 CGitDiff::DiffNull(&file1, fromwhere, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2718 else
2720 if( file1.m_ParentNo & MERGE_MASK)
2722 CTGitPath base, theirs, mine, merge;
2724 CString temppath;
2725 GetTempPath(temppath);
2726 temppath.TrimRight(_T("\\"));
2728 mine.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".LOCAL") + file1.GetFileExtension());
2729 theirs.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".REMOTE") + file1.GetFileExtension());
2730 base.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".BASE") + file1.GetFileExtension());
2732 CFile tempfile;
2733 //create a empty file, incase stage is not three
2734 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2735 tempfile.Close();
2736 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2737 tempfile.Close();
2738 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2739 tempfile.Close();
2741 merge.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".Merged") + file1.GetFileExtension());
2743 int parent1=-1, parent2 =-1;
2744 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
2746 if(m_arStatusArray[i]->GetGitPathString() == file1.GetGitPathString())
2748 if(m_arStatusArray[i]->m_ParentNo & MERGE_MASK)
2751 else
2753 if(parent1<0)
2754 parent1 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2755 else if (parent2 <0)
2756 parent2 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2761 if(g_Git.GetOneFile(m_CurrentVersion, file1, (CString&)merge.GetWinPathString()))
2762 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2764 if(parent1>=0)
2766 CString str;
2767 str.Format(_T("%s^%d"), (LPCTSTR)this->m_CurrentVersion, parent1 + 1);
2769 if(g_Git.GetOneFile(str, file1, (CString&)mine.GetWinPathString()))
2770 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2773 if(parent2>=0)
2775 CString str;
2776 str.Format(_T("%s^%d"), (LPCTSTR)this->m_CurrentVersion, parent2 + 1);
2778 if(g_Git.GetOneFile(str, file1, (CString&)theirs.GetWinPathString()))
2779 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2782 if(parent1>=0 && parent2>=0)
2784 CString cmd, output;
2785 cmd.Format(_T("git.exe merge-base %s^%d %s^%d"), (LPCTSTR)this->m_CurrentVersion, parent1 + 1,
2786 this->m_CurrentVersion,parent2+1);
2788 if (!g_Git.Run(cmd, &output, nullptr, CP_UTF8))
2790 if(g_Git.GetOneFile(output.Left(40), file1, (CString&)base.GetWinPathString()))
2791 CMessageBox::Show(GetSafeHwnd(), IDS_STATUSLIST_FAILEDGETBASEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2794 CAppUtils::StartExtMerge(!!(GetAsyncKeyState(VK_SHIFT) & 0x8000), base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL");
2796 else
2798 CString str;
2799 if( (file1.m_ParentNo&PARENT_MASK) == 0)
2800 str = _T("~1");
2801 else
2802 str.Format(_T("^%d"), (file1.m_ParentNo&PARENT_MASK)+1);
2803 CGitDiff::Diff(&file1,&file2,
2804 m_CurrentVersion,
2805 m_CurrentVersion + str, false, false, 0, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000));
2811 CString CGitStatusListCtrl::GetStatisticsString(bool simple)
2813 CString sNormal = CString(MAKEINTRESOURCE(IDS_STATUSNORMAL));
2814 CString sAdded = CString(MAKEINTRESOURCE(IDS_STATUSADDED));
2815 CString sDeleted = CString(MAKEINTRESOURCE(IDS_STATUSDELETED));
2816 CString sModified = CString(MAKEINTRESOURCE(IDS_STATUSMODIFIED));
2817 CString sConflicted = CString(MAKEINTRESOURCE(IDS_STATUSCONFLICTED));
2818 CString sUnversioned = CString(MAKEINTRESOURCE(IDS_STATUSUNVERSIONED));
2819 CString sRenamed = CString(MAKEINTRESOURCE(IDS_STATUSREPLACED));
2820 CString sToolTip;
2821 if(simple)
2823 sToolTip.Format(IDS_STATUSLIST_STATUSLINE1,
2824 this->m_nLineAdded,this->m_nLineDeleted,
2825 (LPCTSTR)sModified, m_nModified,
2826 (LPCTSTR)sAdded, m_nAdded,
2827 (LPCTSTR)sDeleted, m_nDeleted,
2828 (LPCTSTR)sRenamed, m_nRenamed
2831 else
2833 sToolTip.Format(IDS_STATUSLIST_STATUSLINE2,
2834 this->m_nLineAdded,this->m_nLineDeleted,
2835 (LPCTSTR)sNormal, m_nNormal,
2836 (LPCTSTR)sUnversioned, m_nUnversioned,
2837 (LPCTSTR)sModified, m_nModified,
2838 (LPCTSTR)sAdded, m_nAdded,
2839 (LPCTSTR)sDeleted, m_nDeleted,
2840 (LPCTSTR)sConflicted, m_nConflicted
2843 CString sStats;
2844 sStats.Format(IDS_COMMITDLG_STATISTICSFORMAT, m_nSelected, GetItemCount());
2845 if (m_pStatLabel)
2846 m_pStatLabel->SetWindowText(sStats);
2848 if (m_pSelectButton)
2850 if (m_nSelected == 0)
2851 m_pSelectButton->SetCheck(BST_UNCHECKED);
2852 else if (m_nSelected != GetItemCount())
2853 m_pSelectButton->SetCheck(BST_INDETERMINATE);
2854 else
2855 m_pSelectButton->SetCheck(BST_CHECKED);
2858 if (m_pConfirmButton)
2859 m_pConfirmButton->EnableWindow(m_nSelected>0);
2861 return sToolTip;
2864 CString CGitStatusListCtrl::GetCommonDirectory(bool bStrict)
2866 if (!bStrict)
2868 // not strict means that the selected folder has priority
2869 if (!m_StatusFileList.GetCommonDirectory().IsEmpty())
2870 return m_StatusFileList.GetCommonDirectory().GetWinPath();
2873 CTGitPath commonBaseDirectory;
2874 int nListItems = GetItemCount();
2875 for (int i=0; i<nListItems; ++i)
2877 CTGitPath baseDirectory,*p= (CTGitPath*)this->GetItemData(i);
2878 ASSERT(p);
2879 if (!p)
2880 continue;
2881 baseDirectory = p->GetDirectory();
2883 if(commonBaseDirectory.IsEmpty())
2884 commonBaseDirectory = baseDirectory;
2885 else
2887 if (commonBaseDirectory.GetWinPathString().GetLength() > baseDirectory.GetWinPathString().GetLength())
2889 if (baseDirectory.IsAncestorOf(commonBaseDirectory))
2890 commonBaseDirectory = baseDirectory;
2894 return g_Git.CombinePath(commonBaseDirectory);
2897 void CGitStatusListCtrl::SelectAll(bool bSelect, bool /*bIncludeNoCommits*/)
2899 CWaitCursor waitCursor;
2900 // block here so the LVN_ITEMCHANGED messages
2901 // get ignored
2902 m_bBlock = TRUE;
2903 SetRedraw(FALSE);
2905 int nListItems = GetItemCount();
2906 if (bSelect)
2907 m_nSelected = nListItems;
2908 else
2909 m_nSelected = 0;
2911 for (int i=0; i<nListItems; ++i)
2913 //FileEntry * entry = GetListEntry(i);
2914 //ASSERT(entry);
2915 CTGitPath *path = (CTGitPath *) GetItemData(i);
2916 if (!path)
2917 continue;
2918 //if ((bIncludeNoCommits)||(entry->GetChangeList().Compare(SVNSLC_IGNORECHANGELIST)))
2919 SetEntryCheck(path,i,bSelect);
2922 // unblock before redrawing
2923 m_bBlock = FALSE;
2924 SetRedraw(TRUE);
2925 GetStatisticsString();
2926 NotifyCheck();
2929 void CGitStatusListCtrl::Check(DWORD dwCheck, bool check)
2931 CWaitCursor waitCursor;
2932 // block here so the LVN_ITEMCHANGED messages
2933 // get ignored
2934 m_bBlock = TRUE;
2935 SetRedraw(FALSE);
2937 int nListItems = GetItemCount();
2939 for (int i = 0; i < nListItems; ++i)
2941 CTGitPath *entry = (CTGitPath *) GetItemData(i);
2942 if (!entry)
2943 continue;
2945 DWORD showFlags = entry->m_Action;
2946 if (entry->IsDirectory())
2947 showFlags |= GITSLC_SHOWSUBMODULES;
2948 else
2949 showFlags |= GITSLC_SHOWFILES;
2951 if (check && (showFlags & dwCheck) && !GetCheck(i) && !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules && !(dwCheck & GITSLC_SHOWSUBMODULES)))
2953 SetEntryCheck(entry, i, true);
2954 m_nSelected++;
2956 else if (!check && (showFlags & dwCheck) && GetCheck(i))
2958 SetEntryCheck(entry, i, false);
2959 m_nSelected--;
2962 // unblock before redrawing
2963 m_bBlock = FALSE;
2964 SetRedraw(TRUE);
2965 GetStatisticsString();
2966 NotifyCheck();
2969 void CGitStatusListCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
2971 LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR);
2972 *pResult = 0;
2973 if (m_bBlock)
2974 return;
2976 CTGitPath *entry=(CTGitPath *)GetItemData(pGetInfoTip->iItem);
2978 if (entry)
2979 if (pGetInfoTip->cchTextMax > entry->GetGitPathString().GetLength() + g_Git.m_CurrentDir.GetLength())
2981 CString str = g_Git.CombinePath(entry->GetWinPathString());
2982 _tcsncpy_s(pGetInfoTip->pszText, pGetInfoTip->cchTextMax, str.GetBuffer(), pGetInfoTip->cchTextMax - 1);
2986 void CGitStatusListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
2988 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
2990 // Take the default processing unless we set this to something else below.
2991 *pResult = CDRF_DODEFAULT;
2993 // First thing - check the draw stage. If it's the control's prepaint
2994 // stage, then tell Windows we want messages for every item.
2996 switch (pLVCD->nmcd.dwDrawStage)
2998 case CDDS_PREPAINT:
2999 *pResult = CDRF_NOTIFYITEMDRAW;
3000 break;
3001 case CDDS_ITEMPREPAINT:
3003 // This is the prepaint stage for an item. Here's where we set the
3004 // item's text color. Our return value will tell Windows to draw the
3005 // item itself, but it will use the new color we set here.
3007 // Tell Windows to paint the control itself.
3008 *pResult = CDRF_DODEFAULT;
3009 if (m_bBlock)
3010 return;
3012 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
3014 if (m_arStatusArray.size() > (DWORD_PTR)pLVCD->nmcd.dwItemSpec)
3016 //FileEntry * entry = GetListEntry((int)pLVCD->nmcd.dwItemSpec);
3017 CTGitPath *entry=(CTGitPath *)GetItemData((int)pLVCD->nmcd.dwItemSpec);
3018 if (!entry)
3019 return;
3021 // coloring
3022 // ========
3023 // black : unversioned, normal
3024 // purple : added
3025 // blue : modified
3026 // brown : missing, deleted, replaced
3027 // green : merged (or potential merges)
3028 // red : conflicts or sure conflicts
3029 if(entry->m_Action & CTGitPath::LOGACTIONS_GRAY)
3030 crText = RGB(128,128,128);
3031 else if(entry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3032 crText = m_Colors.GetColor(CColors::Conflict);
3033 else if(entry->m_Action & (CTGitPath::LOGACTIONS_MODIFIED))
3034 crText = m_Colors.GetColor(CColors::Modified);
3035 else if(entry->m_Action & (CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
3036 crText = m_Colors.GetColor(CColors::Added);
3037 else if(entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
3038 crText = m_Colors.GetColor(CColors::Deleted);
3039 else if(entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
3040 crText = m_Colors.GetColor(CColors::Renamed);
3041 else if(entry->m_Action & CTGitPath::LOGACTIONS_MERGED)
3042 crText = m_Colors.GetColor(CColors::Merged);
3043 else
3044 crText = GetSysColor(COLOR_WINDOWTEXT);
3045 // Store the color back in the NMLVCUSTOMDRAW struct.
3046 pLVCD->clrText = crText;
3049 break;
3053 BOOL CGitStatusListCtrl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
3055 if (pWnd != this)
3056 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3057 if (!m_bBlock)
3059 HCURSOR hCur = LoadCursor(nullptr, IDC_ARROW);
3060 SetCursor(hCur);
3061 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3063 HCURSOR hCur = LoadCursor(nullptr, IDC_WAIT);
3064 SetCursor(hCur);
3065 return TRUE;
3068 void CGitStatusListCtrl::RemoveListEntry(int index)
3070 Locker lock(m_critSec);
3071 DeleteItem(index);
3073 m_arStatusArray.erase(m_arStatusArray.cbegin() + index);
3075 #if 0
3076 delete m_arStatusArray[m_arListArray[index]];
3077 m_arStatusArray.erase(m_arStatusArray.begin()+m_arListArray[index]);
3078 m_arListArray.erase(m_arListArray.begin()+index);
3079 for (int i=index; i< (int)m_arListArray.size(); ++i)
3081 m_arListArray[i]--;
3083 #endif
3086 ///< Set a checkbox on an entry in the listbox
3087 // NEVER, EVER call SetCheck directly, because you'll end-up with the checkboxes and the 'checked' flag getting out of sync
3088 void CGitStatusListCtrl::SetEntryCheck(CTGitPath* pEntry, int listboxIndex, bool bCheck)
3090 pEntry->m_Checked = bCheck;
3091 m_mapFilenameToChecked[pEntry->GetGitPathString()] = bCheck;
3092 SetCheck(listboxIndex, bCheck);
3095 #if 0
3096 void CGitStatusListCtrl::SetCheckOnAllDescendentsOf(const FileEntry* parentEntry, bool bCheck)
3098 int nListItems = GetItemCount();
3099 for (int j=0; j< nListItems ; ++j)
3101 FileEntry * childEntry = GetListEntry(j);
3102 ASSERT(childEntry);
3103 if (!childEntry || childEntry == parentEntry)
3104 continue;
3105 if (childEntry->checked != bCheck)
3107 if (parentEntry->path.IsAncestorOf(childEntry->path))
3109 SetEntryCheck(childEntry,j,bCheck);
3110 if(bCheck)
3111 m_nSelected++;
3112 else
3113 m_nSelected--;
3118 #endif
3120 void CGitStatusListCtrl::WriteCheckedNamesToPathList(CTGitPathList& pathList)
3122 pathList.Clear();
3123 int nListItems = GetItemCount();
3124 for (int i = 0; i< nListItems; ++i)
3126 CTGitPath * entry = (CTGitPath*)GetItemData(i);
3127 ASSERT(entry);
3128 if (entry->m_Checked)
3129 pathList.AddPath(*entry);
3131 pathList.SortByPathname();
3135 /// Build a path list of all the selected items in the list (NOTE - SELECTED, not CHECKED)
3136 void CGitStatusListCtrl::FillListOfSelectedItemPaths(CTGitPathList& pathList, bool /*bNoIgnored*/)
3138 pathList.Clear();
3140 POSITION pos = GetFirstSelectedItemPosition();
3141 int index;
3142 while ((index = GetNextSelectedItem(pos)) >= 0)
3144 CTGitPath * entry = (CTGitPath*)GetItemData(index);
3145 //if ((bNoIgnored)&&(entry->status == git_wc_status_ignored))
3146 // continue;
3147 pathList.AddPath(*entry);
3151 UINT CGitStatusListCtrl::OnGetDlgCode()
3153 // we want to process the return key and not have that one
3154 // routed to the default pushbutton
3155 return CListCtrl::OnGetDlgCode() | DLGC_WANTALLKEYS;
3158 void CGitStatusListCtrl::OnNMReturn(NMHDR * /*pNMHDR*/, LRESULT *pResult)
3160 *pResult = 0;
3161 if (m_bBlock)
3162 return;
3163 if (!CheckMultipleDiffs())
3164 return;
3165 bool needsRefresh = false;
3166 POSITION pos = GetFirstSelectedItemPosition();
3167 while ( pos )
3169 int index = GetNextSelectedItem(pos);
3170 if (index < 0)
3171 return;
3172 CTGitPath *file=(CTGitPath*)GetItemData(index);
3173 if (file == nullptr)
3174 return;
3175 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
3176 OpenFile(file, OPEN);
3177 else if ((file->m_Action & CTGitPath::LOGACTIONS_UNMERGED))
3179 if (CAppUtils::ConflictEdit(*file, !!(GetAsyncKeyState(VK_SHIFT) & 0x8000), m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
3181 CString conflictedFile = g_Git.CombinePath(file);
3182 needsRefresh = needsRefresh || !PathFileExists(conflictedFile);
3185 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))
3186 continue;
3187 else
3189 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
3190 StartDiffTwo(index);
3191 else
3192 StartDiff(index);
3195 if (needsRefresh && GetLogicalParent() && GetLogicalParent()->GetSafeHwnd())
3196 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
3199 void CGitStatusListCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
3201 // Since we catch all keystrokes (to have the enter key processed here instead
3202 // of routed to the default pushbutton) we have to make sure that other
3203 // keys like Tab and Esc still do what they're supposed to do
3204 // Tab = change focus to next/previous control
3205 // Esc = quit the dialog
3206 switch (nChar)
3208 case (VK_TAB):
3210 ::PostMessage(GetLogicalParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
3211 return;
3213 break;
3214 case (VK_ESCAPE):
3216 ::SendMessage(GetLogicalParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
3218 break;
3221 CListCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
3224 void CGitStatusListCtrl::PreSubclassWindow()
3226 __super::PreSubclassWindow();
3227 EnableToolTips(TRUE);
3228 SetWindowTheme(GetSafeHwnd(), L"Explorer", nullptr);
3231 void CGitStatusListCtrl::OnPaint()
3233 LRESULT defres = Default();
3234 if ((m_bBusy) || (m_bEmpty))
3236 CString str;
3237 if (m_bBusy)
3239 if (m_sBusy.IsEmpty())
3240 str.LoadString(IDS_STATUSLIST_BUSYMSG);
3241 else
3242 str = m_sBusy;
3244 else
3246 if (m_sEmpty.IsEmpty())
3247 str.LoadString(IDS_STATUSLIST_EMPTYMSG);
3248 else
3249 str = m_sEmpty;
3251 COLORREF clrText = ::GetSysColor(COLOR_WINDOWTEXT);
3252 COLORREF clrTextBk;
3253 if (IsWindowEnabled())
3254 clrTextBk = ::GetSysColor(COLOR_WINDOW);
3255 else
3256 clrTextBk = ::GetSysColor(COLOR_3DFACE);
3258 CRect rc;
3259 GetClientRect(&rc);
3260 CHeaderCtrl* pHC = GetHeaderCtrl();
3261 if (pHC)
3263 CRect rcH;
3264 pHC->GetItemRect(0, &rcH);
3265 rc.top += rcH.bottom;
3267 CDC* pDC = GetDC();
3269 CMyMemDC memDC(pDC, &rc);
3271 memDC.SetTextColor(clrText);
3272 memDC.SetBkColor(clrTextBk);
3273 memDC.BitBlt(rc.left, rc.top, rc.Width(), rc.Height(), pDC, rc.left, rc.top, SRCCOPY);
3274 rc.top += 10;
3275 CGdiObject * oldfont = memDC.SelectStockObject(DEFAULT_GUI_FONT);
3276 memDC.DrawText(str, rc, DT_CENTER | DT_VCENTER |
3277 DT_WORDBREAK | DT_NOPREFIX | DT_NOCLIP);
3278 memDC.SelectObject(oldfont);
3280 ReleaseDC(pDC);
3282 if (defres)
3284 // the Default() call did not process the WM_PAINT message!
3285 // Validate the update region ourselves to avoid
3286 // an endless loop repainting
3287 CRect rc;
3288 GetUpdateRect(&rc, FALSE);
3289 if (!rc.IsRectEmpty())
3290 ValidateRect(rc);
3294 void CGitStatusListCtrl::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
3296 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
3298 Locker lock(m_critSec);
3300 CTGitPathList pathList;
3301 FillListOfSelectedItemPaths(pathList);
3302 if (pathList.IsEmpty())
3303 return;
3305 auto pdsrc = std::make_unique<CIDropSource>();
3306 if (!pdsrc)
3307 return;
3308 pdsrc->AddRef();
3310 GitDataObject* pdobj = new GitDataObject(pathList, m_CurrentVersion);
3311 if (!pdobj)
3312 return;
3313 pdobj->AddRef();
3315 CDragSourceHelper dragsrchelper;
3317 // Something strange is going on here:
3318 // InitializeFromWindow() crashes bad if group view is enabled.
3319 // Since I haven't been able to find out *why* it crashes, I'm disabling
3320 // the group view right before the call to InitializeFromWindow() and
3321 // re-enable it again after the call is finished.
3323 SetRedraw(false);
3324 BOOL bGroupView = IsGroupViewEnabled();
3325 if (bGroupView)
3326 EnableGroupView(false);
3327 dragsrchelper.InitializeFromWindow(m_hWnd, pNMLV->ptAction, pdobj);
3328 if (bGroupView)
3329 EnableGroupView(true);
3330 SetRedraw(true);
3331 //dragsrchelper.InitializeFromBitmap()
3332 pdsrc->m_pIDataObj = pdobj;
3333 pdsrc->m_pIDataObj->AddRef();
3335 // Initiate the Drag & Drop
3336 DWORD dwEffect;
3337 m_bOwnDrag = true;
3338 ::DoDragDrop(pdobj, pdsrc.get(), DROPEFFECT_MOVE | DROPEFFECT_COPY, &dwEffect);
3339 m_bOwnDrag = false;
3340 pdsrc->Release();
3341 pdsrc.release();
3342 pdobj->Release();
3344 *pResult = 0;
3347 bool CGitStatusListCtrl::EnableFileDrop()
3349 m_bFileDropsEnabled = true;
3350 return true;
3353 bool CGitStatusListCtrl::HasPath(const CTGitPath& path)
3355 for (size_t i=0; i < m_arStatusArray.size(); ++i)
3357 if (m_arStatusArray[i]->IsEquivalentTo(path))
3358 return true;
3361 return false;
3364 BOOL CGitStatusListCtrl::PreTranslateMessage(MSG* pMsg)
3366 if (pMsg->message == WM_KEYDOWN)
3368 switch (pMsg->wParam)
3370 case 'A':
3372 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3374 // select all entries
3375 for (int i=0; i<GetItemCount(); ++i)
3376 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3377 return TRUE;
3380 break;
3381 case 'C':
3382 case VK_INSERT:
3384 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3386 // copy all selected paths to the clipboard
3387 if (GetAsyncKeyState(VK_SHIFT)&0x8000)
3388 CopySelectedEntriesToClipboard(GITSLC_COLSTATUS);
3389 else
3390 CopySelectedEntriesToClipboard(0);
3391 return TRUE;
3394 break;
3395 case VK_DELETE:
3397 if ((GetSelectedCount() > 0) && (m_dwContextMenus & GITSLC_POPDELETE))
3399 m_bBlock = TRUE;
3400 CTGitPath * filepath = (CTGitPath *)GetItemData(GetSelectionMark());
3401 if (filepath != nullptr && (filepath->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)))
3402 DeleteSelectedFiles();
3403 m_bBlock = FALSE;
3406 break;
3410 return __super::PreTranslateMessage(pMsg);
3413 bool CGitStatusListCtrl::CopySelectedEntriesToClipboard(DWORD dwCols)
3415 static HINSTANCE hResourceHandle(AfxGetResourceHandle());
3416 // WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
3418 CString sClipboard;
3419 CString temp;
3420 //TCHAR buf[100];
3421 if (GetSelectedCount() == 0)
3422 return false;
3424 // first add the column titles as the first line
3425 // We needn't head when only path copy
3426 //temp.LoadString(IDS_STATUSLIST_COLFILE);
3427 //sClipboard = temp;
3429 DWORD selection = 0;
3430 for (int i = 0, count = m_ColumnManager.GetColumnCount(); i < count; ++i)
3431 if ( ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3432 || ((dwCols != 1) && (i < 32) && ((dwCols & (1 << i)) != 0)))
3434 sClipboard += _T("\t") + m_ColumnManager.GetName(i);
3436 if (i < 32)
3437 selection += 1 << i;
3440 if(dwCols)
3441 sClipboard += _T("\r\n");
3443 POSITION pos = GetFirstSelectedItemPosition();
3444 int index;
3445 while ((index = GetNextSelectedItem(pos)) >= 0)
3447 CTGitPath * entry = (CTGitPath*)GetItemData(index);
3448 if (!entry)
3449 continue;
3451 sClipboard += entry->GetWinPathString();
3452 if (selection & GITSLC_COLFILENAME)
3453 sClipboard += _T("\t")+entry->GetFileOrDirectoryName();
3454 if (selection & GITSLC_COLEXT)
3455 sClipboard += _T("\t")+entry->GetFileExtension();
3457 if (selection & GITSLC_COLSTATUS)
3458 sClipboard += _T("\t")+entry->GetActionName();
3459 #if 0
3460 if (selection & SVNSLC_COLDATE)
3462 TCHAR datebuf[SVN_DATE_BUFFER];
3463 apr_time_t date = entry->last_commit_date;
3464 SVN::formatDate(datebuf, date, true);
3465 if (date)
3466 temp = datebuf;
3467 else
3468 temp.Empty();
3469 sClipboard += _T("\t")+temp;
3471 for ( int i = SVNSLC_NUMCOLUMNS, count = m_ColumnManager.GetColumnCount()
3472 ; i < count
3473 ; ++i)
3475 if ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3477 CString value
3478 = entry->present_props[m_ColumnManager.GetName(i)];
3479 sClipboard += _T("\t") + value;
3482 #endif
3483 if (selection & GITSLC_COLADD)
3484 sClipboard += _T("\t")+entry->m_StatAdd;
3485 if (selection & GITSLC_COLDEL)
3486 sClipboard += _T("\t")+entry->m_StatDel;
3488 sClipboard += _T("\r\n");
3491 return CStringUtils::WriteAsciiStringToClipboard(sClipboard);
3494 size_t CGitStatusListCtrl::GetNumberOfChangelistsInSelection()
3496 #if 0
3497 std::set<CString> changelists;
3498 POSITION pos = GetFirstSelectedItemPosition();
3499 int index;
3500 while ((index = GetNextSelectedItem(pos)) >= 0)
3502 FileEntry * entry = GetListEntry(index);
3503 if (!entry->changelist.IsEmpty())
3504 changelists.insert(entry->changelist);
3506 return changelists.size();
3507 #endif
3508 return 0;
3511 bool CGitStatusListCtrl::PrepareGroups(bool bForce /* = false */)
3513 bool bHasGroups=false;
3514 int max =0;
3516 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
3518 int ParentNo = m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3519 if( ParentNo > max)
3520 max=m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3523 if (((m_dwShow & GITSLC_SHOWUNVERSIONED) && !m_UnRevFileList.IsEmpty()) ||
3524 ((m_dwShow & GITSLC_SHOWIGNORED) && !m_IgnoreFileList.IsEmpty()) ||
3525 (m_dwShow & (GITSLC_SHOWASSUMEVALID | GITSLC_SHOWSKIPWORKTREE) && !m_LocalChangesIgnoredFileList.IsEmpty()) ||
3526 max>0 || bForce)
3528 bHasGroups = true;
3531 RemoveAllGroups();
3532 EnableGroupView(bHasGroups);
3534 TCHAR groupname[1024] = { 0 };
3535 int groupindex = 0;
3537 if(bHasGroups)
3539 LVGROUP grp = {0};
3540 grp.cbSize = sizeof(LVGROUP);
3541 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3542 groupindex=0;
3544 //if(m_UnRevFileList.GetCount()>0)
3545 if(max >0)
3547 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MERGEDFILES)), 1023);
3548 grp.pszHeader = groupname;
3549 grp.iGroupId = MERGE_MASK;
3550 grp.uAlign = LVGA_HEADER_LEFT;
3551 InsertGroup(0, &grp);
3553 CAutoRepository repository(g_Git.GetGitRepository());
3554 if (!repository)
3555 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3556 for (int i = 0; i <= max; ++i)
3558 CString str;
3559 str.Format(IDS_STATUSLIST_GROUP_DIFFWITHPARENT, i+1);
3560 if (repository)
3562 CString rev;
3563 rev.Format(_T("%s^%d"), (LPCTSTR)m_CurrentVersion, i + 1);
3564 CGitHash hash;
3565 if (!CGit::GetHash(repository, hash, rev))
3566 str += _T(": ") + hash.ToString().Left(g_Git.GetShortHASHLength());
3568 grp.pszHeader = str.GetBuffer();
3569 str.ReleaseBuffer();
3570 grp.iGroupId = i;
3571 grp.uAlign = LVGA_HEADER_LEFT;
3572 InsertGroup(i+1, &grp);
3575 else
3577 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MODIFIEDFILES)), 1023);
3578 grp.pszHeader = groupname;
3579 grp.iGroupId = groupindex;
3580 grp.uAlign = LVGA_HEADER_LEFT;
3581 InsertGroup(groupindex++, &grp);
3584 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_NOTVERSIONEDFILES)), 1023);
3585 grp.pszHeader = groupname;
3586 grp.iGroupId = groupindex;
3587 grp.uAlign = LVGA_HEADER_LEFT;
3588 InsertGroup(groupindex++, &grp);
3591 //if(m_IgnoreFileList.GetCount()>0)
3593 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNOREDFILES)), 1023);
3594 grp.pszHeader = groupname;
3595 grp.iGroupId = groupindex;
3596 grp.uAlign = LVGA_HEADER_LEFT;
3597 InsertGroup(groupindex++, &grp);
3601 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNORELOCALCHANGES)), 1023);
3602 grp.pszHeader = groupname;
3603 grp.iGroupId = groupindex;
3604 grp.uAlign = LVGA_HEADER_LEFT;
3605 InsertGroup(groupindex++, &grp);
3610 #if 0
3611 m_bHasIgnoreGroup = false;
3613 // now add the items which don't belong to a group
3614 LVGROUP grp = {0};
3615 grp.cbSize = sizeof(LVGROUP);
3616 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3617 CString sUnassignedName(MAKEINTRESOURCE(IDS_STATUSLIST_UNASSIGNED_CHANGESET));
3618 _tcsncpy_s(groupname, 1024, (LPCTSTR)sUnassignedName, 1023);
3619 grp.pszHeader = groupname;
3620 grp.iGroupId = groupindex;
3621 grp.uAlign = LVGA_HEADER_LEFT;
3622 InsertGroup(groupindex++, &grp);
3624 for (auto it = m_changelists.cbegin(); it != m_changelists.cend(); ++it)
3626 if (it->first.Compare(SVNSLC_IGNORECHANGELIST)!=0)
3628 LVGROUP grp = {0};
3629 grp.cbSize = sizeof(LVGROUP);
3630 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3631 _tcsncpy_s(groupname, 1024, it->first, 1023);
3632 grp.pszHeader = groupname;
3633 grp.iGroupId = groupindex;
3634 grp.uAlign = LVGA_HEADER_LEFT;
3635 it->second = InsertGroup(groupindex++, &grp);
3637 else
3638 m_bHasIgnoreGroup = true;
3641 if (m_bHasIgnoreGroup)
3643 // and now add the group 'ignore-on-commit'
3644 std::map<CString,int>::iterator it = m_changelists.find(SVNSLC_IGNORECHANGELIST);
3645 if (it != m_changelists.end())
3647 grp.cbSize = sizeof(LVGROUP);
3648 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3649 _tcsncpy_s(groupname, 1024, SVNSLC_IGNORECHANGELIST, 1023);
3650 grp.pszHeader = groupname;
3651 grp.iGroupId = groupindex;
3652 grp.uAlign = LVGA_HEADER_LEFT;
3653 it->second = InsertGroup(groupindex, &grp);
3656 #endif
3657 return bHasGroups;
3660 void CGitStatusListCtrl::NotifyCheck()
3662 CWnd* pParent = GetLogicalParent();
3663 if (pParent && pParent->GetSafeHwnd())
3665 pParent->SendMessage(GITSLNM_CHECKCHANGED, m_nSelected);
3669 int CGitStatusListCtrl::UpdateFileList(CTGitPathList *list)
3671 m_CurrentVersion = GIT_REV_ZERO;
3673 g_Git.GetWorkingTreeChanges(m_StatusFileList, m_amend, list);
3675 BOOL bDeleteChecked = FALSE;
3676 int deleteFromIndex = 0;
3677 bool needsRefresh = false;
3678 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
3680 CTGitPath * gitpatch=(CTGitPath*)&m_StatusFileList[i];
3681 gitpatch->m_Checked = TRUE;
3683 if ((gitpatch->m_Action & (CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_REPLACED | CTGitPath::LOGACTIONS_MODIFIED)) && !gitpatch->Exists())
3685 if (!bDeleteChecked)
3687 CString message;
3688 message.Format(IDS_ASK_REMOVE_FROM_INDEX, gitpatch->GetWinPath());
3689 deleteFromIndex = CMessageBox::ShowCheck(GetSafeHwnd(), message, _T("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);
3691 if (deleteFromIndex == 1)
3693 CString err;
3694 if (g_Git.Run(_T("git.exe checkout -- \"") + gitpatch->GetWinPathString() + _T("\""), &err, CP_UTF8))
3695 MessageBox(_T("Restoring from index failed:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
3696 else
3697 needsRefresh = true;
3699 else if (deleteFromIndex == 2)
3701 CString err;
3702 if (g_Git.Run(_T("git.exe rm -f --cache -- \"") + gitpatch->GetWinPathString() + _T("\""), &err, CP_UTF8))
3703 MessageBox(_T("Removing from index failed:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
3704 else
3705 needsRefresh = true;
3709 m_arStatusArray.push_back((CTGitPath*)&m_StatusFileList[i]);
3712 if (needsRefresh)
3713 MessageBox(_T("Due to changes to the index, please refresh the dialog (e.g., by pressing F5)."), _T("TortoiseGit"), MB_ICONINFORMATION);
3715 return 0;
3718 int CGitStatusListCtrl::UpdateWithGitPathList(CTGitPathList &list)
3720 m_arStatusArray.clear();
3721 for (int i = 0; i < list.GetCount(); ++i)
3723 CTGitPath * gitpath=(CTGitPath*)&list[i];
3725 if(gitpath ->m_Action & CTGitPath::LOGACTIONS_HIDE)
3726 continue;
3728 gitpath->m_Checked = TRUE;
3729 m_arStatusArray.push_back((CTGitPath*)&list[i]);
3731 return 0;
3734 int CGitStatusListCtrl::UpdateUnRevFileList(CTGitPathList &list)
3736 m_UnRevFileList = list;
3737 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
3739 CTGitPath * gitpatch=(CTGitPath*)&m_UnRevFileList[i];
3740 gitpatch->m_Checked = FALSE;
3741 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
3743 return 0;
3746 int CGitStatusListCtrl::UpdateUnRevFileList(CTGitPathList *List)
3748 CString err;
3749 if (m_UnRevFileList.FillUnRev(CTGitPath::LOGACTIONS_UNVER, List, &err))
3751 CMessageBox::Show(GetSafeHwnd(), _T("Failed to get UnRev file list\n") + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3752 return -1;
3755 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
3757 CTGitPath * gitpatch=(CTGitPath*)&m_UnRevFileList[i];
3758 gitpatch->m_Checked = FALSE;
3759 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
3761 return 0;
3764 int CGitStatusListCtrl::UpdateIgnoreFileList(CTGitPathList *List)
3766 CString err;
3767 if (m_IgnoreFileList.FillUnRev(CTGitPath::LOGACTIONS_IGNORE, List, &err))
3769 CMessageBox::Show(GetSafeHwnd(), _T("Failed to get Ignore file list\n") + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3770 return -1;
3773 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
3775 CTGitPath * gitpatch=(CTGitPath*)&m_IgnoreFileList[i];
3776 gitpatch->m_Checked = FALSE;
3777 m_arStatusArray.push_back((CTGitPath*)&m_IgnoreFileList[i]);
3779 return 0;
3782 int CGitStatusListCtrl::UpdateLocalChangesIgnoredFileList(CTGitPathList *list)
3784 m_LocalChangesIgnoredFileList.FillBasedOnIndexFlags(GIT_IDXENTRY_VALID, GIT_IDXENTRY_SKIP_WORKTREE, list);
3785 for (int i = 0; i < m_LocalChangesIgnoredFileList.GetCount(); ++i)
3787 CTGitPath * gitpatch = (CTGitPath*)&m_LocalChangesIgnoredFileList[i];
3788 gitpatch->m_Checked = FALSE;
3789 m_arStatusArray.push_back((CTGitPath*)&m_LocalChangesIgnoredFileList[i]);
3791 return 0;
3794 int CGitStatusListCtrl::UpdateFileList(int mask,bool once,CTGitPathList *List)
3796 if(mask&CGitStatusListCtrl::FILELIST_MODIFY)
3798 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_MODIFY)))
3800 UpdateFileList(List);
3801 m_FileLoaded|=CGitStatusListCtrl::FILELIST_MODIFY;
3804 if (mask & CGitStatusListCtrl::FILELIST_UNVER || mask & CGitStatusListCtrl::FILELIST_IGNORE)
3806 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_UNVER)))
3808 UpdateUnRevFileList(List);
3809 m_FileLoaded|=CGitStatusListCtrl::FILELIST_UNVER;
3811 if(mask&CGitStatusListCtrl::FILELIST_IGNORE && (once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_IGNORE))))
3813 UpdateIgnoreFileList(List);
3814 m_FileLoaded |= CGitStatusListCtrl::FILELIST_IGNORE;
3817 if (mask & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED && (once || (!(m_FileLoaded & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED))))
3819 UpdateLocalChangesIgnoredFileList(List);
3820 m_FileLoaded |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
3822 return 0;
3825 void CGitStatusListCtrl::Clear()
3827 m_FileLoaded=0;
3828 this->DeleteAllItems();
3829 this->m_arListArray.clear();
3830 this->m_arStatusArray.clear();
3831 this->m_changelists.clear();
3834 bool CGitStatusListCtrl::CheckMultipleDiffs()
3836 UINT selCount = GetSelectedCount();
3837 if (selCount > max(3, (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\NumDiffWarning"), 10)))
3839 CString message;
3840 message.Format(IDS_STATUSLIST_WARN_MAXDIFF, selCount);
3841 return ::MessageBox(GetSafeHwnd(), message, _T("TortoiseGit"), MB_YESNO | MB_ICONQUESTION) == IDYES;
3843 return true;
3846 //////////////////////////////////////////////////////////////////////////
3847 #if 0
3848 bool CGitStatusListCtrlDropTarget::OnDrop(FORMATETC* pFmtEtc, STGMEDIUM& medium, DWORD * /*pdwEffect*/, POINTL pt)
3850 if(pFmtEtc->cfFormat == CF_HDROP && medium.tymed == TYMED_HGLOBAL)
3852 HDROP hDrop = (HDROP)GlobalLock(medium.hGlobal);
3853 if (hDrop)
3855 TCHAR szFileName[MAX_PATH] = {0};
3857 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, nullptr, 0);
3859 POINT clientpoint;
3860 clientpoint.x = pt.x;
3861 clientpoint.y = pt.y;
3862 ScreenToClient(m_hTargetWnd, &clientpoint);
3863 if ((m_pSVNStatusListCtrl->IsGroupViewEnabled())&&(m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
3865 CTSVNPathList changelistItems;
3866 for(UINT i = 0; i < cFiles; ++i)
3868 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
3869 changelistItems.AddPath(CTSVNPath(szFileName));
3871 // find the changelist name
3872 CString sChangelist;
3873 LONG_PTR nGroup = m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint);
3874 for (std::map<CString, int>::iterator it = m_pSVNStatusListCtrl->m_changelists.begin(); it != m_pSVNStatusListCtrl->m_changelists.end(); ++it)
3875 if (it->second == nGroup)
3876 sChangelist = it->first;
3877 if (!sChangelist.IsEmpty())
3879 SVN git;
3880 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
3882 for (int l=0; l<changelistItems.GetCount(); ++l)
3884 int index = m_pSVNStatusListCtrl->GetIndex(changelistItems[l]);
3885 if (index >= 0)
3887 CSVNStatusListCtrl::FileEntry * e = m_pSVNStatusListCtrl->GetListEntry(index);
3888 if (e)
3890 e->changelist = sChangelist;
3891 if (!e->IsFolder())
3893 if (m_pSVNStatusListCtrl->m_changelists.find(e->changelist)!=m_pSVNStatusListCtrl->m_changelists.end())
3894 m_pSVNStatusListCtrl->SetItemGroup(index, m_pSVNStatusListCtrl->m_changelists[e->changelist]);
3895 else
3896 m_pSVNStatusListCtrl->SetItemGroup(index, 0);
3900 else
3902 HWND hParentWnd = GetParent(m_hTargetWnd);
3903 if (hParentWnd)
3904 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
3908 else
3909 CMessageBox::Show(m_pSVNStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
3911 else
3913 SVN git;
3914 if (git.RemoveFromChangeList(changelistItems, CStringArray(), git_depth_empty))
3916 for (int l=0; l<changelistItems.GetCount(); ++l)
3918 int index = m_pSVNStatusListCtrl->GetIndex(changelistItems[l]);
3919 if (index >= 0)
3921 CSVNStatusListCtrl::FileEntry * e = m_pSVNStatusListCtrl->GetListEntry(index);
3922 if (e)
3924 e->changelist = sChangelist;
3925 m_pSVNStatusListCtrl->SetItemGroup(index, 0);
3928 else
3930 HWND hParentWnd = GetParent(m_hTargetWnd);
3931 if (hParentWnd)
3932 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
3936 else
3937 CMessageBox::Show(m_pSVNStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
3940 else
3942 for(UINT i = 0; i < cFiles; ++i)
3944 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
3945 HWND hParentWnd = GetParent(m_hTargetWnd);
3946 if (hParentWnd)
3947 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)szFileName);
3951 GlobalUnlock(medium.hGlobal);
3953 return true; //let base free the medium
3956 HRESULT STDMETHODCALLTYPE CSVNStatusListCtrlDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD __RPC_FAR *pdwEffect)
3958 CIDropTarget::DragOver(grfKeyState, pt, pdwEffect);
3959 *pdwEffect = DROPEFFECT_COPY;
3960 if (m_pSVNStatusListCtrl)
3962 POINT clientpoint;
3963 clientpoint.x = pt.x;
3964 clientpoint.y = pt.y;
3965 ScreenToClient(m_hTargetWnd, &clientpoint);
3966 if ((m_pSVNStatusListCtrl->IsGroupViewEnabled())&&(m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
3967 *pdwEffect = DROPEFFECT_MOVE;
3968 else if ((!m_pSVNStatusListCtrl->m_bFileDropsEnabled)||(m_pSVNStatusListCtrl->m_bOwnDrag))
3969 *pdwEffect = DROPEFFECT_NONE;
3971 return S_OK;
3974 #endif
3976 void CGitStatusListCtrl::FilesExport()
3978 CString exportDir;
3979 // export all changed files to a folder
3980 CBrowseFolder browseFolder;
3981 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
3982 if (browseFolder.Show(GetSafeHwnd(), exportDir) != CBrowseFolder::OK)
3983 return;
3985 POSITION pos = GetFirstSelectedItemPosition();
3986 int index;
3987 while ((index = GetNextSelectedItem(pos)) >= 0)
3989 CTGitPath *fd = (CTGitPath*)GetItemData(index);
3990 // we cannot export directories or folders
3991 if ((fd->m_Action & CTGitPath::LOGACTIONS_DELETED) || fd->IsDirectory())
3992 continue;
3994 CPathUtils::MakeSureDirectoryPathExists(exportDir + _T("\\") + fd->GetContainingDirectory().GetWinPathString());
3995 CString filename = exportDir + _T("\\") + fd->GetWinPathString();
3996 if (m_CurrentVersion == GIT_REV_ZERO)
3998 if (!CopyFile(g_Git.CombinePath(fd), filename, false))
4000 MessageBox(CFormatMessageWrapper(), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
4001 return;
4004 else
4006 if (g_Git.GetOneFile(m_CurrentVersion, *fd, filename))
4008 CString out;
4009 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)fd->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)filename);
4010 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)
4011 return;
4017 void CGitStatusListCtrl::FileSaveAs(CTGitPath *path)
4019 CString filename;
4020 filename.Format(_T("%s-%s%s"), (LPCTSTR)path->GetBaseFilename(), (LPCTSTR)this->m_CurrentVersion.Left(g_Git.GetShortHASHLength()), (LPCTSTR)path->GetFileExtension());
4021 CFileDialog dlg(FALSE, nullptr, filename, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, nullptr);
4023 CString currentpath = g_Git.CombinePath(path->GetContainingDirectory());
4024 dlg.m_ofn.lpstrInitialDir = currentpath;
4026 CString cmd,out;
4027 INT_PTR ret = dlg.DoModal();
4028 SetCurrentDirectory(g_Git.m_CurrentDir);
4029 if (ret == IDOK)
4031 filename = dlg.GetPathName();
4032 if(m_CurrentVersion == GIT_REV_ZERO)
4034 if(!CopyFile(g_Git.CombinePath(path), filename, false))
4036 MessageBox(CFormatMessageWrapper(), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
4037 return;
4040 else
4042 if(g_Git.GetOneFile(m_CurrentVersion,*path,filename))
4044 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)path->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)filename);
4045 CMessageBox::Show(GetSafeHwnd(), g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), L"TortoiseGit", MB_OK);
4046 return;
4052 int CGitStatusListCtrl::RevertSelectedItemToVersion(bool parent)
4054 if(this->m_CurrentVersion.IsEmpty())
4055 return 0;
4056 if(this->m_CurrentVersion == GIT_REV_ZERO)
4057 return 0;
4059 POSITION pos = GetFirstSelectedItemPosition();
4060 int index;
4061 CString cmd,out;
4062 std::map<CString, int> versionMap;
4063 while ((index = GetNextSelectedItem(pos)) >= 0)
4065 CTGitPath *fentry=(CTGitPath*)GetItemData(index);
4066 CString version;
4067 if (parent)
4069 int parentNo = fentry->m_ParentNo & PARENT_MASK;
4070 CString ref;
4071 ref.Format(_T("%s^%d"), (LPCTSTR)m_CurrentVersion, parentNo + 1);
4072 CGitHash hash;
4073 if (g_Git.GetHash(hash, ref))
4075 MessageBox(g_Git.GetGitLastErr(_T("Could not get hash of ref \"") + ref + _T("\".")), _T("TortoiseGit"), MB_ICONERROR);
4076 continue;
4079 version = hash.ToString();
4081 else
4082 version = m_CurrentVersion;
4084 CString filename = fentry->GetGitPathString();
4085 if (!fentry->GetGitOldPathString().IsEmpty())
4086 filename = fentry->GetGitOldPathString();
4087 cmd.Format(_T("git.exe checkout %s -- \"%s\""), (LPCTSTR)version, (LPCTSTR)filename);
4088 out.Empty();
4089 if (g_Git.Run(cmd, &out, CP_UTF8))
4091 if (MessageBox(out, _T("TortoiseGit"), MB_ICONEXCLAMATION | MB_OKCANCEL) == IDCANCEL)
4092 continue;
4094 else
4095 versionMap[version]++;
4098 out.Empty();
4099 for (auto it = versionMap.cbegin(); it != versionMap.cend(); ++it)
4101 CString versionEntry;
4102 versionEntry.Format(IDS_STATUSLIST_FILESREVERTED, it->second, (LPCTSTR)it->first);
4103 out += versionEntry + _T("\r\n");
4105 if (!out.IsEmpty())
4106 CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", MB_OK);
4107 return 0;
4110 void CGitStatusListCtrl::OpenFile(CTGitPath*filepath,int mode)
4112 CString file;
4113 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
4114 file = g_Git.CombinePath(filepath);
4115 else
4117 CString temppath;
4118 GetTempPath(temppath);
4119 TCHAR szTempName[MAX_PATH] = {0};
4120 GetTempFileName(temppath, filepath->GetBaseFilename(), 0, szTempName);
4121 CString temp(szTempName);
4122 DeleteFile(szTempName);
4123 CreateDirectory(szTempName, nullptr);
4124 file.Format(_T("%s\\%s_%s%s"),
4125 (LPCTSTR)temp,
4126 (LPCTSTR)filepath->GetBaseFilename(),
4127 (LPCTSTR)m_CurrentVersion.Left(g_Git.GetShortHASHLength()),
4128 (LPCTSTR)filepath->GetFileExtension());
4129 CString cmd,out;
4130 if(g_Git.GetOneFile(m_CurrentVersion, *filepath, file))
4132 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)filepath->GetGitPathString(), (LPCTSTR)m_CurrentVersion, (LPCTSTR)file);
4133 CMessageBox::Show(GetSafeHwnd(), g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), L"TortoiseGit", MB_OK);
4134 return;
4136 SetFileAttributes(file, FILE_ATTRIBUTE_READONLY);
4138 if(mode == ALTERNATIVEEDITOR)
4140 CAppUtils::LaunchAlternativeEditor(file);
4141 return;
4144 if (mode == OPEN)
4145 CAppUtils::ShellOpen(file, GetSafeHwnd());
4146 else
4147 CAppUtils::ShowOpenWithDialog(file, GetSafeHwnd());
4150 void CGitStatusListCtrl::DeleteSelectedFiles()
4152 //Collect paths
4153 std::vector<int> selectIndex;
4155 POSITION pos = GetFirstSelectedItemPosition();
4156 int index;
4157 while ((index = GetNextSelectedItem(pos)) >= 0)
4158 selectIndex.push_back(index);
4160 CAutoRepository repo = g_Git.GetGitRepository();
4161 if (!repo)
4163 MessageBox(g_Git.GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_OK);
4164 return;
4166 CAutoIndex gitIndex;
4167 if (git_repository_index(gitIndex.GetPointer(), repo))
4169 g_Git.GetLibGit2LastErr(_T("Could not open index."));
4170 return;
4172 int needWriteIndex = 0;
4174 //Create file-list ('\0' separated) for SHFileOperation
4175 CString filelist;
4176 for (size_t i = 0; i < selectIndex.size(); ++i)
4178 index = selectIndex[i];
4180 CTGitPath * path=(CTGitPath*)GetItemData(index);
4181 ASSERT(path);
4182 if (path == nullptr)
4183 continue;
4185 // do not report errors as we could remove an unversioned file
4186 needWriteIndex += git_index_remove_bypath(gitIndex, CUnicodeUtils::GetUTF8(path->GetGitPathString())) == 0 ? 1 : 0;
4188 if (!path->Exists())
4189 continue;
4191 filelist += path->GetWinPathString();
4192 filelist += _T("|");
4194 filelist += _T("|");
4195 int len = filelist.GetLength();
4196 auto buf = std::make_unique<TCHAR[]>(len + 2);
4197 _tcscpy_s(buf.get(), len + 2, filelist);
4198 CStringUtils::PipesToNulls(buf.get(), len + 2);
4199 SHFILEOPSTRUCT fileop;
4200 fileop.hwnd = this->m_hWnd;
4201 fileop.wFunc = FO_DELETE;
4202 fileop.pFrom = buf.get();
4203 fileop.pTo = nullptr;
4204 fileop.fFlags = FOF_NO_CONNECTED_ELEMENTS | ((GetAsyncKeyState(VK_SHIFT) & 0x8000) ? 0 : FOF_ALLOWUNDO);
4205 fileop.lpszProgressTitle = _T("deleting file");
4206 int result = SHFileOperation(&fileop);
4208 if ((result == 0 || len == 1) && (!fileop.fAnyOperationsAborted))
4210 if (needWriteIndex && git_index_write(gitIndex))
4211 MessageBox(g_Git.GetLibGit2LastErr(_T("Could not write index.")), _T("TortoiseGit"), MB_OK);
4213 if (needWriteIndex)
4215 CWnd* pParent = GetLogicalParent();
4216 if (pParent && pParent->GetSafeHwnd())
4217 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
4218 SetRedraw(TRUE);
4219 return;
4222 SetRedraw(FALSE);
4223 POSITION pos2 = nullptr;
4224 while ((pos2 = GetFirstSelectedItemPosition()) != nullptr)
4226 int index2 = GetNextSelectedItem(pos2);
4227 if (GetCheck(index2))
4228 m_nSelected--;
4229 m_nTotal--;
4231 RemoveListEntry(index2);
4233 SetRedraw(TRUE);
4237 BOOL CGitStatusListCtrl::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
4239 switch (message)
4241 case WM_MENUCHAR: // only supported by IContextMenu3
4242 if (g_IContext3)
4244 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4245 return TRUE;
4247 break;
4249 case WM_DRAWITEM:
4250 case WM_MEASUREITEM:
4251 if (wParam)
4252 break; // if wParam != 0 then the message is not menu-related
4254 case WM_INITMENU:
4255 case WM_INITMENUPOPUP:
4257 HMENU hMenu = (HMENU)wParam;
4258 if ((hMenu == m_hShellMenu) && (GetMenuItemCount(hMenu) == 0))
4260 // the shell submenu is populated only on request, i.e. right
4261 // before the submenu is shown
4262 if (g_pFolderhook)
4264 delete g_pFolderhook;
4265 g_pFolderhook = nullptr;
4267 CTGitPathList targetList;
4268 FillListOfSelectedItemPaths(targetList);
4269 if (!targetList.IsEmpty())
4271 // get IShellFolder interface of Desktop (root of shell namespace)
4272 if (g_psfDesktopFolder)
4273 g_psfDesktopFolder->Release();
4274 SHGetDesktopFolder(&g_psfDesktopFolder); // needed to obtain full qualified pidl
4276 // ParseDisplayName creates a PIDL from a file system path relative to the IShellFolder interface
4277 // but since we use the Desktop as our interface and the Desktop is the namespace root
4278 // that means that it's a fully qualified PIDL, which is what we need
4280 if (g_pidlArray)
4282 for (int i = 0; i < g_pidlArrayItems; i++)
4284 if (g_pidlArray[i])
4285 CoTaskMemFree(g_pidlArray[i]);
4287 CoTaskMemFree(g_pidlArray);
4288 g_pidlArray = nullptr;
4289 g_pidlArrayItems = 0;
4291 int nItems = targetList.GetCount();
4292 g_pidlArray = (LPITEMIDLIST *)CoTaskMemAlloc((nItems + 10) * sizeof(LPITEMIDLIST));
4293 SecureZeroMemory(g_pidlArray, (nItems + 10) * sizeof(LPITEMIDLIST));
4294 int succeededItems = 0;
4295 PIDLIST_RELATIVE pidl = nullptr;
4297 int bufsize = 1024;
4298 auto filepath = std::make_unique<WCHAR[]>(bufsize);
4299 for (int i = 0; i < nItems; i++)
4301 CString fullPath = g_Git.CombinePath(targetList[i].GetWinPath());
4302 if (bufsize < fullPath.GetLength())
4304 bufsize = fullPath.GetLength() + 3;
4305 filepath = std::make_unique<WCHAR[]>(bufsize);
4307 wcscpy_s(filepath.get(), bufsize, fullPath);
4308 if (SUCCEEDED(g_psfDesktopFolder->ParseDisplayName(nullptr, 0, filepath.get(), nullptr, &pidl, nullptr)))
4309 g_pidlArray[succeededItems++] = pidl; // copy pidl to pidlArray
4311 if (succeededItems == 0)
4313 CoTaskMemFree(g_pidlArray);
4314 g_pidlArray = nullptr;
4317 g_pidlArrayItems = succeededItems;
4319 if (g_pidlArrayItems)
4321 CString ext = targetList[0].GetFileExtension();
4323 ASSOCIATIONELEMENT const rgAssocItem[] =
4325 { ASSOCCLASS_PROGID_STR, nullptr, ext },
4326 { ASSOCCLASS_SYSTEM_STR, nullptr, ext },
4327 { ASSOCCLASS_APP_STR, nullptr, ext },
4328 { ASSOCCLASS_STAR, nullptr, nullptr },
4329 { ASSOCCLASS_FOLDER, nullptr, nullptr },
4331 IQueryAssociations* pIQueryAssociations = nullptr;
4332 if (FAILED(AssocCreateForClasses(rgAssocItem, ARRAYSIZE(rgAssocItem), IID_IQueryAssociations, (void**)&pIQueryAssociations)))
4333 pIQueryAssociations = nullptr; // not a problem, it works without this
4335 g_pFolderhook = new CIShellFolderHook(g_psfDesktopFolder, targetList);
4336 LPCONTEXTMENU icm1 = nullptr;
4338 DEFCONTEXTMENU dcm = { 0 };
4339 dcm.hwnd = m_hWnd;
4340 dcm.psf = g_pFolderhook;
4341 dcm.cidl = g_pidlArrayItems;
4342 dcm.apidl = (PCUITEMID_CHILD_ARRAY)g_pidlArray;
4343 dcm.punkAssociationInfo = pIQueryAssociations;
4344 if (SUCCEEDED(SHCreateDefaultContextMenu(&dcm, IID_IContextMenu, (void**)&icm1)))
4346 int iMenuType = 0; // to know which version of IContextMenu is supported
4347 if (icm1)
4348 { // since we got an IContextMenu interface we can now obtain the higher version interfaces via that
4349 if (icm1->QueryInterface(IID_IContextMenu3, (void**)&m_pContextMenu) == S_OK)
4350 iMenuType = 3;
4351 else if (icm1->QueryInterface(IID_IContextMenu2, (void**)&m_pContextMenu) == S_OK)
4352 iMenuType = 2;
4354 if (m_pContextMenu)
4355 icm1->Release(); // we can now release version 1 interface, cause we got a higher one
4356 else
4358 // since no higher versions were found
4359 // redirect ppContextMenu to version 1 interface
4360 iMenuType = 1;
4361 m_pContextMenu = icm1;
4364 if (m_pContextMenu)
4366 // lets fill the our popup menu
4367 UINT flags = CMF_NORMAL;
4368 flags |= (GetKeyState(VK_SHIFT) & 0x8000) != 0 ? CMF_EXTENDEDVERBS : 0;
4369 m_pContextMenu->QueryContextMenu(hMenu, 0, SHELL_MIN_CMD, SHELL_MAX_CMD, flags);
4372 // subclass window to handle menu related messages in CShellContextMenu
4373 if (iMenuType > 1) // only subclass if its version 2 or 3
4375 if (iMenuType == 2)
4376 g_IContext2 = (LPCONTEXTMENU2)m_pContextMenu;
4377 else // version 3
4378 g_IContext3 = (LPCONTEXTMENU3)m_pContextMenu;
4382 if (pIQueryAssociations)
4383 pIQueryAssociations->Release();
4386 if (g_IContext3)
4387 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4388 else if (g_IContext2)
4389 g_IContext2->HandleMenuMsg(message, wParam, lParam);
4390 return TRUE;
4394 break;
4395 default:
4396 break;
4399 return __super::OnWndMsg(message, wParam, lParam, pResult);