Drop unused files and gettext translations stuff
[TortoiseGit.git] / src / Git / GitStatusListCtrl.cpp
blob376d578be359bfa15744a736103e6d4f2273aeec
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - TortoiseGit
4 // Copyright (C) 2003-2008, 2013-2014 - 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 "DropFiles.h"
42 #include "ProgressCommands/AddProgressCommand.h"
43 #include "IconMenu.h"
44 #include "FormatMessageWrapper.h"
45 #include "BrowseFolder.h"
47 const UINT CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED
48 = ::RegisterWindowMessage(_T("GITSLNM_ITEMCOUNTCHANGED"));
49 const UINT CGitStatusListCtrl::GITSLNM_NEEDSREFRESH
50 = ::RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
51 const UINT CGitStatusListCtrl::GITSLNM_ADDFILE
52 = ::RegisterWindowMessage(_T("GITSLNM_ADDFILE"));
53 const UINT CGitStatusListCtrl::GITSLNM_CHECKCHANGED
54 = ::RegisterWindowMessage(_T("GITSLNM_CHECKCHANGED"));
55 const UINT CGitStatusListCtrl::GITSLNM_ITEMCHANGED
56 = ::RegisterWindowMessage(_T("GITSLNM_ITEMCHANGED"));
58 struct icompare
60 bool operator() (const std::wstring& lhs, const std::wstring& rhs) const
62 // no logical comparison here: we need this sorted strictly
63 return _wcsicmp(lhs.c_str(), rhs.c_str()) < 0;
67 class CIShellFolderHook : public IShellFolder
69 public:
70 CIShellFolderHook(LPSHELLFOLDER sf, const CTGitPathList& pathlist)
72 sf->AddRef();
73 m_iSF = sf;
74 // it seems the paths in the HDROP need to be sorted, otherwise
75 // it might not work properly or even crash.
76 // to get the items sorted, we just add them to a set
77 for (int i = 0; i < pathlist.GetCount(); ++i)
78 sortedpaths.insert((LPCTSTR)g_Git.CombinePath(pathlist[i].GetWinPath()));
81 ~CIShellFolderHook() { m_iSF->Release(); }
83 // IUnknown methods --------
84 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject) { return m_iSF->QueryInterface(riid, ppvObject); }
85 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return m_iSF->AddRef(); }
86 virtual ULONG STDMETHODCALLTYPE Release(void) { return m_iSF->Release(); }
88 // IShellFolder methods ----
89 virtual HRESULT STDMETHODCALLTYPE GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv);
91 virtual HRESULT STDMETHODCALLTYPE CompareIDs(LPARAM lParam, __RPC__in PCUIDLIST_RELATIVE pidl1, __RPC__in PCUIDLIST_RELATIVE pidl2) { return m_iSF->CompareIDs(lParam, pidl1, pidl2); }
92 virtual HRESULT STDMETHODCALLTYPE GetDisplayNameOf(__RPC__in_opt PCUITEMID_CHILD pidl, SHGDNF uFlags, __RPC__out STRRET *pName) { return m_iSF->GetDisplayNameOf(pidl, uFlags, pName); }
93 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); }
94 virtual HRESULT STDMETHODCALLTYPE EnumObjects(__RPC__in_opt HWND hwndOwner, SHCONTF grfFlags, __RPC__deref_out_opt IEnumIDList **ppenumIDList) { return m_iSF->EnumObjects(hwndOwner, grfFlags, ppenumIDList); }
95 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); }
96 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); }
97 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); }
98 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); }
99 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); }
101 protected:
102 LPSHELLFOLDER m_iSF;
103 std::set<std::wstring, icompare> sortedpaths;
106 HRESULT STDMETHODCALLTYPE CIShellFolderHook::GetUIObjectOf(HWND hwndOwner, UINT cidl, PCUITEMID_CHILD_ARRAY apidl, REFIID riid, UINT *rgfReserved, void **ppv)
108 if (InlineIsEqualGUID(riid, IID_IDataObject))
110 HRESULT hres = m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, IID_IDataObject, NULL, ppv);
111 if (FAILED(hres))
112 return hres;
114 IDataObject * idata = (LPDATAOBJECT)(*ppv);
115 // the IDataObject returned here doesn't have a HDROP, so we create one ourselves and add it to the IDataObject
116 // the HDROP is necessary for most context menu handlers
117 int nLength = 0;
118 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
120 nLength += (int)it->size();
121 nLength += 1; // '\0' separator
123 int nBufferSize = sizeof(DROPFILES) + ((nLength + 5)*sizeof(TCHAR));
124 std::unique_ptr<char[]> pBuffer(new char[nBufferSize]);
125 SecureZeroMemory(pBuffer.get(), nBufferSize);
126 DROPFILES* df = (DROPFILES*)pBuffer.get();
127 df->pFiles = sizeof(DROPFILES);
128 df->fWide = 1;
129 TCHAR* pFilenames = (TCHAR*)((BYTE*)(pBuffer.get()) + sizeof(DROPFILES));
130 TCHAR* pCurrentFilename = pFilenames;
132 for (auto it = sortedpaths.cbegin(); it != sortedpaths.cend(); ++it)
134 wcscpy_s(pCurrentFilename, it->size() + 1, it->c_str());
135 pCurrentFilename += it->size();
136 *pCurrentFilename = '\0'; // separator between file names
137 pCurrentFilename++;
139 *pCurrentFilename = '\0'; // terminate array
140 pCurrentFilename++;
141 *pCurrentFilename = '\0'; // terminate array
142 STGMEDIUM medium = { 0 };
143 medium.tymed = TYMED_HGLOBAL;
144 medium.hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE, nBufferSize + 20);
145 if (medium.hGlobal)
147 LPVOID pMem = ::GlobalLock(medium.hGlobal);
148 if (pMem)
150 memcpy(pMem, pBuffer.get(), nBufferSize);
151 GlobalUnlock(medium.hGlobal);
152 FORMATETC formatetc = { 0 };
153 formatetc.cfFormat = CF_HDROP;
154 formatetc.dwAspect = DVASPECT_CONTENT;
155 formatetc.lindex = -1;
156 formatetc.tymed = TYMED_HGLOBAL;
157 medium.pUnkForRelease = nullptr;
158 hres = idata->SetData(&formatetc, &medium, TRUE);
159 return hres;
162 return E_OUTOFMEMORY;
164 else
166 // just pass it on to the base object
167 return m_iSF->GetUIObjectOf(hwndOwner, cidl, apidl, riid, rgfReserved, ppv);
171 IContextMenu2 * g_IContext2 = nullptr;
172 IContextMenu3 * g_IContext3 = nullptr;
173 CIShellFolderHook * g_pFolderhook = nullptr;
174 IShellFolder * g_psfDesktopFolder = nullptr;
175 LPITEMIDLIST * g_pidlArray = nullptr;
176 int g_pidlArrayItems = 0;
178 #define SHELL_MIN_CMD 10000
179 #define SHELL_MAX_CMD 20000
181 HRESULT CALLBACK dfmCallback(IShellFolder * /*psf*/, HWND /*hwnd*/, IDataObject * /*pdtobj*/, UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/)
183 switch (uMsg)
185 case DFM_MERGECONTEXTMENU:
186 return S_OK;
187 case DFM_INVOKECOMMAND:
188 case DFM_INVOKECOMMANDEX:
189 case DFM_GETDEFSTATICID: // Required for Windows 7 to pick a default
190 return S_FALSE;
192 return E_NOTIMPL;
195 BEGIN_MESSAGE_MAP(CGitStatusListCtrl, CListCtrl)
196 ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHdnItemclick)
197 ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHdnItemclick)
198 ON_NOTIFY(HDN_ENDTRACK, 0, OnColumnResized)
199 ON_NOTIFY(HDN_ENDDRAG, 0, OnColumnMoved)
200 ON_NOTIFY_REFLECT_EX(LVN_ITEMCHANGED, OnLvnItemchanged)
201 ON_WM_CONTEXTMENU()
202 ON_NOTIFY_REFLECT(NM_DBLCLK, OnNMDblclk)
203 ON_NOTIFY_REFLECT(LVN_GETINFOTIP, OnLvnGetInfoTip)
204 ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw)
205 ON_WM_SETCURSOR()
206 ON_WM_GETDLGCODE()
207 ON_NOTIFY_REFLECT(NM_RETURN, OnNMReturn)
208 ON_WM_KEYDOWN()
209 ON_WM_PAINT()
210 ON_NOTIFY(HDN_BEGINTRACKA, 0, &CGitStatusListCtrl::OnHdnBegintrack)
211 ON_NOTIFY(HDN_BEGINTRACKW, 0, &CGitStatusListCtrl::OnHdnBegintrack)
212 ON_NOTIFY(HDN_ITEMCHANGINGA, 0, &CGitStatusListCtrl::OnHdnItemchanging)
213 ON_NOTIFY(HDN_ITEMCHANGINGW, 0, &CGitStatusListCtrl::OnHdnItemchanging)
214 ON_WM_DESTROY()
215 ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
216 ON_NOTIFY_REFLECT(LVN_ITEMCHANGING, &CGitStatusListCtrl::OnLvnItemchanging)
217 END_MESSAGE_MAP()
221 CGitStatusListCtrl::CGitStatusListCtrl() : CListCtrl()
222 //, m_HeadRev(GitRev::REV_HEAD)
223 , m_pbCanceled(NULL)
224 , m_pStatLabel(NULL)
225 , m_pSelectButton(NULL)
226 , m_pConfirmButton(NULL)
227 , m_bBusy(false)
228 , m_bEmpty(false)
229 , m_bShowIgnores(false)
230 , m_pDropTarget(NULL)
231 , m_bIgnoreRemoveOnly(false)
232 , m_bCheckChildrenWithParent(false)
233 , m_bUnversionedLast(true)
234 , m_bHasChangeLists(false)
235 , m_bHasLocks(false)
236 , m_bBlock(false)
237 , m_bBlockUI(false)
238 , m_bHasCheckboxes(false)
239 , m_bCheckIfGroupsExist(true)
240 , m_bFileDropsEnabled(false)
241 , m_bOwnDrag(false)
242 , m_dwDefaultColumns(0)
243 , m_ColumnManager(this)
244 , m_bAscending(false)
245 , m_nSortedColumn(-1)
246 , m_bHasExternalsFromDifferentRepos(false)
247 , m_sNoPropValueText(MAKEINTRESOURCE(IDS_STATUSLIST_NOPROPVALUE))
248 , m_amend(false)
249 , m_bDoNotAutoselectSubmodules(false)
250 , m_bHasWC(true)
251 , m_hwndLogicalParent(NULL)
252 , m_bHasUnversionedItems(FALSE)
253 , m_nTargetCount(0)
254 , m_bHasExternals(false)
255 , m_bHasIgnoreGroup(false)
256 , m_nUnversioned(0)
257 , m_nNormal(0)
258 , m_nModified(0)
259 , m_nAdded(0)
260 , m_nDeleted(0)
261 , m_nConflicted(0)
262 , m_nTotal(0)
263 , m_nSelected(0)
264 , m_nRenamed(0)
265 , m_nShownUnversioned(0)
266 , m_nShownModified(0)
267 , m_nShownAdded(0)
268 , m_nShownDeleted(0)
269 , m_nShownConflicted(0)
270 , m_nShownFiles(0)
271 , m_nShownSubmodules(0)
272 , m_dwShow(0)
273 , m_bShowFolders(false)
274 , m_bUpdate(false)
275 , m_dwContextMenus(0)
276 , m_nIconFolder(0)
277 , m_nRestoreOvl(0)
278 , pfnSHCreateDefaultContextMenu(nullptr)
279 , pfnAssocCreateForClasses(nullptr)
280 , m_pContextMenu(nullptr)
281 , m_hShellMenu(nullptr)
283 m_FileLoaded=0;
284 m_dwDefaultColumns = 0;
285 m_critSec.Init();
286 m_bIsRevertTheirMy = false;
287 this->m_nLineAdded =this->m_nLineDeleted =0;
288 m_ShellDll = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
289 if (m_ShellDll)
291 pfnSHCreateDefaultContextMenu = (FNSHCreateDefaultContextMenu)::GetProcAddress(m_ShellDll, "SHCreateDefaultContextMenu");
292 pfnAssocCreateForClasses = (FNAssocCreateForClasses)::GetProcAddress(m_ShellDll, "AssocCreateForClasses");
296 CGitStatusListCtrl::~CGitStatusListCtrl()
298 // if (m_pDropTarget)
299 // delete m_pDropTarget;
300 ClearStatusArray();
303 void CGitStatusListCtrl::ClearStatusArray()
305 #if 0
306 Locker lock(m_critSec);
307 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
309 delete m_arStatusArray[i];
311 m_arStatusArray.clear();
312 #endif
315 void CGitStatusListCtrl::Init(DWORD dwColumns, const CString& sColumnInfoContainer, unsigned __int64 dwContextMenus /* = GitSLC_POPALL */, bool bHasCheckboxes /* = true */, bool bHasWC /* = true */, DWORD allowedColumns /* = 0xffffffff */)
317 Locker lock(m_critSec);
319 m_dwDefaultColumns = dwColumns | 1;
320 m_dwContextMenus = dwContextMenus;
321 m_bHasCheckboxes = bHasCheckboxes;
322 m_bHasWC = bHasWC;
324 // set the extended style of the listcontrol
325 // the style LVS_EX_FULLROWSELECT interferes with the background watermark image but it's more important to be able to select in the whole row.
326 CRegDWORD regFullRowSelect(_T("Software\\TortoiseGit\\FullRowSelect"), TRUE);
327 DWORD exStyle = LVS_EX_HEADERDRAGDROP | LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_SUBITEMIMAGES;
328 if (DWORD(regFullRowSelect))
329 exStyle |= LVS_EX_FULLROWSELECT;
330 exStyle |= (bHasCheckboxes ? LVS_EX_CHECKBOXES : 0);
331 SetRedraw(false);
332 SetExtendedStyle(exStyle);
334 SetWindowTheme(m_hWnd, L"Explorer", NULL);
336 m_nIconFolder = SYS_IMAGE_LIST().GetDirIconIndex();
337 m_nRestoreOvl = SYS_IMAGE_LIST().AddIcon((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_RESTOREOVL), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));
338 SYS_IMAGE_LIST().SetOverlayImage(m_nRestoreOvl, OVL_RESTORE);
339 SetImageList(&SYS_IMAGE_LIST(), LVSIL_SMALL);
341 // keep CSorter::operator() in sync!!
342 static UINT standardColumnNames[GITSLC_NUMCOLUMNS]
343 = { IDS_STATUSLIST_COLFILE
344 , IDS_STATUSLIST_COLFILENAME
345 , IDS_STATUSLIST_COLEXT
346 , IDS_STATUSLIST_COLSTATUS
347 , IDS_STATUSLIST_COLADD
348 , IDS_STATUSLIST_COLDEL
349 , IDS_STATUSLIST_COLLASTMODIFIED
350 , IDS_STATUSLIST_COLSIZE
353 m_ColumnManager.SetNames(standardColumnNames,GITSLC_NUMCOLUMNS);
354 m_ColumnManager.ReadSettings(m_dwDefaultColumns, 0xffffffff & ~(allowedColumns | m_dwDefaultColumns), sColumnInfoContainer, GITSLC_NUMCOLUMNS);
356 // enable file drops
357 #if 0
358 if (m_pDropTarget == NULL)
360 m_pDropTarget = new CGitStatusListCtrlDropTarget(this);
361 RegisterDragDrop(m_hWnd,m_pDropTarget);
362 // create the supported formats:
363 FORMATETC ftetc={0};
364 ftetc.dwAspect = DVASPECT_CONTENT;
365 ftetc.lindex = -1;
366 ftetc.tymed = TYMED_HGLOBAL;
367 ftetc.cfFormat=CF_HDROP;
368 m_pDropTarget->AddSuportedFormat(ftetc);
370 #endif
372 SetRedraw(true);
375 bool CGitStatusListCtrl::SetBackgroundImage(UINT nID)
377 return CAppUtils::SetListCtrlBackgroundImage(GetSafeHwnd(), nID);
380 BOOL CGitStatusListCtrl::GetStatus ( const CTGitPathList* pathList
381 , bool bUpdate /* = FALSE */
382 , bool bShowIgnores /* = false */
383 , bool bShowUnRev /* = false */
384 , bool bShowLocalChangesIgnored /* = false */)
386 Locker lock(m_critSec);
387 int mask= CGitStatusListCtrl::FILELIST_MODIFY;
388 if(bShowIgnores)
389 mask|= CGitStatusListCtrl::FILELIST_IGNORE;
390 if(bShowUnRev)
391 mask|= CGitStatusListCtrl::FILELIST_UNVER;
392 if (bShowLocalChangesIgnored)
393 mask |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
394 this->UpdateFileList(mask,bUpdate,(CTGitPathList*)pathList);
396 if (pathList && m_mapDirectFiles.empty())
398 // remember files which are selected by users so that those can be preselected
399 for (int i = 0; i < pathList->GetCount(); ++i)
400 if (!(*pathList)[i].IsDirectory())
401 m_mapDirectFiles[(*pathList)[i].GetGitPathString()] = true;
404 #if 0
405 int refetchcounter = 0;
406 BOOL bRet = TRUE;
407 Invalidate();
408 // force the cursor to change
409 POINT pt;
410 GetCursorPos(&pt);
411 SetCursorPos(pt.x, pt.y);
413 m_mapFilenameToChecked.clear();
414 //m_StatusUrlList.Clear();
415 bool bHasChangelists = (m_changelists.size() > 1 || (!m_changelists.empty() && !m_bHasIgnoreGroup));
416 m_changelists.clear();
417 for (size_t i=0; i < m_arStatusArray.size(); i++)
419 FileEntry * entry = m_arStatusArray[i];
420 if ( bHasChangelists && entry->checked)
422 // If change lists are present, remember all checked entries
423 CString path = entry->GetPath().GetGitPathString();
424 m_mapFilenameToChecked[path] = true;
426 if ( (entry->status==git_wc_status_unversioned || entry->status==git_wc_status_missing ) && entry->checked )
428 // The user manually selected an unversioned or missing file. We remember
429 // this so that the selection can be restored when refreshing.
430 CString path = entry->GetPath().GetGitPathString();
431 m_mapFilenameToChecked[path] = true;
433 else if ( entry->status > git_wc_status_normal && !entry->checked )
435 // The user manually deselected a versioned file. We remember
436 // this so that the deselection can be restored when refreshing.
437 CString path = entry->GetPath().GetGitPathString();
438 m_mapFilenameToChecked[path] = false;
442 // use a sorted path list to make sure we fetch the status of
443 // parent items first, *then* the child items (if any)
444 CTGitPathList sortedPathList = pathList;
445 sortedPathList.SortByPathname();
448 bRet = TRUE;
449 m_nTargetCount = 0;
450 m_bHasExternalsFromDifferentRepos = FALSE;
451 m_bHasExternals = FALSE;
452 m_bHasUnversionedItems = FALSE;
453 m_bHasLocks = false;
454 m_bHasChangeLists = false;
455 m_bShowIgnores = bShowIgnores;
456 m_nSortedColumn = 0;
457 m_bBlock = TRUE;
458 m_bBusy = true;
459 m_bEmpty = false;
460 Invalidate();
462 // first clear possible status data left from
463 // previous GetStatus() calls
464 ClearStatusArray();
466 m_StatusFileList = sortedPathList;
468 // Since Git_client_status() returns all files, even those in
469 // folders included with Git:externals we need to check if all
470 // files we get here belongs to the same repository.
471 // It is possible to commit changes in an external folder, as long
472 // as the folder belongs to the same repository (but another path),
473 // but it is not possible to commit all files if the externals are
474 // from a different repository.
476 // To check if all files belong to the same repository, we compare the
477 // UUID's - if they're identical then the files belong to the same
478 // repository and can be committed. But if they're different, then
479 // tell the user to commit all changes in the external folders
480 // first and exit.
481 CStringA sUUID; // holds the repo UUID
482 CTGitPathList arExtPaths; // list of Git:external paths
484 GitConfig config;
486 m_sURL.Empty();
488 m_nTargetCount = sortedPathList.GetCount();
490 GitStatus status(m_pbCanceled);
491 if(m_nTargetCount > 1 && sortedPathList.AreAllPathsFilesInOneDirectory())
493 // This is a special case, where we've been given a list of files
494 // all from one folder
495 // We handle them by setting a status filter, then requesting the Git status of
496 // all the files in the directory, filtering for the ones we're interested in
497 status.SetFilter(sortedPathList);
499 // if all selected entries are files, we don't do a recursive status
500 // fetching. But if only one is a directory, we have to recurse.
501 git_depth_t depth = git_depth_files;
502 // We have set a filter. If all selected items were files or we fetch
503 // the status not recursively, then we have to include
504 // ignored items too - the user has selected them
505 bool bShowIgnoresRight = true;
506 for (int fcindex=0; fcindex<sortedPathList.GetCount(); ++fcindex)
508 if (sortedPathList[fcindex].IsDirectory())
510 depth = git_depth_infinity;
511 bShowIgnoresRight = false;
512 break;
515 if(!FetchStatusForSingleTarget(config, status, sortedPathList.GetCommonDirectory(), bUpdate, sUUID, arExtPaths, true, depth, bShowIgnoresRight))
517 bRet = FALSE;
520 else
522 for(int nTarget = 0; nTarget < m_nTargetCount; nTarget++)
524 // check whether the path we want the status for is already fetched due to status-fetching
525 // of a parent path.
526 // this check is only done for file paths, because folder paths could be included already
527 // but not recursively
528 if (sortedPathList[nTarget].IsDirectory() || GetListEntry(sortedPathList[nTarget]) == NULL)
530 if(!FetchStatusForSingleTarget(config, status, sortedPathList[nTarget], bUpdate, sUUID,
531 arExtPaths, false, git_depth_infinity, bShowIgnores))
533 bRet = FALSE;
539 // remove the 'helper' files of conflicted items from the list.
540 // otherwise they would appear as unversioned files.
541 for (INT_PTR cind = 0; cind < m_ConflictFileList.GetCount(); ++cind)
543 for (size_t i=0; i < m_arStatusArray.size(); i++)
545 if (m_arStatusArray[i]->GetPath().IsEquivalentTo(m_ConflictFileList[cind]))
547 delete m_arStatusArray[i];
548 m_arStatusArray.erase(m_arStatusArray.begin()+i);
549 break;
553 refetchcounter++;
554 } while(!BuildStatistics() && (refetchcounter < 2) && (*m_pbCanceled==false));
556 m_bBlock = FALSE;
557 m_bBusy = false;
558 GetCursorPos(&pt);
559 SetCursorPos(pt.x, pt.y);
560 return bRet;
561 #endif
562 BuildStatistics();
563 return TRUE;
566 // Get the show-flags bitmap value which corresponds to a particular Git status
567 DWORD CGitStatusListCtrl::GetShowFlagsFromGitStatus(git_wc_status_kind status)
569 switch (status)
571 case git_wc_status_none:
572 case git_wc_status_unversioned:
573 return GITSLC_SHOWUNVERSIONED;
574 case git_wc_status_ignored:
575 if (!m_bShowIgnores)
576 return GITSLC_SHOWDIRECTS;
577 return GITSLC_SHOWDIRECTS|GITSLC_SHOWIGNORED;
578 case git_wc_status_incomplete:
579 return GITSLC_SHOWINCOMPLETE;
580 case git_wc_status_normal:
581 return GITSLC_SHOWNORMAL;
582 case git_wc_status_external:
583 return GITSLC_SHOWEXTERNAL;
584 case git_wc_status_added:
585 return GITSLC_SHOWADDED;
586 case git_wc_status_missing:
587 return GITSLC_SHOWMISSING;
588 case git_wc_status_deleted:
589 return GITSLC_SHOWREMOVED;
590 case git_wc_status_replaced:
591 return GITSLC_SHOWREPLACED;
592 case git_wc_status_modified:
593 return GITSLC_SHOWMODIFIED;
594 case git_wc_status_merged:
595 return GITSLC_SHOWMERGED;
596 case git_wc_status_conflicted:
597 return GITSLC_SHOWCONFLICTED;
598 case git_wc_status_obstructed:
599 return GITSLC_SHOWOBSTRUCTED;
600 default:
601 // we should NEVER get here!
602 ASSERT(FALSE);
603 break;
605 return 0;
608 void CGitStatusListCtrl::Show(unsigned int dwShow, unsigned int dwCheck /*=0*/, bool /*bShowFolders*/ /* = true */,BOOL UpdateStatusList,bool UseStoredCheckStatus)
610 CWinApp * pApp = AfxGetApp();
611 if (pApp)
612 pApp->DoWaitCursor(1);
614 Locker lock(m_critSec);
615 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
617 //SetItemCount(listIndex);
618 SetRedraw(FALSE);
619 DeleteAllItems();
620 m_nSelected = 0;
622 m_nShownUnversioned = 0;
623 m_nShownModified = 0;
624 m_nShownAdded = 0;
625 m_nShownDeleted = 0;
626 m_nShownConflicted = 0;
627 m_nShownFiles = 0;
628 m_nShownSubmodules = 0;
630 if(UpdateStatusList)
632 m_arStatusArray.clear();
633 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
635 m_arStatusArray.push_back((CTGitPath*)&m_StatusFileList[i]);
638 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
640 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
643 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
645 m_arStatusArray.push_back((CTGitPath*)&m_IgnoreFileList[i]);
648 PrepareGroups();
649 if (m_nSortedColumn >= 0)
651 CSorter predicate (&m_ColumnManager, m_nSortedColumn, m_bAscending);
652 std::sort(m_arStatusArray.begin(), m_arStatusArray.end(), predicate);
655 int index =0;
656 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
658 //set default checkbox status
659 CTGitPath* entry = ((CTGitPath*)m_arStatusArray[i]);
660 CString path = entry->GetGitPathString();
661 if (!m_mapFilenameToChecked.empty() && m_mapFilenameToChecked.find(path) != m_mapFilenameToChecked.end())
663 entry->m_Checked=m_mapFilenameToChecked[path];
665 else if (!UseStoredCheckStatus)
667 bool autoSelectSubmodules = !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules);
668 if ((entry->m_Action & dwCheck || dwShow & GITSLC_SHOWDIRECTFILES && m_mapDirectFiles.find(path) != m_mapDirectFiles.end()) && autoSelectSubmodules)
669 entry->m_Checked=true;
670 else
671 entry->m_Checked=false;
672 m_mapFilenameToChecked[path] = entry->m_Checked;
675 if(entry->m_Action & dwShow)
677 AddEntry(entry,langID,index);
678 index++;
682 int maxcol = ((CHeaderCtrl*)(GetDlgItem(0)))->GetItemCount()-1;
683 for (int col = 0; col <= maxcol; col++)
684 SetColumnWidth (col, m_ColumnManager.GetWidth (col, true));
686 SetRedraw(TRUE);
687 GetStatisticsString();
689 CHeaderCtrl * pHeader = GetHeaderCtrl();
690 HDITEM HeaderItem = {0};
691 HeaderItem.mask = HDI_FORMAT;
692 for (int i=0; i<pHeader->GetItemCount(); ++i)
694 pHeader->GetItem(i, &HeaderItem);
695 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
696 pHeader->SetItem(i, &HeaderItem);
698 if (m_nSortedColumn >= 0)
700 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
701 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
702 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
705 #if 0
706 if (nSelectedEntry)
708 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
709 EnsureVisible(nSelectedEntry, false);
711 else
713 // Restore the item at the top of the list.
714 for (int i=0;GetTopIndex() != nTopIndex;i++)
716 if ( !EnsureVisible(nTopIndex+i,false) )
718 break;
722 #endif
723 if (pApp)
724 pApp->DoWaitCursor(-1);
726 Invalidate();
728 m_dwShow = dwShow;
730 this->BuildStatistics();
732 #if 0
734 CWinApp * pApp = AfxGetApp();
735 if (pApp)
736 pApp->DoWaitCursor(1);
738 m_bShowFolders = bShowFolders;
740 int nTopIndex = GetTopIndex();
741 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
742 int nSelectedEntry = 0;
743 if (posSelectedEntry)
744 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
745 SetRedraw(FALSE);
746 DeleteAllItems();
748 PrepareGroups();
750 m_arListArray.clear();
752 m_arListArray.reserve(m_arStatusArray.size());
753 SetItemCount (static_cast<int>(m_arStatusArray.size()));
755 int listIndex = 0;
756 for (size_t i=0; i < m_arStatusArray.size(); ++i)
758 FileEntry * entry = m_arStatusArray[i];
759 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
760 continue;
761 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
762 continue;
763 if (entry->IsFolder() && (!bShowFolders))
764 continue; // don't show folders if they're not wanted.
766 #if 0
767 git_wc_status_kind status = GitStatus::GetMoreImportant(entry->status, entry->remotestatus);
768 DWORD showFlags = GetShowFlagsFromGitStatus(status);
769 if (entry->IsLocked())
770 showFlags |= SVNSLC_SHOWLOCKS;
771 if (entry->switched)
772 showFlags |= SVNSLC_SHOWSWITCHED;
773 if (!entry->changelist.IsEmpty())
774 showFlags |= SVNSLC_SHOWINCHANGELIST;
775 #endif
776 bool bAllowCheck = ((entry->changelist.Compare(GITSLC_IGNORECHANGELIST) != 0)
777 && (m_bCheckIfGroupsExist || (m_changelists.empty() || (m_changelists.size() == 1 && m_bHasIgnoreGroup))));
779 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
780 #if 0
781 if (status != Git_wc_status_ignored || (entry->direct) || (dwShow & GitSLC_SHOWIGNORED))
783 if ((!entry->IsFolder()) && (status == Git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
785 if (PathFileExists(entry->GetPath().GetWinPath()))
787 m_arListArray.push_back(i);
788 if ((dwCheck & SVNSLC_SHOWREMOVEDANDPRESENT)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
790 if (bAllowCheck)
791 entry->checked = true;
793 AddEntry(entry, langID, listIndex++);
796 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
798 m_arListArray.push_back(i);
799 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
801 if (bAllowCheck)
802 entry->checked = true;
804 AddEntry(entry, langID, listIndex++);
806 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
808 m_arListArray.push_back(i);
809 if ((dwCheck & showFlags)||((dwCheck & SVNSLC_SHOWDIRECTS)&&(entry->direct)))
811 if (bAllowCheck)
812 entry->checked = true;
814 AddEntry(entry, langID, listIndex++);
817 #endif
820 SetItemCount(listIndex);
822 m_ColumnManager.UpdateRelevance (m_arStatusArray, m_arListArray);
824 int maxcol = ((CHeaderCtrl*)(GetDlgItem(0)))->GetItemCount()-1;
825 for (int col = 0; col <= maxcol; col++)
826 SetColumnWidth (col, m_ColumnManager.GetWidth (col, true));
828 SetRedraw(TRUE);
829 GetStatisticsString();
831 CHeaderCtrl * pHeader = GetHeaderCtrl();
832 HDITEM HeaderItem = {0};
833 HeaderItem.mask = HDI_FORMAT;
834 for (int i=0; i<pHeader->GetItemCount(); ++i)
836 pHeader->GetItem(i, &HeaderItem);
837 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
838 pHeader->SetItem(i, &HeaderItem);
840 if (m_nSortedColumn)
842 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
843 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
844 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
847 if (nSelectedEntry)
849 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
850 EnsureVisible(nSelectedEntry, false);
852 else
854 // Restore the item at the top of the list.
855 for (int i=0;GetTopIndex() != nTopIndex;i++)
857 if ( !EnsureVisible(nTopIndex+i,false) )
859 break;
864 if (pApp)
865 pApp->DoWaitCursor(-1);
867 m_bEmpty = (GetItemCount() == 0);
868 Invalidate();
869 #endif
873 void CGitStatusListCtrl::Show(unsigned int /*dwShow*/, const CTGitPathList& checkedList, bool /*bShowFolders*/ /* = true */)
875 DeleteAllItems();
876 for (int i = 0; i < checkedList.GetCount(); ++i)
877 this->AddEntry((CTGitPath *)&checkedList[i],0,i);
878 return ;
879 #if 0
881 Locker lock(m_critSec);
882 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
884 CWinApp * pApp = AfxGetApp();
885 if (pApp)
886 pApp->DoWaitCursor(1);
887 m_dwShow = dwShow;
888 m_bShowFolders = bShowFolders;
889 m_nSelected = 0;
890 int nTopIndex = GetTopIndex();
891 POSITION posSelectedEntry = GetFirstSelectedItemPosition();
892 int nSelectedEntry = 0;
893 if (posSelectedEntry)
894 nSelectedEntry = GetNextSelectedItem(posSelectedEntry);
895 SetRedraw(FALSE);
896 DeleteAllItems();
898 PrepareGroups();
900 m_arListArray.clear();
902 m_arListArray.reserve(m_arStatusArray.size());
903 SetItemCount (static_cast<int>(m_arStatusArray.size()));
905 int listIndex = 0;
906 for (size_t i=0; i < m_arStatusArray.size(); ++i)
908 FileEntry * entry = m_arStatusArray[i];
909 if ((entry->inexternal) && (!(dwShow & SVNSLC_SHOWINEXTERNALS)))
910 continue;
911 if ((entry->differentrepo || entry->isNested) && (! (dwShow & SVNSLC_SHOWEXTERNALFROMDIFFERENTREPO)))
912 continue;
913 if (entry->IsFolder() && (!bShowFolders))
914 continue; // don't show folders if they're not wanted.
915 #if 0
916 git_wc_status_kind status = SVNStatus::GetMoreImportant(entry->status, entry->remotestatus);
917 DWORD showFlags = GetShowFlagsFromSVNStatus(status);
918 if (entry->IsLocked())
919 showFlags |= SVNSLC_SHOWLOCKS;
920 if (!entry->changelist.IsEmpty())
921 showFlags |= SVNSLC_SHOWINCHANGELIST;
923 // status_ignored is a special case - we must have the 'direct' flag set to add a status_ignored item
924 if (status != git_wc_status_ignored || (entry->direct) || (dwShow & SVNSLC_SHOWIGNORED))
926 for (int npath = 0; npath < checkedList.GetCount(); ++npath)
928 if (entry->GetPath().IsEquivalentTo(checkedList[npath]))
930 entry->checked = true;
931 break;
934 if ((!entry->IsFolder()) && (status == git_wc_status_deleted) && (dwShow & SVNSLC_SHOWREMOVEDANDPRESENT))
936 if (PathFileExists(entry->GetPath().GetWinPath()))
938 m_arListArray.push_back(i);
939 AddEntry(entry, langID, listIndex++);
942 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFILES)&&(entry->direct)&&(!entry->IsFolder())))
944 m_arListArray.push_back(i);
945 AddEntry(entry, langID, listIndex++);
947 else if ((dwShow & showFlags)||((dwShow & SVNSLC_SHOWDIRECTFOLDER)&&(entry->direct)&&entry->IsFolder()))
949 m_arListArray.push_back(i);
950 AddEntry(entry, langID, listIndex++);
952 else if (entry->switched)
954 m_arListArray.push_back(i);
955 AddEntry(entry, langID, listIndex++);
958 #endif
961 SetItemCount(listIndex);
963 int maxcol = ((CHeaderCtrl*)(GetDlgItem(0)))->GetItemCount()-1;
964 for (int col = 0; col <= maxcol; col++)
965 SetColumnWidth (col, m_ColumnManager.GetWidth (col, true));
967 SetRedraw(TRUE);
968 GetStatisticsString();
970 CHeaderCtrl * pHeader = GetHeaderCtrl();
971 HDITEM HeaderItem = {0};
972 HeaderItem.mask = HDI_FORMAT;
973 for (int i=0; i<pHeader->GetItemCount(); ++i)
975 pHeader->GetItem(i, &HeaderItem);
976 HeaderItem.fmt &= ~(HDF_SORTDOWN | HDF_SORTUP);
977 pHeader->SetItem(i, &HeaderItem);
979 if (m_nSortedColumn)
981 pHeader->GetItem(m_nSortedColumn, &HeaderItem);
982 HeaderItem.fmt |= (m_bAscending ? HDF_SORTUP : HDF_SORTDOWN);
983 pHeader->SetItem(m_nSortedColumn, &HeaderItem);
986 if (nSelectedEntry)
988 SetItemState(nSelectedEntry, LVIS_SELECTED, LVIS_SELECTED);
989 EnsureVisible(nSelectedEntry, false);
991 else
993 // Restore the item at the top of the list.
994 for (int i=0;GetTopIndex() != nTopIndex;i++)
996 if ( !EnsureVisible(nTopIndex+i,false) )
998 break;
1003 if (pApp)
1004 pApp->DoWaitCursor(-1);
1006 m_bEmpty = (GetItemCount() == 0);
1007 Invalidate();
1008 #endif
1011 int CGitStatusListCtrl::GetColumnIndex(int mask)
1013 for (int i = 0; i < 32; ++i)
1014 if(mask&0x1)
1015 return i;
1016 else
1017 mask=mask>>1;
1018 return -1;
1020 void CGitStatusListCtrl::AddEntry(CTGitPath * GitPath, WORD /*langID*/, int listIndex)
1022 static CString from(MAKEINTRESOURCE(IDS_STATUSLIST_FROM));
1023 static HINSTANCE hResourceHandle(AfxGetResourceHandle());
1024 static bool abbreviateRenamings(((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\AbbreviateRenamings"), FALSE)) == TRUE);
1025 static bool relativeTimes = (CRegDWORD(_T("Software\\TortoiseGit\\RelativeTimes"), FALSE) != FALSE);
1027 CString path = GitPath->GetGitPathString();
1029 m_bBlock = TRUE;
1030 int index = listIndex;
1031 int nCol = 1;
1032 CString entryname = GitPath->GetGitPathString();
1033 int icon_idx = 0;
1034 if (GitPath->IsDirectory())
1036 icon_idx = m_nIconFolder;
1037 m_nShownSubmodules++;
1039 else
1041 icon_idx = SYS_IMAGE_LIST().GetPathIconIndex(*GitPath);
1042 m_nShownFiles++;
1044 switch (GitPath->m_Action)
1046 case CTGitPath::LOGACTIONS_ADDED:
1047 case CTGitPath::LOGACTIONS_COPY:
1048 m_nShownAdded++;
1049 break;
1050 case CTGitPath::LOGACTIONS_DELETED:
1051 m_nShownDeleted++;
1052 break;
1053 case CTGitPath::LOGACTIONS_REPLACED:
1054 case CTGitPath::LOGACTIONS_MODIFIED:
1055 case CTGitPath::LOGACTIONS_MERGED:
1056 m_nShownModified++;
1057 break;
1058 case CTGitPath::LOGACTIONS_UNMERGED:
1059 m_nShownConflicted++;
1060 break;
1061 case CTGitPath::LOGACTIONS_UNVER:
1062 m_nShownUnversioned++;
1063 break;
1064 default:
1065 m_nShownUnversioned++;
1066 break;
1068 if(GitPath->m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !GitPath->GetGitOldPathString().IsEmpty())
1070 if (!abbreviateRenamings)
1072 // relative path
1073 CString rename;
1074 rename.Format(from, GitPath->GetGitOldPathString());
1075 entryname += _T(" ") + rename;
1077 else
1079 CTGitPathList tgpl;
1080 tgpl.AddPath(*GitPath);
1081 CTGitPath old(GitPath->GetGitOldPathString());
1082 tgpl.AddPath(old);
1083 CString commonRoot = tgpl.GetCommonRoot().GetGitPathString();
1084 if (!commonRoot.IsEmpty())
1085 commonRoot += _T("/");
1086 if (old.GetFileOrDirectoryName() == GitPath->GetFileOrDirectoryName() && old.GetContainingDirectory().GetGitPathString() != "" && GitPath->GetContainingDirectory().GetGitPathString())
1088 entryname = commonRoot + _T("{") + GitPath->GetGitOldPathString().Mid(commonRoot.GetLength(), old.GetGitPathString().GetLength() - commonRoot.GetLength() - old.GetFileOrDirectoryName().GetLength() - 1) + _T(" => ") + GitPath->GetGitPathString().Mid(commonRoot.GetLength(), GitPath->GetGitPathString().GetLength() - commonRoot.GetLength() - old.GetFileOrDirectoryName().GetLength() - 1) + _T("}/") + old.GetFileOrDirectoryName();
1090 else if (!commonRoot.IsEmpty())
1092 entryname = commonRoot + _T("{") + GitPath->GetGitOldPathString().Mid(commonRoot.GetLength()) + _T(" => ") + GitPath->GetGitPathString().Mid(commonRoot.GetLength()) + _T("}");
1094 else
1096 entryname = GitPath->GetGitOldPathString().Mid(commonRoot.GetLength()) + _T(" => ") + GitPath->GetGitPathString().Mid(commonRoot.GetLength());
1101 InsertItem(index, entryname, icon_idx);
1102 if (m_restorepaths.find(GitPath->GetWinPathString()) != m_restorepaths.end())
1103 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), TVIS_OVERLAYMASK);
1105 this->SetItemData(index, (DWORD_PTR)GitPath);
1106 // SVNSLC_COLFILENAME
1107 SetItemText(index, nCol++, GitPath->GetFileOrDirectoryName());
1108 // SVNSLC_COLEXT
1109 SetItemText(index, nCol++, GitPath->GetFileExtension());
1110 // SVNSLC_COLSTATUS
1111 SetItemText(index, nCol++, GitPath->GetActionName());
1113 SetItemText(index, GetColumnIndex(GITSLC_COLADD),GitPath->m_StatAdd);
1114 SetItemText(index, GetColumnIndex(GITSLC_COLDEL),GitPath->m_StatDel);
1117 CString modificationDate;
1118 __int64 filetime = GitPath->GetLastWriteTime();
1119 if (filetime && (GitPath->m_Action != CTGitPath::LOGACTIONS_DELETED))
1121 FILETIME* f = (FILETIME*)(__int64*)&filetime;
1122 modificationDate = CLoglistUtils::FormatDateAndTime(CTime(g_Git.filetime_to_time_t(f)), DATE_SHORTDATE, true, relativeTimes);
1124 SetItemText(index, GetColumnIndex(GITSLC_COLMODIFICATIONDATE), modificationDate);
1126 // SVNSLC_COLSIZE
1127 if (GitPath->IsDirectory())
1128 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), _T(""));
1129 else
1131 TCHAR buf[100] = { 0 };
1132 StrFormatByteSize64(GitPath->GetFileSize(), buf, 100);
1133 SetItemText(index, GetColumnIndex(GITSLC_COLSIZE), buf);
1136 SetCheck(index, GitPath->m_Checked);
1137 if (GitPath->m_Checked)
1138 m_nSelected++;
1140 if ((GitPath->m_Action & CTGitPath::LOGACTIONS_SKIPWORKTREE) || (GitPath->m_Action & CTGitPath::LOGACTIONS_ASSUMEVALID))
1141 SetItemGroup(index, 3);
1142 else if (GitPath->m_Action & CTGitPath::LOGACTIONS_IGNORE)
1143 SetItemGroup(index, 2);
1144 else if( GitPath->m_Action & CTGitPath::LOGACTIONS_UNVER)
1145 SetItemGroup(index,1);
1146 else
1148 SetItemGroup(index, GitPath->m_ParentNo&(PARENT_MASK|MERGE_MASK));
1151 m_bBlock = FALSE;
1156 bool CGitStatusListCtrl::SetItemGroup(int item, int groupindex)
1158 // if ((m_dwContextMenus & SVNSLC_POPCHANGELISTS) == NULL)
1159 // return false;
1160 if (groupindex < 0)
1161 return false;
1162 LVITEM i = {0};
1163 i.mask = LVIF_GROUPID;
1164 i.iItem = item;
1165 i.iSubItem = 0;
1166 i.iGroupId = groupindex;
1168 return !!SetItem(&i);
1171 void CGitStatusListCtrl::OnHdnItemclick(NMHDR *pNMHDR, LRESULT *pResult)
1173 LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
1174 *pResult = 0;
1175 if (m_bBlock || m_arStatusArray.empty())
1176 return;
1177 m_bBlock = TRUE;
1178 if (m_nSortedColumn == phdr->iItem)
1179 m_bAscending = !m_bAscending;
1180 else
1181 m_bAscending = TRUE;
1182 m_nSortedColumn = phdr->iItem;
1183 Show(m_dwShow, 0, m_bShowFolders,false,true);
1185 m_bBlock = FALSE;
1188 void CGitStatusListCtrl::OnLvnItemchanging(NMHDR *pNMHDR, LRESULT *pResult)
1190 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
1191 *pResult = 0;
1193 #define ISCHECKED(x) ((x) ? ((((x)&LVIS_STATEIMAGEMASK)>>12)-1) : FALSE)
1194 if ((m_bBlock)&&(m_bBlockUI))
1196 // if we're blocked, prevent changing of the check state
1197 if ((!ISCHECKED(pNMLV->uOldState) && ISCHECKED(pNMLV->uNewState))||
1198 (ISCHECKED(pNMLV->uOldState) && !ISCHECKED(pNMLV->uNewState)))
1199 *pResult = TRUE;
1203 BOOL CGitStatusListCtrl::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
1205 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
1206 *pResult = 0;
1207 CWnd* pParent = GetLogicalParent();
1208 if (NULL != pParent && NULL != pParent->GetSafeHwnd())
1210 pParent->SendMessage(GITSLNM_ITEMCHANGED, pNMLV->iItem);
1213 if ((pNMLV->uNewState==0)||(pNMLV->uNewState & LVIS_SELECTED)||(pNMLV->uNewState & LVIS_FOCUSED))
1214 return FALSE;
1216 if (m_bBlock)
1217 return FALSE;
1219 bool bSelected = !!(ListView_GetItemState(m_hWnd, pNMLV->iItem, LVIS_SELECTED) & LVIS_SELECTED);
1220 int nListItems = GetItemCount();
1222 m_bBlock = TRUE;
1223 // was the item checked?
1225 //CTGitPath *gitpath=(CTGitPath*)GetItemData(pNMLV->iItem);
1226 //gitpath->m_Checked=GetCheck(pNMLV->iItem);
1228 if (GetCheck(pNMLV->iItem))
1230 CheckEntry(pNMLV->iItem, nListItems);
1231 if (bSelected)
1233 POSITION pos = GetFirstSelectedItemPosition();
1234 int index;
1235 while ((index = GetNextSelectedItem(pos)) >= 0)
1237 if (index != pNMLV->iItem)
1238 CheckEntry(index, nListItems);
1242 else
1244 UncheckEntry(pNMLV->iItem, nListItems);
1245 if (bSelected)
1247 POSITION pos = GetFirstSelectedItemPosition();
1248 int index;
1249 while ((index = GetNextSelectedItem(pos)) >= 0)
1251 if (index != pNMLV->iItem)
1252 UncheckEntry(index, nListItems);
1257 GetStatisticsString();
1258 m_bBlock = FALSE;
1259 NotifyCheck();
1261 return FALSE;
1264 void CGitStatusListCtrl::OnColumnResized(NMHDR *pNMHDR, LRESULT *pResult)
1266 m_ColumnManager.OnColumnResized(pNMHDR,pResult);
1268 *pResult = FALSE;
1271 void CGitStatusListCtrl::OnColumnMoved(NMHDR *pNMHDR, LRESULT *pResult)
1273 m_ColumnManager.OnColumnMoved(pNMHDR, pResult);
1275 Invalidate(FALSE);
1278 void CGitStatusListCtrl::CheckEntry(int index, int /*nListItems*/)
1280 Locker lock(m_critSec);
1281 //FileEntry * entry = GetListEntry(index);
1282 CTGitPath *path=(CTGitPath*)GetItemData(index);
1283 ASSERT(path != NULL);
1284 if (path == NULL)
1285 return;
1286 m_mapFilenameToChecked[path->GetGitPathString()] = true;
1287 SetCheck(index, TRUE);
1288 //entry = GetListEntry(index);
1289 // if an unversioned item was checked, then we need to check if
1290 // the parent folders are unversioned too. If the parent folders actually
1291 // are unversioned, then check those too.
1292 #if 0
1293 if (entry->status == git_wc_status_unversioned)
1295 // we need to check the parent folder too
1296 const CTGitPath& folderpath = entry->path;
1297 for (int i=0; i< nListItems; ++i)
1299 FileEntry * testEntry = GetListEntry(i);
1300 ASSERT(testEntry != NULL);
1301 if (testEntry == NULL)
1302 continue;
1303 if (!testEntry->checked)
1305 if (testEntry->path.IsAncestorOf(folderpath) && (!testEntry->path.IsEquivalentTo(folderpath)))
1307 SetEntryCheck(testEntry,i,true);
1308 m_nSelected++;
1313 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1314 if ( (entry->status == git_wc_status_deleted) || (m_bCheckChildrenWithParent) || (bShift) )
1316 // if a deleted folder gets checked, we have to check all
1317 // children of that folder too.
1318 if (entry->path.IsDirectory())
1320 SetCheckOnAllDescendentsOf(entry, true);
1323 // if a deleted file or folder gets checked, we have to
1324 // check all parents of this item too.
1325 for (int i=0; i<nListItems; ++i)
1327 FileEntry * testEntry = GetListEntry(i);
1328 ASSERT(testEntry != NULL);
1329 if (testEntry == NULL)
1330 continue;
1331 if (!testEntry->checked)
1333 if (testEntry->path.IsAncestorOf(entry->path) && (!testEntry->path.IsEquivalentTo(entry->path)))
1335 if ((testEntry->status == git_wc_status_deleted)||(m_bCheckChildrenWithParent))
1337 SetEntryCheck(testEntry,i,true);
1338 m_nSelected++;
1339 // now we need to check all children of this parent folder
1340 SetCheckOnAllDescendentsOf(testEntry, true);
1346 #endif
1347 if ( !path->m_Checked )
1349 path->m_Checked = TRUE;
1350 m_nSelected++;
1354 void CGitStatusListCtrl::UncheckEntry(int index, int /*nListItems*/)
1356 Locker lock(m_critSec);
1357 CTGitPath *path=(CTGitPath*)GetItemData(index);
1358 ASSERT(path != NULL);
1359 if (path == NULL)
1360 return;
1361 SetCheck(index, FALSE);
1362 m_mapFilenameToChecked[path->GetGitPathString()] = false;
1363 //entry = GetListEntry(index);
1364 // item was unchecked
1365 #if 0
1366 if (entry->path.IsDirectory())
1368 // disable all files within an unselected folder, except when unchecking a folder with property changes
1369 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1370 if ( (entry->status != git_wc_status_modified) || (bShift) )
1372 SetCheckOnAllDescendentsOf(entry, false);
1375 else if (entry->status == git_wc_status_deleted)
1377 // a "deleted" file was unchecked, so uncheck all parent folders
1378 // and all children of those parents
1379 for (int i=0; i<nListItems; i++)
1381 FileEntry * testEntry = GetListEntry(i);
1382 ASSERT(testEntry != NULL);
1383 if (testEntry == NULL)
1384 continue;
1385 if (testEntry->checked)
1387 if (testEntry->path.IsAncestorOf(entry->path))
1389 if (testEntry->status == git_wc_status_deleted)
1391 SetEntryCheck(testEntry,i,false);
1392 m_nSelected--;
1394 SetCheckOnAllDescendentsOf(testEntry, false);
1400 #endif
1401 if ( path->m_Checked )
1403 path->m_Checked = FALSE;
1404 m_nSelected--;
1407 bool CGitStatusListCtrl::BuildStatistics()
1410 bool bRefetchStatus = false;
1412 // now gather some statistics
1413 m_nUnversioned = 0;
1414 m_nNormal = 0;
1415 m_nModified = 0;
1416 m_nAdded = 0;
1417 m_nDeleted = 0;
1418 m_nConflicted = 0;
1419 m_nTotal = 0;
1420 m_nSelected = 0;
1421 m_nLineAdded = 0;
1422 m_nLineDeleted = 0;
1423 m_nRenamed = 0;
1425 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
1427 int status=((CTGitPath*)m_arStatusArray[i])->m_Action;
1429 m_nLineAdded += _tstol(((CTGitPath*)m_arStatusArray[i])->m_StatAdd);
1430 m_nLineDeleted += _tstol(((CTGitPath*)m_arStatusArray[i])->m_StatDel);
1432 if(status&(CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
1433 m_nAdded++;
1435 if(status&CTGitPath::LOGACTIONS_DELETED)
1436 m_nDeleted++;
1438 if(status&(CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_MODIFIED))
1439 m_nModified++;
1441 if(status&CTGitPath::LOGACTIONS_UNMERGED)
1442 m_nConflicted++;
1444 if(status&(CTGitPath::LOGACTIONS_IGNORE|CTGitPath::LOGACTIONS_UNVER))
1445 m_nUnversioned++;
1447 if(status&(CTGitPath::LOGACTIONS_REPLACED))
1448 m_nRenamed++;
1450 if(((CTGitPath*)m_arStatusArray[i])->m_Checked)
1451 m_nSelected++;
1453 return !bRefetchStatus;
1457 int CGitStatusListCtrl::GetGroupFromPoint(POINT * ppt)
1459 // the point must be relative to the upper left corner of the control
1461 if (ppt == NULL)
1462 return -1;
1463 if (!IsGroupViewEnabled())
1464 return -1;
1466 POINT pt = *ppt;
1467 pt.x = 10;
1468 UINT flags = 0;
1469 int nItem = -1;
1470 RECT rc;
1471 GetWindowRect(&rc);
1472 while (((flags & LVHT_BELOW) == 0)&&(pt.y < rc.bottom))
1474 nItem = HitTest(pt, &flags);
1475 if ((flags & LVHT_ONITEM)||(flags & LVHT_EX_GROUP_HEADER))
1477 // the first item below the point
1479 // check if the point is too much right (i.e. if the point
1480 // is farther to the right than the width of the item)
1481 RECT r;
1482 GetItemRect(nItem, &r, LVIR_LABEL);
1483 if (ppt->x > r.right)
1484 return -1;
1486 LVITEM lv = {0};
1487 lv.mask = LVIF_GROUPID;
1488 lv.iItem = nItem;
1489 GetItem(&lv);
1490 int groupID = lv.iGroupId;
1491 // now we search upwards and check if the item above this one
1492 // belongs to another group. If it belongs to the same group,
1493 // we're not over a group header
1494 while (pt.y >= 0)
1496 pt.y -= 2;
1497 nItem = HitTest(pt, &flags);
1498 if ((flags & LVHT_ONITEM)&&(nItem >= 0))
1500 // the first item below the point
1501 LVITEM lv = {0};
1502 lv.mask = LVIF_GROUPID;
1503 lv.iItem = nItem;
1504 GetItem(&lv);
1505 if (lv.iGroupId != groupID)
1506 return groupID;
1507 else
1508 return -1;
1511 if (pt.y < 0)
1512 return groupID;
1513 return -1;
1515 pt.y += 2;
1517 return -1;
1520 void CGitStatusListCtrl::OnContextMenuGroup(CWnd * /*pWnd*/, CPoint point)
1522 POINT clientpoint = point;
1523 ScreenToClient(&clientpoint);
1524 if ((IsGroupViewEnabled())&&(GetGroupFromPoint(&clientpoint) >= 0))
1526 CMenu popup;
1527 if (popup.CreatePopupMenu())
1529 CString temp;
1530 temp.LoadString(IDS_STATUSLIST_CHECKGROUP);
1531 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_CHECKGROUP, temp);
1532 temp.LoadString(IDS_STATUSLIST_UNCHECKGROUP);
1533 popup.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_UNCHECKGROUP, temp);
1534 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this, 0);
1535 bool bCheck = false;
1536 switch (cmd)
1538 case IDGITLC_CHECKGROUP:
1539 bCheck = true;
1540 // fall through here
1541 case IDGITLC_UNCHECKGROUP:
1543 int group = GetGroupFromPoint(&clientpoint);
1544 // go through all items and check/uncheck those assigned to the group
1545 // but block the OnLvnItemChanged handler
1546 m_bBlock = true;
1547 LVITEM lv;
1548 for (int i=0; i<GetItemCount(); ++i)
1550 SecureZeroMemory(&lv, sizeof(LVITEM));
1551 lv.mask = LVIF_GROUPID;
1552 lv.iItem = i;
1553 GetItem(&lv);
1555 if (lv.iGroupId == group)
1557 CTGitPath * entry = (CTGitPath*)GetItemData(i);
1558 if (entry)
1560 bool bOldCheck = entry->m_Checked;
1561 SetEntryCheck(entry, i, bCheck);
1562 if (bCheck != bOldCheck)
1564 if (bCheck)
1565 m_nSelected++;
1566 else
1567 m_nSelected--;
1573 GetStatisticsString();
1574 NotifyCheck();
1575 m_bBlock = false;
1577 break;
1583 void CGitStatusListCtrl::OnContextMenuList(CWnd * pWnd, CPoint point)
1586 //WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1588 bool bShift = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
1589 CTGitPath * filepath;
1591 int selIndex = GetSelectionMark();
1592 if ((point.x == -1) && (point.y == -1))
1594 CRect rect;
1595 GetItemRect(selIndex, &rect, LVIR_LABEL);
1596 ClientToScreen(&rect);
1597 point = rect.CenterPoint();
1599 if ((GetSelectedCount() == 0) && (m_bHasCheckboxes))
1601 // nothing selected could mean the context menu is requested for
1602 // a group header
1603 OnContextMenuGroup(pWnd, point);
1605 else if (selIndex >= 0)
1607 //FileEntry * entry = GetListEntry(selIndex);
1609 filepath = (CTGitPath * )GetItemData(selIndex);
1611 ASSERT(filepath != NULL);
1612 if (filepath == NULL)
1613 return;
1615 //const CTGitPath& filepath = entry->path;
1616 int wcStatus = filepath->m_Action;
1617 // entry is selected, now show the popup menu
1618 Locker lock(m_critSec);
1619 CIconMenu popup;
1620 CMenu changelistSubMenu;
1621 CMenu ignoreSubMenu;
1622 CMenu shellMenu;
1623 if (popup.CreatePopupMenu())
1625 //Add Menu for version controlled file
1627 if (GetSelectedCount() > 0 && wcStatus & CTGitPath::LOGACTIONS_UNMERGED)
1629 if (GetSelectedCount() == 1 && (m_dwContextMenus & GITSLC_POPCONFLICT)/*&&(entry->textstatus == git_wc_status_conflicted)*/)
1631 popup.AppendMenuIcon(IDGITLC_EDITCONFLICT, IDS_MENUCONFLICT, IDI_CONFLICT);
1633 if (m_dwContextMenus & GITSLC_POPRESOLVE)
1635 popup.AppendMenuIcon(IDGITLC_RESOLVECONFLICT, IDS_STATUSLIST_CONTEXT_RESOLVED, IDI_RESOLVE);
1637 if ((m_dwContextMenus & GITSLC_POPRESOLVE)/*&&(entry->textstatus == git_wc_status_conflicted)*/)
1639 popup.AppendMenuIcon(IDGITLC_RESOLVETHEIRS, IDS_SVNPROGRESS_MENUUSETHEIRS, IDI_RESOLVE);
1640 popup.AppendMenuIcon(IDGITLC_RESOLVEMINE, IDS_SVNPROGRESS_MENUUSEMINE, IDI_RESOLVE);
1642 if ((m_dwContextMenus & GITSLC_POPCONFLICT)||(m_dwContextMenus & GITSLC_POPRESOLVE))
1643 popup.AppendMenu(MF_SEPARATOR);
1646 if (GetSelectedCount() > 0)
1648 if (wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
1650 if (m_dwContextMenus & GITSLC_POPADD)
1652 //if ( entry->IsFolder() )
1654 // popup.AppendMenuIcon(IDSVNLC_ADD_RECURSIVE, IDS_STATUSLIST_CONTEXT_ADD_RECURSIVE, IDI_ADD);
1656 //else
1658 popup.AppendMenuIcon(IDGITLC_ADD, IDS_STATUSLIST_CONTEXT_ADD, IDI_ADD);
1661 if (m_dwContextMenus & GITSLC_POPCOMMIT)
1663 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1668 if (!(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) && GetSelectedCount() > 0)
1670 bool bEntryAdded = false;
1671 if (m_dwContextMenus & GITSLC_POPCOMPAREWITHBASE)
1673 if(filepath->m_ParentNo & MERGE_MASK)
1674 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_TREE_DIFF, IDI_DIFF);
1675 else
1676 popup.AppendMenuIcon(IDGITLC_COMPARE, IDS_LOG_COMPAREWITHBASE, IDI_DIFF);
1678 popup.SetDefaultItem(IDGITLC_COMPARE, FALSE);
1679 bEntryAdded = true;
1682 if (!g_Git.IsInitRepos() && (m_dwContextMenus & GITSLC_POPGNUDIFF))
1684 popup.AppendMenuIcon(IDGITLC_GNUDIFF1, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1685 bEntryAdded = true;
1688 if ((m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPAREWC)) && m_bHasWC)
1690 if ((!m_CurrentVersion.IsEmpty()) && m_CurrentVersion != GIT_REV_ZERO)
1692 popup.AppendMenuIcon(IDGITLC_COMPAREWC, IDS_LOG_POPUP_COMPARE, IDI_DIFF);
1693 bEntryAdded = true;
1697 if (bEntryAdded)
1698 popup.AppendMenu(MF_SEPARATOR);
1701 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
1703 if(GetSelectedCount() == 1)
1705 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_COMPARETWOREVISIONS))
1707 popup.AppendMenuIcon(IDGITLC_COMPARETWOREVISIONS, IDS_LOG_POPUP_COMPARETWO, IDI_DIFF);
1708 popup.SetDefaultItem(IDGITLC_COMPARETWOREVISIONS, FALSE);
1710 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_GNUDIFF2REVISIONS))
1712 popup.AppendMenuIcon(IDGITLC_GNUDIFF2REVISIONS, IDS_LOG_POPUP_GNUDIFF, IDI_DIFF);
1717 //Select Multi item
1718 if (GetSelectedCount() > 0)
1720 if ((GetSelectedCount() == 2) && (m_dwContextMenus & GITSLC_POPCOMPARETWOFILES) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO))
1722 POSITION pos = GetFirstSelectedItemPosition();
1723 int index = GetNextSelectedItem(pos);
1724 if (index >= 0)
1726 CTGitPath * entry2 = NULL;
1727 bool bothItemsAreExistingFiles = true;
1728 entry2 = (CTGitPath * )GetItemData(index);
1729 if (entry2)
1730 bothItemsAreExistingFiles = !entry2->IsDirectory() && entry2->Exists();
1731 index = GetNextSelectedItem(pos);
1732 if (index >= 0)
1734 entry2 = (CTGitPath * )GetItemData(index);
1735 if (entry2)
1736 bothItemsAreExistingFiles = bothItemsAreExistingFiles && !entry2->IsDirectory() && entry2->Exists();
1737 if (bothItemsAreExistingFiles)
1738 popup.AppendMenuIcon(IDGITLC_COMPARETWOFILES, IDS_STATUSLIST_CONTEXT_COMPARETWOFILES, IDI_DIFF);
1744 if ( (GetSelectedCount() >0 ) && (!(wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))) && m_bHasWC)
1746 if ((m_dwContextMenus & GITSLC_POPCOMMIT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && !(wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1748 popup.AppendMenuIcon(IDGITLC_COMMIT, IDS_STATUSLIST_CONTEXT_COMMIT, IDI_COMMIT);
1751 if ((m_dwContextMenus & GITSLC_POPREVERT) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO))
1753 popup.AppendMenuIcon(IDGITLC_REVERT, IDS_MENUREVERT, IDI_REVERT);
1756 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)))
1758 popup.AppendMenuIcon(IDGITLC_SKIPWORKTREE, IDS_STATUSLIST_SKIPWORKTREE);
1761 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)))
1763 popup.AppendMenuIcon(IDGITLC_ASSUMEVALID, IDS_MENUASSUMEVALID);
1766 if ((m_dwContextMenus & GITLC_POPUNSETIGNORELOCALCHANGES) && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && (wcStatus & (CTGitPath::LOGACTIONS_SKIPWORKTREE | CTGitPath::LOGACTIONS_ASSUMEVALID)))
1768 popup.AppendMenuIcon(IDGITLC_UNSETIGNORELOCALCHANGES, IDS_STATUSLIST_UNSETIGNORELOCALCHANGES);
1771 if (m_dwContextMenus & GITSLC_POPRESTORE && !filepath->IsDirectory())
1773 if (m_restorepaths.find(filepath->GetWinPathString()) == m_restorepaths.end())
1774 popup.AppendMenuIcon(IDGITLC_CREATERESTORE, IDS_MENUCREATERESTORE, IDI_RESTORE);
1775 else
1776 popup.AppendMenuIcon(IDGITLC_RESTOREPATH, IDS_MENURESTORE, IDI_RESTORE);
1779 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOREV)) && ( !this->m_CurrentVersion.IsEmpty() )
1780 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1782 popup.AppendMenuIcon(IDGITLC_REVERTTOREV, IDS_LOG_POPUP_REVERTTOREV, IDI_REVERT);
1785 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_REVERTTOPARENT)) && ( !this->m_CurrentVersion.IsEmpty() )
1786 && this->m_CurrentVersion != GIT_REV_ZERO && !(wcStatus & CTGitPath::LOGACTIONS_ADDED))
1788 popup.AppendMenuIcon(IDGITLC_REVERTTOPARENT, IDS_LOG_POPUP_REVERTTOPARENT, IDI_REVERT);
1792 if ((GetSelectedCount() == 1)&&(!(wcStatus & CTGitPath::LOGACTIONS_UNVER))
1793 &&(!(wcStatus & CTGitPath::LOGACTIONS_IGNORE)))
1795 if (m_dwContextMenus & GITSLC_POPSHOWLOG)
1797 popup.AppendMenuIcon(IDGITLC_LOG, IDS_REPOBROWSE_SHOWLOG, IDI_LOG);
1799 if (m_dwContextMenus & GITSLC_POPSHOWLOGSUBMODULE && filepath->IsDirectory())
1801 popup.AppendMenuIcon(IDGITLC_LOGSUBMODULE, IDS_LOG_SUBMODULE, IDI_LOG);
1803 if (m_dwContextMenus & GITSLC_POPSHOWLOGOLDNAME && (wcStatus & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY) && !filepath->GetGitOldPathString().IsEmpty()))
1805 popup.AppendMenuIcon(IDGITLC_LOGOLDNAME, IDS_STATUSLIST_SHOWLOGOLDNAME, IDI_LOG);
1807 if (m_dwContextMenus & GITSLC_POPBLAME && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC)
1809 popup.AppendMenuIcon(IDGITLC_BLAME, IDS_MENUBLAME, IDI_BLAME);
1813 if (GetSelectedCount() > 0)
1815 if ((m_dwContextMenus & GetContextMenuBit(IDGITLC_EXPORT)) && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1816 popup.AppendMenuIcon(IDGITLC_EXPORT, IDS_LOG_POPUP_EXPORT, IDI_EXPORT);
1819 // if ((wcStatus != git_wc_status_deleted)&&(wcStatus != git_wc_status_missing) && (GetSelectedCount() == 1))
1820 if ( (GetSelectedCount() == 1) )
1822 if (m_dwContextMenus & this->GetContextMenuBit(IDGITLC_SAVEAS) && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1824 popup.AppendMenuIcon(IDGITLC_SAVEAS, IDS_LOG_POPUP_SAVE, IDI_SAVEAS);
1827 if (m_dwContextMenus & GITSLC_POPOPEN && ! filepath->IsDirectory() && !(wcStatus & CTGitPath::LOGACTIONS_DELETED))
1829 popup.AppendMenuIcon(IDGITLC_VIEWREV, IDS_LOG_POPUP_VIEWREV);
1830 popup.AppendMenuIcon(IDGITLC_OPEN, IDS_REPOBROWSE_OPEN, IDI_OPEN);
1831 popup.AppendMenuIcon(IDGITLC_OPENWITH, IDS_LOG_POPUP_OPENWITH, IDI_OPEN);
1832 if (wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) {
1833 popup.SetDefaultItem(IDGITLC_OPEN, FALSE);
1837 if (m_dwContextMenus & GITSLC_POPEXPLORE && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC)
1839 popup.AppendMenuIcon(IDGITLC_EXPLORE, IDS_STATUSLIST_CONTEXT_EXPLORE, IDI_EXPLORER);
1843 if (GetSelectedCount() > 0)
1845 // if (((wcStatus == git_wc_status_unversioned)||(wcStatus == git_wc_status_ignored))&&(m_dwContextMenus & SVNSLC_POPDELETE))
1846 // {
1847 // popup.AppendMenuIcon(IDSVNLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1848 // }
1849 // 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))
1850 // {
1851 // if (bShift)
1852 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVEKEEP, IDI_DELETE);
1853 // else
1854 // popup.AppendMenuIcon(IDGitLC_REMOVE, IDS_MENUREMOVE, IDI_DELETE);
1855 // }
1856 if ((wcStatus & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))/*||(wcStatus == git_wc_status_deleted)*/)
1858 if (m_dwContextMenus & GITSLC_POPDELETE)
1860 popup.AppendMenuIcon(IDGITLC_DELETE, IDS_MENUREMOVE, IDI_DELETE);
1863 if ( (wcStatus & CTGitPath::LOGACTIONS_UNVER || wcStatus & CTGitPath::LOGACTIONS_DELETED) )
1865 if (m_dwContextMenus & GITSLC_POPIGNORE)
1868 CTGitPathList ignorelist;
1869 FillListOfSelectedItemPaths(ignorelist);
1870 //check if all selected entries have the same extension
1871 bool bSameExt = true;
1872 CString sExt;
1873 for (int i=0; i<ignorelist.GetCount(); ++i)
1875 if (sExt.IsEmpty() && (i==0))
1876 sExt = ignorelist[i].GetFileExtension();
1877 else if (sExt.CompareNoCase(ignorelist[i].GetFileExtension())!=0)
1878 bSameExt = false;
1880 if (bSameExt)
1882 if (ignoreSubMenu.CreateMenu())
1884 CString ignorepath;
1885 if (ignorelist.GetCount()==1)
1886 ignorepath = ignorelist[0].GetFileOrDirectoryName();
1887 else
1888 ignorepath.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1889 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNORE, ignorepath);
1890 ignorepath = _T("*")+sExt;
1891 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREMASK, ignorepath);
1892 if (ignorelist.GetCount() == 1 && !ignorelist[0].GetContainingDirectory().GetGitPathString().IsEmpty())
1893 ignoreSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDGITLC_IGNOREFOLDER, ignorelist[0].GetContainingDirectory().GetGitPathString());
1894 CString temp;
1895 temp.LoadString(IDS_MENUIGNORE);
1896 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)ignoreSubMenu.m_hMenu, temp);
1899 else
1901 CString temp;
1902 if (ignorelist.GetCount()==1)
1904 temp.LoadString(IDS_MENUIGNORE);
1906 else
1908 temp.Format(IDS_MENUIGNOREMULTIPLE, ignorelist.GetCount());
1910 popup.AppendMenuIcon(IDGITLC_IGNORE, temp, IDI_IGNORE);
1911 temp.Format(IDS_MENUIGNOREMULTIPLEMASK, ignorelist.GetCount());
1912 popup.AppendMenuIcon(IDGITLC_IGNOREMASK, temp, IDI_IGNORE);
1920 if (GetSelectedCount() > 0)
1922 popup.AppendMenu(MF_SEPARATOR);
1923 popup.AppendMenuIcon(IDGITLC_COPY, IDS_STATUSLIST_CONTEXT_COPY, IDI_COPYCLIP);
1924 popup.AppendMenuIcon(IDGITLC_COPYEXT, IDS_STATUSLIST_CONTEXT_COPYEXT, IDI_COPYCLIP);
1925 #if 0
1926 if ((m_dwContextMenus & SVNSLC_POPCHANGELISTS))
1927 &&(wcStatus != git_wc_status_unversioned)&&(wcStatus != git_wc_status_none))
1929 popup.AppendMenu(MF_SEPARATOR);
1930 // changelist commands
1931 size_t numChangelists = GetNumberOfChangelistsInSelection();
1932 if (numChangelists > 0)
1934 popup.AppendMenuIcon(IDSVNLC_REMOVEFROMCS, IDS_STATUSLIST_CONTEXT_REMOVEFROMCS);
1936 if ((!entry->IsFolder())&&(changelistSubMenu.CreateMenu()))
1938 CString temp;
1939 temp.LoadString(IDS_STATUSLIST_CONTEXT_CREATECS);
1940 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATECS, temp);
1942 if (entry->changelist.Compare(SVNSLC_IGNORECHANGELIST))
1944 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1945 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, IDSVNLC_CREATEIGNORECS, SVNSLC_IGNORECHANGELIST);
1948 if (!m_changelists.empty())
1950 // find the changelist names
1951 bool bNeedSeparator = true;
1952 int cmdID = IDSVNLC_MOVETOCS;
1953 for (std::map<CString, int>::const_iterator it = m_changelists.begin(); it != m_changelists.end(); ++it)
1955 if ((entry->changelist.Compare(it->first))&&(it->first.Compare(SVNSLC_IGNORECHANGELIST)))
1957 if (bNeedSeparator)
1959 changelistSubMenu.AppendMenu(MF_SEPARATOR);
1960 bNeedSeparator = false;
1962 changelistSubMenu.AppendMenu(MF_STRING | MF_ENABLED, cmdID, it->first);
1963 cmdID++;
1967 temp.LoadString(IDS_STATUSLIST_CONTEXT_MOVETOCS);
1968 popup.AppendMenu(MF_POPUP|MF_STRING, (UINT_PTR)changelistSubMenu.GetSafeHmenu(), temp);
1971 #endif
1974 m_hShellMenu = nullptr;
1975 if (pfnSHCreateDefaultContextMenu && pfnAssocCreateForClasses && GetSelectedCount() > 0 && !(wcStatus & CTGitPath::LOGACTIONS_DELETED) && m_bHasWC && (this->m_CurrentVersion.IsEmpty() || this->m_CurrentVersion == GIT_REV_ZERO) && shellMenu.CreatePopupMenu())
1977 // insert the shell context menu
1978 popup.AppendMenu(MF_SEPARATOR);
1979 popup.InsertMenu((UINT)-1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)shellMenu.m_hMenu, CString(MAKEINTRESOURCE(IDS_STATUSLIST_CONTEXT_SHELL)));
1980 m_hShellMenu = shellMenu.m_hMenu;
1983 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this, 0);
1984 g_IContext2 = nullptr;
1985 g_IContext3 = nullptr;
1986 if (m_pContextMenu)
1988 if (cmd >= SHELL_MIN_CMD && cmd <= SHELL_MAX_CMD) // see if returned idCommand belongs to shell menu entries)
1990 CMINVOKECOMMANDINFOEX cmi = { 0 };
1991 cmi.cbSize = sizeof(CMINVOKECOMMANDINFOEX);
1992 cmi.fMask = CMIC_MASK_UNICODE | CMIC_MASK_PTINVOKE;
1993 if (GetKeyState(VK_CONTROL) < 0)
1994 cmi.fMask |= CMIC_MASK_CONTROL_DOWN;
1995 if (bShift)
1996 cmi.fMask |= CMIC_MASK_SHIFT_DOWN;
1997 cmi.hwnd = m_hWnd;
1998 cmi.lpVerb = MAKEINTRESOURCEA(cmd - SHELL_MIN_CMD);
1999 cmi.lpVerbW = MAKEINTRESOURCEW(cmd - SHELL_MIN_CMD);
2000 cmi.nShow = SW_SHOWNORMAL;
2001 cmi.ptInvoke = point;
2003 m_pContextMenu->InvokeCommand((LPCMINVOKECOMMANDINFO)&cmi);
2005 cmd = 0;
2007 m_pContextMenu->Release();
2008 m_pContextMenu = nullptr;
2010 if (g_pFolderhook)
2012 delete g_pFolderhook;
2013 g_pFolderhook = nullptr;
2015 if (g_psfDesktopFolder)
2017 g_psfDesktopFolder->Release();
2018 g_psfDesktopFolder = nullptr;
2020 for (int i = 0; i < g_pidlArrayItems; i++)
2022 if (g_pidlArray[i])
2023 CoTaskMemFree(g_pidlArray[i]);
2025 if (g_pidlArray)
2026 CoTaskMemFree(g_pidlArray);
2027 g_pidlArray = nullptr;
2028 g_pidlArrayItems = 0;
2030 m_bBlock = TRUE;
2031 AfxGetApp()->DoWaitCursor(1);
2032 //int iItemCountBeforeMenuCmd = GetItemCount();
2033 //bool bForce = false;
2034 switch (cmd)
2036 case IDGITLC_VIEWREV:
2037 OpenFile(filepath, ALTERNATIVEEDITOR);
2038 break;
2040 case IDGITLC_OPEN:
2041 OpenFile(filepath,OPEN);
2042 break;
2044 case IDGITLC_OPENWITH:
2045 OpenFile(filepath,OPEN_WITH);
2046 break;
2048 case IDGITLC_EXPLORE:
2049 CAppUtils::ExploreTo(GetSafeHwnd(), g_Git.CombinePath(filepath));
2050 break;
2052 case IDGITLC_CREATERESTORE:
2054 POSITION pos = GetFirstSelectedItemPosition();
2055 while (pos)
2057 int index = GetNextSelectedItem(pos);
2058 CTGitPath * entry2 = (CTGitPath * )GetItemData(index);
2059 ASSERT(entry2 != NULL);
2060 if (entry2 == NULL || entry2->IsDirectory())
2061 continue;
2062 if (m_restorepaths.find(entry2->GetWinPathString()) != m_restorepaths.end())
2063 continue;
2064 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2065 // delete the temp file: the temp file has the FILE_ATTRIBUTE_TEMPORARY flag set
2066 // and copying the real file over it would leave that temp flag.
2067 DeleteFile(tempFile.GetWinPath());
2068 if (CopyFile(g_Git.CombinePath(entry2), tempFile.GetWinPath(), FALSE))
2070 m_restorepaths[entry2->GetWinPathString()] = tempFile.GetWinPathString();
2071 SetItemState(index, INDEXTOOVERLAYMASK(OVL_RESTORE), LVIS_OVERLAYMASK);
2074 Invalidate();
2076 break;
2078 case IDGITLC_RESTOREPATH:
2080 if (CMessageBox::Show(m_hWnd, IDS_STATUSLIST_RESTOREPATH, IDS_APPNAME, 2, IDI_QUESTION, IDS_RESTOREBUTTON, IDS_ABORTBUTTON) == 2)
2081 break;
2082 POSITION pos = GetFirstSelectedItemPosition();
2083 while (pos)
2085 int index = GetNextSelectedItem(pos);
2086 CTGitPath * entry2 = (CTGitPath * )GetItemData(index);
2087 ASSERT(entry2 != NULL);
2088 if (entry2 == NULL)
2089 continue;
2090 if (m_restorepaths.find(entry2->GetWinPathString()) == m_restorepaths.end())
2091 continue;
2092 if (CopyFile(m_restorepaths[entry2->GetWinPathString()], g_Git.CombinePath(entry2), FALSE))
2094 m_restorepaths.erase(entry2->GetWinPathString());
2095 SetItemState(index, 0, LVIS_OVERLAYMASK);
2098 Invalidate();
2100 break;
2102 // Compare current version and work copy.
2103 case IDGITLC_COMPAREWC:
2105 if (!CheckMultipleDiffs())
2106 break;
2107 POSITION pos = GetFirstSelectedItemPosition();
2108 while ( pos )
2110 int index = GetNextSelectedItem(pos);
2111 StartDiffWC(index);
2114 break;
2116 // Compare with base version. when current version is zero, compare workcopy and HEAD.
2117 case IDGITLC_COMPARE:
2119 if (!CheckMultipleDiffs())
2120 break;
2121 POSITION pos = GetFirstSelectedItemPosition();
2122 while ( pos )
2124 int index = GetNextSelectedItem(pos);
2125 StartDiff(index);
2128 break;
2130 case IDGITLC_COMPARETWOREVISIONS:
2132 POSITION pos = GetFirstSelectedItemPosition();
2133 while ( pos )
2135 int index = GetNextSelectedItem(pos);
2136 StartDiffTwo(index);
2139 break;
2141 case IDGITLC_COMPARETWOFILES:
2143 POSITION pos = GetFirstSelectedItemPosition();
2144 CTGitPath * firstfilepath = NULL, * secondfilepath = NULL;
2145 if (pos)
2147 firstfilepath = (CTGitPath * )GetItemData(GetNextSelectedItem(pos));
2148 ASSERT(firstfilepath != NULL);
2149 if (firstfilepath == NULL)
2150 break;
2152 secondfilepath = (CTGitPath * )GetItemData(GetNextSelectedItem(pos));
2153 ASSERT(secondfilepath != NULL);
2154 if (secondfilepath == NULL)
2155 break;
2157 CString sCmd;
2158 sCmd.Format(_T("/command:diff /path:\"%s\" /path2:\"%s\" /hwnd:%p"), firstfilepath->GetWinPath(), secondfilepath->GetWinPath(), (void*)m_hWnd);
2159 CAppUtils::RunTortoiseGitProc(sCmd);
2162 break;
2164 case IDGITLC_GNUDIFF1:
2166 POSITION pos = GetFirstSelectedItemPosition();
2167 while (pos)
2169 CTGitPath * selectedFilepath = (CTGitPath * )GetItemData(GetNextSelectedItem(pos));
2170 if (m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
2172 CString fromwhere;
2173 if (m_amend)
2174 fromwhere = _T("~1");
2175 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, GitRev::GetHead() + fromwhere, *selectedFilepath, GitRev::GetWorkingCopy());
2177 else
2179 if ((selectedFilepath->m_ParentNo & (PARENT_MASK | MERGE_MASK)) == 0)
2180 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, m_CurrentVersion + _T("~1"), *selectedFilepath, m_CurrentVersion);
2181 else
2183 CString str;
2184 if (!(selectedFilepath->m_ParentNo & MERGE_MASK))
2185 str.Format(_T("%s^%d"), m_CurrentVersion, (selectedFilepath->m_ParentNo & PARENT_MASK) + 1);
2187 CAppUtils::StartShowUnifiedDiff(m_hWnd, *selectedFilepath, str, *selectedFilepath, m_CurrentVersion, false, false, false, false, !!(selectedFilepath->m_ParentNo & MERGE_MASK));
2192 break;
2194 case IDGITLC_GNUDIFF2REVISIONS:
2196 CAppUtils::StartShowUnifiedDiff(m_hWnd, *filepath, m_Rev2, *filepath, m_Rev1);
2198 break;
2200 case IDGITLC_ADD:
2202 CTGitPathList paths;
2203 FillListOfSelectedItemPaths(paths, true);
2205 CGitProgressDlg progDlg;
2206 AddProgressCommand addCommand;
2207 progDlg.SetCommand(&addCommand);
2208 addCommand.SetPathList(paths);
2209 progDlg.SetItemCount(paths.GetCount());
2210 progDlg.DoModal();
2212 // reset unchecked status
2213 POSITION pos = GetFirstSelectedItemPosition();
2214 int index;
2215 while ((index = GetNextSelectedItem(pos)) >= 0)
2217 m_mapFilenameToChecked.erase(((CTGitPath*)GetItemData(index))->GetGitPathString());
2220 if (NULL != GetLogicalParent() && NULL != GetLogicalParent()->GetSafeHwnd())
2221 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2223 SetRedraw(TRUE);
2225 break;
2227 case IDGITLC_DELETE:
2228 DeleteSelectedFiles();
2229 break;
2231 case IDGITLC_BLAME:
2233 CAppUtils::LaunchTortoiseBlame(g_Git.CombinePath(filepath), m_CurrentVersion);
2235 break;
2237 case IDGITLC_LOG:
2238 case IDGITLC_LOGSUBMODULE:
2240 CString sCmd;
2241 sCmd.Format(_T("/command:log /path:\"%s\""), g_Git.CombinePath(filepath));
2242 if (cmd == IDGITLC_LOG && filepath->IsDirectory())
2243 sCmd += _T(" /submodule");
2244 if (!m_sDisplayedBranch.IsEmpty())
2245 sCmd += _T(" /range:\"") + m_sDisplayedBranch + _T("\"");
2246 CAppUtils::RunTortoiseGitProc(sCmd, false, !(cmd == IDGITLC_LOGSUBMODULE));
2248 break;
2250 case IDGITLC_LOGOLDNAME:
2252 CTGitPath oldName(filepath->GetGitOldPathString());
2253 CString sCmd;
2254 sCmd.Format(_T("/command:log /path:\"%s\""), g_Git.CombinePath(oldName));
2255 if (!m_sDisplayedBranch.IsEmpty())
2256 sCmd += _T(" /range:\"") + m_sDisplayedBranch + _T("\"");
2257 CAppUtils::RunTortoiseGitProc(sCmd);
2259 break;
2261 case IDGITLC_EDITCONFLICT:
2263 if (CAppUtils::ConflictEdit(*filepath, false, m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2265 CString conflictedFile = g_Git.CombinePath(filepath);
2266 if (!PathFileExists(conflictedFile) && NULL != GetLogicalParent() && NULL != GetLogicalParent()->GetSafeHwnd())
2267 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2270 break;
2272 case IDGITLC_RESOLVETHEIRS: //follow up
2273 case IDGITLC_RESOLVEMINE: //follow up
2274 case IDGITLC_RESOLVECONFLICT:
2276 if (CMessageBox::Show(m_hWnd, IDS_PROC_RESOLVE, IDS_APPNAME, MB_ICONQUESTION | MB_YESNO)==IDYES)
2278 POSITION pos = GetFirstSelectedItemPosition();
2279 while (pos != 0)
2281 int index;
2282 index = GetNextSelectedItem(pos);
2283 CTGitPath * fentry =(CTGitPath*) this->GetItemData(index);
2284 if(fentry == NULL)
2285 continue;
2287 CAppUtils::resolve_with resolveWith = CAppUtils::RESOLVE_WITH_CURRENT;
2288 if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE))
2289 resolveWith = CAppUtils::RESOLVE_WITH_THEIRS;
2290 else if (((!this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVEMINE) || ((this->m_bIsRevertTheirMy) && cmd == IDGITLC_RESOLVETHEIRS))
2291 resolveWith = CAppUtils::RESOLVE_WITH_MINE;
2292 if (CAppUtils::ResolveConflict(*fentry, resolveWith) == 0 && fentry->m_Action & CTGitPath::LOGACTIONS_UNMERGED && CRegDWORD(_T("Software\\TortoiseGit\\RefreshFileListAfterResolvingConflict"), TRUE) == TRUE)
2294 CWnd* pParent = GetLogicalParent();
2295 if (pParent && pParent->GetSafeHwnd())
2296 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2297 SetRedraw(TRUE);
2298 break;
2301 Show(m_dwShow, 0, m_bShowFolders,0,true);
2304 break;
2306 case IDGITLC_IGNORE:
2308 CTGitPathList ignorelist;
2309 //std::vector<CString> toremove;
2310 FillListOfSelectedItemPaths(ignorelist, true);
2312 if(!CAppUtils::IgnoreFile(ignorelist,false))
2313 break;
2315 SetRedraw(FALSE);
2316 CWnd* pParent = GetLogicalParent();
2317 if (NULL != pParent && NULL != pParent->GetSafeHwnd())
2319 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2321 SetRedraw(TRUE);
2323 break;
2325 case IDGITLC_IGNOREMASK:
2327 CString common;
2328 CString ext=filepath->GetFileExtension();
2329 CTGitPathList ignorelist;
2330 FillListOfSelectedItemPaths(ignorelist, true);
2332 if (!CAppUtils::IgnoreFile(ignorelist,true))
2333 break;
2335 SetRedraw(FALSE);
2336 CWnd* pParent = GetLogicalParent();
2337 if (NULL != pParent && NULL != pParent->GetSafeHwnd())
2339 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2342 SetRedraw(TRUE);
2344 break;
2346 case IDGITLC_IGNOREFOLDER:
2348 CTGitPathList ignorelist;
2349 ignorelist.AddPath(filepath->GetContainingDirectory());
2351 if (!CAppUtils::IgnoreFile(ignorelist, false))
2352 break;
2354 SetRedraw(FALSE);
2355 CWnd *pParent = GetLogicalParent();
2356 if (NULL != pParent && NULL != pParent->GetSafeHwnd())
2357 pParent->SendMessage(GITSLNM_NEEDSREFRESH);
2359 SetRedraw(TRUE);
2361 break;
2362 case IDGITLC_COMMIT:
2364 CTGitPathList targetList;
2365 FillListOfSelectedItemPaths(targetList);
2366 CTGitPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2367 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2368 CString commandline = _T("/command:commit /pathfile:\"");
2369 commandline += tempFile.GetWinPathString();
2370 commandline += _T("\"");
2371 commandline += _T(" /deletepathfile");
2372 CAppUtils::RunTortoiseGitProc(commandline);
2374 break;
2375 case IDGITLC_REVERT:
2377 // If at least one item is not in the status "added"
2378 // we ask for a confirmation
2379 BOOL bConfirm = FALSE;
2380 POSITION pos = GetFirstSelectedItemPosition();
2381 int index;
2382 while ((index = GetNextSelectedItem(pos)) >= 0)
2384 //FileEntry * fentry = GetListEntry(index);
2385 CTGitPath *fentry=(CTGitPath*)GetItemData(index);
2386 if(fentry && fentry->m_Action &CTGitPath::LOGACTIONS_MODIFIED && !fentry->IsDirectory())
2388 bConfirm = TRUE;
2389 break;
2393 CString str;
2394 str.Format(IDS_PROC_WARNREVERT,GetSelectedCount());
2396 if (!bConfirm || CMessageBox::Show(this->m_hWnd, str, _T("TortoiseGit"), MB_YESNO | MB_ICONQUESTION)==IDYES)
2398 CTGitPathList targetList;
2399 FillListOfSelectedItemPaths(targetList);
2401 // make sure that the list is reverse sorted, so that
2402 // children are removed before any parents
2403 targetList.SortByPathname(true);
2405 // put all reverted files in the trashbin, except the ones with 'added'
2406 // status because they are not restored by the revert.
2407 CTGitPathList delList;
2408 POSITION pos = GetFirstSelectedItemPosition();
2409 int index;
2410 while ((index = GetNextSelectedItem(pos)) >= 0)
2412 CTGitPath *entry=(CTGitPath *)GetItemData(index);
2413 if (entry&&(!(entry->m_Action& CTGitPath::LOGACTIONS_ADDED))
2414 && (!(entry->m_Action& CTGitPath::LOGACTIONS_REPLACED)) && !entry->IsDirectory())
2416 CTGitPath fullpath;
2417 fullpath.SetFromWin(g_Git.CombinePath(entry));
2418 delList.AddPath(fullpath);
2421 if (DWORD(CRegDWORD(_T("Software\\TortoiseGit\\RevertWithRecycleBin"), TRUE)))
2422 delList.DeleteAllFiles(true);
2424 CString revertToCommit = _T("HEAD");
2425 if (m_amend)
2426 revertToCommit = _T("HEAD~1");
2427 CString err;
2428 if (g_Git.Revert(revertToCommit, targetList, err))
2430 CMessageBox::Show(this->m_hWnd, _T("Revert failed:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
2432 else
2434 bool updateStatusList = false;
2435 for (int i = 0 ; i < targetList.GetCount(); ++i)
2437 int nListboxEntries = GetItemCount();
2438 for (int nItem=0; nItem<nListboxEntries; ++nItem)
2440 CTGitPath *path=(CTGitPath*)GetItemData(nItem);
2441 if (path->GetGitPathString()==targetList[i].GetGitPathString() && !path->IsDirectory())
2443 if(path->m_Action & CTGitPath::LOGACTIONS_ADDED)
2445 path->m_Action = CTGitPath::LOGACTIONS_UNVER;
2446 SetEntryCheck(path,nItem,false);
2447 updateStatusList = true;
2448 #if 0 // revert an added file and some entry will be cloned (part 1/2)
2449 SetItemGroup(nItem,1);
2450 this->m_StatusFileList.RemoveItem(*path);
2451 this->m_UnRevFileList.AddPath(*path);
2452 //this->m_IgnoreFileList.RemoveItem(*path);
2453 #endif
2455 else
2457 if (GetCheck(nItem))
2458 m_nSelected--;
2459 RemoveListEntry(nItem);
2461 break;
2463 else if (path->GetGitPathString()==targetList[i].GetGitPathString() && path->IsDirectory() && path->IsWCRoot())
2465 CString sCmd;
2466 sCmd.Format(_T("/command:revert /path:\"%s\""), path->GetGitPathString());
2467 CCommonAppUtils::RunTortoiseGitProc(sCmd);
2471 SetRedraw(TRUE);
2472 SaveColumnWidths();
2473 #if 0 // revert an added file and some entry will be cloned (part 2/2)
2474 Show(m_dwShow, 0, m_bShowFolders,updateStatusList,true);
2475 NotifyCheck();
2476 #else
2477 if (updateStatusList && nullptr != GetLogicalParent() && nullptr != GetLogicalParent()->GetSafeHwnd())
2478 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2479 #endif
2483 break;
2485 case IDGITLC_ASSUMEVALID:
2486 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_ASSUMEVALID, BST_CHECKED, BST_INDETERMINATE);
2487 break;
2488 case IDGITLC_SKIPWORKTREE:
2489 SetGitIndexFlagsForSelectedFiles(IDS_PROC_MARK_SKIPWORKTREE, BST_INDETERMINATE, BST_CHECKED);
2490 break;
2491 case IDGITLC_UNSETIGNORELOCALCHANGES:
2492 SetGitIndexFlagsForSelectedFiles(IDS_PROC_UNSET_IGNORELOCALCHANGES, BST_UNCHECKED, BST_UNCHECKED);
2493 break;
2494 case IDGITLC_COPY:
2495 CopySelectedEntriesToClipboard(0);
2496 break;
2497 case IDGITLC_COPYEXT:
2498 CopySelectedEntriesToClipboard((DWORD)-1);
2499 break;
2500 case IDGITLC_EXPORT:
2501 FilesExport();
2502 break;
2503 case IDGITLC_SAVEAS:
2504 FileSaveAs(filepath);
2505 break;
2507 case IDGITLC_REVERTTOREV:
2508 RevertSelectedItemToVersion();
2509 break;
2510 case IDGITLC_REVERTTOPARENT:
2511 RevertSelectedItemToVersion(true);
2512 break;
2513 #if 0
2514 case IDSVNLC_COMMIT:
2516 CTSVNPathList targetList;
2517 FillListOfSelectedItemPaths(targetList);
2518 CTSVNPath tempFile = CTempFiles::Instance().GetTempFilePath(false);
2519 VERIFY(targetList.WriteToFile(tempFile.GetWinPathString()));
2520 CString commandline = CPathUtils::GetAppDirectory();
2521 commandline += _T("TortoiseGitProc.exe /command:commit /pathfile:\"");
2522 commandline += tempFile.GetWinPathString();
2523 commandline += _T("\"");
2524 commandline += _T(" /deletepathfile");
2525 CAppUtils::LaunchApplication(commandline, NULL, false);
2527 break;
2528 case IDSVNLC_CREATEIGNORECS:
2529 CreateChangeList(SVNSLC_IGNORECHANGELIST);
2530 break;
2531 case IDSVNLC_CREATECS:
2533 CCreateChangelistDlg dlg;
2534 if (dlg.DoModal() == IDOK)
2536 CreateChangeList(dlg.m_sName);
2539 break;
2540 default:
2542 if (cmd < IDSVNLC_MOVETOCS)
2543 break;
2544 CTSVNPathList changelistItems;
2545 FillListOfSelectedItemPaths(changelistItems);
2547 // find the changelist name
2548 CString sChangelist;
2549 int cmdID = IDSVNLC_MOVETOCS;
2550 SetRedraw(FALSE);
2551 for (std::map<CString, int>::const_iterator it = m_changelists.begin(); it != m_changelists.end(); ++it)
2553 if ((it->first.Compare(SVNSLC_IGNORECHANGELIST))&&(entry->changelist.Compare(it->first)))
2555 if (cmd == cmdID)
2557 sChangelist = it->first;
2559 cmdID++;
2562 if (!sChangelist.IsEmpty())
2564 SVN git;
2565 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
2567 // The changelists were moved, but we now need to run through the selected items again
2568 // and update their changelist
2569 POSITION pos = GetFirstSelectedItemPosition();
2570 int index;
2571 while ((index = GetNextSelectedItem(pos)) >= 0)
2573 FileEntry * e = GetListEntry(index);
2574 e->changelist = sChangelist;
2575 if (!e->IsFolder())
2577 if (m_changelists.find(e->changelist)!=m_changelists.end())
2578 SetItemGroup(index, m_changelists[e->changelist]);
2579 else
2580 SetItemGroup(index, 0);
2584 else
2586 CMessageBox::Show(m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
2589 SetRedraw(TRUE);
2591 break;
2592 #endif
2594 } // switch (cmd)
2595 m_bBlock = FALSE;
2596 AfxGetApp()->DoWaitCursor(-1);
2597 GetStatisticsString();
2598 //int iItemCountAfterMenuCmd = GetItemCount();
2599 //if (iItemCountAfterMenuCmd != iItemCountBeforeMenuCmd)
2601 // CWnd* pParent = GetParent();
2602 // if (NULL != pParent && NULL != pParent->GetSafeHwnd())
2603 // {
2604 // pParent->SendMessage(SVNSLNM_ITEMCOUNTCHANGED);
2605 // }
2607 } // if (popup.CreatePopupMenu())
2608 } // if (selIndex >= 0)
2612 void CGitStatusListCtrl::SetGitIndexFlagsForSelectedFiles(UINT message, BOOL assumevalid, BOOL skipworktree)
2614 if (CMessageBox::Show(GetSafeHwnd(), message, IDS_APPNAME, MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
2615 return;
2617 CAutoRepository repository(g_Git.GetGitRepository());
2618 if (!repository)
2620 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2621 return;
2624 CAutoIndex gitindex;
2625 if (git_repository_index(gitindex.GetPointer(), repository))
2627 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2628 return;
2631 POSITION pos = GetFirstSelectedItemPosition();
2632 int index = -1;
2633 while ((index = GetNextSelectedItem(pos)) >= 0)
2635 CTGitPath * path = (CTGitPath *)GetItemData(index);
2636 ASSERT(path);
2637 if (path == nullptr)
2638 continue;
2640 size_t idx;
2641 if (!git_index_find(&idx, gitindex, CUnicodeUtils::GetMulti(path->GetGitPathString(), CP_UTF8)))
2643 git_index_entry *e = const_cast<git_index_entry *>(git_index_get_byindex(gitindex, idx)); // HACK
2644 if (assumevalid == BST_UNCHECKED)
2645 e->flags &= ~GIT_IDXENTRY_VALID;
2646 else if (assumevalid == BST_CHECKED)
2647 e->flags |= GIT_IDXENTRY_VALID;
2648 if (skipworktree == BST_UNCHECKED)
2649 e->flags_extended &= ~GIT_IDXENTRY_SKIP_WORKTREE;
2650 else if (skipworktree == BST_CHECKED)
2651 e->flags_extended |= GIT_IDXENTRY_SKIP_WORKTREE;
2652 git_index_add(gitindex, e);
2654 else
2655 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2658 if (git_index_write(gitindex))
2660 CMessageBox::Show(m_hWnd, g_Git.GetLibGit2LastErr(), _T("TortoiseGit"), MB_ICONERROR);
2661 return;
2664 if (nullptr != GetLogicalParent() && nullptr != GetLogicalParent()->GetSafeHwnd())
2665 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2667 SetRedraw(TRUE);
2670 void CGitStatusListCtrl::OnContextMenuHeader(CWnd * pWnd, CPoint point)
2672 Locker lock(m_critSec);
2673 m_ColumnManager.OnContextMenuHeader(pWnd,point,!!IsGroupViewEnabled());
2676 void CGitStatusListCtrl::OnContextMenu(CWnd* pWnd, CPoint point)
2679 if (pWnd == this)
2681 OnContextMenuList(pWnd, point);
2682 } // if (pWnd == this)
2683 else if (pWnd == GetHeaderCtrl())
2685 OnContextMenuHeader(pWnd, point);
2689 void CGitStatusListCtrl::OnNMDblclk(NMHDR *pNMHDR, LRESULT *pResult)
2692 Locker lock(m_critSec);
2693 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
2694 *pResult = 0;
2695 if (m_bBlock)
2696 return;
2698 if (pNMLV->iItem < 0)
2699 return;
2701 CTGitPath *file=(CTGitPath*)GetItemData(pNMLV->iItem);
2703 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)) {
2704 OpenFile(file, OPEN);
2705 return;
2707 if( file->m_Action&CTGitPath::LOGACTIONS_UNMERGED )
2709 if (CAppUtils::ConflictEdit(*file, false, m_bIsRevertTheirMy, GetLogicalParent() ? GetLogicalParent()->GetSafeHwnd() : nullptr))
2711 CString conflictedFile = g_Git.CombinePath(file);
2712 if (!PathFileExists(conflictedFile) && NULL != GetLogicalParent() && NULL != GetLogicalParent()->GetSafeHwnd())
2713 GetLogicalParent()->SendMessage(GITSLNM_NEEDSREFRESH);
2716 else
2718 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
2719 StartDiffTwo(pNMLV->iItem);
2720 else
2721 StartDiff(pNMLV->iItem);
2725 void CGitStatusListCtrl::StartDiffTwo(int fileindex)
2727 if(fileindex<0)
2728 return;
2730 auto ptr = (CTGitPath*)GetItemData(fileindex);
2731 if (ptr == nullptr)
2732 return;
2733 CTGitPath file1 = *ptr;
2735 if (file1.m_Action & CTGitPath::LOGACTIONS_ADDED)
2736 CGitDiff::DiffNull(&file1, m_Rev1, true);
2737 else if (file1.m_Action & CTGitPath::LOGACTIONS_DELETED)
2738 CGitDiff::DiffNull(&file1, m_Rev2, false);
2739 else
2740 CGitDiff::Diff(&file1, &file1, m_Rev1, m_Rev2);
2743 void CGitStatusListCtrl::StartDiffWC(int fileindex)
2745 if(fileindex<0)
2746 return;
2748 CString Ver;
2749 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion== GIT_REV_ZERO)
2750 return;
2752 auto ptr = (CTGitPath*)GetItemData(fileindex);
2753 if (ptr == nullptr)
2754 return;
2755 CTGitPath file1 = *ptr;
2756 file1.m_Action = 0; // reset action, so that diff is not started as added/deleted file; see issue #1757
2758 CGitDiff::Diff(&file1,&file1, GIT_REV_ZERO, m_CurrentVersion);
2762 void CGitStatusListCtrl::StartDiff(int fileindex)
2764 if(fileindex<0)
2765 return;
2767 auto ptr = (CTGitPath*)GetItemData(fileindex);
2768 if (ptr == nullptr)
2769 return;
2770 CTGitPath file1 = *ptr;
2771 CTGitPath file2;
2772 if(file1.m_Action & (CTGitPath::LOGACTIONS_REPLACED|CTGitPath::LOGACTIONS_COPY))
2774 file2.SetFromGit(file1.GetGitOldPathString());
2776 else
2778 file2=file1;
2781 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion== GIT_REV_ZERO)
2783 CString fromwhere;
2784 if(m_amend && (file1.m_Action & CTGitPath::LOGACTIONS_ADDED) == 0)
2785 fromwhere = _T("~1");
2786 if( g_Git.IsInitRepos())
2787 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2788 GIT_REV_ZERO);
2789 else if( file1.m_Action&CTGitPath::LOGACTIONS_ADDED )
2790 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2791 m_CurrentVersion+fromwhere,true);
2792 else if( file1.m_Action&CTGitPath::LOGACTIONS_DELETED )
2793 CGitDiff::DiffNull((CTGitPath*)GetItemData(fileindex),
2794 GitRev::GetHead()+fromwhere,false);
2795 else
2796 CGitDiff::Diff(&file1,&file2,
2797 CString(GIT_REV_ZERO),
2798 GitRev::GetHead()+fromwhere);
2800 else
2802 CGitHash hash;
2803 CString fromwhere = m_CurrentVersion+_T("~1");
2804 if(m_amend)
2805 fromwhere = m_CurrentVersion+_T("~2");
2806 bool revfail = !!g_Git.GetHash(hash, fromwhere);
2807 if (revfail || (file1.m_Action & file1.LOGACTIONS_ADDED))
2809 CGitDiff::DiffNull(&file1,m_CurrentVersion,true);
2812 else if (file1.m_Action & file1.LOGACTIONS_DELETED)
2814 if (file1.m_ParentNo > 0)
2815 fromwhere.Format(_T("%s^%d"), m_CurrentVersion, file1.m_ParentNo + 1);
2817 CGitDiff::DiffNull(&file1,fromwhere,false);
2819 else
2821 if( file1.m_ParentNo & MERGE_MASK)
2824 CTGitPath base, theirs, mine, merge;
2826 CString temppath;
2827 GetTempPath(temppath);
2828 temppath.TrimRight(_T("\\"));
2830 mine.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".LOCAL") + file1.GetFileExtension());
2831 theirs.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".REMOTE") + file1.GetFileExtension());
2832 base.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".BASE") + file1.GetFileExtension());
2834 CFile tempfile;
2835 //create a empty file, incase stage is not three
2836 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2837 tempfile.Close();
2838 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2839 tempfile.Close();
2840 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
2841 tempfile.Close();
2843 merge.SetFromGit(temppath + _T("\\") + file1.GetFileOrDirectoryName() + _T(".Merged") + file1.GetFileExtension());
2845 int parent1=-1, parent2 =-1;
2846 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
2848 if(m_arStatusArray[i]->GetGitPathString() == file1.GetGitPathString())
2850 if(m_arStatusArray[i]->m_ParentNo & MERGE_MASK)
2853 else
2855 if(parent1<0)
2857 parent1 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2859 else if (parent2 <0)
2861 parent2 = m_arStatusArray[i]->m_ParentNo & PARENT_MASK;
2867 if(g_Git.GetOneFile(m_CurrentVersion, file1, (CString&)merge.GetWinPathString()))
2869 CMessageBox::Show(NULL, IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2872 if(parent1>=0)
2874 CString str;
2875 str.Format(_T("%s^%d"),this->m_CurrentVersion, parent1+1);
2877 if(g_Git.GetOneFile(str, file1, (CString&)mine.GetWinPathString()))
2879 CMessageBox::Show(NULL, IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2883 if(parent2>=0)
2885 CString str;
2886 str.Format(_T("%s^%d"),this->m_CurrentVersion, parent2+1);
2888 if(g_Git.GetOneFile(str, file1, (CString&)theirs.GetWinPathString()))
2890 CMessageBox::Show(NULL, IDS_STATUSLIST_FAILEDGETMERGEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2894 if(parent1>=0 && parent2>=0)
2896 CString cmd, output;
2897 cmd.Format(_T("git.exe merge-base %s^%d %s^%d"), this->m_CurrentVersion, parent1+1,
2898 this->m_CurrentVersion,parent2+1);
2900 if (g_Git.Run(cmd, &output, NULL, CP_UTF8))
2903 else
2905 if(g_Git.GetOneFile(output.Left(40), file1, (CString&)base.GetWinPathString()))
2907 CMessageBox::Show(NULL, IDS_STATUSLIST_FAILEDGETBASEFILE, IDS_APPNAME, MB_OK | MB_ICONERROR);
2911 CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
2914 else
2916 CString str;
2917 if( (file1.m_ParentNo&PARENT_MASK) == 0)
2919 str = _T("~1");
2921 else
2923 str.Format(_T("^%d"), (file1.m_ParentNo&PARENT_MASK)+1);
2925 CGitDiff::Diff(&file1,&file2,
2926 m_CurrentVersion,
2927 m_CurrentVersion+str);
2933 CString CGitStatusListCtrl::GetStatisticsString(bool simple)
2935 CString sNormal = CString(MAKEINTRESOURCE(IDS_STATUSNORMAL));
2936 CString sAdded = CString(MAKEINTRESOURCE(IDS_STATUSADDED));
2937 CString sDeleted = CString(MAKEINTRESOURCE(IDS_STATUSDELETED));
2938 CString sModified = CString(MAKEINTRESOURCE(IDS_STATUSMODIFIED));
2939 CString sConflicted = CString(MAKEINTRESOURCE(IDS_STATUSCONFLICTED));
2940 CString sUnversioned = CString(MAKEINTRESOURCE(IDS_STATUSUNVERSIONED));
2941 CString sRenamed = CString(MAKEINTRESOURCE(IDS_STATUSREPLACED));
2942 CString sToolTip;
2943 if(simple)
2945 sToolTip.Format(IDS_STATUSLIST_STATUSLINE1,
2946 this->m_nLineAdded,this->m_nLineDeleted,
2947 (LPCTSTR)sModified, m_nModified,
2948 (LPCTSTR)sAdded, m_nAdded,
2949 (LPCTSTR)sDeleted, m_nDeleted,
2950 (LPCTSTR)sRenamed, m_nRenamed
2953 else
2955 sToolTip.Format(IDS_STATUSLIST_STATUSLINE2,
2956 this->m_nLineAdded,this->m_nLineDeleted,
2957 (LPCTSTR)sNormal, m_nNormal,
2958 (LPCTSTR)sUnversioned, m_nUnversioned,
2959 (LPCTSTR)sModified, m_nModified,
2960 (LPCTSTR)sAdded, m_nAdded,
2961 (LPCTSTR)sDeleted, m_nDeleted,
2962 (LPCTSTR)sConflicted, m_nConflicted
2965 CString sStats;
2966 sStats.Format(IDS_COMMITDLG_STATISTICSFORMAT, m_nSelected, GetItemCount());
2967 if (m_pStatLabel)
2969 m_pStatLabel->SetWindowText(sStats);
2972 if (m_pSelectButton)
2974 if (m_nSelected == 0)
2975 m_pSelectButton->SetCheck(BST_UNCHECKED);
2976 else if (m_nSelected != GetItemCount())
2977 m_pSelectButton->SetCheck(BST_INDETERMINATE);
2978 else
2979 m_pSelectButton->SetCheck(BST_CHECKED);
2982 if (m_pConfirmButton)
2984 m_pConfirmButton->EnableWindow(m_nSelected>0);
2987 return sToolTip;
2992 CString CGitStatusListCtrl::GetCommonDirectory(bool bStrict)
2994 if (!bStrict)
2996 // not strict means that the selected folder has priority
2997 if (!m_StatusFileList.GetCommonDirectory().IsEmpty())
2998 return m_StatusFileList.GetCommonDirectory().GetWinPath();
3001 CTGitPath commonBaseDirectory;
3002 int nListItems = GetItemCount();
3003 for (int i=0; i<nListItems; ++i)
3005 CTGitPath baseDirectory,*p= (CTGitPath*)this->GetItemData(i);
3006 ASSERT(p);
3007 if(p==NULL)
3008 continue;
3009 baseDirectory = p->GetDirectory();
3011 if(commonBaseDirectory.IsEmpty())
3013 commonBaseDirectory = baseDirectory;
3015 else
3017 if (commonBaseDirectory.GetWinPathString().GetLength() > baseDirectory.GetWinPathString().GetLength())
3019 if (baseDirectory.IsAncestorOf(commonBaseDirectory))
3020 commonBaseDirectory = baseDirectory;
3024 return g_Git.CombinePath(commonBaseDirectory);
3028 void CGitStatusListCtrl::SelectAll(bool bSelect, bool /*bIncludeNoCommits*/)
3030 CWaitCursor waitCursor;
3031 // block here so the LVN_ITEMCHANGED messages
3032 // get ignored
3033 m_bBlock = TRUE;
3034 SetRedraw(FALSE);
3036 int nListItems = GetItemCount();
3037 if (bSelect)
3038 m_nSelected = nListItems;
3039 else
3040 m_nSelected = 0;
3042 for (int i=0; i<nListItems; ++i)
3044 //FileEntry * entry = GetListEntry(i);
3045 //ASSERT(entry != NULL);
3046 CTGitPath *path = (CTGitPath *) GetItemData(i);
3047 if (path == NULL)
3048 continue;
3049 //if ((bIncludeNoCommits)||(entry->GetChangeList().Compare(SVNSLC_IGNORECHANGELIST)))
3050 SetEntryCheck(path,i,bSelect);
3053 // unblock before redrawing
3054 m_bBlock = FALSE;
3055 SetRedraw(TRUE);
3056 GetStatisticsString();
3057 NotifyCheck();
3060 void CGitStatusListCtrl::Check(DWORD dwCheck, bool check)
3062 CWaitCursor waitCursor;
3063 // block here so the LVN_ITEMCHANGED messages
3064 // get ignored
3065 m_bBlock = TRUE;
3066 SetRedraw(FALSE);
3068 int nListItems = GetItemCount();
3070 for (int i = 0; i < nListItems; ++i)
3072 CTGitPath *entry = (CTGitPath *) GetItemData(i);
3073 if (entry == NULL)
3074 continue;
3076 DWORD showFlags = entry->m_Action;
3077 if (entry->IsDirectory())
3078 showFlags |= GITSLC_SHOWSUBMODULES;
3079 else
3080 showFlags |= GITSLC_SHOWFILES;
3082 if (check && (showFlags & dwCheck) && !GetCheck(i) && !(entry->IsDirectory() && m_bDoNotAutoselectSubmodules && !(dwCheck & GITSLC_SHOWSUBMODULES)))
3084 SetEntryCheck(entry, i, true);
3085 m_nSelected++;
3087 else if (!check && (showFlags & dwCheck) && GetCheck(i))
3089 SetEntryCheck(entry, i, false);
3090 m_nSelected--;
3093 // unblock before redrawing
3094 m_bBlock = FALSE;
3095 SetRedraw(TRUE);
3096 GetStatisticsString();
3097 NotifyCheck();
3100 void CGitStatusListCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
3102 LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR);
3103 *pResult = 0;
3104 if (m_bBlock)
3105 return;
3107 CTGitPath *entry=(CTGitPath *)GetItemData(pGetInfoTip->iItem);
3109 if (entry)
3110 if (pGetInfoTip->cchTextMax > entry->GetGitPathString().GetLength() + g_Git.m_CurrentDir.GetLength())
3112 CString str = g_Git.CombinePath(entry->GetWinPathString());
3113 _tcsncpy_s(pGetInfoTip->pszText, pGetInfoTip->cchTextMax, str.GetBuffer(), str.GetLength());
3117 void CGitStatusListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
3119 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
3121 // Take the default processing unless we set this to something else below.
3122 *pResult = CDRF_DODEFAULT;
3124 // First thing - check the draw stage. If it's the control's prepaint
3125 // stage, then tell Windows we want messages for every item.
3127 switch (pLVCD->nmcd.dwDrawStage)
3129 case CDDS_PREPAINT:
3130 *pResult = CDRF_NOTIFYITEMDRAW;
3131 break;
3132 case CDDS_ITEMPREPAINT:
3134 // This is the prepaint stage for an item. Here's where we set the
3135 // item's text color. Our return value will tell Windows to draw the
3136 // item itself, but it will use the new color we set here.
3138 // Tell Windows to paint the control itself.
3139 *pResult = CDRF_DODEFAULT;
3140 if (m_bBlock)
3141 return;
3143 COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
3145 if (m_arStatusArray.size() > (DWORD_PTR)pLVCD->nmcd.dwItemSpec)
3148 //FileEntry * entry = GetListEntry((int)pLVCD->nmcd.dwItemSpec);
3149 CTGitPath *entry=(CTGitPath *)GetItemData((int)pLVCD->nmcd.dwItemSpec);
3150 if (entry == NULL)
3151 return;
3153 // coloring
3154 // ========
3155 // black : unversioned, normal
3156 // purple : added
3157 // blue : modified
3158 // brown : missing, deleted, replaced
3159 // green : merged (or potential merges)
3160 // red : conflicts or sure conflicts
3161 if(entry->m_Action & CTGitPath::LOGACTIONS_GRAY)
3163 crText = RGB(128,128,128);
3166 else if(entry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3168 crText = m_Colors.GetColor(CColors::Conflict);
3171 else if(entry->m_Action & (CTGitPath::LOGACTIONS_MODIFIED))
3173 crText = m_Colors.GetColor(CColors::Modified);
3176 else if(entry->m_Action & (CTGitPath::LOGACTIONS_ADDED|CTGitPath::LOGACTIONS_COPY))
3178 crText = m_Colors.GetColor(CColors::Added);
3180 else if(entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
3182 crText = m_Colors.GetColor(CColors::Deleted);
3184 else if(entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
3186 crText = m_Colors.GetColor(CColors::Renamed);
3188 else if(entry->m_Action & CTGitPath::LOGACTIONS_MERGED)
3190 crText = m_Colors.GetColor(CColors::Merged);
3192 else
3194 crText = GetSysColor(COLOR_WINDOWTEXT);
3196 // Store the color back in the NMLVCUSTOMDRAW struct.
3197 pLVCD->clrText = crText;
3200 break;
3204 BOOL CGitStatusListCtrl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
3206 if (pWnd != this)
3207 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3208 if (!m_bBlock)
3210 HCURSOR hCur = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
3211 SetCursor(hCur);
3212 return CListCtrl::OnSetCursor(pWnd, nHitTest, message);
3214 HCURSOR hCur = LoadCursor(NULL, MAKEINTRESOURCE(IDC_WAIT));
3215 SetCursor(hCur);
3216 return TRUE;
3219 void CGitStatusListCtrl::RemoveListEntry(int index)
3222 Locker lock(m_critSec);
3223 DeleteItem(index);
3225 m_arStatusArray.erase(m_arStatusArray.begin()+index);
3227 #if 0
3228 delete m_arStatusArray[m_arListArray[index]];
3229 m_arStatusArray.erase(m_arStatusArray.begin()+m_arListArray[index]);
3230 m_arListArray.erase(m_arListArray.begin()+index);
3231 for (int i=index; i< (int)m_arListArray.size(); ++i)
3233 m_arListArray[i]--;
3235 #endif
3238 ///< Set a checkbox on an entry in the listbox
3239 // NEVER, EVER call SetCheck directly, because you'll end-up with the checkboxes and the 'checked' flag getting out of sync
3240 void CGitStatusListCtrl::SetEntryCheck(CTGitPath* pEntry, int listboxIndex, bool bCheck)
3242 pEntry->m_Checked = bCheck;
3243 m_mapFilenameToChecked[pEntry->GetGitPathString()] = bCheck;
3244 SetCheck(listboxIndex, bCheck);
3247 #if 0
3248 void CGitStatusListCtrl::SetCheckOnAllDescendentsOf(const FileEntry* parentEntry, bool bCheck)
3251 int nListItems = GetItemCount();
3252 for (int j=0; j< nListItems ; ++j)
3254 FileEntry * childEntry = GetListEntry(j);
3255 ASSERT(childEntry != NULL);
3256 if (childEntry == NULL || childEntry == parentEntry)
3257 continue;
3258 if (childEntry->checked != bCheck)
3260 if (parentEntry->path.IsAncestorOf(childEntry->path))
3262 SetEntryCheck(childEntry,j,bCheck);
3263 if(bCheck)
3265 m_nSelected++;
3267 else
3269 m_nSelected--;
3276 #endif
3278 void CGitStatusListCtrl::WriteCheckedNamesToPathList(CTGitPathList& pathList)
3281 pathList.Clear();
3282 int nListItems = GetItemCount();
3283 for (int i = 0; i< nListItems; ++i)
3285 CTGitPath * entry = (CTGitPath*)GetItemData(i);
3286 ASSERT(entry != NULL);
3287 if (entry->m_Checked)
3289 pathList.AddPath(*entry);
3292 pathList.SortByPathname();
3297 /// Build a path list of all the selected items in the list (NOTE - SELECTED, not CHECKED)
3298 void CGitStatusListCtrl::FillListOfSelectedItemPaths(CTGitPathList& pathList, bool /*bNoIgnored*/)
3300 pathList.Clear();
3302 POSITION pos = GetFirstSelectedItemPosition();
3303 int index;
3304 while ((index = GetNextSelectedItem(pos)) >= 0)
3306 CTGitPath * entry = (CTGitPath*)GetItemData(index);
3307 //if ((bNoIgnored)&&(entry->status == git_wc_status_ignored))
3308 // continue;
3309 pathList.AddPath(*entry);
3313 UINT CGitStatusListCtrl::OnGetDlgCode()
3315 // we want to process the return key and not have that one
3316 // routed to the default pushbutton
3317 return CListCtrl::OnGetDlgCode() | DLGC_WANTALLKEYS;
3320 void CGitStatusListCtrl::OnNMReturn(NMHDR * /*pNMHDR*/, LRESULT *pResult)
3322 *pResult = 0;
3323 if (m_bBlock)
3324 return;
3325 if (!CheckMultipleDiffs())
3326 return;
3327 POSITION pos = GetFirstSelectedItemPosition();
3328 while ( pos )
3330 int index = GetNextSelectedItem(pos);
3331 if (index < 0)
3332 return;
3333 CTGitPath *file=(CTGitPath*)GetItemData(index);
3334 if (file == nullptr)
3335 return;
3336 if (file->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE))
3338 OpenFile(file, OPEN);
3340 else
3342 if (!m_Rev1.IsEmpty() && !m_Rev2.IsEmpty())
3343 StartDiffTwo(index);
3344 else
3345 StartDiff(index);
3350 void CGitStatusListCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
3352 // Since we catch all keystrokes (to have the enter key processed here instead
3353 // of routed to the default pushbutton) we have to make sure that other
3354 // keys like Tab and Esc still do what they're supposed to do
3355 // Tab = change focus to next/previous control
3356 // Esc = quit the dialog
3357 switch (nChar)
3359 case (VK_TAB):
3361 ::PostMessage(GetLogicalParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
3362 return;
3364 break;
3365 case (VK_ESCAPE):
3367 ::SendMessage(GetLogicalParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
3369 break;
3372 CListCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
3375 void CGitStatusListCtrl::PreSubclassWindow()
3377 CListCtrl::PreSubclassWindow();
3378 EnableToolTips(TRUE);
3379 SetWindowTheme(GetSafeHwnd(), L"Explorer", NULL);
3382 void CGitStatusListCtrl::OnPaint()
3384 LRESULT defres = Default();
3385 if ((m_bBusy)||(m_bEmpty))
3387 CString str;
3388 if (m_bBusy)
3390 if (m_sBusy.IsEmpty())
3391 str.LoadString(IDS_STATUSLIST_BUSYMSG);
3392 else
3393 str = m_sBusy;
3395 else
3397 if (m_sEmpty.IsEmpty())
3398 str.LoadString(IDS_STATUSLIST_EMPTYMSG);
3399 else
3400 str = m_sEmpty;
3402 COLORREF clrText = ::GetSysColor(COLOR_WINDOWTEXT);
3403 COLORREF clrTextBk;
3404 if (IsWindowEnabled())
3405 clrTextBk = ::GetSysColor(COLOR_WINDOW);
3406 else
3407 clrTextBk = ::GetSysColor(COLOR_3DFACE);
3409 CRect rc;
3410 GetClientRect(&rc);
3411 CHeaderCtrl* pHC;
3412 pHC = GetHeaderCtrl();
3413 if (pHC != NULL)
3415 CRect rcH;
3416 pHC->GetItemRect(0, &rcH);
3417 rc.top += rcH.bottom;
3419 CDC* pDC = GetDC();
3421 CMyMemDC memDC(pDC, &rc);
3423 memDC.SetTextColor(clrText);
3424 memDC.SetBkColor(clrTextBk);
3425 memDC.FillSolidRect(rc, clrTextBk);
3426 rc.top += 10;
3427 CGdiObject * oldfont = memDC.SelectStockObject(DEFAULT_GUI_FONT);
3428 memDC.DrawText(str, rc, DT_CENTER | DT_VCENTER |
3429 DT_WORDBREAK | DT_NOPREFIX | DT_NOCLIP);
3430 memDC.SelectObject(oldfont);
3432 ReleaseDC(pDC);
3434 if (defres)
3436 // the Default() call did not process the WM_PAINT message!
3437 // Validate the update region ourselves to avoid
3438 // an endless loop repainting
3439 CRect rc;
3440 GetUpdateRect(&rc, FALSE);
3441 if (!rc.IsRectEmpty())
3442 ValidateRect(rc);
3446 // prevent users from extending our hidden (size 0) columns
3447 void CGitStatusListCtrl::OnHdnBegintrack(NMHDR *pNMHDR, LRESULT *pResult)
3449 m_ColumnManager.OnHdnBegintrack(pNMHDR, pResult);
3452 // prevent any function from extending our hidden (size 0) columns
3453 void CGitStatusListCtrl::OnHdnItemchanging(NMHDR *pNMHDR, LRESULT *pResult)
3455 if(!m_ColumnManager.OnHdnItemchanging(pNMHDR, pResult))
3456 Default();
3459 void CGitStatusListCtrl::OnDestroy()
3461 SaveColumnWidths(true);
3462 CListCtrl::OnDestroy();
3465 void CGitStatusListCtrl::OnBeginDrag(NMHDR* /*pNMHDR*/, LRESULT* pResult)
3467 Locker lock(m_critSec);
3468 CDropFiles dropFiles; // class for creating DROPFILES struct
3470 int index;
3471 POSITION pos = GetFirstSelectedItemPosition();
3472 if (!pos)
3473 return;
3475 bool bTempDirCreated = false;
3476 CString tempDir;
3477 while ( (index = GetNextSelectedItem(pos)) >= 0 )
3479 CTGitPath *path = (CTGitPath *)GetItemData(index); // m_arStatusArray[index] does not work with SyncDlg
3480 if (path->IsDirectory())
3481 continue;
3483 CString version;
3484 if (!this->m_CurrentVersion.IsEmpty() && this->m_CurrentVersion != GIT_REV_ZERO)
3486 if (path->m_Action & CTGitPath::LOGACTIONS_DELETED)
3487 version.Format(_T("%s^%d"), m_CurrentVersion, (path->m_ParentNo + 1) & PARENT_MASK);
3488 else
3489 version = m_CurrentVersion;
3491 else
3493 if (path->m_Action & CTGitPath::LOGACTIONS_DELETED)
3494 version = _T("HEAD");
3497 CString tempFile;
3498 if (version.IsEmpty())
3500 TCHAR abspath[MAX_PATH] = {0};
3501 PathCombine(abspath, g_Git.m_CurrentDir, path->GetWinPath());
3502 tempFile = abspath;
3504 else
3506 if (!bTempDirCreated)
3508 tempDir = GetTempFile();
3509 ::DeleteFile(tempDir);
3510 ::CreateDirectory(tempDir, NULL);
3511 bTempDirCreated = true;
3513 tempFile = tempDir + _T("\\") + path->GetWinPathString();
3514 CString tempSubDir = tempDir + _T("\\") + path->GetContainingDirectory().GetWinPathString();
3515 CPathUtils::MakeSureDirectoryPathExists(tempSubDir);
3516 if (g_Git.GetOneFile(version, *path, tempFile))
3518 CString out;
3519 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, path->GetGitPathString(), version, tempFile);
3520 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), _T("TortoiseGit"), MB_OK);
3521 return;
3524 dropFiles.AddFile(tempFile);
3527 if (!dropFiles.IsEmpty())
3529 m_bOwnDrag = true;
3530 dropFiles.CreateStructure();
3531 m_bOwnDrag = false;
3533 *pResult = 0;
3536 void CGitStatusListCtrl::SaveColumnWidths(bool bSaveToRegistry /* = false */)
3538 int maxcol = ((CHeaderCtrl*)(GetDlgItem(0)))->GetItemCount()-1;
3539 for (int col = 0; col <= maxcol; col++)
3540 if (m_ColumnManager.IsVisible (col))
3541 m_ColumnManager.ColumnResized (col);
3543 if (bSaveToRegistry)
3544 m_ColumnManager.WriteSettings();
3547 bool CGitStatusListCtrl::EnableFileDrop()
3549 m_bFileDropsEnabled = true;
3550 return true;
3553 bool CGitStatusListCtrl::HasPath(const CTGitPath& path)
3555 for (size_t i=0; i < m_arStatusArray.size(); ++i)
3557 if (m_arStatusArray[i]->IsEquivalentTo(path))
3558 return true;
3561 return false;
3564 BOOL CGitStatusListCtrl::PreTranslateMessage(MSG* pMsg)
3566 if (pMsg->message == WM_KEYDOWN)
3568 switch (pMsg->wParam)
3570 case 'A':
3572 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3574 // select all entries
3575 for (int i=0; i<GetItemCount(); ++i)
3577 SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
3579 return TRUE;
3582 break;
3583 case 'C':
3584 case VK_INSERT:
3586 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
3588 // copy all selected paths to the clipboard
3589 if (GetAsyncKeyState(VK_SHIFT)&0x8000)
3590 CopySelectedEntriesToClipboard(GITSLC_COLSTATUS);
3591 else
3592 CopySelectedEntriesToClipboard(0);
3593 return TRUE;
3596 break;
3597 case VK_DELETE:
3599 if ((GetSelectedCount() > 0) && (m_dwContextMenus & GITSLC_POPDELETE))
3601 m_bBlock = TRUE;
3602 CTGitPath * filepath = (CTGitPath *)GetItemData(GetSelectionMark());
3603 if (filepath != nullptr && (filepath->m_Action & (CTGitPath::LOGACTIONS_UNVER | CTGitPath::LOGACTIONS_IGNORE)))
3604 DeleteSelectedFiles();
3605 m_bBlock = FALSE;
3608 break;
3612 return CListCtrl::PreTranslateMessage(pMsg);
3615 bool CGitStatusListCtrl::CopySelectedEntriesToClipboard(DWORD dwCols)
3618 static HINSTANCE hResourceHandle(AfxGetResourceHandle());
3619 // WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
3621 CString sClipboard;
3622 CString temp;
3623 //TCHAR buf[100];
3624 if (GetSelectedCount() == 0)
3625 return false;
3627 // first add the column titles as the first line
3628 // We needn't head when only path copy
3629 //temp.LoadString(IDS_STATUSLIST_COLFILE);
3630 //sClipboard = temp;
3632 DWORD selection = 0;
3633 for (int i = 0, count = m_ColumnManager.GetColumnCount(); i < count; ++i)
3634 if ( ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3635 || ((dwCols != 1) && (i < 32) && ((dwCols & (1 << i)) != 0)))
3637 sClipboard += _T("\t") + m_ColumnManager.GetName(i);
3639 if (i < 32)
3640 selection += 1 << i;
3643 if(dwCols)
3644 sClipboard += _T("\r\n");
3646 POSITION pos = GetFirstSelectedItemPosition();
3647 int index;
3648 while ((index = GetNextSelectedItem(pos)) >= 0)
3650 CTGitPath * entry = (CTGitPath*)GetItemData(index);
3651 if(entry == NULL)
3652 continue;
3654 sClipboard += entry->GetWinPathString();
3655 if (selection & GITSLC_COLFILENAME)
3657 sClipboard += _T("\t")+entry->GetFileOrDirectoryName();
3659 if (selection & GITSLC_COLEXT)
3661 sClipboard += _T("\t")+entry->GetFileExtension();
3664 if (selection & GITSLC_COLSTATUS)
3666 sClipboard += _T("\t")+entry->GetActionName();
3668 #if 0
3669 if (selection & SVNSLC_COLDATE)
3671 TCHAR datebuf[SVN_DATE_BUFFER];
3672 apr_time_t date = entry->last_commit_date;
3673 SVN::formatDate(datebuf, date, true);
3674 if (date)
3675 temp = datebuf;
3676 else
3677 temp.Empty();
3678 sClipboard += _T("\t")+temp;
3680 for ( int i = SVNSLC_NUMCOLUMNS, count = m_ColumnManager.GetColumnCount()
3681 ; i < count
3682 ; ++i)
3684 if ((dwCols == -1) && m_ColumnManager.IsVisible (i))
3686 CString value
3687 = entry->present_props[m_ColumnManager.GetName(i)];
3688 sClipboard += _T("\t") + value;
3691 #endif
3692 if (selection & GITSLC_COLADD)
3694 sClipboard += _T("\t")+entry->m_StatAdd;
3696 if (selection & GITSLC_COLDEL)
3698 sClipboard += _T("\t")+entry->m_StatDel;
3701 sClipboard += _T("\r\n");
3704 return CStringUtils::WriteAsciiStringToClipboard(sClipboard);
3707 size_t CGitStatusListCtrl::GetNumberOfChangelistsInSelection()
3709 #if 0
3710 std::set<CString> changelists;
3711 POSITION pos = GetFirstSelectedItemPosition();
3712 int index;
3713 while ((index = GetNextSelectedItem(pos)) >= 0)
3715 FileEntry * entry = GetListEntry(index);
3716 if (!entry->changelist.IsEmpty())
3717 changelists.insert(entry->changelist);
3719 return changelists.size();
3720 #endif
3721 return 0;
3724 bool CGitStatusListCtrl::PrepareGroups(bool bForce /* = false */)
3727 bool bHasGroups=false;
3728 int max =0;
3730 for (size_t i = 0; i < m_arStatusArray.size(); ++i)
3732 int ParentNo = m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3733 if( ParentNo > max)
3734 max=m_arStatusArray[i]->m_ParentNo&PARENT_MASK;
3737 if (!m_UnRevFileList.IsEmpty() ||
3738 !m_IgnoreFileList.IsEmpty() ||
3739 !m_LocalChangesIgnoredFileList.IsEmpty() ||
3740 max>0 || bForce)
3742 bHasGroups = true;
3745 RemoveAllGroups();
3746 EnableGroupView(bHasGroups);
3748 TCHAR groupname[1024] = { 0 };
3749 int groupindex = 0;
3751 if(bHasGroups)
3753 LVGROUP grp = {0};
3754 grp.cbSize = sizeof(LVGROUP);
3755 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3756 groupindex=0;
3758 //if(m_UnRevFileList.GetCount()>0)
3759 if(max >0)
3761 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MERGEDFILES)), 1023);
3762 grp.pszHeader = groupname;
3763 grp.iGroupId = MERGE_MASK;
3764 grp.uAlign = LVGA_HEADER_LEFT;
3765 InsertGroup(0, &grp);
3767 CAutoRepository repository(g_Git.GetGitRepository());
3768 if (!repository)
3769 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3770 for (int i = 0; i <= max; ++i)
3772 CString str;
3773 str.Format(IDS_STATUSLIST_GROUP_DIFFWITHPARENT, i+1);
3774 if (repository)
3776 CString rev;
3777 rev.Format(_T("%s^%d"), m_CurrentVersion, i + 1);
3778 CGitHash hash;
3779 if (!CGit::GetHash(repository, hash, rev))
3780 str += _T(": ") + hash.ToString().Left(g_Git.GetShortHASHLength());
3782 grp.pszHeader = str.GetBuffer();
3783 str.ReleaseBuffer();
3784 grp.iGroupId = i;
3785 grp.uAlign = LVGA_HEADER_LEFT;
3786 InsertGroup(i+1, &grp);
3789 else
3791 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_MODIFIEDFILES)), 1023);
3792 grp.pszHeader = groupname;
3793 grp.iGroupId = groupindex;
3794 grp.uAlign = LVGA_HEADER_LEFT;
3795 InsertGroup(groupindex++, &grp);
3799 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_NOTVERSIONEDFILES)), 1023);
3800 grp.pszHeader = groupname;
3801 grp.iGroupId = groupindex;
3802 grp.uAlign = LVGA_HEADER_LEFT;
3803 InsertGroup(groupindex++, &grp);
3806 //if(m_IgnoreFileList.GetCount()>0)
3808 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNOREDFILES)), 1023);
3809 grp.pszHeader = groupname;
3810 grp.iGroupId = groupindex;
3811 grp.uAlign = LVGA_HEADER_LEFT;
3812 InsertGroup(groupindex++, &grp);
3816 _tcsncpy_s(groupname, 1024, (LPCTSTR)CString(MAKEINTRESOURCE(IDS_STATUSLIST_GROUP_IGNORELOCALCHANGES)), 1023);
3817 grp.pszHeader = groupname;
3818 grp.iGroupId = groupindex;
3819 grp.uAlign = LVGA_HEADER_LEFT;
3820 InsertGroup(groupindex++, &grp);
3825 #if 0
3826 m_bHasIgnoreGroup = false;
3828 // now add the items which don't belong to a group
3829 LVGROUP grp = {0};
3830 grp.cbSize = sizeof(LVGROUP);
3831 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3832 CString sUnassignedName(MAKEINTRESOURCE(IDS_STATUSLIST_UNASSIGNED_CHANGESET));
3833 _tcsncpy_s(groupname, 1024, (LPCTSTR)sUnassignedName, 1023);
3834 grp.pszHeader = groupname;
3835 grp.iGroupId = groupindex;
3836 grp.uAlign = LVGA_HEADER_LEFT;
3837 InsertGroup(groupindex++, &grp);
3839 for (std::map<CString,int>::iterator it = m_changelists.begin(); it != m_changelists.end(); ++it)
3841 if (it->first.Compare(SVNSLC_IGNORECHANGELIST)!=0)
3843 LVGROUP grp = {0};
3844 grp.cbSize = sizeof(LVGROUP);
3845 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3846 _tcsncpy_s(groupname, 1024, it->first, 1023);
3847 grp.pszHeader = groupname;
3848 grp.iGroupId = groupindex;
3849 grp.uAlign = LVGA_HEADER_LEFT;
3850 it->second = InsertGroup(groupindex++, &grp);
3852 else
3853 m_bHasIgnoreGroup = true;
3856 if (m_bHasIgnoreGroup)
3858 // and now add the group 'ignore-on-commit'
3859 std::map<CString,int>::iterator it = m_changelists.find(SVNSLC_IGNORECHANGELIST);
3860 if (it != m_changelists.end())
3862 grp.cbSize = sizeof(LVGROUP);
3863 grp.mask = LVGF_ALIGN | LVGF_GROUPID | LVGF_HEADER;
3864 _tcsncpy_s(groupname, 1024, SVNSLC_IGNORECHANGELIST, 1023);
3865 grp.pszHeader = groupname;
3866 grp.iGroupId = groupindex;
3867 grp.uAlign = LVGA_HEADER_LEFT;
3868 it->second = InsertGroup(groupindex, &grp);
3871 #endif
3872 return bHasGroups;
3875 void CGitStatusListCtrl::NotifyCheck()
3877 CWnd* pParent = GetLogicalParent();
3878 if (NULL != pParent && NULL != pParent->GetSafeHwnd())
3880 pParent->SendMessage(GITSLNM_CHECKCHANGED, m_nSelected);
3884 int CGitStatusListCtrl::UpdateFileList(git_revnum_t hash,CTGitPathList *list)
3886 CString cmdList;
3887 BYTE_VECTOR out;
3888 this->m_bBusy=TRUE;
3889 m_CurrentVersion=hash;
3891 int count = 0;
3892 if(list == NULL)
3893 count = 1;
3894 else
3895 count = list->GetCount();
3897 CString head = _T("HEAD");
3898 if(m_amend)
3899 head = _T("HEAD~1");
3901 if(hash == GIT_REV_ZERO)
3903 for (int i = 0; i < count; ++i)
3905 BYTE_VECTOR cmdout;
3906 cmdout.clear();
3907 CString cmd;
3908 if(!g_Git.IsInitRepos())
3910 if (CGit::ms_bCygwinGit)
3912 // Prevent showing all files as modified when using cygwin's git
3913 if (list == NULL)
3914 cmd = (_T("git.exe status --"));
3915 else
3916 cmd.Format(_T("git.exe status -- \"%s\""), (*list)[i].GetGitPathString());
3917 cmdList += cmd + _T("\n");
3918 g_Git.Run(cmd, &cmdout);
3919 cmdout.clear();
3922 // also list staged files which will be in the commit
3923 cmd=(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"));
3924 cmdList += cmd + _T("\n");
3925 g_Git.Run(cmd, &cmdout);
3927 if(list == NULL)
3928 cmd=(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3929 else
3930 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""),(*list)[i].GetGitPathString());
3931 cmdList += cmd + _T("\n");
3933 BYTE_VECTOR cmdErr;
3934 if(g_Git.Run(cmd, &cmdout, &cmdErr))
3936 int last = cmdErr.RevertFind(0,-1);
3937 CString str;
3938 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last -1);
3939 CMessageBox::Show(NULL, str, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
3942 out.append(cmdout, 0);
3944 else // Init Repository
3946 //We will list all added file for init repository because commit will comit these
3947 //if(list == NULL)
3948 cmd=_T("git.exe ls-files -s -t -z");
3949 cmdList += cmd + _T("\n");
3950 //else
3951 // cmd.Format(_T("git.exe ls-files -s -t -z -- \"%s\""),(*list)[i].GetGitPathString());
3953 g_Git.Run(cmd, &cmdout);
3954 //out+=cmdout;
3955 out.append(cmdout,0);
3957 break;
3961 if(g_Git.IsInitRepos())
3963 if (m_StatusFileList.ParserFromLsFile(out))
3965 CString tempFile1 = GetTempFile();
3966 CFile file1(tempFile1, CFile::modeWrite | CFile::typeBinary);
3967 file1.Write(out.data(), (UINT)out.size());
3968 file1.Close();
3969 CString tempFile2 = GetTempFile();
3970 CFile file2(tempFile2, CFile::modeWrite);
3971 file2.Write(cmdList, sizeof(TCHAR) * cmdList.GetLength());
3972 file2.Close();
3973 CMessageBox::Show(NULL, _T("Parse ls-files failed!\nPlease inspect ") + tempFile1 + _T("\nand ") + tempFile2, _T("TortoiseGit"), MB_OK);
3975 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
3976 ((CTGitPath&)(m_StatusFileList[i])).m_Action=CTGitPath::LOGACTIONS_ADDED;
3978 else
3979 this->m_StatusFileList.ParserFromLog(out);
3981 //handle delete conflict case, when remote : modified, local : deleted.
3982 for (int i = 0; i < count; ++i)
3984 BYTE_VECTOR cmdout;
3985 CString cmd;
3987 if(list == NULL)
3988 cmd=_T("git.exe ls-files -u -t -z");
3989 else
3990 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),(*list)[i].GetGitPathString());
3992 g_Git.Run(cmd, &cmdout);
3994 CTGitPathList conflictlist;
3995 conflictlist.ParserFromLog(cmdout);
3996 for (int i = 0; i < conflictlist.GetCount(); ++i)
3998 CTGitPath *p=m_StatusFileList.LookForGitPath(conflictlist[i].GetGitPathString());
3999 if(p)
4000 p->m_Action|=CTGitPath::LOGACTIONS_UNMERGED;
4001 else
4002 m_StatusFileList.AddPath(conflictlist[i]);
4006 // handle source files of file renames/moves (issue #860)
4007 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
4008 for (int i = 0; i < count; ++i)
4010 BYTE_VECTOR cmdout;
4011 CString cmd;
4013 if(list == NULL)
4014 cmd = _T("git.exe ls-files -d -z");
4015 else
4016 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""),(*list)[i].GetGitPathString());
4018 g_Git.Run(cmd, &cmdout);
4020 CTGitPathList deletelist;
4021 deletelist.ParserFromLog(cmdout, true);
4022 BOOL bDeleteChecked = FALSE;
4023 int deleteFromIndex = 0;
4024 for (int i = 0; i < deletelist.GetCount(); ++i)
4026 CTGitPath *p = m_StatusFileList.LookForGitPath(deletelist[i].GetGitPathString());
4027 if(!p)
4028 m_StatusFileList.AddPath(deletelist[i]);
4029 else if ((p->m_Action == CTGitPath::LOGACTIONS_ADDED || p->m_Action == CTGitPath::LOGACTIONS_REPLACED) && !p->Exists())
4031 if (!bDeleteChecked)
4033 CString message;
4034 message.Format(IDS_ASK_REMOVE_FROM_INDEX, p->GetWinPathString());
4035 deleteFromIndex = CMessageBox::ShowCheck(m_hWnd, message, _T("TortoiseGit"), 1, IDI_EXCLAMATION, CString(MAKEINTRESOURCE(IDS_REMOVE_FROM_INDEX)), CString(MAKEINTRESOURCE(IDS_IGNOREBUTTON)), NULL, NULL, CString(MAKEINTRESOURCE(IDS_DO_SAME_FOR_REST)), &bDeleteChecked);
4037 if (deleteFromIndex == 1)
4039 g_Git.Run(_T("git.exe rm -f --cache -- \"") + p->GetWinPathString() + _T("\""), &cmdout);
4040 m_StatusFileList.RemoveItem(*p);
4046 else
4048 int count = 0;
4049 if(list == NULL)
4050 count = 1;
4051 else
4052 count = list->GetCount();
4054 for (int i = 0; i < count; ++i)
4056 BYTE_VECTOR cmdout;
4057 CString cmd;
4058 if(list == NULL)
4059 cmd.Format(_T("git.exe diff-tree --raw --numstat -C -M -z %s --"), hash);
4060 else
4061 cmd.Format(_T("git.exe diff-tree --raw --numstat -C -M %s -z -- \"%s\""),hash,(*list)[i].GetGitPathString());
4063 g_Git.Run(cmd, &cmdout, NULL);
4065 out.append(cmdout);
4067 this->m_StatusFileList.ParserFromLog(out);
4071 for (int i = 0; i < m_StatusFileList.GetCount(); ++i)
4073 CTGitPath * gitpatch=(CTGitPath*)&m_StatusFileList[i];
4074 gitpatch->m_Checked = TRUE;
4075 m_arStatusArray.push_back((CTGitPath*)&m_StatusFileList[i]);
4078 this->m_bBusy=FALSE;
4079 return 0;
4082 int CGitStatusListCtrl::UpdateWithGitPathList(CTGitPathList &list)
4084 m_arStatusArray.clear();
4085 for (int i = 0; i < list.GetCount(); ++i)
4087 CTGitPath * gitpath=(CTGitPath*)&list[i];
4089 if(gitpath ->m_Action & CTGitPath::LOGACTIONS_HIDE)
4090 continue;
4092 gitpath->m_Checked = TRUE;
4093 m_arStatusArray.push_back((CTGitPath*)&list[i]);
4095 return 0;
4098 int CGitStatusListCtrl::UpdateUnRevFileList(CTGitPathList &list)
4100 m_UnRevFileList = list;
4101 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
4103 CTGitPath * gitpatch=(CTGitPath*)&m_UnRevFileList[i];
4104 gitpatch->m_Checked = FALSE;
4105 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
4107 return 0;
4110 int CGitStatusListCtrl::UpdateUnRevFileList(CTGitPathList *List)
4112 CString err;
4113 if (m_UnRevFileList.FillUnRev(CTGitPath::LOGACTIONS_UNVER, List, &err))
4115 CMessageBox::Show(NULL, _T("Failed to get UnRev file list\n") + err, _T("TortoiseGit"), MB_OK);
4116 return -1;
4119 for (int i = 0; i < m_UnRevFileList.GetCount(); ++i)
4121 CTGitPath * gitpatch=(CTGitPath*)&m_UnRevFileList[i];
4122 gitpatch->m_Checked = FALSE;
4123 m_arStatusArray.push_back((CTGitPath*)&m_UnRevFileList[i]);
4125 return 0;
4128 int CGitStatusListCtrl::UpdateIgnoreFileList(CTGitPathList *List)
4130 CString err;
4131 if (m_IgnoreFileList.FillUnRev(CTGitPath::LOGACTIONS_IGNORE, List, &err))
4133 CMessageBox::Show(NULL, _T("Failed to get Ignore file list\n") + err, _T("TortoiseGit"), MB_OK);
4134 return -1;
4137 for (int i = 0; i < m_IgnoreFileList.GetCount(); ++i)
4139 CTGitPath * gitpatch=(CTGitPath*)&m_IgnoreFileList[i];
4140 gitpatch->m_Checked = FALSE;
4141 m_arStatusArray.push_back((CTGitPath*)&m_IgnoreFileList[i]);
4143 return 0;
4146 int CGitStatusListCtrl::UpdateLocalChangesIgnoredFileList(CTGitPathList *list)
4148 m_LocalChangesIgnoredFileList.FillBasedOnIndexFlags(GIT_IDXENTRY_VALID | GIT_IDXENTRY_SKIP_WORKTREE, list);
4149 for (int i = 0; i < m_LocalChangesIgnoredFileList.GetCount(); ++i)
4151 CTGitPath * gitpatch = (CTGitPath*)&m_LocalChangesIgnoredFileList[i];
4152 gitpatch->m_Checked = FALSE;
4153 m_arStatusArray.push_back((CTGitPath*)&m_LocalChangesIgnoredFileList[i]);
4155 return 0;
4158 int CGitStatusListCtrl::UpdateFileList(int mask,bool once,CTGitPathList *List)
4160 if(mask&CGitStatusListCtrl::FILELIST_MODIFY)
4162 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_MODIFY)))
4164 UpdateFileList(git_revnum_t(GIT_REV_ZERO),List);
4165 m_FileLoaded|=CGitStatusListCtrl::FILELIST_MODIFY;
4168 if (mask & CGitStatusListCtrl::FILELIST_UNVER || mask & CGitStatusListCtrl::FILELIST_IGNORE)
4170 if(once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_UNVER)))
4172 UpdateUnRevFileList(List);
4173 m_FileLoaded|=CGitStatusListCtrl::FILELIST_UNVER;
4175 if(mask&CGitStatusListCtrl::FILELIST_IGNORE && (once || (!(m_FileLoaded&CGitStatusListCtrl::FILELIST_IGNORE))))
4177 UpdateIgnoreFileList(List);
4178 m_FileLoaded |= CGitStatusListCtrl::FILELIST_IGNORE;
4181 if (mask & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED && (once || (!(m_FileLoaded & CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED))))
4183 UpdateLocalChangesIgnoredFileList(List);
4184 m_FileLoaded |= CGitStatusListCtrl::FILELIST_LOCALCHANGESIGNORED;
4186 return 0;
4189 void CGitStatusListCtrl::Clear()
4191 m_FileLoaded=0;
4192 this->DeleteAllItems();
4193 this->m_arListArray.clear();
4194 this->m_arStatusArray.clear();
4195 this->m_changelists.clear();
4198 bool CGitStatusListCtrl::CheckMultipleDiffs()
4200 UINT selCount = GetSelectedCount();
4201 if (selCount > max(3, (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\NumDiffWarning"), 10)))
4203 CString message;
4204 message.Format(CString(MAKEINTRESOURCE(IDS_STATUSLIST_WARN_MAXDIFF)), selCount);
4205 return ::MessageBox(GetSafeHwnd(), message, _T("TortoiseGit"), MB_YESNO | MB_ICONQUESTION) == IDYES;
4207 return true;
4209 //////////////////////////////////////////////////////////////////////////
4210 #if 0
4211 bool CGitStatusListCtrlDropTarget::OnDrop(FORMATETC* pFmtEtc, STGMEDIUM& medium, DWORD * /*pdwEffect*/, POINTL pt)
4213 if(pFmtEtc->cfFormat == CF_HDROP && medium.tymed == TYMED_HGLOBAL)
4215 HDROP hDrop = (HDROP)GlobalLock(medium.hGlobal);
4216 if(hDrop != NULL)
4218 TCHAR szFileName[MAX_PATH] = {0};
4220 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
4222 POINT clientpoint;
4223 clientpoint.x = pt.x;
4224 clientpoint.y = pt.y;
4225 ScreenToClient(m_hTargetWnd, &clientpoint);
4226 if ((m_pSVNStatusListCtrl->IsGroupViewEnabled())&&(m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
4228 CTSVNPathList changelistItems;
4229 for(UINT i = 0; i < cFiles; ++i)
4231 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
4232 changelistItems.AddPath(CTSVNPath(szFileName));
4234 // find the changelist name
4235 CString sChangelist;
4236 LONG_PTR nGroup = m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint);
4237 for (std::map<CString, int>::iterator it = m_pSVNStatusListCtrl->m_changelists.begin(); it != m_pSVNStatusListCtrl->m_changelists.end(); ++it)
4238 if (it->second == nGroup)
4239 sChangelist = it->first;
4240 if (!sChangelist.IsEmpty())
4242 SVN git;
4243 if (git.AddToChangeList(changelistItems, sChangelist, git_depth_empty))
4245 for (int l=0; l<changelistItems.GetCount(); ++l)
4247 int index = m_pSVNStatusListCtrl->GetIndex(changelistItems[l]);
4248 if (index >= 0)
4250 CSVNStatusListCtrl::FileEntry * e = m_pSVNStatusListCtrl->GetListEntry(index);
4251 if (e)
4253 e->changelist = sChangelist;
4254 if (!e->IsFolder())
4256 if (m_pSVNStatusListCtrl->m_changelists.find(e->changelist)!=m_pSVNStatusListCtrl->m_changelists.end())
4257 m_pSVNStatusListCtrl->SetItemGroup(index, m_pSVNStatusListCtrl->m_changelists[e->changelist]);
4258 else
4259 m_pSVNStatusListCtrl->SetItemGroup(index, 0);
4263 else
4265 HWND hParentWnd = GetParent(m_hTargetWnd);
4266 if (hParentWnd != NULL)
4267 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
4271 else
4273 CMessageBox::Show(m_pSVNStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
4276 else
4278 SVN git;
4279 if (git.RemoveFromChangeList(changelistItems, CStringArray(), git_depth_empty))
4281 for (int l=0; l<changelistItems.GetCount(); ++l)
4283 int index = m_pSVNStatusListCtrl->GetIndex(changelistItems[l]);
4284 if (index >= 0)
4286 CSVNStatusListCtrl::FileEntry * e = m_pSVNStatusListCtrl->GetListEntry(index);
4287 if (e)
4289 e->changelist = sChangelist;
4290 m_pSVNStatusListCtrl->SetItemGroup(index, 0);
4293 else
4295 HWND hParentWnd = GetParent(m_hTargetWnd);
4296 if (hParentWnd != NULL)
4297 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)changelistItems[l].GetWinPath());
4301 else
4303 CMessageBox::Show(m_pSVNStatusListCtrl->m_hWnd, git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
4307 else
4309 for(UINT i = 0; i < cFiles; ++i)
4311 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
4312 HWND hParentWnd = GetParent(m_hTargetWnd);
4313 if (hParentWnd != NULL)
4314 ::SendMessage(hParentWnd, CSVNStatusListCtrl::SVNSLNM_ADDFILE, 0, (LPARAM)szFileName);
4318 GlobalUnlock(medium.hGlobal);
4320 return true; //let base free the medium
4322 HRESULT STDMETHODCALLTYPE CSVNStatusListCtrlDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD __RPC_FAR *pdwEffect)
4324 CIDropTarget::DragOver(grfKeyState, pt, pdwEffect);
4325 *pdwEffect = DROPEFFECT_COPY;
4326 if (m_pSVNStatusListCtrl)
4328 POINT clientpoint;
4329 clientpoint.x = pt.x;
4330 clientpoint.y = pt.y;
4331 ScreenToClient(m_hTargetWnd, &clientpoint);
4332 if ((m_pSVNStatusListCtrl->IsGroupViewEnabled())&&(m_pSVNStatusListCtrl->GetGroupFromPoint(&clientpoint) >= 0))
4334 *pdwEffect = DROPEFFECT_MOVE;
4336 else if ((!m_pSVNStatusListCtrl->m_bFileDropsEnabled)||(m_pSVNStatusListCtrl->m_bOwnDrag))
4338 *pdwEffect = DROPEFFECT_NONE;
4341 return S_OK;
4344 #endif
4346 void CGitStatusListCtrl::FilesExport()
4348 CString exportDir;
4349 // export all changed files to a folder
4350 CBrowseFolder browseFolder;
4351 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
4352 if (browseFolder.Show(GetSafeHwnd(), exportDir) != CBrowseFolder::OK)
4353 return;
4355 POSITION pos = GetFirstSelectedItemPosition();
4356 int index;
4357 while ((index = GetNextSelectedItem(pos)) >= 0)
4359 CTGitPath *fd = (CTGitPath*)GetItemData(index);
4360 // we cannot export directories or folders
4361 if (fd->m_Action == CTGitPath::LOGACTIONS_DELETED || fd->IsDirectory())
4362 continue;
4364 CAppUtils::CreateMultipleDirectory(exportDir + _T("\\") + fd->GetContainingDirectory().GetWinPathString());
4365 CString filename = exportDir + _T("\\") + fd->GetWinPathString();
4366 if (m_CurrentVersion == GIT_REV_ZERO)
4368 if (!CopyFile(g_Git.CombinePath(fd), filename, false))
4370 MessageBox(CFormatMessageWrapper(), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
4371 return;
4374 else
4376 if (g_Git.GetOneFile(m_CurrentVersion, *fd, filename))
4378 CString out;
4379 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, fd->GetGitPathString(), m_CurrentVersion, filename);
4380 if (CMessageBox::Show(nullptr, g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), _T("TortoiseGit"), 2, IDI_WARNING, CString(MAKEINTRESOURCE(IDS_IGNOREBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 2)
4381 return;
4387 void CGitStatusListCtrl::FileSaveAs(CTGitPath *path)
4389 CString filename;
4390 filename.Format(_T("%s-%s%s"), path->GetBaseFilename(), this->m_CurrentVersion.Left(g_Git.GetShortHASHLength()), path->GetFileExtension());
4391 CFileDialog dlg(FALSE,NULL,
4392 filename,
4393 OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
4394 NULL);
4395 CString currentpath;
4396 currentpath = g_Git.CombinePath(path->GetContainingDirectory());
4398 dlg.m_ofn.lpstrInitialDir=currentpath.GetBuffer();
4400 CString cmd,out;
4401 INT_PTR ret = dlg.DoModal();
4402 SetCurrentDirectory(g_Git.m_CurrentDir);
4403 if (ret == IDOK)
4405 filename = dlg.GetPathName();
4406 if(m_CurrentVersion == GIT_REV_ZERO)
4408 if(!CopyFile(g_Git.CombinePath(path), filename, false))
4410 MessageBox(CFormatMessageWrapper(), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
4411 return;
4415 else
4417 if(g_Git.GetOneFile(m_CurrentVersion,*path,filename))
4419 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, path->GetGitPathString(), m_CurrentVersion, filename);
4420 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), _T("TortoiseGit"), MB_OK);
4421 return;
4428 int CGitStatusListCtrl::RevertSelectedItemToVersion(bool parent)
4430 if(this->m_CurrentVersion.IsEmpty())
4431 return 0;
4432 if(this->m_CurrentVersion == GIT_REV_ZERO)
4433 return 0;
4435 POSITION pos = GetFirstSelectedItemPosition();
4436 int index;
4437 CString cmd,out;
4438 std::map<CString, int> versionMap;
4439 while ((index = GetNextSelectedItem(pos)) >= 0)
4441 CTGitPath *fentry=(CTGitPath*)GetItemData(index);
4442 CString version;
4443 if (parent)
4445 int parentNo = fentry->m_ParentNo & PARENT_MASK;
4446 CString ref;
4447 ref.Format(_T("%s^%d"), m_CurrentVersion, parentNo + 1);
4448 CGitHash hash;
4449 if (g_Git.GetHash(hash, ref))
4451 MessageBox(g_Git.GetGitLastErr(_T("Could not get hash of ref \"") + ref + _T("\".")), _T("TortoiseGit"), MB_ICONERROR);
4452 continue;
4455 version = hash.ToString();
4457 else
4458 version = m_CurrentVersion;
4460 CString filename = fentry->GetGitPathString();
4461 if (!fentry->GetGitOldPathString().IsEmpty())
4462 filename = fentry->GetGitOldPathString();
4463 cmd.Format(_T("git.exe checkout %s -- \"%s\""), version, filename);
4464 out.Empty();
4465 if (g_Git.Run(cmd, &out, CP_UTF8))
4467 if (MessageBox(out, _T("TortoiseGit"), MB_ICONEXCLAMATION | MB_OKCANCEL) == IDCANCEL)
4468 continue;
4470 else
4471 versionMap[version]++;
4474 out.Empty();
4475 for (auto it = versionMap.begin(); it != versionMap.end(); ++it)
4477 CString versionEntry;
4478 versionEntry.Format(IDS_STATUSLIST_FILESREVERTED, it->second, it->first);
4479 out += versionEntry + _T("\r\n");
4481 if (!out.IsEmpty())
4482 CMessageBox::Show(nullptr, out, _T("TortoiseGit"), MB_OK);
4483 return 0;
4486 void CGitStatusListCtrl::OpenFile(CTGitPath*filepath,int mode)
4488 CString file;
4489 if(this->m_CurrentVersion.IsEmpty() || m_CurrentVersion == GIT_REV_ZERO)
4491 file = g_Git.CombinePath(filepath);
4493 else
4495 CString temppath;
4496 GetTempPath(temppath);
4497 TCHAR szTempName[MAX_PATH] = {0};
4498 GetTempFileName(temppath, filepath->GetBaseFilename(), 0, szTempName);
4499 CString temp(szTempName);
4500 DeleteFile(szTempName);
4501 CreateDirectory(szTempName, NULL);
4502 file.Format(_T("%s\\%s_%s%s"),
4503 temp,
4504 filepath->GetBaseFilename(),
4505 m_CurrentVersion.Left(g_Git.GetShortHASHLength()),
4506 filepath->GetFileExtension());
4507 CString cmd,out;
4508 if(g_Git.GetOneFile(m_CurrentVersion, *filepath, file))
4510 out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, filepath->GetGitPathString(), m_CurrentVersion, file);
4511 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), _T("TortoiseGit"), MB_OK);
4512 return;
4514 SetFileAttributes(file, FILE_ATTRIBUTE_READONLY);
4516 if(mode == ALTERNATIVEEDITOR)
4518 CAppUtils::LaunchAlternativeEditor(file);
4519 return;
4522 if (mode == OPEN)
4523 CAppUtils::ShellOpen(file, GetSafeHwnd());
4524 else
4525 CAppUtils::ShowOpenWithDialog(file, GetSafeHwnd());
4528 void CGitStatusListCtrl::DeleteSelectedFiles()
4530 //Collect paths
4531 std::vector<int> selectIndex;
4533 POSITION pos = GetFirstSelectedItemPosition();
4534 int index;
4535 while ((index = GetNextSelectedItem(pos)) >= 0)
4537 selectIndex.push_back(index);
4540 //Create file-list ('\0' separated) for SHFileOperation
4541 CString filelist;
4542 for (size_t i = 0; i < selectIndex.size(); ++i)
4544 index = selectIndex[i];
4546 CTGitPath * path=(CTGitPath*)GetItemData(index);
4547 ASSERT(path);
4548 if (path == nullptr)
4549 continue;
4551 filelist += path->GetWinPathString();
4552 filelist += _T("|");
4554 filelist += _T("|");
4555 int len = filelist.GetLength();
4556 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 2]);
4557 _tcscpy_s(buf.get(), len + 2, filelist);
4558 CStringUtils::PipesToNulls(buf.get(), len + 2);
4559 SHFILEOPSTRUCT fileop;
4560 fileop.hwnd = this->m_hWnd;
4561 fileop.wFunc = FO_DELETE;
4562 fileop.pFrom = buf.get();
4563 fileop.pTo = NULL;
4564 fileop.fFlags = FOF_NO_CONNECTED_ELEMENTS | ((GetAsyncKeyState(VK_SHIFT) & 0x8000) ? 0 : FOF_ALLOWUNDO);
4565 fileop.lpszProgressTitle = _T("deleting file");
4566 int result = SHFileOperation(&fileop);
4568 if ((result == 0) && (!fileop.fAnyOperationsAborted))
4570 SetRedraw(FALSE);
4571 POSITION pos = NULL;
4572 while ((pos = GetFirstSelectedItemPosition()) != 0)
4574 int index = GetNextSelectedItem(pos);
4575 if (GetCheck(index))
4576 m_nSelected--;
4577 m_nTotal--;
4579 RemoveListEntry(index);
4581 SetRedraw(TRUE);
4585 BOOL CGitStatusListCtrl::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
4587 switch (message)
4589 case WM_MENUCHAR: // only supported by IContextMenu3
4590 if (g_IContext3)
4592 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4593 return TRUE;
4595 break;
4597 case WM_DRAWITEM:
4598 case WM_MEASUREITEM:
4599 if (wParam)
4600 break; // if wParam != 0 then the message is not menu-related
4602 case WM_INITMENU:
4603 case WM_INITMENUPOPUP:
4605 HMENU hMenu = (HMENU)wParam;
4606 if (pfnSHCreateDefaultContextMenu && pfnAssocCreateForClasses && (hMenu == m_hShellMenu) && (GetMenuItemCount(hMenu) == 0))
4608 // the shell submenu is populated only on request, i.e. right
4609 // before the submenu is shown
4610 if (g_pFolderhook)
4612 delete g_pFolderhook;
4613 g_pFolderhook = nullptr;
4615 CTGitPathList targetList;
4616 FillListOfSelectedItemPaths(targetList);
4617 if (targetList.GetCount() > 0)
4619 // get IShellFolder interface of Desktop (root of shell namespace)
4620 if (g_psfDesktopFolder)
4621 g_psfDesktopFolder->Release();
4622 SHGetDesktopFolder(&g_psfDesktopFolder); // needed to obtain full qualified pidl
4624 // ParseDisplayName creates a PIDL from a file system path relative to the IShellFolder interface
4625 // but since we use the Desktop as our interface and the Desktop is the namespace root
4626 // that means that it's a fully qualified PIDL, which is what we need
4628 if (g_pidlArray)
4630 for (int i = 0; i < g_pidlArrayItems; i++)
4632 if (g_pidlArray[i])
4633 CoTaskMemFree(g_pidlArray[i]);
4635 CoTaskMemFree(g_pidlArray);
4636 g_pidlArray = nullptr;
4637 g_pidlArrayItems = 0;
4639 int nItems = targetList.GetCount();
4640 g_pidlArray = (LPITEMIDLIST *)CoTaskMemAlloc((nItems + 10) * sizeof(LPITEMIDLIST));
4641 SecureZeroMemory(g_pidlArray, (nItems + 10) * sizeof(LPITEMIDLIST));
4642 int succeededItems = 0;
4643 PIDLIST_RELATIVE pidl = nullptr;
4645 size_t bufsize = 1024;
4646 std::unique_ptr<WCHAR[]> filepath(new WCHAR[bufsize]);
4647 for (size_t i = 0; i < nItems; i++)
4649 CString fullPath = g_Git.CombinePath(targetList[i].GetWinPath());
4650 if (bufsize < fullPath.GetLength())
4652 bufsize = fullPath.GetLength() + 3;
4653 filepath = std::unique_ptr<WCHAR[]>(new WCHAR[bufsize]);
4655 wcscpy_s(filepath.get(), bufsize, fullPath);
4656 if (SUCCEEDED(g_psfDesktopFolder->ParseDisplayName(nullptr, 0, filepath.get(), nullptr, &pidl, nullptr)))
4657 g_pidlArray[succeededItems++] = pidl; // copy pidl to pidlArray
4659 if (succeededItems == 0)
4661 CoTaskMemFree(g_pidlArray);
4662 g_pidlArray = nullptr;
4665 g_pidlArrayItems = succeededItems;
4667 if (g_pidlArrayItems)
4669 CString ext = targetList[0].GetFileExtension();
4671 ASSOCIATIONELEMENT const rgAssocItem[] =
4673 { ASSOCCLASS_PROGID_STR, NULL, ext },
4674 { ASSOCCLASS_SYSTEM_STR, NULL, ext },
4675 { ASSOCCLASS_APP_STR, NULL, ext },
4676 { ASSOCCLASS_STAR, NULL, NULL },
4677 { ASSOCCLASS_FOLDER, NULL, NULL },
4679 IQueryAssociations * pIQueryAssociations;
4680 pfnAssocCreateForClasses(rgAssocItem, ARRAYSIZE(rgAssocItem), IID_IQueryAssociations, (void**)&pIQueryAssociations);
4682 g_pFolderhook = new CIShellFolderHook(g_psfDesktopFolder, targetList);
4683 LPCONTEXTMENU icm1 = nullptr;
4685 DEFCONTEXTMENU dcm = { 0 };
4686 dcm.hwnd = m_hWnd;
4687 dcm.psf = g_pFolderhook;
4688 dcm.cidl = g_pidlArrayItems;
4689 dcm.apidl = (PCUITEMID_CHILD_ARRAY)g_pidlArray;
4690 dcm.punkAssociationInfo = pIQueryAssociations;
4691 if (SUCCEEDED(pfnSHCreateDefaultContextMenu(&dcm, IID_IContextMenu, (void**)&icm1)))
4693 int iMenuType = 0; // to know which version of IContextMenu is supported
4694 if (icm1)
4695 { // since we got an IContextMenu interface we can now obtain the higher version interfaces via that
4696 if (icm1->QueryInterface(IID_IContextMenu3, (void**)&m_pContextMenu) == S_OK)
4697 iMenuType = 3;
4698 else if (icm1->QueryInterface(IID_IContextMenu2, (void**)&m_pContextMenu) == S_OK)
4699 iMenuType = 2;
4701 if (m_pContextMenu)
4702 icm1->Release(); // we can now release version 1 interface, cause we got a higher one
4703 else
4705 // since no higher versions were found
4706 // redirect ppContextMenu to version 1 interface
4707 iMenuType = 1;
4708 m_pContextMenu = icm1;
4711 if (m_pContextMenu)
4713 // lets fill the our popup menu
4714 UINT flags = CMF_NORMAL;
4715 flags |= (GetKeyState(VK_SHIFT) & 0x8000) != 0 ? CMF_EXTENDEDVERBS : 0;
4716 m_pContextMenu->QueryContextMenu(hMenu, 0, SHELL_MIN_CMD, SHELL_MAX_CMD, flags);
4719 // subclass window to handle menu related messages in CShellContextMenu
4720 if (iMenuType > 1) // only subclass if its version 2 or 3
4722 if (iMenuType == 2)
4723 g_IContext2 = (LPCONTEXTMENU2)m_pContextMenu;
4724 else // version 3
4725 g_IContext3 = (LPCONTEXTMENU3)m_pContextMenu;
4729 pIQueryAssociations->Release();
4732 if (g_IContext3)
4733 g_IContext3->HandleMenuMsg2(message, wParam, lParam, pResult);
4734 else if (g_IContext2)
4735 g_IContext2->HandleMenuMsg(message, wParam, lParam);
4736 return TRUE;
4740 break;
4741 default:
4742 break;
4745 return CListCtrl::OnWndMsg(message, wParam, lParam, pResult);