Show copy icon in log message context menu
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blob22bd50c31d6cd688c772ef93c0e5ccc4f7b662bb
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2012, 2014 - TortoiseSVN
4 // Copyright (C) 2008-2014 - TortoiseGit
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "ShellExt.h"
22 #include "ItemIDList.h"
23 #include "PreserveChdir.h"
24 #include "UnicodeUtils.h"
25 #include "GitStatus.h"
26 #include "TGitPath.h"
27 #include "PathUtils.h"
28 #include "CreateProcessHelper.h"
29 #include "FormatMessageWrapper.h"
30 #include "..\TGitCache\CacheInterface.h"
31 #include "resource.h"
33 #define GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
34 #define GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
36 int g_shellidlist=RegisterClipboardFormat(CFSTR_SHELLIDLIST);
38 extern MenuInfo menuInfo[];
39 static int g_syncSeq = 0;
41 STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST pIDFolder,
42 LPDATAOBJECT pDataObj,
43 HKEY hRegKey)
45 __try
47 return Initialize_Wrap(pIDFolder, pDataObj, hRegKey);
49 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
52 return E_FAIL;
55 STDMETHODIMP CShellExt::Initialize_Wrap(LPCITEMIDLIST pIDFolder,
56 LPDATAOBJECT pDataObj,
57 HKEY /* hRegKey */)
59 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Shell :: Initialize\n");
60 PreserveChdir preserveChdir;
61 files_.clear();
62 folder_.clear();
63 uuidSource.clear();
64 uuidTarget.clear();
65 itemStates = 0;
66 itemStatesFolder = 0;
67 stdstring statuspath;
68 git_wc_status_kind fetchedstatus = git_wc_status_none;
69 // get selected files/folders
70 if (pDataObj)
72 STGMEDIUM medium;
73 FORMATETC fmte = {(CLIPFORMAT)g_shellidlist,
74 (DVTARGETDEVICE FAR *)NULL,
75 DVASPECT_CONTENT,
76 -1,
77 TYMED_HGLOBAL};
78 HRESULT hres = pDataObj->GetData(&fmte, &medium);
80 if (SUCCEEDED(hres) && medium.hGlobal)
82 if (m_State == FileStateDropHandler)
85 FORMATETC etc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
86 STGMEDIUM stg = { TYMED_HGLOBAL };
87 if ( FAILED( pDataObj->GetData ( &etc, &stg )))
89 ReleaseStgMedium ( &medium );
90 return E_INVALIDARG;
94 HDROP drop = (HDROP)GlobalLock(stg.hGlobal);
95 if ( NULL == drop )
97 ReleaseStgMedium ( &stg );
98 ReleaseStgMedium ( &medium );
99 return E_INVALIDARG;
102 int count = DragQueryFile(drop, (UINT)-1, NULL, 0);
103 if (count == 1)
104 itemStates |= ITEMIS_ONLYONE;
105 for (int i = 0; i < count; i++)
107 // find the path length in chars
108 UINT len = DragQueryFile(drop, i, NULL, 0);
109 if (len == 0)
110 continue;
111 std::unique_ptr<TCHAR[]> szFileName(new TCHAR[len + 1]);
112 if (0 == DragQueryFile(drop, i, szFileName.get(), len + 1))
113 continue;
114 stdstring str = stdstring(szFileName.get());
115 if ((!str.empty()) && (g_ShellCache.IsContextPathAllowed(szFileName.get())))
117 if (itemStates & ITEMIS_ONLYONE)
119 CTGitPath strpath;
120 strpath.SetFromWin(str.c_str());
121 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
122 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
124 files_.push_back(str);
125 if (i == 0)
127 //get the git status of the item
128 git_wc_status_kind status = git_wc_status_none;
129 CTGitPath askedpath;
130 askedpath.SetFromWin(str.c_str());
131 CString workTreePath;
132 askedpath.HasAdminDir(&workTreePath);
133 uuidSource = workTreePath;
136 if (g_ShellCache.GetCacheType() == ShellCache::exe && g_ShellCache.IsPathAllowed(str.c_str()))
138 CTGitPath tpath(str.c_str());
139 if (!tpath.HasAdminDir())
141 status = git_wc_status_none;
142 continue;
144 if (tpath.IsAdminDir())
146 status = git_wc_status_none;
147 continue;
149 TGITCacheResponse itemStatus;
150 SecureZeroMemory(&itemStatus, sizeof(itemStatus));
151 if (m_remoteCacheLink.GetStatusFromRemoteCache(tpath, &itemStatus, true))
153 fetchedstatus = status = GitStatus::GetMoreImportant(itemStatus.m_status.text_status, itemStatus.m_status.prop_status);
154 if (askedpath.IsDirectory())//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
156 itemStates |= ITEMIS_FOLDER;
157 if ((status != git_wc_status_unversioned) && (status != git_wc_status_ignored) && (status != git_wc_status_none))
158 itemStates |= ITEMIS_FOLDERINGIT;
162 else
164 GitStatus stat;
165 stat.GetStatus(CTGitPath(str.c_str()), false, false, true);
166 if (stat.status)
168 statuspath = str;
169 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
170 fetchedstatus = status;
171 if ( askedpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
173 itemStates |= ITEMIS_FOLDER;
174 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
175 itemStates |= ITEMIS_FOLDERINGIT;
177 //if ((stat.status->entry)&&(stat.status->entry->uuid))
178 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
180 else
182 // sometimes, git_client_status() returns with an error.
183 // in that case, we have to check if the working copy is versioned
184 // anyway to show the 'correct' context menu
185 if (askedpath.HasAdminDir())
186 status = git_wc_status_normal;
190 catch ( ... )
192 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Exception in GitStatus::GetStatus()\n");
195 // TODO: should we really assume any sub-directory to be versioned
196 // or only if it contains versioned files
197 itemStates |= askedpath.GetAdminDirMask();
199 if ((status == git_wc_status_unversioned) || (status == git_wc_status_ignored) || (status == git_wc_status_none))
200 itemStates &= ~ITEMIS_INGIT;
202 if (status == git_wc_status_ignored)
203 itemStates |= ITEMIS_IGNORED;
204 if (status == git_wc_status_normal)
205 itemStates |= ITEMIS_NORMAL;
206 if (status == git_wc_status_conflicted)
207 itemStates |= ITEMIS_CONFLICTED;
208 if (status == git_wc_status_added)
209 itemStates |= ITEMIS_ADDED;
210 if (status == git_wc_status_deleted)
211 itemStates |= ITEMIS_DELETED;
214 } // for (int i = 0; i < count; i++)
215 GlobalUnlock ( drop );
216 ReleaseStgMedium ( &stg );
218 } // if (m_State == FileStateDropHandler)
219 else
222 //Enumerate PIDLs which the user has selected
223 CIDA* cida = (CIDA*)GlobalLock(medium.hGlobal);
224 ItemIDList parent( GetPIDLFolder (cida));
226 int count = cida->cidl;
227 BOOL statfetched = FALSE;
228 for (int i = 0; i < count; ++i)
230 ItemIDList child (GetPIDLItem (cida, i), &parent);
231 stdstring str = child.toString();
232 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(str.c_str())))
234 //check if our menu is requested for a git admin directory
235 if (g_GitAdminDir.IsAdminDirPath(str.c_str()))
236 continue;
238 files_.push_back(str);
239 CTGitPath strpath;
240 strpath.SetFromWin(str.c_str());
241 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
242 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
243 if (!statfetched)
245 //get the git status of the item
246 git_wc_status_kind status = git_wc_status_none;
247 if ((g_ShellCache.IsSimpleContext())&&(strpath.IsDirectory()))
249 if (strpath.HasAdminDir())
250 status = git_wc_status_normal;
252 else
256 if (g_ShellCache.GetCacheType() == ShellCache::exe && g_ShellCache.IsPathAllowed(str.c_str()))
258 CTGitPath tpath(str.c_str());
259 if(!tpath.HasAdminDir())
261 status = git_wc_status_none;
262 continue;
264 if(tpath.IsAdminDir())
266 status = git_wc_status_none;
267 continue;
269 TGITCacheResponse itemStatus;
270 SecureZeroMemory(&itemStatus, sizeof(itemStatus));
271 if (m_remoteCacheLink.GetStatusFromRemoteCache(tpath, &itemStatus, true))
273 fetchedstatus = status = GitStatus::GetMoreImportant(itemStatus.m_status.text_status, itemStatus.m_status.prop_status);
274 if (strpath.IsDirectory())//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
276 itemStates |= ITEMIS_FOLDER;
277 if ((status != git_wc_status_unversioned) && (status != git_wc_status_ignored) && (status != git_wc_status_none))
278 itemStates |= ITEMIS_FOLDERINGIT;
280 if (status == git_wc_status_conflicted)//if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
281 itemStates |= ITEMIS_CONFLICTED;
284 else
286 GitStatus stat;
287 if (strpath.HasAdminDir())
288 stat.GetStatus(strpath, false, false, true);
289 statuspath = str;
290 if (stat.status)
292 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
293 fetchedstatus = status;
294 if ( strpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
296 itemStates |= ITEMIS_FOLDER;
297 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
298 itemStates |= ITEMIS_FOLDERINGIT;
300 // TODO: do we need to check that it's not a dir? does conflict options makes sense for dir in git?
301 if (status == git_wc_status_conflicted)//if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
302 itemStates |= ITEMIS_CONFLICTED;
303 //if ((stat.status->entry)&&(stat.status->entry->uuid))
304 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
306 else
308 // sometimes, git_client_status() returns with an error.
309 // in that case, we have to check if the working copy is versioned
310 // anyway to show the 'correct' context menu
311 if (strpath.HasAdminDir())
313 status = git_wc_status_normal;
314 fetchedstatus = status;
318 statfetched = TRUE;
320 catch ( ... )
322 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Exception in GitStatus::GetStatus()\n");
326 itemStates |= strpath.GetAdminDirMask();
328 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
329 itemStates &= ~ITEMIS_INGIT;
330 if (status == git_wc_status_ignored)
332 itemStates |= ITEMIS_IGNORED;
335 if (status == git_wc_status_normal)
336 itemStates |= ITEMIS_NORMAL;
337 if (status == git_wc_status_conflicted)
338 itemStates |= ITEMIS_CONFLICTED;
339 if (status == git_wc_status_added)
340 itemStates |= ITEMIS_ADDED;
341 if (status == git_wc_status_deleted)
342 itemStates |= ITEMIS_DELETED;
345 } // for (int i = 0; i < count; ++i)
346 ItemIDList child (GetPIDLItem (cida, 0), &parent);
347 if (g_ShellCache.HasGITAdminDir(child.toString().c_str(), FALSE))
348 itemStates |= ITEMIS_INVERSIONEDFOLDER;
350 if (g_GitAdminDir.IsBareRepo(child.toString().c_str()))
351 itemStates = ITEMIS_BAREREPO;
353 GlobalUnlock(medium.hGlobal);
355 // if the item is a versioned folder, check if there's a patch file
356 // in the clipboard to be used in "Apply Patch"
357 UINT cFormatDiff = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
358 if (cFormatDiff)
360 if (IsClipboardFormatAvailable(cFormatDiff))
361 itemStates |= ITEMIS_PATCHINCLIPBOARD;
363 if (IsClipboardFormatAvailable(CF_HDROP))
364 itemStates |= ITEMIS_PATHINCLIPBOARD;
368 ReleaseStgMedium ( &medium );
369 if (medium.pUnkForRelease)
371 IUnknown* relInterface = (IUnknown*)medium.pUnkForRelease;
372 relInterface->Release();
377 // get folder background
378 if (pIDFolder)
381 ItemIDList list(pIDFolder);
382 folder_ = list.toString();
383 git_wc_status_kind status = git_wc_status_none;
384 if (IsClipboardFormatAvailable(CF_HDROP))
385 itemStatesFolder |= ITEMIS_PATHINCLIPBOARD;
387 CTGitPath askedpath;
388 askedpath.SetFromWin(folder_.c_str());
390 if (g_ShellCache.IsContextPathAllowed(folder_.c_str()))
392 if (folder_.compare(statuspath)!=0)
394 CString worktreePath;
395 askedpath.HasAdminDir(&worktreePath);
396 uuidTarget = worktreePath;
399 if (g_ShellCache.GetCacheType() == ShellCache::exe && g_ShellCache.IsPathAllowed(folder_.c_str()))
401 CTGitPath tpath(folder_.c_str());
402 if(!tpath.HasAdminDir())
403 status = git_wc_status_none;
404 else if(tpath.IsAdminDir())
405 status = git_wc_status_none;
406 else
408 TGITCacheResponse itemStatus;
409 SecureZeroMemory(&itemStatus, sizeof(itemStatus));
410 if (m_remoteCacheLink.GetStatusFromRemoteCache(tpath, &itemStatus, true))
411 status = GitStatus::GetMoreImportant(itemStatus.m_status.text_status, itemStatus.m_status.prop_status);
414 else
416 GitStatus stat;
417 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
418 if (stat.status)
420 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
421 // if ((stat.status->entry)&&(stat.status->entry->uuid))
422 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
425 else
427 // sometimes, git_client_status() returns with an error.
428 // in that case, we have to check if the working copy is versioned
429 // anyway to show the 'correct' context menu
430 if (askedpath.HasAdminDir())
431 status = git_wc_status_normal;
435 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
436 itemStatesFolder |= askedpath.GetAdminDirMask();
438 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
439 itemStates &= ~ITEMIS_INGIT;
441 if (status == git_wc_status_normal)
442 itemStatesFolder |= ITEMIS_NORMAL;
443 if (status == git_wc_status_conflicted)
444 itemStatesFolder |= ITEMIS_CONFLICTED;
445 if (status == git_wc_status_added)
446 itemStatesFolder |= ITEMIS_ADDED;
447 if (status == git_wc_status_deleted)
448 itemStatesFolder |= ITEMIS_DELETED;
451 catch ( ... )
453 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Exception in GitStatus::GetStatus()\n");
456 else
458 status = fetchedstatus;
460 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
461 itemStatesFolder |= askedpath.GetAdminDirMask();
463 if (status == git_wc_status_ignored)
464 itemStatesFolder |= ITEMIS_IGNORED;
465 itemStatesFolder |= ITEMIS_FOLDER;
466 if (files_.empty())
467 itemStates |= ITEMIS_ONLYONE;
468 if (m_State != FileStateDropHandler)
469 itemStates |= itemStatesFolder;
471 else
473 folder_.clear();
474 status = fetchedstatus;
477 if (files_.size() == 2)
478 itemStates |= ITEMIS_TWO;
479 if ((files_.size() == 1)&&(g_ShellCache.IsContextPathAllowed(files_.front().c_str())))
482 itemStates |= ITEMIS_ONLYONE;
483 if (m_State != FileStateDropHandler)
485 if (PathIsDirectory(files_.front().c_str()))
487 folder_ = files_.front();
488 git_wc_status_kind status = git_wc_status_none;
489 CTGitPath askedpath;
490 askedpath.SetFromWin(folder_.c_str());
492 if (folder_.compare(statuspath)!=0)
496 GitStatus stat;
497 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
498 if (stat.status)
500 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
501 // if ((stat.status->entry)&&(stat.status->entry->uuid))
502 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
505 catch ( ... )
507 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Exception in GitStatus::GetStatus()\n");
510 else
512 status = fetchedstatus;
514 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
515 itemStates |= askedpath.GetAdminDirMask();
517 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
518 itemStates &= ~ITEMIS_INGIT;
520 if (status == git_wc_status_ignored)
521 itemStates |= ITEMIS_IGNORED;
522 itemStates |= ITEMIS_FOLDER;
523 if (status == git_wc_status_added)
524 itemStates |= ITEMIS_ADDED;
525 if (status == git_wc_status_deleted)
526 itemStates |= ITEMIS_DELETED;
533 return S_OK;
536 void CShellExt::InsertGitMenu(BOOL istop, HMENU menu, UINT pos, UINT_PTR id, UINT stringid, UINT icon, UINT idCmdFirst, GitCommands com, UINT /*uFlags*/)
538 TCHAR menutextbuffer[512] = {0};
539 TCHAR verbsbuffer[255] = {0};
540 MAKESTRING(stringid);
542 if (istop)
544 //menu entry for the top context menu, so append an "Git " before
545 //the menu text to indicate where the entry comes from
546 _tcscpy_s(menutextbuffer, 255, _T("Git "));
547 if (!g_ShellCache.HasShellMenuAccelerators())
549 // remove the accelerators
550 tstring temp = stringtablebuffer;
551 temp.erase(std::remove(temp.begin(), temp.end(), '&'), temp.end());
552 _tcscpy_s(stringtablebuffer, 255, temp.c_str());
555 _tcscat_s(menutextbuffer, 255, stringtablebuffer);
557 // insert branch name into "Git Commit..." entry, so it looks like "Git Commit "master"..."
558 // so we have an easy and fast way to check the current branch
559 // (the other alternative is using a separate disabled menu entry, the code is already done but commented out)
560 if (com == ShellMenuCommit)
562 // get branch name
563 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
564 CString sProjectRoot;
565 CString sBranchName;
567 if (path.GetAdminDirMask() & ITEMIS_SUBMODULE)
569 if (istop)
570 _tcscpy_s(menutextbuffer, 255, _T("Git "));
571 _tcscat_s(menutextbuffer, 255, CString(MAKEINTRESOURCE(IDS_MENUCOMMITSUBMODULE)));
574 if (path.HasAdminDir(&sProjectRoot) && !CGit::GetCurrentBranchFromFile(sProjectRoot, sBranchName))
576 if (sBranchName.GetLength() == 40)
578 // if SHA1 only show 4 first bytes
579 BOOL bIsSha1 = TRUE;
580 for (int i=0; i<40; i++)
581 if ( !iswxdigit(sBranchName[i]) )
583 bIsSha1 = FALSE;
584 break;
586 if (bIsSha1)
587 sBranchName = sBranchName.Left(8) + _T("....");
590 // sanity check
591 if (sBranchName.GetLength() > 64)
592 sBranchName = sBranchName.Left(64) + _T("...");
594 // scan to before "..."
595 LPTSTR s = menutextbuffer + _tcslen(menutextbuffer)-1;
596 if (s > menutextbuffer)
598 while (s > menutextbuffer)
600 if (*s != _T('.'))
602 s++;
603 break;
605 s--;
608 else
610 s = menutextbuffer;
613 // append branch name and end with ...
614 _tcscpy_s(s, 255 - _tcslen(menutextbuffer) - 1, _T(" -> \"") + sBranchName + _T("\"..."));
618 if (com == ShellMenuDiffLater)
620 std::wstring sPath = regDiffLater;
621 if (!sPath.empty())
623 // add the path of the saved file
624 wchar_t compact[40] = {0};
625 PathCompactPathEx(compact, sPath.c_str(), _countof(compact) - 1, 0);
626 CString sMenu;
627 sMenu.Format(IDS_MENUDIFFNOW, compact);
628 wcscpy_s(menutextbuffer, sMenu);
632 MENUITEMINFO menuiteminfo;
633 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
634 menuiteminfo.cbSize = sizeof(menuiteminfo);
635 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
636 menuiteminfo.fType = MFT_STRING;
637 menuiteminfo.dwTypeData = menutextbuffer;
638 if (icon)
640 menuiteminfo.fMask |= MIIM_BITMAP;
641 menuiteminfo.hbmpItem = SysInfo::Instance().IsVistaOrLater() ? m_iconBitmapUtils.IconToBitmapPARGB32(g_hResInst, icon) : HBMMENU_CALLBACK;
643 menuiteminfo.wID = (UINT)id;
644 InsertMenuItem(menu, pos, TRUE, &menuiteminfo);
646 if (istop)
648 //menu entry for the top context menu, so append an "Git " before
649 //the menu text to indicate where the entry comes from
650 _tcscpy_s(menutextbuffer, 255, _T("Git "));
652 LoadString(g_hResInst, stringid, verbsbuffer, _countof(verbsbuffer));
653 _tcscat_s(menutextbuffer, 255, verbsbuffer);
654 stdstring verb = stdstring(menutextbuffer);
655 if (verb.find('&') != -1)
657 verb.erase(verb.find('&'),1);
659 myVerbsMap[verb] = id - idCmdFirst;
660 myVerbsMap[verb] = id;
661 myVerbsIDMap[id - idCmdFirst] = verb;
662 myVerbsIDMap[id] = verb;
663 // We store the relative and absolute diameter
664 // (drawitem callback uses absolute, others relative)
665 myIDMap[id - idCmdFirst] = com;
666 myIDMap[id] = com;
667 if (!istop)
668 mySubMenuMap[pos] = com;
671 bool CShellExt::WriteClipboardPathsToTempFile(stdstring& tempfile)
673 bool bRet = true;
674 tempfile = stdstring();
675 //write all selected files and paths to a temporary file
676 //for TortoiseGitProc.exe to read out again.
677 DWORD written = 0;
678 DWORD pathlength = GetTortoiseGitTempPath(0, NULL);
679 std::unique_ptr<TCHAR[]> path(new TCHAR[pathlength + 1]);
680 std::unique_ptr<TCHAR[]> tempFile(new TCHAR[pathlength + 100]);
681 GetTortoiseGitTempPath(pathlength+1, path.get());
682 GetTempFileName(path.get(), _T("git"), 0, tempFile.get());
683 tempfile = stdstring(tempFile.get());
685 CAutoFile file = ::CreateFile(tempFile.get(),
686 GENERIC_WRITE,
687 FILE_SHARE_READ,
689 CREATE_ALWAYS,
690 FILE_ATTRIBUTE_TEMPORARY,
693 if (!file)
694 return false;
696 if (!IsClipboardFormatAvailable(CF_HDROP))
697 return false;
698 if (!OpenClipboard(NULL))
699 return false;
701 stdstring sClipboardText;
702 HGLOBAL hglb = GetClipboardData(CF_HDROP);
703 HDROP hDrop = (HDROP)GlobalLock(hglb);
704 if(hDrop != NULL)
706 TCHAR szFileName[MAX_PATH] = {0};
707 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
708 for(UINT i = 0; i < cFiles; ++i)
710 DragQueryFile(hDrop, i, szFileName, _countof(szFileName));
711 stdstring filename = szFileName;
712 ::WriteFile (file, filename.c_str(), (DWORD)filename.size()*sizeof(TCHAR), &written, 0);
713 ::WriteFile (file, _T("\n"), 2, &written, 0);
715 GlobalUnlock(hDrop);
717 else bRet = false;
718 GlobalUnlock(hglb);
720 CloseClipboard();
722 return bRet;
725 stdstring CShellExt::WriteFileListToTempFile()
727 //write all selected files and paths to a temporary file
728 //for TortoiseGitProc.exe to read out again.
729 DWORD pathlength = GetTortoiseGitTempPath(0, NULL);
730 std::unique_ptr<TCHAR[]> path(new TCHAR[pathlength + 1]);
731 std::unique_ptr<TCHAR[]> tempFile(new TCHAR[pathlength + 100]);
732 GetTortoiseGitTempPath(pathlength + 1, path.get());
733 GetTempFileName(path.get(), _T("git"), 0, tempFile.get());
734 stdstring retFilePath = stdstring(tempFile.get());
736 CAutoFile file = ::CreateFile (tempFile.get(),
737 GENERIC_WRITE,
738 FILE_SHARE_READ,
740 CREATE_ALWAYS,
741 FILE_ATTRIBUTE_TEMPORARY,
744 if (!file)
745 return stdstring();
747 DWORD written = 0;
748 if (files_.empty())
750 ::WriteFile (file, folder_.c_str(), (DWORD)folder_.size()*sizeof(TCHAR), &written, 0);
751 ::WriteFile (file, _T("\n"), 2, &written, 0);
754 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
756 ::WriteFile (file, I->c_str(), (DWORD)I->size()*sizeof(TCHAR), &written, 0);
757 ::WriteFile (file, _T("\n"), 2, &written, 0);
759 return retFilePath;
762 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
764 if (!CRegStdDWORD(L"Software\\TortoiseGit\\EnableDragContextMenu", TRUE))
765 return S_OK;
767 PreserveChdir preserveChdir;
768 LoadLangDll();
770 if ((uFlags & CMF_DEFAULTONLY)!=0)
771 return S_OK; //we don't change the default action
773 if (files_.empty() || folder_.empty())
774 return S_OK;
776 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
777 return S_OK;
779 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
781 //the drop handler only has eight commands, but not all are visible at the same time:
782 //if the source file(s) are under version control then those files can be moved
783 //to the new location or they can be moved with a rename,
784 //if they are unversioned then they can be added to the working copy
785 //if they are versioned, they also can be exported to an unversioned location
786 UINT idCmd = idCmdFirst;
788 // Git move here
789 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
790 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
791 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
793 // Git move and rename here
794 // available if source is a single, versioned but not added item, target is versioned, source and target from same repository or target folder is added
795 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
796 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
798 // Git copy here
799 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
800 //if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
801 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
803 // Git copy and rename here, source and target from same repository
804 // available if source is a single, versioned but not added item, target is versioned or target folder is added
805 //if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
806 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
808 // Git add here
809 // available if target is versioned and source is either unversioned or from another repository
810 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
811 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
813 // Git export here
814 // available if source is versioned and a folder
815 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
816 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
818 // Git export all here
819 // available if source is versioned and a folder
820 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
821 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
823 // apply patch
824 // available if source is a patchfile
825 if (itemStates & ITEMIS_PATCHFILE)
826 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
828 // separator
829 if (idCmd != idCmdFirst)
830 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
832 TweakMenu(hMenu);
834 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
837 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
838 UINT indexMenu,
839 UINT idCmdFirst,
840 UINT idCmdLast,
841 UINT uFlags)
843 __try
845 return QueryContextMenu_Wrap(hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags);
847 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
850 return E_FAIL;
853 STDMETHODIMP CShellExt::QueryContextMenu_Wrap(HMENU hMenu,
854 UINT indexMenu,
855 UINT idCmdFirst,
856 UINT /*idCmdLast*/,
857 UINT uFlags)
859 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Shell :: QueryContextMenu itemStates=%ld\n", itemStates);
860 PreserveChdir preserveChdir;
862 //first check if our drop handler is called
863 //and then (if true) provide the context menu for the
864 //drop handler
865 if (m_State == FileStateDropHandler)
867 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
870 if ((uFlags & CMF_DEFAULTONLY)!=0)
871 return S_OK; //we don't change the default action
873 if (files_.empty() && folder_.empty())
874 return S_OK;
876 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
877 return S_OK;
879 int csidlarray[] =
881 CSIDL_BITBUCKET,
882 CSIDL_CDBURN_AREA,
883 CSIDL_COMMON_FAVORITES,
884 CSIDL_COMMON_STARTMENU,
885 CSIDL_COMPUTERSNEARME,
886 CSIDL_CONNECTIONS,
887 CSIDL_CONTROLS,
888 CSIDL_COOKIES,
889 CSIDL_FAVORITES,
890 CSIDL_FONTS,
891 CSIDL_HISTORY,
892 CSIDL_INTERNET,
893 CSIDL_INTERNET_CACHE,
894 CSIDL_NETHOOD,
895 CSIDL_NETWORK,
896 CSIDL_PRINTERS,
897 CSIDL_PRINTHOOD,
898 CSIDL_RECENT,
899 CSIDL_SENDTO,
900 CSIDL_STARTMENU,
903 if (IsIllegalFolder(folder_, csidlarray))
904 return S_OK;
906 if (folder_.empty())
908 // folder is empty, but maybe files are selected
909 if (files_.empty())
910 return S_OK; // nothing selected - we don't have a menu to show
911 // check whether a selected entry is an UID - those are namespace extensions
912 // which we can't handle
913 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
915 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
916 return S_OK;
919 else
921 if (_tcsncmp(folder_.c_str(), _T("::{"), 3) == 0)
922 return S_OK;
925 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
927 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT|ITEMIS_BAREREPO|ITEMIS_TWO))==0)
928 return S_OK;
931 //check if our menu is requested for a git admin directory
932 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
933 return S_OK;
935 if (uFlags & CMF_EXTENDEDVERBS)
936 itemStates |= ITEMIS_EXTENDED;
938 regDiffLater.read();
939 if (!std::wstring(regDiffLater).empty())
940 itemStates |= ITEMIS_HASDIFFLATER;
942 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
943 if ( bShortcut && (files_.size()==1))
945 // Don't show the context menu for a link if the
946 // destination is not part of a working copy.
947 // It would only show the standard menu items
948 // which are already shown for the lnk-file.
949 CString path = files_.front().c_str();
950 if ( !g_GitAdminDir.HasAdminDir(path) )
952 return S_OK;
956 //check if we already added our menu entry for a folder.
957 //we check that by iterating through all menu entries and check if
958 //the dwItemData member points to our global ID string. That string is set
959 //by our shell extension when the folder menu is inserted.
960 TCHAR menubuf[MAX_PATH] = {0};
961 int count = GetMenuItemCount(hMenu);
962 for (int i=0; i<count; ++i)
964 MENUITEMINFO miif;
965 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
966 miif.cbSize = sizeof(MENUITEMINFO);
967 miif.fMask = MIIM_DATA;
968 miif.dwTypeData = menubuf;
969 miif.cch = _countof(menubuf);
970 GetMenuItemInfo(hMenu, i, TRUE, &miif);
971 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
972 return S_OK;
975 LoadLangDll();
976 UINT idCmd = idCmdFirst;
978 //create the sub menu
979 HMENU subMenu = CreateMenu();
980 int indexSubMenu = 0;
982 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
983 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
984 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
986 int menuIndex = 0;
987 bool bAddSeparator = false;
988 bool bMenuEntryAdded = false;
989 bool bMenuEmpty = true;
990 // insert separator at start
991 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
992 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
994 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
996 if (menuInfo[menuIndex].command == ShellSeparator)
998 // we don't add a separator immediately. Because there might not be
999 // another 'normal' menu entry after we insert a separator.
1000 // we simply set a flag here, indicating that before the next
1001 // 'normal' menu entry, a separator should be added.
1002 if (!bMenuEmpty)
1003 bAddSeparator = true;
1004 if (bMenuEntryAdded)
1005 bAddSeparator = true;
1007 else
1009 // check the conditions whether to show the menu entry or not
1010 bool bInsertMenu = ShouldInsertItem(menuInfo[menuIndex]);
1011 if (menuInfo[menuIndex].menuID & menuex)
1013 if( !(itemStates & ITEMIS_EXTENDED) )
1015 bInsertMenu = false;
1019 if (menuInfo[menuIndex].menuID & (~menumask))
1021 if (bInsertMenu)
1023 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1024 // insert a separator
1025 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1027 bAddSeparator = false;
1028 bMenuEntryAdded = false;
1029 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1030 idCmd++;
1033 // handle special cases (sub menus)
1034 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1036 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1037 bMenuEntryAdded = true;
1039 else
1041 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1043 // insert the menu entry
1044 InsertGitMenu( bIsTop,
1045 bIsTop ? hMenu : subMenu,
1046 bIsTop ? indexMenu++ : indexSubMenu++,
1047 idCmd++,
1048 menuInfo[menuIndex].menuTextID,
1049 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1050 idCmdFirst,
1051 menuInfo[menuIndex].command,
1052 uFlags);
1053 if (!bIsTop)
1055 bMenuEntryAdded = true;
1056 bMenuEmpty = false;
1057 bAddSeparator = false;
1063 menuIndex++;
1066 // do not show TortoiseGit menu if it's empty
1067 if (bMenuEmpty)
1069 if (idCmd - idCmdFirst > 0)
1071 //separator after
1072 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1074 TweakMenu(hMenu);
1076 //return number of menu items added
1077 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1080 //add sub menu to main context menu
1081 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1082 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1083 MAKESTRING(IDS_MENUSUBMENU);
1084 if (!g_ShellCache.HasShellMenuAccelerators())
1086 // remove the accelerators
1087 tstring temp = stringtablebuffer;
1088 temp.erase(std::remove(temp.begin(), temp.end(), '&'), temp.end());
1089 _tcscpy_s(stringtablebuffer, temp.c_str());
1091 MENUITEMINFO menuiteminfo;
1092 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1093 menuiteminfo.cbSize = sizeof(menuiteminfo);
1094 menuiteminfo.fType = MFT_STRING;
1095 menuiteminfo.dwTypeData = stringtablebuffer;
1097 UINT uIcon = bShowIcons ? IDI_APP : 0;
1098 if (!folder_.empty())
1100 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1101 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1102 myIDMap[idCmd] = ShellSubMenuFolder;
1103 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1105 else if (!bShortcut && (files_.size()==1))
1107 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1108 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1109 myIDMap[idCmd] = ShellSubMenuFile;
1111 else if (bShortcut && (files_.size()==1))
1113 uIcon = bShowIcons ? IDI_MENULINK : 0;
1114 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1115 myIDMap[idCmd] = ShellSubMenuLink;
1117 else if (!files_.empty())
1119 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1120 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1121 myIDMap[idCmd] = ShellSubMenuMultiple;
1123 else
1125 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1126 myIDMap[idCmd] = ShellSubMenu;
1128 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1129 if (uIcon)
1131 menuiteminfo.fMask |= MIIM_BITMAP;
1132 menuiteminfo.hbmpItem = SysInfo::Instance().IsVistaOrLater() ? m_iconBitmapUtils.IconToBitmapPARGB32(g_hResInst, uIcon) : HBMMENU_CALLBACK;
1134 menuiteminfo.hSubMenu = subMenu;
1135 menuiteminfo.wID = idCmd++;
1136 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1138 //separator after
1139 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1141 TweakMenu(hMenu);
1143 //return number of menu items added
1144 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1147 void CShellExt::TweakMenu(HMENU hMenu)
1149 MENUINFO MenuInfo = {};
1150 MenuInfo.cbSize = sizeof(MenuInfo);
1151 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1152 MenuInfo.dwStyle = MNS_CHECKORBMP;
1153 SetMenuInfo(hMenu, &MenuInfo);
1156 void CShellExt::AddPathCommand(tstring& gitCmd, LPCTSTR command, bool bFilesAllowed)
1158 gitCmd += command;
1159 gitCmd += _T(" /path:\"");
1160 if ((bFilesAllowed) && !files_.empty())
1161 gitCmd += files_.front();
1162 else
1163 gitCmd += folder_;
1164 gitCmd += _T("\"");
1167 void CShellExt::AddPathFileCommand(tstring& gitCmd, LPCTSTR command)
1169 tstring tempfile = WriteFileListToTempFile();
1170 gitCmd += command;
1171 gitCmd += _T(" /pathfile:\"");
1172 gitCmd += tempfile;
1173 gitCmd += _T("\"");
1174 gitCmd += _T(" /deletepathfile");
1177 void CShellExt::AddPathFileDropCommand(tstring& gitCmd, LPCTSTR command)
1179 tstring tempfile = WriteFileListToTempFile();
1180 gitCmd += command;
1181 gitCmd += _T(" /pathfile:\"");
1182 gitCmd += tempfile;
1183 gitCmd += _T("\"");
1184 gitCmd += _T(" /deletepathfile");
1185 gitCmd += _T(" /droptarget:\"");
1186 gitCmd += folder_;
1187 gitCmd += _T("\"");
1190 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1192 __try
1194 return InvokeCommand_Wrap(lpcmi);
1196 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1199 return E_FAIL;
1202 // This is called when you invoke a command on the menu:
1203 STDMETHODIMP CShellExt::InvokeCommand_Wrap(LPCMINVOKECOMMANDINFO lpcmi)
1205 PreserveChdir preserveChdir;
1206 HRESULT hr = E_INVALIDARG;
1207 if (lpcmi == NULL)
1208 return hr;
1210 if (!files_.empty() || !folder_.empty())
1212 UINT_PTR idCmd = LOWORD(lpcmi->lpVerb);
1214 if (HIWORD(lpcmi->lpVerb))
1216 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1217 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1218 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1219 idCmd = verb_it->second;
1220 else
1221 return hr;
1224 // See if we have a handler interface for this id
1225 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1226 if (id_it != myIDMap.end() && id_it->first == idCmd)
1228 tstring tortoiseProcPath = CPathUtils::GetAppDirectory(g_hmodThisDll) + _T("TortoiseGitProc.exe");
1229 tstring tortoiseMergePath = CPathUtils::GetAppDirectory(g_hmodThisDll) + _T("TortoiseGitMerge.exe");
1231 //TortoiseGitProc expects a command line of the form:
1232 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1233 // or
1234 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1236 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1237 //* pathfile is a path to a temporary file which contains a list of file paths
1238 stdstring gitCmd = _T(" /command:");
1239 stdstring tempfile;
1240 switch (id_it->second)
1242 //#region case
1243 case ShellMenuSync:
1245 TCHAR syncSeq[12] = { 0 };
1246 _stprintf_s(syncSeq, _T("%d"), g_syncSeq++);
1247 AddPathCommand(gitCmd, L"sync", false);
1248 gitCmd += _T(" /seq:");
1249 gitCmd += syncSeq;
1251 break;
1252 case ShellMenuSubSync:
1253 AddPathFileCommand(gitCmd, L"subsync");
1254 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1256 gitCmd += _T(" /bkpath:\"");
1257 gitCmd += folder_;
1258 gitCmd += _T("\"");
1260 break;
1261 case ShellMenuUpdateExt:
1262 AddPathFileCommand(gitCmd, L"subupdate");
1263 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1265 gitCmd += _T(" /bkpath:\"");
1266 gitCmd += folder_;
1267 gitCmd += _T("\"");
1269 break;
1270 case ShellMenuCommit:
1271 AddPathFileCommand(gitCmd, L"commit");
1272 break;
1273 case ShellMenuAdd:
1274 AddPathFileCommand(gitCmd, L"add");
1275 break;
1276 case ShellMenuIgnore:
1277 AddPathFileCommand(gitCmd, L"ignore");
1278 break;
1279 case ShellMenuIgnoreCaseSensitive:
1280 AddPathFileCommand(gitCmd, L"ignore");
1281 gitCmd += _T(" /onlymask");
1282 break;
1283 case ShellMenuDeleteIgnore:
1284 AddPathFileCommand(gitCmd, L"ignore");
1285 gitCmd += _T(" /delete");
1286 break;
1287 case ShellMenuDeleteIgnoreCaseSensitive:
1288 AddPathFileCommand(gitCmd, L"ignore");
1289 gitCmd += _T(" /delete /onlymask");
1290 break;
1291 case ShellMenuUnIgnore:
1292 AddPathFileCommand(gitCmd, L"unignore");
1293 break;
1294 case ShellMenuUnIgnoreCaseSensitive:
1295 AddPathFileCommand(gitCmd, L"unignore");
1296 gitCmd += _T(" /onlymask");
1297 break;
1298 case ShellMenuMergeAbort:
1299 AddPathCommand(gitCmd, L"merge", false);
1300 gitCmd += _T(" /abort");
1301 break;
1302 case ShellMenuRevert:
1303 AddPathFileCommand(gitCmd, L"revert");
1304 break;
1305 case ShellMenuCleanup:
1306 AddPathFileCommand(gitCmd, L"cleanup");
1307 break;
1308 case ShellMenuSendMail:
1309 AddPathFileCommand(gitCmd, L"sendmail");
1310 break;
1311 case ShellMenuResolve:
1312 AddPathFileCommand(gitCmd, L"resolve");
1313 break;
1314 case ShellMenuSwitch:
1315 AddPathCommand(gitCmd, L"switch", false);
1316 break;
1317 case ShellMenuExport:
1318 AddPathCommand(gitCmd, L"export", false);
1319 break;
1320 case ShellMenuAbout:
1321 gitCmd += _T("about");
1322 break;
1323 case ShellMenuCreateRepos:
1324 AddPathCommand(gitCmd, L"repocreate", false);
1325 break;
1326 case ShellMenuMerge:
1327 AddPathCommand(gitCmd, L"merge", false);
1328 break;
1329 case ShellMenuCopy:
1330 AddPathCommand(gitCmd, L"copy", true);
1331 break;
1332 case ShellMenuSettings:
1333 AddPathCommand(gitCmd, L"settings", true);
1334 break;
1335 case ShellMenuHelp:
1336 gitCmd += _T("help");
1337 break;
1338 case ShellMenuRename:
1339 AddPathCommand(gitCmd, L"rename", true);
1340 break;
1341 case ShellMenuRemove:
1342 AddPathFileCommand(gitCmd, L"remove");
1343 break;
1344 case ShellMenuRemoveKeep:
1345 AddPathFileCommand(gitCmd, L"remove");
1346 gitCmd += _T(" /keep");
1347 break;
1348 case ShellMenuDiff:
1349 gitCmd += _T("diff /path:\"");
1350 if (files_.size() == 1)
1351 gitCmd += files_.front();
1352 else if (files_.size() == 2)
1354 std::vector<stdstring>::iterator I = files_.begin();
1355 gitCmd += *I;
1356 ++I;
1357 gitCmd += _T("\" /path2:\"");
1358 gitCmd += *I;
1360 else
1361 gitCmd += folder_;
1362 gitCmd += _T("\"");
1363 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1364 gitCmd += _T(" /alternative");
1365 break;
1366 case ShellMenuDiffLater:
1367 if (lpcmi->fMask & CMIC_MASK_CONTROL_DOWN)
1369 gitCmd.clear();
1370 regDiffLater.removeValue();
1372 else if (files_.size() == 1)
1374 if (std::wstring(regDiffLater).empty())
1376 gitCmd.clear();
1377 regDiffLater = files_[0];
1379 else
1381 AddPathCommand(gitCmd, L"diff", true);
1382 gitCmd += _T(" /path2:\"");
1383 gitCmd += std::wstring(regDiffLater);
1384 gitCmd += _T("\"");
1385 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1386 gitCmd += _T(" /alternative");
1387 regDiffLater.removeValue();
1390 else
1392 gitCmd.clear();
1394 break;
1395 case ShellMenuPrevDiff:
1396 AddPathCommand(gitCmd, L"prevdiff", true);
1397 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1398 gitCmd += _T(" /alternative");
1399 break;
1400 case ShellMenuDiffTwo:
1401 AddPathCommand(gitCmd, L"diffcommits", true);
1402 break;
1403 case ShellMenuDropCopyAdd:
1404 AddPathFileDropCommand(gitCmd, L"dropcopyadd");
1405 break;
1406 case ShellMenuDropCopy:
1407 AddPathFileDropCommand(gitCmd, L"dropcopy");
1408 break;
1409 case ShellMenuDropCopyRename:
1410 AddPathFileDropCommand(gitCmd, L"dropcopy");
1411 gitCmd += _T("\" /rename";)
1412 break;
1413 case ShellMenuDropMove:
1414 AddPathFileDropCommand(gitCmd, L"dropmove");
1415 break;
1416 case ShellMenuDropMoveRename:
1417 AddPathFileDropCommand(gitCmd, L"dropmove");
1418 gitCmd += _T("\" /rename";)
1419 break;
1420 case ShellMenuDropExport:
1421 AddPathFileDropCommand(gitCmd, L"dropexport");
1422 break;
1423 case ShellMenuDropExportExtended:
1424 AddPathFileDropCommand(gitCmd, L"dropexport");
1425 gitCmd += _T(" /extended");
1426 break;
1427 case ShellMenuLog:
1428 case ShellMenuLogSubmoduleFolder:
1429 AddPathCommand(gitCmd, L"log", true);
1430 if (id_it->second == ShellMenuLogSubmoduleFolder)
1431 gitCmd += _T(" /submodule");
1432 break;
1433 case ShellMenuDaemon:
1434 AddPathCommand(gitCmd, L"daemon", true);
1435 break;
1436 case ShellMenuRevisionGraph:
1437 AddPathCommand(gitCmd, L"revisiongraph", true);
1438 break;
1439 case ShellMenuConflictEditor:
1440 AddPathCommand(gitCmd, L"conflicteditor", true);
1441 break;
1442 case ShellMenuGitSVNRebase:
1443 AddPathCommand(gitCmd, L"svnrebase", false);
1444 break;
1445 case ShellMenuGitSVNDCommit:
1446 AddPathCommand(gitCmd, L"svndcommit", true);
1447 break;
1448 case ShellMenuGitSVNDFetch:
1449 AddPathCommand(gitCmd, L"svnfetch", false);
1450 break;
1451 case ShellMenuGitSVNIgnore:
1452 AddPathCommand(gitCmd, L"svnignore", false);
1453 break;
1454 case ShellMenuRebase:
1455 AddPathCommand(gitCmd, L"rebase", false);
1456 break;
1457 case ShellMenuShowChanged:
1458 if (files_.size() > 1)
1460 AddPathFileCommand(gitCmd, L"repostatus");
1462 else
1464 AddPathCommand(gitCmd, L"repostatus", true);
1466 break;
1467 case ShellMenuRepoBrowse:
1468 AddPathCommand(gitCmd, L"repobrowser", false);
1469 break;
1470 case ShellMenuRefBrowse:
1471 AddPathCommand(gitCmd, L"refbrowse", false);
1472 break;
1473 case ShellMenuRefLog:
1474 AddPathCommand(gitCmd, L"reflog", false);
1475 break;
1476 case ShellMenuStashSave:
1477 AddPathCommand(gitCmd, L"stashsave", true);
1478 break;
1479 case ShellMenuStashApply:
1480 AddPathCommand(gitCmd, L"stashapply", false);
1481 break;
1482 case ShellMenuStashPop:
1483 AddPathCommand(gitCmd, L"stashpop", false);
1484 break;
1485 case ShellMenuStashList:
1486 AddPathCommand(gitCmd, L"reflog", false);
1487 gitCmd += _T(" /ref:refs/stash");
1488 break;
1489 case ShellMenuBisectStart:
1490 AddPathCommand(gitCmd, L"bisect", false);
1491 gitCmd += _T("\" /start");
1492 break;
1493 case ShellMenuBisectGood:
1494 AddPathCommand(gitCmd, L"bisect", false);
1495 gitCmd += _T("\" /good");
1496 break;
1497 case ShellMenuBisectBad:
1498 AddPathCommand(gitCmd, L"bisect", false);
1499 gitCmd += _T("\" /bad");
1500 break;
1501 case ShellMenuBisectReset:
1502 AddPathCommand(gitCmd, L"bisect", false);
1503 gitCmd += _T("\" /reset");
1504 break;
1505 case ShellMenuSubAdd:
1506 AddPathCommand(gitCmd, L"subadd", false);
1507 break;
1508 case ShellMenuBlame:
1509 AddPathCommand(gitCmd, L"blame", true);
1510 break;
1511 case ShellMenuApplyPatch:
1512 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1514 // if there's a patch file in the clipboard, we save it
1515 // to a temporary file and tell TortoiseGitMerge to use that one
1516 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1517 if ((cFormat)&&(OpenClipboard(NULL)))
1519 HGLOBAL hglb = GetClipboardData(cFormat);
1520 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1522 DWORD len = GetTortoiseGitTempPath(0, NULL);
1523 std::unique_ptr<TCHAR[]> path(new TCHAR[len + 1]);
1524 std::unique_ptr<TCHAR[]> tempF(new TCHAR[len + 100]);
1525 GetTortoiseGitTempPath(len + 1, path.get());
1526 GetTempFileName(path.get(), TEXT("git"), 0, tempF.get());
1527 std::wstring sTempFile = std::wstring(tempF.get());
1529 FILE * outFile;
1530 size_t patchlen = strlen(lpstr);
1531 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1532 if(outFile)
1534 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1535 if (size == patchlen)
1537 itemStates |= ITEMIS_PATCHFILE;
1538 files_.clear();
1539 files_.push_back(sTempFile);
1541 fclose(outFile);
1543 GlobalUnlock(hglb);
1544 CloseClipboard();
1547 if (itemStates & ITEMIS_PATCHFILE)
1549 gitCmd = _T(" /diff:\"");
1550 if (!files_.empty())
1552 gitCmd += files_.front();
1553 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1555 gitCmd += _T("\" /patchpath:\"");
1556 gitCmd += folder_;
1559 else
1560 gitCmd += folder_;
1561 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1562 gitCmd += _T("\" /wc");
1563 else
1564 gitCmd += _T("\"");
1566 else
1568 gitCmd = _T(" /patchpath:\"");
1569 if (!files_.empty())
1570 gitCmd += files_.front();
1571 else
1572 gitCmd += folder_;
1573 gitCmd += _T("\"");
1575 myIDMap.clear();
1576 myVerbsIDMap.clear();
1577 myVerbsMap.clear();
1578 RunCommand(tortoiseMergePath, gitCmd, _T("TortoiseGitMerge launch failed"));
1579 return S_OK;
1580 break;
1581 case ShellMenuClipPaste:
1582 if (WriteClipboardPathsToTempFile(tempfile))
1584 bool bCopy = true;
1585 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1586 if (cPrefDropFormat)
1588 if (OpenClipboard(lpcmi->hwnd))
1590 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1591 if (hglb)
1593 DWORD* effect = (DWORD*) GlobalLock(hglb);
1594 if (*effect == DROPEFFECT_MOVE)
1595 bCopy = false;
1596 GlobalUnlock(hglb);
1598 CloseClipboard();
1602 if (bCopy)
1603 gitCmd += _T("pastecopy /pathfile:\"");
1604 else
1605 gitCmd += _T("pastemove /pathfile:\"");
1606 gitCmd += tempfile;
1607 gitCmd += _T("\"");
1608 gitCmd += _T(" /deletepathfile");
1609 gitCmd += _T(" /droptarget:\"");
1610 gitCmd += folder_;
1611 gitCmd += _T("\"");
1613 else return S_OK;
1614 break;
1615 case ShellMenuClone:
1616 AddPathCommand(gitCmd, L"clone", false);
1617 break;
1618 case ShellMenuPull:
1619 AddPathCommand(gitCmd, L"pull", false);
1620 break;
1621 case ShellMenuPush:
1622 AddPathCommand(gitCmd, L"push", false);
1623 break;
1624 case ShellMenuBranch:
1625 AddPathCommand(gitCmd, L"branch", false);
1626 break;
1627 case ShellMenuTag:
1628 AddPathCommand(gitCmd, L"tag", false);
1629 break;
1630 case ShellMenuFormatPatch:
1631 AddPathCommand(gitCmd, L"formatpatch", false);
1632 break;
1633 case ShellMenuImportPatch:
1634 AddPathFileCommand(gitCmd, L"importpatch");
1635 break;
1636 case ShellMenuFetch:
1637 AddPathCommand(gitCmd, L"fetch", false);
1638 break;
1640 default:
1641 break;
1642 //#endregion
1643 } // switch (id_it->second)
1644 if (!gitCmd.empty())
1646 gitCmd += _T(" /hwnd:");
1647 TCHAR buf[30] = { 0 };
1648 _stprintf_s(buf, _T("%p"), (void*)lpcmi->hwnd);
1649 gitCmd += buf;
1650 myIDMap.clear();
1651 myVerbsIDMap.clear();
1652 myVerbsMap.clear();
1653 RunCommand(tortoiseProcPath, gitCmd, _T("TortoiseProc launch failed"));
1655 hr = S_OK;
1656 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
1657 } // if (files_.empty() || folder_.empty())
1658 return hr;
1662 // This is for the status bar and things like that:
1663 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
1664 UINT uFlags,
1665 UINT FAR * reserved,
1666 LPSTR pszName,
1667 UINT cchMax)
1669 __try
1671 return GetCommandString_Wrap(idCmd, uFlags, reserved, pszName, cchMax);
1673 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1676 return E_FAIL;
1679 // This is for the status bar and things like that:
1680 STDMETHODIMP CShellExt::GetCommandString_Wrap(UINT_PTR idCmd,
1681 UINT uFlags,
1682 UINT FAR * /*reserved*/,
1683 LPSTR pszName,
1684 UINT cchMax)
1686 PreserveChdir preserveChdir;
1687 //do we know the id?
1688 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1689 if (id_it == myIDMap.end() || id_it->first != idCmd)
1691 return E_INVALIDARG; //no, we don't
1694 LoadLangDll();
1695 HRESULT hr = E_INVALIDARG;
1697 MAKESTRING(IDS_MENUDESCDEFAULT);
1698 int menuIndex = 0;
1699 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1701 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
1703 MAKESTRING(menuInfo[menuIndex].menuDescID);
1704 break;
1706 menuIndex++;
1709 const TCHAR * desc = stringtablebuffer;
1710 switch(uFlags)
1712 case GCS_HELPTEXTA:
1714 std::string help = WideToMultibyte(desc);
1715 lstrcpynA(pszName, help.c_str(), cchMax);
1716 hr = S_OK;
1717 break;
1719 case GCS_HELPTEXTW:
1721 wide_string help = desc;
1722 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
1723 hr = S_OK;
1724 break;
1726 case GCS_VERBA:
1728 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
1729 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
1731 std::string help = WideToMultibyte(verb_id_it->second);
1732 lstrcpynA(pszName, help.c_str(), cchMax);
1733 hr = S_OK;
1736 break;
1737 case GCS_VERBW:
1739 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
1740 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
1742 wide_string help = verb_id_it->second;
1743 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": verb : %ws\n", help.c_str());
1744 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
1745 hr = S_OK;
1748 break;
1750 return hr;
1753 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
1755 __try
1757 return HandleMenuMsg_Wrap(uMsg, wParam, lParam);
1759 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1762 return E_FAIL;
1765 STDMETHODIMP CShellExt::HandleMenuMsg_Wrap(UINT uMsg, WPARAM wParam, LPARAM lParam)
1767 LRESULT res;
1768 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
1771 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
1773 __try
1775 return HandleMenuMsg2_Wrap(uMsg, wParam, lParam, pResult);
1777 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1780 return E_FAIL;
1783 STDMETHODIMP CShellExt::HandleMenuMsg2_Wrap(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
1785 PreserveChdir preserveChdir;
1787 LRESULT res;
1788 if (pResult == NULL)
1789 pResult = &res;
1790 *pResult = FALSE;
1792 LoadLangDll();
1793 switch (uMsg)
1795 case WM_MEASUREITEM:
1797 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
1798 if (lpmis==NULL)
1799 break;
1800 lpmis->itemWidth = 16;
1801 lpmis->itemHeight = 16;
1802 *pResult = TRUE;
1804 break;
1805 case WM_DRAWITEM:
1807 LPCTSTR resource;
1808 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
1809 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
1810 return S_OK; //not for a menu
1811 resource = GetMenuTextFromResource((int)myIDMap[lpdis->itemID]);
1812 if (resource == NULL)
1813 return S_OK;
1814 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
1815 if (hIcon == NULL)
1816 return S_OK;
1817 DrawIconEx(lpdis->hDC,
1818 lpdis->rcItem.left,
1819 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
1820 hIcon, 16, 16,
1821 0, NULL, DI_NORMAL);
1822 DestroyIcon(hIcon);
1823 *pResult = TRUE;
1825 break;
1826 case WM_MENUCHAR:
1828 TCHAR *szItem;
1829 if (HIWORD(wParam) != MF_POPUP)
1830 return S_OK;
1831 int nChar = LOWORD(wParam);
1832 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
1833 nChar = tolower(nChar);
1834 // we have the char the user pressed, now search that char in all our
1835 // menu items
1836 std::vector<UINT_PTR> accmenus;
1837 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
1839 LPCTSTR resource = GetMenuTextFromResource((int)mySubMenuMap[It->first]);
1840 if (resource == NULL)
1841 continue;
1842 szItem = stringtablebuffer;
1843 TCHAR * amp = _tcschr(szItem, '&');
1844 if (amp == NULL)
1845 continue;
1846 amp++;
1847 int ampChar = LOWORD(*amp);
1848 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
1849 ampChar = tolower(ampChar);
1850 if (ampChar == nChar)
1852 // yep, we found a menu which has the pressed key
1853 // as an accelerator. Add that menu to the list to
1854 // process later.
1855 accmenus.push_back(It->first);
1858 if (accmenus.empty())
1860 // no menu with that accelerator key.
1861 *pResult = MAKELONG(0, MNC_IGNORE);
1862 return S_OK;
1864 if (accmenus.size() == 1)
1866 // Only one menu with that accelerator key. We're lucky!
1867 // So just execute that menu entry.
1868 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
1869 return S_OK;
1871 if (accmenus.size() > 1)
1873 // we have more than one menu item with this accelerator key!
1874 MENUITEMINFO mif;
1875 mif.cbSize = sizeof(MENUITEMINFO);
1876 mif.fMask = MIIM_STATE;
1877 for (std::vector<UINT_PTR>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
1879 GetMenuItemInfo((HMENU)lParam, (UINT)*it, TRUE, &mif);
1880 if (mif.fState == MFS_HILITE)
1882 // this is the selected item, so select the next one
1883 ++it;
1884 if (it == accmenus.end())
1885 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
1886 else
1887 *pResult = MAKELONG(*it, MNC_SELECT);
1888 return S_OK;
1891 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
1894 break;
1895 default:
1896 return S_OK;
1899 return S_OK;
1902 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
1904 TCHAR textbuf[255] = { 0 };
1905 LPCTSTR resource = NULL;
1906 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
1907 space = 6;
1909 int menuIndex = 0;
1910 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1912 if (menuInfo[menuIndex].command == id)
1914 MAKESTRING(menuInfo[menuIndex].menuTextID);
1915 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
1916 switch (id)
1918 case ShellSubMenuMultiple:
1919 case ShellSubMenuLink:
1920 case ShellSubMenuFolder:
1921 case ShellSubMenuFile:
1922 case ShellSubMenu:
1923 space = 0;
1924 break;
1925 default:
1926 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
1927 if (layout & (menuInfo[menuIndex].menuID))
1929 _tcscpy_s(textbuf, 255, _T("Git "));
1930 _tcscat_s(textbuf, 255, stringtablebuffer);
1931 _tcscpy_s(stringtablebuffer, 255, textbuf);
1933 break;
1935 return resource;
1937 menuIndex++;
1939 return NULL;
1942 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
1944 int i=0;
1945 TCHAR buf[MAX_PATH] = {0}; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
1946 LPITEMIDLIST pidl = NULL;
1947 while (cslidarray[i])
1949 ++i;
1950 pidl = NULL;
1951 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
1952 continue;
1953 if (!SHGetPathFromIDList(pidl, buf))
1955 // not a file system path, definitely illegal for our use
1956 CoTaskMemFree(pidl);
1957 continue;
1959 CoTaskMemFree(pidl);
1960 if (_tcslen(buf)==0)
1961 continue;
1962 if (_tcscmp(buf, folder.c_str())==0)
1963 return true;
1965 return false;
1968 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT /*uFlags*/)
1970 HMENU ignoresubmenu = NULL;
1971 int indexignoresub = 0;
1972 bool bShowIgnoreMenu = false;
1973 TCHAR maskbuf[MAX_PATH] = {0}; // MAX_PATH is ok, since this only holds a filename
1974 TCHAR ignorepath[MAX_PATH] = {0}; // MAX_PATH is ok, since this only holds a filename
1975 if (files_.empty())
1976 return false;
1977 UINT icon = bShowIcons ? IDI_IGNORE : 0;
1979 std::vector<stdstring>::iterator I = files_.begin();
1980 if (_tcsrchr(I->c_str(), '\\'))
1981 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
1982 else
1983 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
1984 if ((itemStates & ITEMIS_IGNORED) && (!ignoredprops.empty()))
1986 // check if the item name is ignored or the mask
1987 size_t p = 0;
1988 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
1990 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
1991 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
1993 break;
1995 p++;
1997 if (p!=-1)
1999 ignoresubmenu = CreateMenu();
2000 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2001 stdstring verb = stdstring(ignorepath);
2002 myVerbsMap[verb] = idCmd - idCmdFirst;
2003 myVerbsMap[verb] = idCmd;
2004 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2005 myVerbsIDMap[idCmd] = verb;
2006 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
2007 myIDMap[idCmd++] = ShellMenuUnIgnore;
2008 bShowIgnoreMenu = true;
2010 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2011 if (_tcsrchr(ignorepath, '.'))
2013 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2014 p = ignoredprops.find(maskbuf);
2015 if ((p!=-1) &&
2016 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
2018 if (ignoresubmenu==NULL)
2019 ignoresubmenu = CreateMenu();
2021 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2022 stdstring verb = stdstring(maskbuf);
2023 myVerbsMap[verb] = idCmd - idCmdFirst;
2024 myVerbsMap[verb] = idCmd;
2025 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2026 myVerbsIDMap[idCmd] = verb;
2027 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
2028 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
2029 bShowIgnoreMenu = true;
2033 else if ((itemStates & ITEMIS_IGNORED) == 0)
2035 bShowIgnoreMenu = true;
2036 ignoresubmenu = CreateMenu();
2037 if (itemStates & ITEMIS_ONLYONE)
2039 if (itemStates & ITEMIS_INGIT)
2041 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2042 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2043 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2045 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2046 if (!(itemStates & ITEMIS_FOLDER) && _tcsrchr(ignorepath, '.'))
2048 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2049 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2050 stdstring verb = stdstring(maskbuf);
2051 myVerbsMap[verb] = idCmd - idCmdFirst;
2052 myVerbsMap[verb] = idCmd;
2053 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2054 myVerbsIDMap[idCmd] = verb;
2055 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2056 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2059 else
2061 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2062 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2063 myIDMap[idCmd++] = ShellMenuIgnore;
2065 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2066 if (!(itemStates & ITEMIS_FOLDER) && _tcsrchr(ignorepath, '.'))
2068 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2069 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2070 stdstring verb = stdstring(maskbuf);
2071 myVerbsMap[verb] = idCmd - idCmdFirst;
2072 myVerbsMap[verb] = idCmd;
2073 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2074 myVerbsIDMap[idCmd] = verb;
2075 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2076 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2080 else
2082 if (itemStates & ITEMIS_INGIT)
2084 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
2085 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2086 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2087 stdstring verb = stdstring(ignorepath);
2088 myVerbsMap[verb] = idCmd - idCmdFirst;
2089 myVerbsMap[verb] = idCmd;
2090 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2091 myVerbsIDMap[idCmd] = verb;
2092 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2093 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2095 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
2096 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2097 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2098 verb = stdstring(ignorepath);
2099 myVerbsMap[verb] = idCmd - idCmdFirst;
2100 myVerbsMap[verb] = idCmd;
2101 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2102 myVerbsIDMap[idCmd] = verb;
2103 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2104 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2106 else
2108 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2109 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2110 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2111 stdstring verb = stdstring(ignorepath);
2112 myVerbsMap[verb] = idCmd - idCmdFirst;
2113 myVerbsMap[verb] = idCmd;
2114 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2115 myVerbsIDMap[idCmd] = verb;
2116 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2117 myIDMap[idCmd++] = ShellMenuIgnore;
2119 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2120 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2121 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2122 verb = stdstring(ignorepath);
2123 myVerbsMap[verb] = idCmd - idCmdFirst;
2124 myVerbsMap[verb] = idCmd;
2125 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2126 myVerbsIDMap[idCmd] = verb;
2127 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2128 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2133 if (bShowIgnoreMenu)
2135 MENUITEMINFO menuiteminfo;
2136 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2137 menuiteminfo.cbSize = sizeof(menuiteminfo);
2138 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2139 if (icon)
2141 menuiteminfo.fMask |= MIIM_BITMAP;
2142 menuiteminfo.hbmpItem = SysInfo::Instance().IsVistaOrLater() ? m_iconBitmapUtils.IconToBitmapPARGB32(g_hResInst, icon) : m_iconBitmapUtils.IconToBitmap(g_hResInst, icon);
2144 menuiteminfo.fType = MFT_STRING;
2145 menuiteminfo.hSubMenu = ignoresubmenu;
2146 menuiteminfo.wID = idCmd;
2147 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2148 if (itemStates & ITEMIS_IGNORED)
2149 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2150 else if (itemStates & ITEMIS_INGIT)
2151 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2152 else
2153 GetMenuTextFromResource(ShellMenuIgnoreSub);
2154 menuiteminfo.dwTypeData = stringtablebuffer;
2155 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2157 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2158 if (itemStates & ITEMIS_IGNORED)
2160 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2161 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2163 else
2165 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2166 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2169 return bShowIgnoreMenu;
2172 void CShellExt::RunCommand(const tstring& path, const tstring& command, LPCTSTR errorMessage)
2174 if (CCreateProcessHelper::CreateProcessDetached(path.c_str(), const_cast<TCHAR*>(command.c_str())))
2176 // process started - exit
2177 return;
2180 MessageBox(NULL, CFormatMessageWrapper(), errorMessage, MB_OK | MB_ICONINFORMATION);
2183 bool CShellExt::ShouldInsertItem(const MenuInfo& item) const
2185 return ShouldEnableMenu(item.first) || ShouldEnableMenu(item.second) ||
2186 ShouldEnableMenu(item.third) || ShouldEnableMenu(item.fourth);
2189 bool CShellExt::ShouldEnableMenu(const YesNoPair& pair) const
2191 if (pair.yes && pair.no)
2193 if (((pair.yes & itemStates) == pair.yes) && ((pair.no & (~itemStates)) == pair.no))
2194 return true;
2196 else if ((pair.yes) && ((pair.yes & itemStates) == pair.yes))
2197 return true;
2198 else if ((pair.no) && ((pair.no & (~itemStates)) == pair.no))
2199 return true;
2200 return false;