cleanup: dropped a lot of unused code
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blob79f64b8a576df2e4c892a798a1ec5c0c38b9dee8
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2011 - TortoiseSVN
4 // Copyright (C) 2008-2012 - 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 "GitProperties.h"
26 #include "GitStatus.h"
27 #include "TGitPath.h"
28 #include "CreateProcessHelper.h"
29 #include "FormatMessageWrapper.h"
31 #define GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
32 #define GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
34 int g_shellidlist=RegisterClipboardFormat(CFSTR_SHELLIDLIST);
36 extern MenuInfo menuInfo[];
39 STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST pIDFolder,
40 LPDATAOBJECT pDataObj,
41 HKEY /* hRegKey */)
44 ATLTRACE("Shell :: Initialize\n");
45 PreserveChdir preserveChdir;
46 files_.clear();
47 folder_.erase();
48 uuidSource.erase();
49 uuidTarget.erase();
50 itemStates = 0;
51 itemStatesFolder = 0;
52 stdstring statuspath;
53 git_wc_status_kind fetchedstatus = git_wc_status_none;
54 // get selected files/folders
55 if (pDataObj)
57 STGMEDIUM medium;
58 FORMATETC fmte = {(CLIPFORMAT)g_shellidlist,
59 (DVTARGETDEVICE FAR *)NULL,
60 DVASPECT_CONTENT,
61 -1,
62 TYMED_HGLOBAL};
63 HRESULT hres = pDataObj->GetData(&fmte, &medium);
65 if (SUCCEEDED(hres) && medium.hGlobal)
67 if (m_State == FileStateDropHandler)
70 FORMATETC etc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
71 STGMEDIUM stg = { TYMED_HGLOBAL };
72 if ( FAILED( pDataObj->GetData ( &etc, &stg )))
74 ReleaseStgMedium ( &medium );
75 return E_INVALIDARG;
79 HDROP drop = (HDROP)GlobalLock(stg.hGlobal);
80 if ( NULL == drop )
82 ReleaseStgMedium ( &stg );
83 ReleaseStgMedium ( &medium );
84 return E_INVALIDARG;
87 int count = DragQueryFile(drop, (UINT)-1, NULL, 0);
88 if (count == 1)
89 itemStates |= ITEMIS_ONLYONE;
90 for (int i = 0; i < count; i++)
92 // find the path length in chars
93 UINT len = DragQueryFile(drop, i, NULL, 0);
94 if (len == 0)
95 continue;
96 TCHAR * szFileName = new TCHAR[len+1];
97 if (0 == DragQueryFile(drop, i, szFileName, len+1))
99 delete [] szFileName;
100 continue;
102 stdstring str = stdstring(szFileName);
103 delete [] szFileName;
104 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(szFileName)))
106 if (itemStates & ITEMIS_ONLYONE)
108 CTGitPath strpath;
109 strpath.SetFromWin(str.c_str());
110 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
111 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
113 files_.push_back(str);
114 if (i == 0)
116 //get the Subversion status of the item
117 git_wc_status_kind status = git_wc_status_none;
118 CTGitPath askedpath;
119 askedpath.SetFromWin(str.c_str());
122 GitStatus stat;
123 stat.GetStatus(CTGitPath(str.c_str()), false, false, true);
124 if (stat.status)
126 statuspath = str;
127 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
128 fetchedstatus = status;
129 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
130 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
131 if ( askedpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
133 itemStates |= ITEMIS_FOLDER;
134 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
135 itemStates |= ITEMIS_FOLDERINGIT;
137 //if ((stat.status->entry)&&(stat.status->entry->present_props))
139 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
140 // itemStates |= ITEMIS_NEEDSLOCK;
142 //if ((stat.status->entry)&&(stat.status->entry->uuid))
143 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
145 else
147 // sometimes, git_client_status() returns with an error.
148 // in that case, we have to check if the working copy is versioned
149 // anyway to show the 'correct' context menu
150 if (askedpath.HasAdminDir())
151 status = git_wc_status_normal;
154 catch ( ... )
156 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
159 // TODO: should we really assume any sub-directory to be versioned
160 // or only if it contains versioned files
161 itemStates |= askedpath.GetAdminDirMask();
163 if ((status == git_wc_status_unversioned) || (status == git_wc_status_ignored) || (status == git_wc_status_none))
164 itemStates &= ~ITEMIS_INGIT;
166 if (status == git_wc_status_ignored)
167 itemStates |= ITEMIS_IGNORED;
168 if (status == git_wc_status_normal)
169 itemStates |= ITEMIS_NORMAL;
170 if (status == git_wc_status_conflicted)
171 itemStates |= ITEMIS_CONFLICTED;
172 if (status == git_wc_status_added)
173 itemStates |= ITEMIS_ADDED;
174 if (status == git_wc_status_deleted)
175 itemStates |= ITEMIS_DELETED;
178 } // for (int i = 0; i < count; i++)
179 GlobalUnlock ( drop );
180 ReleaseStgMedium ( &stg );
182 } // if (m_State == FileStateDropHandler)
183 else
186 //Enumerate PIDLs which the user has selected
187 CIDA* cida = (CIDA*)GlobalLock(medium.hGlobal);
188 ItemIDList parent( GetPIDLFolder (cida));
190 int count = cida->cidl;
191 BOOL statfetched = FALSE;
192 for (int i = 0; i < count; ++i)
194 ItemIDList child (GetPIDLItem (cida, i), &parent);
195 stdstring str = child.toString();
196 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(str.c_str())))
198 //check if our menu is requested for a subversion admin directory
199 if (g_GitAdminDir.IsAdminDirPath(str.c_str()))
200 continue;
202 files_.push_back(str);
203 CTGitPath strpath;
204 strpath.SetFromWin(str.c_str());
205 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
206 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
207 if (!statfetched)
209 //get the Subversion status of the item
210 git_wc_status_kind status = git_wc_status_none;
211 if ((g_ShellCache.IsSimpleContext())&&(strpath.IsDirectory()))
213 if (strpath.HasAdminDir())
214 status = git_wc_status_normal;
216 else
220 GitStatus stat;
221 if (strpath.HasAdminDir())
222 stat.GetStatus(strpath, false, false, true);
223 statuspath = str;
224 if (stat.status)
226 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
227 fetchedstatus = status;
228 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
229 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
230 if ( strpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
232 itemStates |= ITEMIS_FOLDER;
233 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
234 itemStates |= ITEMIS_FOLDERINGIT;
236 // TODO: do we need to check that it's not a dir? does conflict options makes sense for dir in git?
237 if (status == git_wc_status_conflicted)//if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
238 itemStates |= ITEMIS_CONFLICTED;
239 //if ((stat.status->entry)&&(stat.status->entry->present_props))
241 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
242 // itemStates |= ITEMIS_NEEDSLOCK;
244 //if ((stat.status->entry)&&(stat.status->entry->uuid))
245 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
247 else
249 // sometimes, git_client_status() returns with an error.
250 // in that case, we have to check if the working copy is versioned
251 // anyway to show the 'correct' context menu
252 if (strpath.HasAdminDir())
254 status = git_wc_status_normal;
255 fetchedstatus = status;
258 statfetched = TRUE;
260 catch ( ... )
262 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
266 itemStates |= strpath.GetAdminDirMask();
268 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
269 itemStates &= ~ITEMIS_INGIT;
270 if (status == git_wc_status_ignored)
272 itemStates |= ITEMIS_IGNORED;
273 // the item is ignored. Get the svn:ignored properties so we can (maybe) later
274 // offer a 'remove from ignored list' entry
275 // GitProperties props(strpath.GetContainingDirectory(), false);
276 // ignoredprops.empty();
277 // for (int p=0; p<props.GetCount(); ++p)
278 // {
279 // if (props.GetItemName(p).compare(stdstring(_T("svn:ignore")))==0)
280 // {
281 // std::string st = props.GetItemValue(p);
282 // ignoredprops = MultibyteToWide(st.c_str());
283 // // remove all escape chars ('\\')
284 // std::remove(ignoredprops.begin(), ignoredprops.end(), '\\');
285 // break;
286 // }
287 // }
290 if (status == git_wc_status_normal)
291 itemStates |= ITEMIS_NORMAL;
292 if (status == git_wc_status_conflicted)
293 itemStates |= ITEMIS_CONFLICTED;
294 if (status == git_wc_status_added)
295 itemStates |= ITEMIS_ADDED;
296 if (status == git_wc_status_deleted)
297 itemStates |= ITEMIS_DELETED;
300 } // for (int i = 0; i < count; ++i)
301 ItemIDList child (GetPIDLItem (cida, 0), &parent);
302 if (g_ShellCache.HasGITAdminDir(child.toString().c_str(), FALSE))
303 itemStates |= ITEMIS_INVERSIONEDFOLDER;
305 if (itemStates == 0 && g_GitAdminDir.IsBareRepo(child.toString().c_str()))
306 itemStates = ITEMIS_BAREREPO;
308 GlobalUnlock(medium.hGlobal);
310 // if the item is a versioned folder, check if there's a patch file
311 // in the clipboard to be used in "Apply Patch"
312 UINT cFormatDiff = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
313 if (cFormatDiff)
315 if (IsClipboardFormatAvailable(cFormatDiff))
316 itemStates |= ITEMIS_PATCHINCLIPBOARD;
318 if (IsClipboardFormatAvailable(CF_HDROP))
319 itemStates |= ITEMIS_PATHINCLIPBOARD;
323 ReleaseStgMedium ( &medium );
324 if (medium.pUnkForRelease)
326 IUnknown* relInterface = (IUnknown*)medium.pUnkForRelease;
327 relInterface->Release();
332 // get folder background
333 if (pIDFolder)
336 ItemIDList list(pIDFolder);
337 folder_ = list.toString();
338 git_wc_status_kind status = git_wc_status_none;
339 if (IsClipboardFormatAvailable(CF_HDROP))
340 itemStatesFolder |= ITEMIS_PATHINCLIPBOARD;
342 CTGitPath askedpath;
343 askedpath.SetFromWin(folder_.c_str());
345 if (g_ShellCache.IsContextPathAllowed(folder_.c_str()))
347 if (folder_.compare(statuspath)!=0)
352 GitStatus stat;
353 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
354 if (stat.status)
356 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
357 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
358 // itemStatesFolder |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
359 // if ((stat.status->entry)&&(stat.status->entry->present_props))
360 // {
361 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
362 // itemStatesFolder |= ITEMIS_NEEDSLOCK;
363 // }
364 // if ((stat.status->entry)&&(stat.status->entry->uuid))
365 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
368 else
370 // sometimes, git_client_status() returns with an error.
371 // in that case, we have to check if the working copy is versioned
372 // anyway to show the 'correct' context menu
373 if (askedpath.HasAdminDir())
374 status = git_wc_status_normal;
377 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
378 itemStatesFolder |= askedpath.GetAdminDirMask();
380 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
381 itemStates &= ~ITEMIS_INGIT;
383 if (status == git_wc_status_normal)
384 itemStatesFolder |= ITEMIS_NORMAL;
385 if (status == git_wc_status_conflicted)
386 itemStatesFolder |= ITEMIS_CONFLICTED;
387 if (status == git_wc_status_added)
388 itemStatesFolder |= ITEMIS_ADDED;
389 if (status == git_wc_status_deleted)
390 itemStatesFolder |= ITEMIS_DELETED;
393 catch ( ... )
395 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
398 else
400 status = fetchedstatus;
402 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
403 itemStatesFolder |= askedpath.GetAdminDirMask();
405 if (status == git_wc_status_ignored)
406 itemStatesFolder |= ITEMIS_IGNORED;
407 itemStatesFolder |= ITEMIS_FOLDER;
408 if (files_.size() == 0)
409 itemStates |= ITEMIS_ONLYONE;
410 if (m_State != FileStateDropHandler)
411 itemStates |= itemStatesFolder;
413 else
415 folder_.clear();
416 status = fetchedstatus;
419 if (files_.size() == 2)
420 itemStates |= ITEMIS_TWO;
421 if ((files_.size() == 1)&&(g_ShellCache.IsContextPathAllowed(files_.front().c_str())))
424 itemStates |= ITEMIS_ONLYONE;
425 if (m_State != FileStateDropHandler)
427 if (PathIsDirectory(files_.front().c_str()))
429 folder_ = files_.front();
430 git_wc_status_kind status = git_wc_status_none;
431 CTGitPath askedpath;
432 askedpath.SetFromWin(folder_.c_str());
434 if (folder_.compare(statuspath)!=0)
438 GitStatus stat;
439 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
440 if (stat.status)
442 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
443 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
444 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
445 // if ((stat.status->entry)&&(stat.status->entry->present_props))
446 // {
447 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
448 // itemStates |= ITEMIS_NEEDSLOCK;
449 // }
450 // if ((stat.status->entry)&&(stat.status->entry->uuid))
451 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
454 catch ( ... )
456 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
459 else
461 status = fetchedstatus;
463 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
464 itemStates |= askedpath.GetAdminDirMask();
466 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
467 itemStates &= ~ITEMIS_INGIT;
469 if (status == git_wc_status_ignored)
470 itemStates |= ITEMIS_IGNORED;
471 itemStates |= ITEMIS_FOLDER;
472 if (status == git_wc_status_added)
473 itemStates |= ITEMIS_ADDED;
474 if (status == git_wc_status_deleted)
475 itemStates |= ITEMIS_DELETED;
482 return S_OK;
485 void CShellExt::InsertGitMenu(BOOL istop, HMENU menu, UINT pos, UINT_PTR id, UINT stringid, UINT icon, UINT idCmdFirst, GitCommands com, UINT /*uFlags*/)
487 TCHAR menutextbuffer[512] = {0};
488 TCHAR verbsbuffer[255] = {0};
489 MAKESTRING(stringid);
491 if (istop)
493 //menu entry for the top context menu, so append an "Git " before
494 //the menu text to indicate where the entry comes from
495 _tcscpy_s(menutextbuffer, 255, _T("Git "));
497 _tcscat_s(menutextbuffer, 255, stringtablebuffer);
498 #if 1
499 // insert branch name into "Git Commit..." entry, so it looks like "Git Commit "master"..."
500 // so we have an easy and fast way to check the current branch
501 // (the other alternative is using a separate disabled menu entry, the code is already done but commented out)
502 if (com == ShellMenuCommit)
504 // get branch name
505 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
506 CString sProjectRoot;
507 CString sBranchName;
509 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
511 if (sBranchName.GetLength() == 40)
513 // if SHA1 only show 4 first bytes
514 BOOL bIsSha1 = TRUE;
515 for (int i=0; i<40; i++)
516 if ( !iswxdigit(sBranchName[i]) )
518 bIsSha1 = FALSE;
519 break;
521 if (bIsSha1)
522 sBranchName = sBranchName.Left(8) + _T("....");
525 // sanity check
526 if (sBranchName.GetLength() > 64)
527 sBranchName = sBranchName.Left(64) + _T("...");
529 // scan to before "..."
530 LPTSTR s = menutextbuffer + _tcslen(menutextbuffer)-1;
531 if (s > menutextbuffer)
533 while (s > menutextbuffer)
535 if (*s != _T('.'))
537 s++;
538 break;
540 s--;
543 else
545 s = menutextbuffer;
548 // append branch name and end with ...
549 _tcscpy(s, _T(" -> \"") + sBranchName + _T("\"..."));
552 #endif
553 MENUITEMINFO menuiteminfo;
554 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
555 menuiteminfo.cbSize = sizeof(menuiteminfo);
556 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
557 menuiteminfo.fType = MFT_STRING;
558 menuiteminfo.dwTypeData = menutextbuffer;
559 if (icon)
561 menuiteminfo.fMask |= MIIM_BITMAP;
562 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
564 menuiteminfo.wID = (UINT)id;
565 InsertMenuItem(menu, pos, TRUE, &menuiteminfo);
567 if (istop)
569 //menu entry for the top context menu, so append an "Git " before
570 //the menu text to indicate where the entry comes from
571 _tcscpy_s(menutextbuffer, 255, _T("Git "));
573 LoadString(g_hResInst, stringid, verbsbuffer, sizeof(verbsbuffer));
574 _tcscat_s(menutextbuffer, 255, verbsbuffer);
575 stdstring verb = stdstring(menutextbuffer);
576 if (verb.find('&') != -1)
578 verb.erase(verb.find('&'),1);
580 myVerbsMap[verb] = id - idCmdFirst;
581 myVerbsMap[verb] = id;
582 myVerbsIDMap[id - idCmdFirst] = verb;
583 myVerbsIDMap[id] = verb;
584 // We store the relative and absolute diameter
585 // (drawitem callback uses absolute, others relative)
586 myIDMap[id - idCmdFirst] = com;
587 myIDMap[id] = com;
588 if (!istop)
589 mySubMenuMap[pos] = com;
592 HBITMAP CShellExt::IconToBitmap(UINT uIcon)
594 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
595 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
596 return bitmap_it->second;
598 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 12, 12, LR_DEFAULTCOLOR);
599 if (!hIcon)
600 return NULL;
602 RECT rect;
604 rect.right = ::GetSystemMetrics(SM_CXMENUCHECK);
605 rect.bottom = ::GetSystemMetrics(SM_CYMENUCHECK);
607 rect.left = rect.top = 0;
609 HWND desktop = ::GetDesktopWindow();
610 if (desktop == NULL)
612 DestroyIcon(hIcon);
613 return NULL;
616 HDC screen_dev = ::GetDC(desktop);
617 if (screen_dev == NULL)
619 DestroyIcon(hIcon);
620 return NULL;
623 // Create a compatible DC
624 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
625 if (dst_hdc == NULL)
627 DestroyIcon(hIcon);
628 ::ReleaseDC(desktop, screen_dev);
629 return NULL;
632 // Create a new bitmap of icon size
633 HBITMAP bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
634 if (bmp == NULL)
636 DestroyIcon(hIcon);
637 ::DeleteDC(dst_hdc);
638 ::ReleaseDC(desktop, screen_dev);
639 return NULL;
642 // Select it into the compatible DC
643 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
644 if (old_dst_bmp == NULL)
646 DestroyIcon(hIcon);
647 return NULL;
650 // Fill the background of the compatible DC with the white color
651 // that is taken by menu routines as transparent
652 ::SetBkColor(dst_hdc, RGB(255, 255, 255));
653 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
655 // Draw the icon into the compatible DC
656 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
658 // Restore settings
659 ::SelectObject(dst_hdc, old_dst_bmp);
660 ::DeleteDC(dst_hdc);
661 ::ReleaseDC(desktop, screen_dev);
662 DestroyIcon(hIcon);
663 if (bmp)
664 bitmaps.insert(bitmap_it, std::make_pair(uIcon, bmp));
665 return bmp;
668 bool CShellExt::WriteClipboardPathsToTempFile(stdstring& tempfile)
670 bool bRet = true;
671 tempfile = stdstring();
672 //write all selected files and paths to a temporary file
673 //for TortoiseProc.exe to read out again.
674 DWORD written = 0;
675 DWORD pathlength = GetTempPath(0, NULL);
676 TCHAR * path = new TCHAR[pathlength+1];
677 TCHAR * tempFile = new TCHAR[pathlength + 100];
678 GetTempPath (pathlength+1, path);
679 GetTempFileName (path, _T("git"), 0, tempFile);
680 tempfile = stdstring(tempFile);
682 CAutoFile file = ::CreateFile (tempFile,
683 GENERIC_WRITE,
684 FILE_SHARE_READ,
686 CREATE_ALWAYS,
687 FILE_ATTRIBUTE_TEMPORARY,
690 delete [] path;
691 delete [] tempFile;
692 if (!file)
693 return false;
695 if (!IsClipboardFormatAvailable(CF_HDROP))
696 return false;
697 if (!OpenClipboard(NULL))
698 return false;
700 stdstring sClipboardText;
701 HGLOBAL hglb = GetClipboardData(CF_HDROP);
702 HDROP hDrop = (HDROP)GlobalLock(hglb);
703 if(hDrop != NULL)
705 TCHAR szFileName[MAX_PATH];
706 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
707 for(UINT i = 0; i < cFiles; ++i)
709 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
710 stdstring filename = szFileName;
711 ::WriteFile (file, filename.c_str(), (DWORD)filename.size()*sizeof(TCHAR), &written, 0);
712 ::WriteFile (file, _T("\n"), 2, &written, 0);
714 GlobalUnlock(hDrop);
716 else bRet = false;
717 GlobalUnlock(hglb);
719 CloseClipboard();
721 return bRet;
724 stdstring CShellExt::WriteFileListToTempFile()
726 //write all selected files and paths to a temporary file
727 //for TortoiseProc.exe to read out again.
728 DWORD pathlength = GetTempPath(0, NULL);
729 TCHAR * path = new TCHAR[pathlength+1];
730 TCHAR * tempFile = new TCHAR[pathlength + 100];
731 GetTempPath (pathlength+1, path);
732 GetTempFileName (path, _T("git"), 0, tempFile);
733 stdstring retFilePath = stdstring(tempFile);
735 CAutoFile file = ::CreateFile (tempFile,
736 GENERIC_WRITE,
737 FILE_SHARE_READ,
739 CREATE_ALWAYS,
740 FILE_ATTRIBUTE_TEMPORARY,
743 delete [] path;
744 delete [] tempFile;
745 if (!file)
746 return stdstring();
748 DWORD written = 0;
749 if (files_.empty())
751 ::WriteFile (file, folder_.c_str(), (DWORD)folder_.size()*sizeof(TCHAR), &written, 0);
752 ::WriteFile (file, _T("\n"), 2, &written, 0);
755 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
757 ::WriteFile (file, I->c_str(), (DWORD)I->size()*sizeof(TCHAR), &written, 0);
758 ::WriteFile (file, _T("\n"), 2, &written, 0);
760 return retFilePath;
763 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
765 PreserveChdir preserveChdir;
766 LoadLangDll();
768 if ((uFlags & CMF_DEFAULTONLY)!=0)
769 return S_OK; //we don't change the default action
771 if ((files_.size() == 0)||(folder_.size() == 0))
772 return S_OK;
774 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
775 return S_OK;
777 if (itemStatesFolder & ITEMIS_FOLDER) // we do not support folders atm, see issue #963
778 return S_OK;
780 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
782 //the drop handler only has eight commands, but not all are visible at the same time:
783 //if the source file(s) are under version control then those files can be moved
784 //to the new location or they can be moved with a rename,
785 //if they are unversioned then they can be added to the working copy
786 //if they are versioned, they also can be exported to an unversioned location
787 UINT idCmd = idCmdFirst;
789 // Git move here
790 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
791 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
792 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
794 // Git move and rename here
795 // 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
796 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
797 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
799 // Git copy here
800 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
801 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
802 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
804 // Git copy and rename here, source and target from same repository
805 // available if source is a single, versioned but not added item, target is versioned or target folder is added
806 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
807 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
809 // Git add here
810 // available if target is versioned and source is either unversioned or from another repository
811 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
812 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
814 // Git export here
815 // available if source is versioned and a folder
816 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
817 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
819 // Git export all here
820 // available if source is versioned and a folder
821 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
822 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
824 // apply patch
825 // available if source is a patchfile
826 if (itemStates & ITEMIS_PATCHFILE)
827 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
829 // separator
830 if (idCmd != idCmdFirst)
831 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
833 TweakMenu(hMenu);
835 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
838 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
839 UINT indexMenu,
840 UINT idCmdFirst,
841 UINT /*idCmdLast*/,
842 UINT uFlags)
844 ATLTRACE("Shell :: QueryContextMenu\n");
845 PreserveChdir preserveChdir;
847 //first check if our drop handler is called
848 //and then (if true) provide the context menu for the
849 //drop handler
850 if (m_State == FileStateDropHandler)
852 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
855 if ((uFlags & CMF_DEFAULTONLY)!=0)
856 return S_OK; //we don't change the default action
858 if ((files_.size() == 0)&&(folder_.size() == 0))
859 return S_OK;
861 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
862 return S_OK;
864 int csidlarray[] =
866 CSIDL_BITBUCKET,
867 CSIDL_CDBURN_AREA,
868 CSIDL_COMMON_FAVORITES,
869 CSIDL_COMMON_STARTMENU,
870 CSIDL_COMPUTERSNEARME,
871 CSIDL_CONNECTIONS,
872 CSIDL_CONTROLS,
873 CSIDL_COOKIES,
874 CSIDL_FAVORITES,
875 CSIDL_FONTS,
876 CSIDL_HISTORY,
877 CSIDL_INTERNET,
878 CSIDL_INTERNET_CACHE,
879 CSIDL_NETHOOD,
880 CSIDL_NETWORK,
881 CSIDL_PRINTERS,
882 CSIDL_PRINTHOOD,
883 CSIDL_RECENT,
884 CSIDL_SENDTO,
885 CSIDL_STARTMENU,
888 if (IsIllegalFolder(folder_, csidlarray))
889 return S_OK;
891 if (folder_.empty())
893 // folder is empty, but maybe files are selected
894 if (files_.size() == 0)
895 return S_OK; // nothing selected - we don't have a menu to show
896 // check whether a selected entry is an UID - those are namespace extensions
897 // which we can't handle
898 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
900 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
901 return S_OK;
905 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
907 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT|ITEMIS_BAREREPO|ITEMIS_TWO))==0)
908 return S_OK;
911 //check if our menu is requested for a subversion admin directory
912 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
913 return S_OK;
915 if (uFlags & CMF_EXTENDEDVERBS)
916 itemStates |= ITEMIS_EXTENDED;
918 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
919 if ( bShortcut && (files_.size()==1))
921 // Don't show the context menu for a link if the
922 // destination is not part of a working copy.
923 // It would only show the standard menu items
924 // which are already shown for the lnk-file.
925 CString path = files_.front().c_str();
926 if ( !g_GitAdminDir.HasAdminDir(path) )
928 return S_OK;
932 //check if we already added our menu entry for a folder.
933 //we check that by iterating through all menu entries and check if
934 //the dwItemData member points to our global ID string. That string is set
935 //by our shell extension when the folder menu is inserted.
936 TCHAR menubuf[MAX_PATH];
937 int count = GetMenuItemCount(hMenu);
938 for (int i=0; i<count; ++i)
940 MENUITEMINFO miif;
941 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
942 miif.cbSize = sizeof(MENUITEMINFO);
943 miif.fMask = MIIM_DATA;
944 miif.dwTypeData = menubuf;
945 miif.cch = _countof(menubuf);
946 GetMenuItemInfo(hMenu, i, TRUE, &miif);
947 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
948 return S_OK;
951 LoadLangDll();
952 UINT idCmd = idCmdFirst;
954 //create the sub menu
955 HMENU subMenu = CreateMenu();
956 int indexSubMenu = 0;
958 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
959 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
960 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
962 int menuIndex = 0;
963 bool bAddSeparator = false;
964 bool bMenuEntryAdded = false;
965 bool bMenuEmpty = true;
966 // insert separator at start
967 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
968 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
970 #if 0
971 if (itemStates & (ITEMIS_INSVN|ITEMIS_FOLDERINSVN))
973 // show current branch name (as a "read-only" menu entry)
975 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
976 CString sProjectRoot;
977 CString sBranchName;
979 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
981 if (sBranchName.GetLength() == 40)
983 // if SHA1 only show 4 first bytes
984 BOOL bIsSha1 = TRUE;
985 for (int i=0; i<40; i++)
986 if ( !iswxdigit(sBranchName[i]) )
988 bIsSha1 = FALSE;
989 break;
991 if (bIsSha1)
992 sBranchName = sBranchName.Left(8) + _T("....");
995 sBranchName = _T('"') + sBranchName + _T('"');
997 const int icon = IDI_COPY;
998 const int pos = indexMenu++;
999 const int id = idCmd++;
1001 MENUITEMINFO menuiteminfo;
1002 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1003 menuiteminfo.cbSize = sizeof(menuiteminfo);
1004 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_STATE;
1005 menuiteminfo.fState = MFS_DISABLED;
1006 menuiteminfo.fType = MFT_STRING;
1007 menuiteminfo.dwTypeData = (LPWSTR)sBranchName.GetString();
1008 if (icon)
1010 menuiteminfo.fMask |= MIIM_BITMAP;
1011 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
1013 if (menuiteminfo.hbmpItem == HBMMENU_CALLBACK)
1015 // WM_DRAWITEM uses myIDMap to get icon, we use the same icon as create branch
1016 myIDMap[id - idCmdFirst] = ShellMenuBranch;
1017 myIDMap[id] = ShellMenuBranch;
1020 menuiteminfo.wID = id;
1021 InsertMenuItem(hMenu, pos, TRUE, &menuiteminfo);
1024 #endif
1026 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1028 if (menuInfo[menuIndex].command == ShellSeparator)
1030 // we don't add a separator immediately. Because there might not be
1031 // another 'normal' menu entry after we insert a separator.
1032 // we simply set a flag here, indicating that before the next
1033 // 'normal' menu entry, a separator should be added.
1034 if (!bMenuEmpty)
1035 bAddSeparator = true;
1037 else
1039 // check the conditions whether to show the menu entry or not
1040 bool bInsertMenu = false;
1042 if (menuInfo[menuIndex].firstyes && menuInfo[menuIndex].firstno)
1044 if (((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes)
1046 ((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1047 bInsertMenu = true;
1049 else if ((menuInfo[menuIndex].firstyes)&&((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes))
1050 bInsertMenu = true;
1051 else if ((menuInfo[menuIndex].firstno)&&((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1052 bInsertMenu = true;
1054 if (menuInfo[menuIndex].secondyes && menuInfo[menuIndex].secondno)
1056 if (((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes)
1058 ((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1059 bInsertMenu = true;
1061 else if ((menuInfo[menuIndex].secondyes)&&((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes))
1062 bInsertMenu = true;
1063 else if ((menuInfo[menuIndex].secondno)&&((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1064 bInsertMenu = true;
1066 if (menuInfo[menuIndex].thirdyes && menuInfo[menuIndex].thirdno)
1068 if (((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes)
1070 ((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1071 bInsertMenu = true;
1073 else if ((menuInfo[menuIndex].thirdyes)&&((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes))
1074 bInsertMenu = true;
1075 else if ((menuInfo[menuIndex].thirdno)&&((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1076 bInsertMenu = true;
1078 if (menuInfo[menuIndex].fourthyes && menuInfo[menuIndex].fourthno)
1080 if (((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes)
1082 ((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1083 bInsertMenu = true;
1085 else if ((menuInfo[menuIndex].fourthyes)&&((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes))
1086 bInsertMenu = true;
1087 else if ((menuInfo[menuIndex].fourthno)&&((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1088 bInsertMenu = true;
1090 if (menuInfo[menuIndex].menuID & menuex)
1092 if( !(itemStates & ITEMIS_EXTENDED) )
1094 bInsertMenu = false;
1098 if (menuInfo[menuIndex].menuID & (~menumask))
1100 if (bInsertMenu)
1102 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1103 // insert a separator
1104 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1106 bAddSeparator = false;
1107 bMenuEntryAdded = false;
1108 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1109 idCmd++;
1112 // handle special cases (sub menus)
1113 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1115 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1117 bMenuEntryAdded = true;
1118 bMenuEmpty = false;
1121 else
1123 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1125 // insert the menu entry
1126 InsertGitMenu( bIsTop,
1127 bIsTop ? hMenu : subMenu,
1128 bIsTop ? indexMenu++ : indexSubMenu++,
1129 idCmd++,
1130 menuInfo[menuIndex].menuTextID,
1131 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1132 idCmdFirst,
1133 menuInfo[menuIndex].command,
1134 uFlags);
1135 if (!bIsTop)
1137 bMenuEntryAdded = true;
1138 bMenuEmpty = false;
1139 bAddSeparator = false;
1145 menuIndex++;
1148 //add sub menu to main context menu
1149 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1150 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1151 MAKESTRING(IDS_MENUSUBMENU);
1152 MENUITEMINFO menuiteminfo;
1153 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1154 menuiteminfo.cbSize = sizeof(menuiteminfo);
1155 menuiteminfo.fType = MFT_STRING;
1156 menuiteminfo.dwTypeData = stringtablebuffer;
1158 UINT uIcon = bShowIcons ? IDI_APP : 0;
1159 if (folder_.size())
1161 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1162 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1163 myIDMap[idCmd] = ShellSubMenuFolder;
1164 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1166 else if (!bShortcut && (files_.size()==1))
1168 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1169 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1170 myIDMap[idCmd] = ShellSubMenuFile;
1172 else if (bShortcut && (files_.size()==1))
1174 uIcon = bShowIcons ? IDI_MENULINK : 0;
1175 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1176 myIDMap[idCmd] = ShellSubMenuLink;
1178 else if (files_.size() > 1)
1180 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1181 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1182 myIDMap[idCmd] = ShellSubMenuMultiple;
1184 else
1186 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1187 myIDMap[idCmd] = ShellSubMenu;
1189 HBITMAP bmp = NULL;
1190 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1191 if (uIcon)
1193 menuiteminfo.fMask |= MIIM_BITMAP;
1194 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(uIcon) : HBMMENU_CALLBACK;
1196 menuiteminfo.hSubMenu = subMenu;
1197 menuiteminfo.wID = idCmd++;
1198 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1200 //separator after
1201 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1203 TweakMenu(hMenu);
1205 //return number of menu items added
1206 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1209 void CShellExt::TweakMenu(HMENU hMenu)
1211 MENUINFO MenuInfo = {};
1212 MenuInfo.cbSize = sizeof(MenuInfo);
1213 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1214 MenuInfo.dwStyle = MNS_CHECKORBMP;
1215 SetMenuInfo(hMenu, &MenuInfo);
1218 // This is called when you invoke a command on the menu:
1219 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1221 PreserveChdir preserveChdir;
1222 HRESULT hr = E_INVALIDARG;
1223 if (lpcmi == NULL)
1224 return hr;
1226 std::string command;
1227 std::string parent;
1228 std::string file;
1230 if ((files_.size() > 0)||(folder_.size() > 0))
1232 UINT_PTR idCmd = LOWORD(lpcmi->lpVerb);
1234 if (HIWORD(lpcmi->lpVerb))
1236 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1237 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1238 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1239 idCmd = verb_it->second;
1240 else
1241 return hr;
1244 // See if we have a handler interface for this id
1245 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1246 if (id_it != myIDMap.end() && id_it->first == idCmd)
1248 CRegStdString tortoiseProcPath(_T("Software\\TortoiseGit\\ProcPath"), _T("TortoiseProc.exe"), false, HKEY_LOCAL_MACHINE);
1249 CRegStdString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T("TortoiseMerge.exe"), false, HKEY_LOCAL_MACHINE);
1251 //TortoiseProc expects a command line of the form:
1252 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1253 // or
1254 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1256 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1257 //* pathfile is a path to a temporary file which contains a list of file paths
1258 stdstring gitCmd = _T(" /command:");
1259 stdstring tempfile;
1260 switch (id_it->second)
1262 //#region case
1263 case ShellMenuSync:
1264 gitCmd += _T("sync /path:\"");
1265 if (files_.size() > 0)
1266 gitCmd += files_.front();
1267 else
1268 gitCmd += folder_;
1269 gitCmd += _T("\"");
1270 break;
1271 case ShellMenuUpdate:
1272 tempfile = WriteFileListToTempFile();
1273 gitCmd += _T("update /pathfile:\"");
1274 gitCmd += tempfile;
1275 gitCmd += _T("\"");
1276 gitCmd += _T(" /deletepathfile");
1277 break;
1278 case ShellMenuSubSync:
1279 tempfile = WriteFileListToTempFile();
1280 gitCmd += _T("subsync /pathfile:\"");
1281 gitCmd += tempfile;
1282 gitCmd += _T("\"");
1283 gitCmd += _T(" /deletepathfile");
1284 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1286 gitCmd += _T(" /bkpath:\"");
1287 gitCmd += folder_;
1288 gitCmd += _T("\"");
1290 break;
1291 case ShellMenuUpdateExt:
1292 tempfile = WriteFileListToTempFile();
1293 gitCmd += _T("subupdate /pathfile:\"");
1294 gitCmd += tempfile;
1295 gitCmd += _T("\"");
1296 gitCmd += _T(" /deletepathfile");
1297 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1299 gitCmd += _T(" /bkpath:\"");
1300 gitCmd += folder_;
1301 gitCmd += _T("\"");
1303 break;
1304 case ShellMenuCommit:
1305 tempfile = WriteFileListToTempFile();
1306 gitCmd += _T("commit /pathfile:\"");
1307 gitCmd += tempfile;
1308 gitCmd += _T("\"");
1309 gitCmd += _T(" /deletepathfile");
1310 break;
1311 case ShellMenuAdd:
1312 case ShellMenuAddAsReplacement:
1313 tempfile = WriteFileListToTempFile();
1314 gitCmd += _T("add /pathfile:\"");
1315 gitCmd += tempfile;
1316 gitCmd += _T("\"");
1317 gitCmd += _T(" /deletepathfile");
1318 break;
1319 case ShellMenuIgnore:
1320 tempfile = WriteFileListToTempFile();
1321 gitCmd += _T("ignore /pathfile:\"");
1322 gitCmd += tempfile;
1323 gitCmd += _T("\"");
1324 gitCmd += _T(" /deletepathfile");
1325 break;
1326 case ShellMenuIgnoreCaseSensitive:
1327 tempfile = WriteFileListToTempFile();
1328 gitCmd += _T("ignore /pathfile:\"");
1329 gitCmd += tempfile;
1330 gitCmd += _T("\"");
1331 gitCmd += _T(" /deletepathfile");
1332 gitCmd += _T(" /onlymask");
1333 break;
1334 case ShellMenuDeleteIgnore:
1335 tempfile = WriteFileListToTempFile();
1336 gitCmd += _T("ignore /delete /pathfile:\"");
1337 gitCmd += tempfile;
1338 gitCmd += _T("\"");
1339 gitCmd += _T(" /deletepathfile");
1340 break;
1341 case ShellMenuDeleteIgnoreCaseSensitive:
1342 tempfile = WriteFileListToTempFile();
1343 gitCmd += _T("ignore /delete /pathfile:\"");
1344 gitCmd += tempfile;
1345 gitCmd += _T("\"");
1346 gitCmd += _T(" /deletepathfile");
1347 gitCmd += _T(" /onlymask");
1348 break;
1349 case ShellMenuUnIgnore:
1350 tempfile = WriteFileListToTempFile();
1351 gitCmd += _T("unignore /pathfile:\"");
1352 gitCmd += tempfile;
1353 gitCmd += _T("\"");
1354 gitCmd += _T(" /deletepathfile");
1355 break;
1356 case ShellMenuUnIgnoreCaseSensitive:
1357 tempfile = WriteFileListToTempFile();
1358 gitCmd += _T("unignore /pathfile:\"");
1359 gitCmd += tempfile;
1360 gitCmd += _T("\"");
1361 gitCmd += _T(" /deletepathfile");
1362 gitCmd += _T(" /onlymask");
1363 break;
1364 case ShellMenuRevert:
1365 tempfile = WriteFileListToTempFile();
1366 gitCmd += _T("revert /pathfile:\"");
1367 gitCmd += tempfile;
1368 gitCmd += _T("\"");
1369 gitCmd += _T(" /deletepathfile");
1370 break;
1371 case ShellMenuCleanup:
1372 tempfile = WriteFileListToTempFile();
1373 gitCmd += _T("cleanup /pathfile:\"");
1374 gitCmd += tempfile;
1375 gitCmd += _T("\"");
1376 gitCmd += _T(" /deletepathfile");
1377 break;
1378 case ShellMenuSendMail:
1379 tempfile = WriteFileListToTempFile();
1380 gitCmd += _T("sendmail /pathfile:\"");
1381 gitCmd += tempfile;
1382 gitCmd += _T("\"");
1383 gitCmd += _T(" /deletepathfile");
1384 break;
1385 case ShellMenuResolve:
1386 tempfile = WriteFileListToTempFile();
1387 gitCmd += _T("resolve /pathfile:\"");
1388 gitCmd += tempfile;
1389 gitCmd += _T("\"");
1390 gitCmd += _T(" /deletepathfile");
1391 break;
1392 case ShellMenuSwitch:
1393 gitCmd += _T("switch /path:\"");
1394 if (files_.size() > 0)
1395 gitCmd += files_.front();
1396 else
1397 gitCmd += folder_;
1398 gitCmd += _T("\"");
1399 break;
1400 case ShellMenuExport:
1401 gitCmd += _T("export /path:\"");
1402 if (files_.size() > 0)
1403 gitCmd += files_.front();
1404 else
1405 gitCmd += folder_;
1406 gitCmd += _T("\"");
1407 break;
1408 case ShellMenuAbout:
1409 gitCmd += _T("about");
1410 break;
1411 case ShellMenuCreateRepos:
1412 gitCmd += _T("repocreate /path:\"");
1413 if (files_.size() > 0)
1414 gitCmd += files_.front();
1415 else
1416 gitCmd += folder_;
1417 gitCmd += _T("\"");
1418 break;
1419 case ShellMenuMerge:
1420 gitCmd += _T("merge /path:\"");
1421 if (files_.size() > 0)
1422 gitCmd += files_.front();
1423 else
1424 gitCmd += folder_;
1425 gitCmd += _T("\"");
1426 break;
1427 case ShellMenuCopy:
1428 gitCmd += _T("copy /path:\"");
1429 if (files_.size() > 0)
1430 gitCmd += files_.front();
1431 else
1432 gitCmd += folder_;
1433 gitCmd += _T("\"");
1434 break;
1435 case ShellMenuSettings:
1436 gitCmd += _T("settings /path:\"");
1437 if (files_.size() > 0)
1438 gitCmd += files_.front();
1439 else
1440 gitCmd += folder_;
1441 gitCmd += _T("\"");
1442 break;
1443 case ShellMenuHelp:
1444 gitCmd += _T("help");
1445 break;
1446 case ShellMenuRename:
1447 gitCmd += _T("rename /path:\"");
1448 if (files_.size() > 0)
1449 gitCmd += files_.front();
1450 else
1451 gitCmd += folder_;
1452 gitCmd += _T("\"");
1453 break;
1454 case ShellMenuRemove:
1455 tempfile = WriteFileListToTempFile();
1456 gitCmd += _T("remove /pathfile:\"");
1457 gitCmd += tempfile;
1458 gitCmd += _T("\"");
1459 gitCmd += _T(" /deletepathfile");
1460 break;
1461 case ShellMenuRemoveKeep:
1462 tempfile = WriteFileListToTempFile();
1463 gitCmd += _T("remove /pathfile:\"");
1464 gitCmd += tempfile;
1465 gitCmd += _T("\"");
1466 gitCmd += _T(" /deletepathfile");
1467 gitCmd += _T(" /keep");
1468 break;
1469 case ShellMenuDiff:
1470 gitCmd += _T("diff /path:\"");
1471 if (files_.size() == 1)
1472 gitCmd += files_.front();
1473 else if (files_.size() == 2)
1475 std::vector<stdstring>::iterator I = files_.begin();
1476 gitCmd += *I;
1477 I++;
1478 gitCmd += _T("\" /path2:\"");
1479 gitCmd += *I;
1481 else
1482 gitCmd += folder_;
1483 gitCmd += _T("\"");
1484 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1485 gitCmd += _T(" /alternative");
1486 break;
1487 case ShellMenuPrevDiff:
1488 gitCmd += _T("prevdiff /path:\"");
1489 if (files_.size() == 1)
1490 gitCmd += files_.front();
1491 else
1492 gitCmd += folder_;
1493 gitCmd += _T("\"");
1494 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1495 gitCmd += _T(" /alternative");
1496 break;
1497 case ShellMenuDiffTwo:
1498 gitCmd += _T("diffcommits /path:\"");
1499 if (files_.size() == 1)
1500 gitCmd += files_.front();
1501 else
1502 gitCmd += folder_;
1503 gitCmd += _T("\"");
1504 break;
1505 case ShellMenuDropCopyAdd:
1506 tempfile = WriteFileListToTempFile();
1507 gitCmd += _T("dropcopyadd /pathfile:\"");
1508 gitCmd += tempfile;
1509 gitCmd += _T("\"");
1510 gitCmd += _T(" /deletepathfile");
1511 gitCmd += _T(" /droptarget:\"");
1512 gitCmd += folder_;
1513 gitCmd += _T("\"";)
1514 break;
1515 case ShellMenuDropCopy:
1516 tempfile = WriteFileListToTempFile();
1517 gitCmd += _T("dropcopy /pathfile:\"");
1518 gitCmd += tempfile;
1519 gitCmd += _T("\"");
1520 gitCmd += _T(" /deletepathfile");
1521 gitCmd += _T(" /droptarget:\"");
1522 gitCmd += folder_;
1523 gitCmd += _T("\"";)
1524 break;
1525 case ShellMenuDropCopyRename:
1526 tempfile = WriteFileListToTempFile();
1527 gitCmd += _T("dropcopy /pathfile:\"");
1528 gitCmd += tempfile;
1529 gitCmd += _T("\"");
1530 gitCmd += _T(" /deletepathfile");
1531 gitCmd += _T(" /droptarget:\"");
1532 gitCmd += folder_;
1533 gitCmd += _T("\" /rename";)
1534 break;
1535 case ShellMenuDropMove:
1536 tempfile = WriteFileListToTempFile();
1537 gitCmd += _T("dropmove /pathfile:\"");
1538 gitCmd += tempfile;
1539 gitCmd += _T("\"");
1540 gitCmd += _T(" /deletepathfile");
1541 gitCmd += _T(" /droptarget:\"");
1542 gitCmd += folder_;
1543 gitCmd += _T("\"");
1544 break;
1545 case ShellMenuDropMoveRename:
1546 tempfile = WriteFileListToTempFile();
1547 gitCmd += _T("dropmove /pathfile:\"");
1548 gitCmd += tempfile;
1549 gitCmd += _T("\"");
1550 gitCmd += _T(" /deletepathfile");
1551 gitCmd += _T(" /droptarget:\"");
1552 gitCmd += folder_;
1553 gitCmd += _T("\" /rename";)
1554 break;
1555 case ShellMenuDropExport:
1556 tempfile = WriteFileListToTempFile();
1557 gitCmd += _T("dropexport /pathfile:\"");
1558 gitCmd += tempfile;
1559 gitCmd += _T("\"");
1560 gitCmd += _T(" /deletepathfile");
1561 gitCmd += _T(" /droptarget:\"");
1562 gitCmd += folder_;
1563 gitCmd += _T("\"");
1564 break;
1565 case ShellMenuDropExportExtended:
1566 tempfile = WriteFileListToTempFile();
1567 gitCmd += _T("dropexport /pathfile:\"");
1568 gitCmd += tempfile;
1569 gitCmd += _T("\"");
1570 gitCmd += _T(" /deletepathfile");
1571 gitCmd += _T(" /droptarget:\"");
1572 gitCmd += folder_;
1573 gitCmd += _T("\"");
1574 gitCmd += _T(" /extended");
1575 break;
1576 case ShellMenuLog:
1577 gitCmd += _T("log /path:\"");
1578 if (files_.size() > 0)
1579 gitCmd += files_.front();
1580 else
1581 gitCmd += folder_;
1582 gitCmd += _T("\"");
1583 break;
1584 case ShellMenuConflictEditor:
1585 gitCmd += _T("conflicteditor /path:\"");
1586 if (files_.size() > 0)
1587 gitCmd += files_.front();
1588 else
1589 gitCmd += folder_;
1590 gitCmd += _T("\"");
1591 break;
1592 case ShellMenuGitSVNRebase:
1593 gitCmd += _T("svnrebase /path:\"");
1594 if (files_.size() > 0)
1595 gitCmd += files_.front();
1596 else
1597 gitCmd += folder_;
1598 gitCmd += _T("\"");
1599 break;
1600 case ShellMenuGitSVNDCommit:
1601 gitCmd += _T("svndcommit /path:\"");
1602 if (files_.size() > 0)
1603 gitCmd += files_.front();
1604 else
1605 gitCmd += folder_;
1606 gitCmd += _T("\"");
1607 break;
1608 case ShellMenuGitSVNDFetch:
1609 gitCmd += _T("svnfetch /path:\"");
1610 if (files_.size() > 0)
1611 gitCmd += files_.front();
1612 else
1613 gitCmd += folder_;
1614 gitCmd += _T("\"");
1615 break;
1616 case ShellMenuGitSVNIgnore:
1617 gitCmd += _T("svnignore /path:\"");
1618 if (files_.size() > 0)
1619 gitCmd += files_.front();
1620 else
1621 gitCmd += folder_;
1622 gitCmd += _T("\"");
1623 break;
1624 case ShellMenuRebase:
1625 gitCmd += _T("rebase /path:\"");
1626 if (files_.size() > 0)
1627 gitCmd += files_.front();
1628 else
1629 gitCmd += folder_;
1630 gitCmd += _T("\"");
1631 break;
1632 case ShellMenuShowChanged:
1633 if (files_.size() > 1)
1635 tempfile = WriteFileListToTempFile();
1636 gitCmd += _T("repostatus /pathfile:\"");
1637 gitCmd += tempfile;
1638 gitCmd += _T("\"");
1639 gitCmd += _T(" /deletepathfile");
1641 else
1643 gitCmd += _T("repostatus /path:\"");
1644 if (files_.size() > 0)
1645 gitCmd += files_.front();
1646 else
1647 gitCmd += folder_;
1648 gitCmd += _T("\"");
1650 break;
1651 case ShellMenuRepoBrowse:
1652 gitCmd += _T("repobrowser /path:\"") + folder_ + _T("\"");
1653 break;
1654 case ShellMenuRefBrowse:
1655 gitCmd += _T("refbrowse /path:\"");
1656 if (files_.size() > 0)
1657 gitCmd += files_.front();
1658 else
1659 gitCmd += folder_;
1660 gitCmd += _T("\"");
1661 break;
1662 case ShellMenuRefLog:
1663 gitCmd += _T("reflog /path:\"");
1664 if (files_.size() > 0)
1665 gitCmd += files_.front();
1666 else
1667 gitCmd += folder_;
1668 gitCmd += _T("\"");
1669 break;
1671 case ShellMenuStashSave:
1672 gitCmd += _T("stashsave /path:\"");
1673 if (files_.size() > 0)
1674 gitCmd += files_.front();
1675 else
1676 gitCmd += folder_;
1677 gitCmd += _T("\"");
1678 break;
1680 case ShellMenuStashApply:
1681 gitCmd += _T("stashapply /path:\"");
1682 if (files_.size() > 0)
1683 gitCmd += files_.front();
1684 else
1685 gitCmd += folder_;
1686 gitCmd += _T("\"");
1687 break;
1689 case ShellMenuStashPop:
1690 gitCmd += _T("stashpop /path:\"");
1691 if (files_.size() > 0)
1692 gitCmd += files_.front();
1693 else
1694 gitCmd += folder_;
1695 gitCmd += _T("\"");
1696 break;
1699 case ShellMenuStashList:
1700 gitCmd += _T("reflog /path:\"");
1701 if (files_.size() > 0)
1702 gitCmd += files_.front();
1703 else
1704 gitCmd += folder_;
1705 gitCmd += _T("\" /ref:refs/stash");
1706 break;
1708 case ShellMenuBisectStart:
1709 gitCmd += _T("bisect /path:\"");
1710 if (files_.size() > 0)
1711 gitCmd += files_.front();
1712 else
1713 gitCmd += folder_;
1714 gitCmd += _T("\" /start");
1715 break;
1717 case ShellMenuBisectGood:
1718 gitCmd += _T("bisect /path:\"");
1719 if (files_.size() > 0)
1720 gitCmd += files_.front();
1721 else
1722 gitCmd += folder_;
1723 gitCmd += _T("\" /good");
1724 break;
1727 case ShellMenuBisectBad:
1728 gitCmd += _T("bisect /path:\"");
1729 if (files_.size() > 0)
1730 gitCmd += files_.front();
1731 else
1732 gitCmd += folder_;
1733 gitCmd += _T("\" /bad");
1734 break;
1736 case ShellMenuBisectReset:
1737 gitCmd += _T("bisect /path:\"");
1738 if (files_.size() > 0)
1739 gitCmd += files_.front();
1740 else
1741 gitCmd += folder_;
1742 gitCmd += _T("\" /reset");
1743 break;
1745 case ShellMenuSubAdd:
1746 gitCmd += _T("subadd /path:\"");
1747 if (files_.size() > 0)
1748 gitCmd += files_.front();
1749 else
1750 gitCmd += folder_;
1751 gitCmd += _T("\"");
1752 break;
1754 case ShellMenuBlame:
1755 gitCmd += _T("blame /path:\"");
1756 if (files_.size() > 0)
1757 gitCmd += files_.front();
1758 else
1759 gitCmd += folder_;
1760 gitCmd += _T("\"");
1761 break;
1762 case ShellMenuApplyPatch:
1763 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1765 // if there's a patch file in the clipboard, we save it
1766 // to a temporary file and tell TortoiseMerge to use that one
1767 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1768 if ((cFormat)&&(OpenClipboard(NULL)))
1770 HGLOBAL hglb = GetClipboardData(cFormat);
1771 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1773 DWORD len = GetTempPath(0, NULL);
1774 TCHAR * path = new TCHAR[len+1];
1775 TCHAR * tempF = new TCHAR[len+100];
1776 GetTempPath (len+1, path);
1777 GetTempFileName (path, TEXT("git"), 0, tempF);
1778 std::wstring sTempFile = std::wstring(tempF);
1779 delete [] path;
1780 delete [] tempF;
1782 FILE * outFile;
1783 size_t patchlen = strlen(lpstr);
1784 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1785 if(outFile)
1787 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1788 if (size == patchlen)
1790 itemStates |= ITEMIS_PATCHFILE;
1791 files_.clear();
1792 files_.push_back(sTempFile);
1794 fclose(outFile);
1796 GlobalUnlock(hglb);
1797 CloseClipboard();
1800 if (itemStates & ITEMIS_PATCHFILE)
1802 gitCmd = _T(" /diff:\"");
1803 if (files_.size() > 0)
1805 gitCmd += files_.front();
1806 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1808 gitCmd += _T("\" /patchpath:\"");
1809 gitCmd += folder_;
1812 else
1813 gitCmd += folder_;
1814 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1815 gitCmd += _T("\" /wc");
1816 else
1817 gitCmd += _T("\"");
1819 else
1821 gitCmd = _T(" /patchpath:\"");
1822 if (files_.size() > 0)
1823 gitCmd += files_.front();
1824 else
1825 gitCmd += folder_;
1826 gitCmd += _T("\"");
1828 myIDMap.clear();
1829 myVerbsIDMap.clear();
1830 myVerbsMap.clear();
1831 RunCommand(tortoiseMergePath, gitCmd, _T("TortoiseMerge launch failed"));
1832 return S_OK;
1833 break;
1834 case ShellMenuProperties:
1835 tempfile = WriteFileListToTempFile();
1836 gitCmd += _T("properties /pathfile:\"");
1837 gitCmd += tempfile;
1838 gitCmd += _T("\"");
1839 gitCmd += _T(" /deletepathfile");
1840 break;
1841 case ShellMenuClipPaste:
1842 if (WriteClipboardPathsToTempFile(tempfile))
1844 bool bCopy = true;
1845 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1846 if (cPrefDropFormat)
1848 if (OpenClipboard(lpcmi->hwnd))
1850 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1851 if (hglb)
1853 DWORD* effect = (DWORD*) GlobalLock(hglb);
1854 if (*effect == DROPEFFECT_MOVE)
1855 bCopy = false;
1856 GlobalUnlock(hglb);
1858 CloseClipboard();
1862 if (bCopy)
1863 gitCmd += _T("pastecopy /pathfile:\"");
1864 else
1865 gitCmd += _T("pastemove /pathfile:\"");
1866 gitCmd += tempfile;
1867 gitCmd += _T("\"");
1868 gitCmd += _T(" /deletepathfile");
1869 gitCmd += _T(" /droptarget:\"");
1870 gitCmd += folder_;
1871 gitCmd += _T("\"");
1873 else return S_OK;
1874 break;
1875 case ShellMenuClone:
1876 gitCmd += _T("clone /path:\"");
1877 if (files_.size() > 0)
1878 gitCmd += files_.front();
1879 else
1880 gitCmd += folder_;
1881 gitCmd += _T("\"");
1882 break;
1883 case ShellMenuPull:
1884 gitCmd += _T("pull /path:\"");
1885 if (files_.size() > 0)
1886 gitCmd += files_.front();
1887 else
1888 gitCmd += folder_;
1889 gitCmd += _T("\"");
1890 break;
1891 case ShellMenuPush:
1892 gitCmd += _T("push /path:\"");
1893 if (files_.size() > 0)
1894 gitCmd += files_.front();
1895 else
1896 gitCmd += folder_;
1897 gitCmd += _T("\"");
1898 break;
1899 case ShellMenuBranch:
1900 gitCmd += _T("branch /path:\"");
1901 if (files_.size() > 0)
1902 gitCmd += files_.front();
1903 else
1904 gitCmd += folder_;
1905 gitCmd += _T("\"");
1906 break;
1908 case ShellMenuTag:
1909 gitCmd += _T("tag /path:\"");
1910 if (files_.size() > 0)
1911 gitCmd += files_.front();
1912 else
1913 gitCmd += folder_;
1914 gitCmd += _T("\"");
1915 break;
1917 case ShellMenuFormatPatch:
1918 gitCmd += _T("formatpatch /path:\"");
1919 if (files_.size() > 0)
1920 gitCmd += files_.front();
1921 else
1922 gitCmd += folder_;
1923 gitCmd += _T("\"");
1924 break;
1926 case ShellMenuImportPatch:
1927 tempfile = WriteFileListToTempFile();
1928 gitCmd += _T("importpatch /pathfile:\"");
1929 gitCmd += tempfile;
1930 gitCmd += _T("\"");
1931 gitCmd += _T(" /deletepathfile");
1932 break;
1934 case ShellMenuCherryPick:
1935 gitCmd += _T("cherrypick /path:\"");
1936 if (files_.size() > 0)
1937 gitCmd += files_.front();
1938 else
1939 gitCmd += folder_;
1940 gitCmd += _T("\"");
1941 break;
1942 case ShellMenuFetch:
1943 gitCmd += _T("fetch /path:\"");
1944 if (files_.size() > 0)
1945 gitCmd += files_.front();
1946 else
1947 gitCmd += folder_;
1948 gitCmd += _T("\"");
1949 break;
1951 default:
1952 break;
1953 //#endregion
1954 } // switch (id_it->second)
1955 gitCmd += _T(" /hwnd:");
1956 TCHAR buf[30];
1957 _stprintf_s(buf, 30, _T("%d"), lpcmi->hwnd);
1958 gitCmd += buf;
1959 myIDMap.clear();
1960 myVerbsIDMap.clear();
1961 myVerbsMap.clear();
1962 RunCommand(tortoiseProcPath, gitCmd, _T("TortoiseProc launch failed"));
1963 hr = S_OK;
1964 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
1965 } // if ((files_.size() > 0)||(folder_.size() > 0))
1966 return hr;
1970 // This is for the status bar and things like that:
1971 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
1972 UINT uFlags,
1973 UINT FAR * /*reserved*/,
1974 LPSTR pszName,
1975 UINT cchMax)
1977 PreserveChdir preserveChdir;
1978 //do we know the id?
1979 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1980 if (id_it == myIDMap.end() || id_it->first != idCmd)
1982 return E_INVALIDARG; //no, we don't
1985 LoadLangDll();
1986 HRESULT hr = E_INVALIDARG;
1988 MAKESTRING(IDS_MENUDESCDEFAULT);
1989 int menuIndex = 0;
1990 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1992 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
1994 MAKESTRING(menuInfo[menuIndex].menuDescID);
1995 break;
1997 menuIndex++;
2000 const TCHAR * desc = stringtablebuffer;
2001 switch(uFlags)
2003 case GCS_HELPTEXTA:
2005 std::string help = WideToMultibyte(desc);
2006 lstrcpynA(pszName, help.c_str(), cchMax);
2007 hr = S_OK;
2008 break;
2010 case GCS_HELPTEXTW:
2012 wide_string help = desc;
2013 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2014 hr = S_OK;
2015 break;
2017 case GCS_VERBA:
2019 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2020 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2022 std::string help = WideToMultibyte(verb_id_it->second);
2023 lstrcpynA(pszName, help.c_str(), cchMax);
2024 hr = S_OK;
2027 break;
2028 case GCS_VERBW:
2030 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2031 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2033 wide_string help = verb_id_it->second;
2034 ATLTRACE("verb : %ws\n", help.c_str());
2035 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2036 hr = S_OK;
2039 break;
2041 return hr;
2044 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
2046 LRESULT res;
2047 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
2050 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
2052 PreserveChdir preserveChdir;
2054 LRESULT res;
2055 if (pResult == NULL)
2056 pResult = &res;
2057 *pResult = FALSE;
2059 LoadLangDll();
2060 switch (uMsg)
2062 case WM_MEASUREITEM:
2064 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
2065 if (lpmis==NULL)
2066 break;
2067 lpmis->itemWidth = 16;
2068 lpmis->itemHeight = 16;
2069 *pResult = TRUE;
2071 break;
2072 case WM_DRAWITEM:
2074 LPCTSTR resource;
2075 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
2076 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
2077 return S_OK; //not for a menu
2078 resource = GetMenuTextFromResource((int)myIDMap[lpdis->itemID]);
2079 if (resource == NULL)
2080 return S_OK;
2081 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2082 if (hIcon == NULL)
2083 return S_OK;
2084 DrawIconEx(lpdis->hDC,
2085 lpdis->rcItem.left,
2086 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
2087 hIcon, 16, 16,
2088 0, NULL, DI_NORMAL);
2089 DestroyIcon(hIcon);
2090 *pResult = TRUE;
2092 break;
2093 case WM_MENUCHAR:
2095 LPCTSTR resource;
2096 TCHAR *szItem;
2097 if (HIWORD(wParam) != MF_POPUP)
2098 return S_OK;
2099 int nChar = LOWORD(wParam);
2100 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
2101 nChar = tolower(nChar);
2102 // we have the char the user pressed, now search that char in all our
2103 // menu items
2104 std::vector<UINT_PTR> accmenus;
2105 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
2107 resource = GetMenuTextFromResource((int)mySubMenuMap[It->first]);
2108 if (resource == NULL)
2109 continue;
2110 szItem = stringtablebuffer;
2111 TCHAR * amp = _tcschr(szItem, '&');
2112 if (amp == NULL)
2113 continue;
2114 amp++;
2115 int ampChar = LOWORD(*amp);
2116 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
2117 ampChar = tolower(ampChar);
2118 if (ampChar == nChar)
2120 // yep, we found a menu which has the pressed key
2121 // as an accelerator. Add that menu to the list to
2122 // process later.
2123 accmenus.push_back(It->first);
2126 if (accmenus.size() == 0)
2128 // no menu with that accelerator key.
2129 *pResult = MAKELONG(0, MNC_IGNORE);
2130 return S_OK;
2132 if (accmenus.size() == 1)
2134 // Only one menu with that accelerator key. We're lucky!
2135 // So just execute that menu entry.
2136 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
2137 return S_OK;
2139 if (accmenus.size() > 1)
2141 // we have more than one menu item with this accelerator key!
2142 MENUITEMINFO mif;
2143 mif.cbSize = sizeof(MENUITEMINFO);
2144 mif.fMask = MIIM_STATE;
2145 for (std::vector<UINT_PTR>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
2147 GetMenuItemInfo((HMENU)lParam, (UINT)*it, TRUE, &mif);
2148 if (mif.fState == MFS_HILITE)
2150 // this is the selected item, so select the next one
2151 ++it;
2152 if (it == accmenus.end())
2153 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2154 else
2155 *pResult = MAKELONG(*it, MNC_SELECT);
2156 return S_OK;
2159 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2162 break;
2163 default:
2164 return S_OK;
2167 return S_OK;
2170 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
2172 TCHAR textbuf[255];
2173 LPCTSTR resource = NULL;
2174 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
2175 space = 6;
2177 int menuIndex = 0;
2178 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2180 if (menuInfo[menuIndex].command == id)
2182 MAKESTRING(menuInfo[menuIndex].menuTextID);
2183 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
2184 switch (id)
2186 case ShellSubMenuMultiple:
2187 case ShellSubMenuLink:
2188 case ShellSubMenuFolder:
2189 case ShellSubMenuFile:
2190 case ShellSubMenu:
2191 space = 0;
2192 break;
2193 default:
2194 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
2195 if (layout & (menuInfo[menuIndex].menuID))
2197 _tcscpy_s(textbuf, 255, _T("Git "));
2198 _tcscat_s(textbuf, 255, stringtablebuffer);
2199 _tcscpy_s(stringtablebuffer, 255, textbuf);
2201 break;
2203 return resource;
2205 menuIndex++;
2207 return NULL;
2210 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
2212 int i=0;
2213 TCHAR buf[MAX_PATH]; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
2214 LPITEMIDLIST pidl = NULL;
2215 while (cslidarray[i])
2217 ++i;
2218 pidl = NULL;
2219 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
2220 continue;
2221 if (!SHGetPathFromIDList(pidl, buf))
2223 // not a file system path, definitely illegal for our use
2224 CoTaskMemFree(pidl);
2225 continue;
2227 CoTaskMemFree(pidl);
2228 if (_tcslen(buf)==0)
2229 continue;
2230 if (_tcscmp(buf, folder.c_str())==0)
2231 return true;
2233 return false;
2236 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT uFlags)
2238 HMENU ignoresubmenu = NULL;
2239 int indexignoresub = 0;
2240 bool bShowIgnoreMenu = false;
2241 TCHAR maskbuf[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2242 TCHAR ignorepath[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2243 if (files_.size() == 0)
2244 return false;
2245 UINT icon = bShowIcons ? IDI_IGNORE : 0;
2247 std::vector<stdstring>::iterator I = files_.begin();
2248 if (_tcsrchr(I->c_str(), '\\'))
2249 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
2250 else
2251 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
2252 if ((itemStates & ITEMIS_IGNORED)&&(ignoredprops.size() > 0))
2254 // check if the item name is ignored or the mask
2255 size_t p = 0;
2256 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
2258 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
2259 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
2261 break;
2263 p++;
2265 if (p!=-1)
2267 ignoresubmenu = CreateMenu();
2268 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2269 stdstring verb = stdstring(ignorepath);
2270 myVerbsMap[verb] = idCmd - idCmdFirst;
2271 myVerbsMap[verb] = idCmd;
2272 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2273 myVerbsIDMap[idCmd] = verb;
2274 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
2275 myIDMap[idCmd++] = ShellMenuUnIgnore;
2276 bShowIgnoreMenu = true;
2278 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2279 if (_tcsrchr(ignorepath, '.'))
2281 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2282 p = ignoredprops.find(maskbuf);
2283 if ((p!=-1) &&
2284 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
2286 if (ignoresubmenu==NULL)
2287 ignoresubmenu = CreateMenu();
2289 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2290 stdstring verb = stdstring(maskbuf);
2291 myVerbsMap[verb] = idCmd - idCmdFirst;
2292 myVerbsMap[verb] = idCmd;
2293 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2294 myVerbsIDMap[idCmd] = verb;
2295 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
2296 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
2297 bShowIgnoreMenu = true;
2301 else if ((itemStates & ITEMIS_IGNORED) == 0)
2303 bShowIgnoreMenu = true;
2304 ignoresubmenu = CreateMenu();
2305 if (itemStates & ITEMIS_ONLYONE)
2307 if (itemStates & ITEMIS_INGIT)
2309 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2310 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2311 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2313 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2314 if (_tcsrchr(ignorepath, '.'))
2316 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2317 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2318 stdstring verb = stdstring(maskbuf);
2319 myVerbsMap[verb] = idCmd - idCmdFirst;
2320 myVerbsMap[verb] = idCmd;
2321 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2322 myVerbsIDMap[idCmd] = verb;
2323 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2324 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2327 else
2329 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2330 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2331 myIDMap[idCmd++] = ShellMenuIgnore;
2333 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2334 if (_tcsrchr(ignorepath, '.'))
2336 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2337 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2338 stdstring verb = stdstring(maskbuf);
2339 myVerbsMap[verb] = idCmd - idCmdFirst;
2340 myVerbsMap[verb] = idCmd;
2341 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2342 myVerbsIDMap[idCmd] = verb;
2343 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2344 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2348 else
2350 if (itemStates & ITEMIS_INGIT)
2352 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
2353 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2354 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2355 stdstring verb = stdstring(ignorepath);
2356 myVerbsMap[verb] = idCmd - idCmdFirst;
2357 myVerbsMap[verb] = idCmd;
2358 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2359 myVerbsIDMap[idCmd] = verb;
2360 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2361 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2363 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
2364 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2365 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2366 verb = stdstring(ignorepath);
2367 myVerbsMap[verb] = idCmd - idCmdFirst;
2368 myVerbsMap[verb] = idCmd;
2369 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2370 myVerbsIDMap[idCmd] = verb;
2371 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2372 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2374 else
2376 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2377 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2378 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2379 stdstring verb = stdstring(ignorepath);
2380 myVerbsMap[verb] = idCmd - idCmdFirst;
2381 myVerbsMap[verb] = idCmd;
2382 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2383 myVerbsIDMap[idCmd] = verb;
2384 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2385 myIDMap[idCmd++] = ShellMenuIgnore;
2387 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2388 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2389 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2390 verb = stdstring(ignorepath);
2391 myVerbsMap[verb] = idCmd - idCmdFirst;
2392 myVerbsMap[verb] = idCmd;
2393 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2394 myVerbsIDMap[idCmd] = verb;
2395 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2396 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2401 if (bShowIgnoreMenu)
2403 MENUITEMINFO menuiteminfo;
2404 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2405 menuiteminfo.cbSize = sizeof(menuiteminfo);
2406 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2407 if (icon)
2409 menuiteminfo.fMask |= MIIM_BITMAP;
2410 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
2412 menuiteminfo.fType = MFT_STRING;
2413 menuiteminfo.hSubMenu = ignoresubmenu;
2414 menuiteminfo.wID = idCmd;
2415 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2416 if (itemStates & ITEMIS_IGNORED)
2417 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2418 else if (itemStates & ITEMIS_INGIT)
2419 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2420 else
2421 GetMenuTextFromResource(ShellMenuIgnoreSub);
2422 menuiteminfo.dwTypeData = stringtablebuffer;
2423 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2425 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2426 if (itemStates & ITEMIS_IGNORED)
2428 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2429 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2431 else
2433 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2434 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2437 return bShowIgnoreMenu;
2440 HBITMAP CShellExt::IconToBitmapPARGB32(UINT uIcon)
2442 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
2443 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
2444 return bitmap_it->second;
2446 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2447 if (!hIcon)
2448 return NULL;
2450 if (pfnBeginBufferedPaint == NULL || pfnEndBufferedPaint == NULL || pfnGetBufferedPaintBits == NULL)
2451 return NULL;
2453 SIZE sizIcon;
2454 sizIcon.cx = GetSystemMetrics(SM_CXSMICON);
2455 sizIcon.cy = GetSystemMetrics(SM_CYSMICON);
2457 RECT rcIcon;
2458 SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy);
2459 HBITMAP hBmp = NULL;
2461 HDC hdcDest = CreateCompatibleDC(NULL);
2462 if (hdcDest)
2464 if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp)))
2466 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp);
2467 if (hbmpOld)
2469 BLENDFUNCTION bfAlpha = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2470 BP_PAINTPARAMS paintParams = {0};
2471 paintParams.cbSize = sizeof(paintParams);
2472 paintParams.dwFlags = BPPF_ERASE;
2473 paintParams.pBlendFunction = &bfAlpha;
2475 HDC hdcBuffer;
2476 HPAINTBUFFER hPaintBuffer = pfnBeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer);
2477 if (hPaintBuffer)
2479 if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL))
2481 // If icon did not have an alpha channel we need to convert buffer to PARGB
2482 ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon);
2485 // This will write the buffer contents to the destination bitmap
2486 pfnEndBufferedPaint(hPaintBuffer, TRUE);
2489 SelectObject(hdcDest, hbmpOld);
2493 DeleteDC(hdcDest);
2496 DestroyIcon(hIcon);
2498 if(hBmp)
2499 bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp));
2500 return hBmp;
2503 HRESULT CShellExt::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP* phBmp)
2505 *phBmp = NULL;
2507 BITMAPINFO bmi;
2508 ZeroMemory(&bmi, sizeof(bmi));
2509 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2510 bmi.bmiHeader.biPlanes = 1;
2511 bmi.bmiHeader.biCompression = BI_RGB;
2513 bmi.bmiHeader.biWidth = psize->cx;
2514 bmi.bmiHeader.biHeight = psize->cy;
2515 bmi.bmiHeader.biBitCount = 32;
2517 HDC hdcUsed = hdc ? hdc : GetDC(NULL);
2518 if (hdcUsed)
2520 *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0);
2521 if (hdc != hdcUsed)
2523 ReleaseDC(NULL, hdcUsed);
2526 return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK;
2529 HRESULT CShellExt::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon)
2531 RGBQUAD *prgbQuad;
2532 int cxRow;
2533 HRESULT hr = pfnGetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow);
2534 if (SUCCEEDED(hr))
2536 ARGB *pargb = reinterpret_cast<ARGB *>(prgbQuad);
2537 if (!HasAlpha(pargb, sizIcon, cxRow))
2539 ICONINFO info;
2540 if (GetIconInfo(hicon, &info))
2542 if (info.hbmMask)
2544 hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow);
2547 DeleteObject(info.hbmColor);
2548 DeleteObject(info.hbmMask);
2553 return hr;
2556 bool CShellExt::HasAlpha(__in ARGB *pargb, SIZE& sizImage, int cxRow)
2558 ULONG cxDelta = cxRow - sizImage.cx;
2559 for (ULONG y = sizImage.cy; y; --y)
2561 for (ULONG x = sizImage.cx; x; --x)
2563 if (*pargb++ & 0xFF000000)
2565 return true;
2569 pargb += cxDelta;
2572 return false;
2575 HRESULT CShellExt::ConvertToPARGB32(HDC hdc, __inout ARGB *pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow)
2577 BITMAPINFO bmi;
2578 ZeroMemory(&bmi, sizeof(bmi));
2579 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2580 bmi.bmiHeader.biPlanes = 1;
2581 bmi.bmiHeader.biCompression = BI_RGB;
2583 bmi.bmiHeader.biWidth = sizImage.cx;
2584 bmi.bmiHeader.biHeight = sizImage.cy;
2585 bmi.bmiHeader.biBitCount = 32;
2587 HRESULT hr = E_OUTOFMEMORY;
2588 HANDLE hHeap = GetProcessHeap();
2589 void *pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight);
2590 if (pvBits)
2592 hr = E_UNEXPECTED;
2593 if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight)
2595 ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth;
2596 ARGB *pargbMask = static_cast<ARGB *>(pvBits);
2598 for (ULONG y = bmi.bmiHeader.biHeight; y; --y)
2600 for (ULONG x = bmi.bmiHeader.biWidth; x; --x)
2602 if (*pargbMask++)
2604 // transparent pixel
2605 *pargb++ = 0;
2607 else
2609 // opaque pixel
2610 *pargb++ |= 0xFF000000;
2614 pargb += cxDelta;
2617 hr = S_OK;
2620 HeapFree(hHeap, 0, pvBits);
2623 return hr;
2626 void CShellExt::RunCommand(const tstring& path, const tstring& command, LPCTSTR errorMessage)
2628 if (CCreateProcessHelper::CreateProcessDetached(path.c_str(), const_cast<TCHAR*>(command.c_str())))
2630 // process started - exit
2631 return;
2634 MessageBox(NULL, CFormatMessageWrapper(), errorMessage, MB_OK | MB_ICONINFORMATION);