deduplicate CreateProcess code
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blob5b0cb9413ff2ddccd7d37d342a89799e6a046b17
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2011 - TortoiseSVN
4 // Copyright (C) 2008-2011 - 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 NOERROR;
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 = 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 HANDLE 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 == INVALID_HANDLE_VALUE)
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(), 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();
720 ::CloseHandle(file);
722 return bRet;
725 stdstring CShellExt::WriteFileListToTempFile()
727 //write all selected files and paths to a temporary file
728 //for TortoiseProc.exe to read out again.
729 DWORD pathlength = GetTempPath(0, NULL);
730 TCHAR * path = new TCHAR[pathlength+1];
731 TCHAR * tempFile = new TCHAR[pathlength + 100];
732 GetTempPath (pathlength+1, path);
733 GetTempFileName (path, _T("git"), 0, tempFile);
734 stdstring retFilePath = stdstring(tempFile);
736 HANDLE file = ::CreateFile (tempFile,
737 GENERIC_WRITE,
738 FILE_SHARE_READ,
740 CREATE_ALWAYS,
741 FILE_ATTRIBUTE_TEMPORARY,
744 delete [] path;
745 delete [] tempFile;
746 if (file == INVALID_HANDLE_VALUE)
747 return stdstring();
749 DWORD written = 0;
750 if (files_.empty())
752 ::WriteFile (file, folder_.c_str(), folder_.size()*sizeof(TCHAR), &written, 0);
753 ::WriteFile (file, _T("\n"), 2, &written, 0);
756 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
758 ::WriteFile (file, I->c_str(), I->size()*sizeof(TCHAR), &written, 0);
759 ::WriteFile (file, _T("\n"), 2, &written, 0);
761 ::CloseHandle(file);
762 return retFilePath;
765 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
767 PreserveChdir preserveChdir;
768 LoadLangDll();
770 if ((uFlags & CMF_DEFAULTONLY)!=0)
771 return NOERROR; //we don't change the default action
773 if ((files_.size() == 0)||(folder_.size() == 0))
774 return NOERROR;
776 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
777 return NOERROR;
779 if (itemStatesFolder & ITEMIS_FOLDER) // we do not support folders atm, see issue #963
780 return NOERROR;
782 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
784 //the drop handler only has eight commands, but not all are visible at the same time:
785 //if the source file(s) are under version control then those files can be moved
786 //to the new location or they can be moved with a rename,
787 //if they are unversioned then they can be added to the working copy
788 //if they are versioned, they also can be exported to an unversioned location
789 UINT idCmd = idCmdFirst;
791 // Git move here
792 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
793 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
794 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
796 // Git move and rename here
797 // 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
798 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
799 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
801 // Git copy here
802 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
803 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
804 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
806 // Git copy and rename here, source and target from same repository
807 // available if source is a single, versioned but not added item, target is versioned or target folder is added
808 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
809 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
811 // Git add here
812 // available if target is versioned and source is either unversioned or from another repository
813 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
814 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
816 // Git export here
817 // available if source is versioned and a folder
818 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
819 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
821 // Git export all here
822 // available if source is versioned and a folder
823 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
824 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
826 // apply patch
827 // available if source is a patchfile
828 if (itemStates & ITEMIS_PATCHFILE)
829 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
831 // separator
832 if (idCmd != idCmdFirst)
833 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
835 TweakMenu(hMenu);
837 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
840 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
841 UINT indexMenu,
842 UINT idCmdFirst,
843 UINT /*idCmdLast*/,
844 UINT uFlags)
846 ATLTRACE("Shell :: QueryContextMenu\n");
847 PreserveChdir preserveChdir;
849 //first check if our drop handler is called
850 //and then (if true) provide the context menu for the
851 //drop handler
852 if (m_State == FileStateDropHandler)
854 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
857 if ((uFlags & CMF_DEFAULTONLY)!=0)
858 return NOERROR; //we don't change the default action
860 if ((files_.size() == 0)&&(folder_.size() == 0))
861 return NOERROR;
863 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
864 return NOERROR;
866 int csidlarray[] =
868 CSIDL_BITBUCKET,
869 CSIDL_CDBURN_AREA,
870 CSIDL_COMMON_FAVORITES,
871 CSIDL_COMMON_STARTMENU,
872 CSIDL_COMPUTERSNEARME,
873 CSIDL_CONNECTIONS,
874 CSIDL_CONTROLS,
875 CSIDL_COOKIES,
876 CSIDL_FAVORITES,
877 CSIDL_FONTS,
878 CSIDL_HISTORY,
879 CSIDL_INTERNET,
880 CSIDL_INTERNET_CACHE,
881 CSIDL_NETHOOD,
882 CSIDL_NETWORK,
883 CSIDL_PRINTERS,
884 CSIDL_PRINTHOOD,
885 CSIDL_RECENT,
886 CSIDL_SENDTO,
887 CSIDL_STARTMENU,
890 if (IsIllegalFolder(folder_, csidlarray))
891 return NOERROR;
893 if (folder_.empty())
895 // folder is empty, but maybe files are selected
896 if (files_.size() == 0)
897 return NOERROR; // nothing selected - we don't have a menu to show
898 // check whether a selected entry is an UID - those are namespace extensions
899 // which we can't handle
900 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
902 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
903 return NOERROR;
907 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
909 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT|ITEMIS_BAREREPO))==0)
910 return S_OK;
913 //check if our menu is requested for a subversion admin directory
914 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
915 return NOERROR;
917 if (uFlags & CMF_EXTENDEDVERBS)
918 itemStates |= ITEMIS_EXTENDED;
920 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
921 if ( bShortcut && (files_.size()==1))
923 // Don't show the context menu for a link if the
924 // destination is not part of a working copy.
925 // It would only show the standard menu items
926 // which are already shown for the lnk-file.
927 CString path = files_.front().c_str();
928 if ( !g_GitAdminDir.HasAdminDir(path) )
930 return NOERROR;
934 //check if we already added our menu entry for a folder.
935 //we check that by iterating through all menu entries and check if
936 //the dwItemData member points to our global ID string. That string is set
937 //by our shell extension when the folder menu is inserted.
938 TCHAR menubuf[MAX_PATH];
939 int count = GetMenuItemCount(hMenu);
940 for (int i=0; i<count; ++i)
942 MENUITEMINFO miif;
943 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
944 miif.cbSize = sizeof(MENUITEMINFO);
945 miif.fMask = MIIM_DATA;
946 miif.dwTypeData = menubuf;
947 miif.cch = _countof(menubuf);
948 GetMenuItemInfo(hMenu, i, TRUE, &miif);
949 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
950 return NOERROR;
953 LoadLangDll();
954 UINT idCmd = idCmdFirst;
956 //create the sub menu
957 HMENU subMenu = CreateMenu();
958 int indexSubMenu = 0;
960 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
961 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
962 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
964 int menuIndex = 0;
965 bool bAddSeparator = false;
966 bool bMenuEntryAdded = false;
967 bool bMenuEmpty = true;
968 // insert separator at start
969 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
970 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
972 #if 0
973 if (itemStates & (ITEMIS_INSVN|ITEMIS_FOLDERINSVN))
975 // show current branch name (as a "read-only" menu entry)
977 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
978 CString sProjectRoot;
979 CString sBranchName;
981 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
983 if (sBranchName.GetLength() == 40)
985 // if SHA1 only show 4 first bytes
986 BOOL bIsSha1 = TRUE;
987 for (int i=0; i<40; i++)
988 if ( !iswxdigit(sBranchName[i]) )
990 bIsSha1 = FALSE;
991 break;
993 if (bIsSha1)
994 sBranchName = sBranchName.Left(8) + _T("....");
997 sBranchName = _T('"') + sBranchName + _T('"');
999 const int icon = IDI_COPY;
1000 const int pos = indexMenu++;
1001 const int id = idCmd++;
1003 MENUITEMINFO menuiteminfo;
1004 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1005 menuiteminfo.cbSize = sizeof(menuiteminfo);
1006 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_STATE;
1007 menuiteminfo.fState = MFS_DISABLED;
1008 menuiteminfo.fType = MFT_STRING;
1009 menuiteminfo.dwTypeData = (LPWSTR)sBranchName.GetString();
1010 if (icon)
1012 menuiteminfo.fMask |= MIIM_BITMAP;
1013 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
1015 if (menuiteminfo.hbmpItem == HBMMENU_CALLBACK)
1017 // WM_DRAWITEM uses myIDMap to get icon, we use the same icon as create branch
1018 myIDMap[id - idCmdFirst] = ShellMenuBranch;
1019 myIDMap[id] = ShellMenuBranch;
1022 menuiteminfo.wID = id;
1023 InsertMenuItem(hMenu, pos, TRUE, &menuiteminfo);
1026 #endif
1028 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1030 if (menuInfo[menuIndex].command == ShellSeparator)
1032 // we don't add a separator immediately. Because there might not be
1033 // another 'normal' menu entry after we insert a separator.
1034 // we simply set a flag here, indicating that before the next
1035 // 'normal' menu entry, a separator should be added.
1036 if (!bMenuEmpty)
1037 bAddSeparator = true;
1039 else
1041 // check the conditions whether to show the menu entry or not
1042 bool bInsertMenu = false;
1044 if (menuInfo[menuIndex].firstyes && menuInfo[menuIndex].firstno)
1046 if (((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes)
1048 ((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1049 bInsertMenu = true;
1051 else if ((menuInfo[menuIndex].firstyes)&&((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes))
1052 bInsertMenu = true;
1053 else if ((menuInfo[menuIndex].firstno)&&((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1054 bInsertMenu = true;
1056 if (menuInfo[menuIndex].secondyes && menuInfo[menuIndex].secondno)
1058 if (((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes)
1060 ((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1061 bInsertMenu = true;
1063 else if ((menuInfo[menuIndex].secondyes)&&((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes))
1064 bInsertMenu = true;
1065 else if ((menuInfo[menuIndex].secondno)&&((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1066 bInsertMenu = true;
1068 if (menuInfo[menuIndex].thirdyes && menuInfo[menuIndex].thirdno)
1070 if (((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes)
1072 ((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1073 bInsertMenu = true;
1075 else if ((menuInfo[menuIndex].thirdyes)&&((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes))
1076 bInsertMenu = true;
1077 else if ((menuInfo[menuIndex].thirdno)&&((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1078 bInsertMenu = true;
1080 if (menuInfo[menuIndex].fourthyes && menuInfo[menuIndex].fourthno)
1082 if (((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes)
1084 ((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1085 bInsertMenu = true;
1087 else if ((menuInfo[menuIndex].fourthyes)&&((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes))
1088 bInsertMenu = true;
1089 else if ((menuInfo[menuIndex].fourthno)&&((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1090 bInsertMenu = true;
1092 if (menuInfo[menuIndex].menuID & menuex)
1094 if( !(itemStates & ITEMIS_EXTENDED) )
1096 bInsertMenu = false;
1100 if (menuInfo[menuIndex].menuID & (~menumask))
1102 if (bInsertMenu)
1104 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1105 // insert a separator
1106 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1108 bAddSeparator = false;
1109 bMenuEntryAdded = false;
1110 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1111 idCmd++;
1114 // handle special cases (sub menus)
1115 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1117 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1119 bMenuEntryAdded = true;
1120 bMenuEmpty = false;
1123 else
1125 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1127 // insert the menu entry
1128 InsertGitMenu( bIsTop,
1129 bIsTop ? hMenu : subMenu,
1130 bIsTop ? indexMenu++ : indexSubMenu++,
1131 idCmd++,
1132 menuInfo[menuIndex].menuTextID,
1133 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1134 idCmdFirst,
1135 menuInfo[menuIndex].command,
1136 uFlags);
1137 if (!bIsTop)
1139 bMenuEntryAdded = true;
1140 bMenuEmpty = false;
1141 bAddSeparator = false;
1147 menuIndex++;
1150 //add sub menu to main context menu
1151 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1152 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1153 MAKESTRING(IDS_MENUSUBMENU);
1154 MENUITEMINFO menuiteminfo;
1155 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1156 menuiteminfo.cbSize = sizeof(menuiteminfo);
1157 menuiteminfo.fType = MFT_STRING;
1158 menuiteminfo.dwTypeData = stringtablebuffer;
1160 UINT uIcon = bShowIcons ? IDI_APP : 0;
1161 if (folder_.size())
1163 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1164 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1165 myIDMap[idCmd] = ShellSubMenuFolder;
1166 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1168 else if (!bShortcut && (files_.size()==1))
1170 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1171 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1172 myIDMap[idCmd] = ShellSubMenuFile;
1174 else if (bShortcut && (files_.size()==1))
1176 uIcon = bShowIcons ? IDI_MENULINK : 0;
1177 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1178 myIDMap[idCmd] = ShellSubMenuLink;
1180 else if (files_.size() > 1)
1182 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1183 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1184 myIDMap[idCmd] = ShellSubMenuMultiple;
1186 else
1188 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1189 myIDMap[idCmd] = ShellSubMenu;
1191 HBITMAP bmp = NULL;
1192 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1193 if (uIcon)
1195 menuiteminfo.fMask |= MIIM_BITMAP;
1196 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(uIcon) : HBMMENU_CALLBACK;
1198 menuiteminfo.hSubMenu = subMenu;
1199 menuiteminfo.wID = idCmd++;
1200 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1202 //separator after
1203 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1205 TweakMenu(hMenu);
1207 //return number of menu items added
1208 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1211 void CShellExt::TweakMenu(HMENU hMenu)
1213 MENUINFO MenuInfo = {};
1214 MenuInfo.cbSize = sizeof(MenuInfo);
1215 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1216 MenuInfo.dwStyle = MNS_CHECKORBMP;
1217 SetMenuInfo(hMenu, &MenuInfo);
1220 // This is called when you invoke a command on the menu:
1221 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1223 PreserveChdir preserveChdir;
1224 HRESULT hr = E_INVALIDARG;
1225 if (lpcmi == NULL)
1226 return hr;
1228 std::string command;
1229 std::string parent;
1230 std::string file;
1232 if ((files_.size() > 0)||(folder_.size() > 0))
1234 UINT idCmd = LOWORD(lpcmi->lpVerb);
1236 if (HIWORD(lpcmi->lpVerb))
1238 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1239 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1240 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1241 idCmd = verb_it->second;
1242 else
1243 return hr;
1246 // See if we have a handler interface for this id
1247 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1248 if (id_it != myIDMap.end() && id_it->first == idCmd)
1250 CRegStdString tortoiseProcPath(_T("Software\\TortoiseGit\\ProcPath"), _T("TortoiseProc.exe"), false, HKEY_LOCAL_MACHINE);
1251 CRegStdString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T("TortoiseMerge.exe"), false, HKEY_LOCAL_MACHINE);
1253 //TortoiseProc expects a command line of the form:
1254 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1255 // or
1256 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1258 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1259 //* pathfile is a path to a temporary file which contains a list of file paths
1260 stdstring gitCmd = _T(" /command:");
1261 stdstring tempfile;
1262 switch (id_it->second)
1264 //#region case
1265 case ShellMenuSync:
1266 gitCmd += _T("sync /path:\"");
1267 if (files_.size() > 0)
1268 gitCmd += files_.front();
1269 else
1270 gitCmd += folder_;
1271 gitCmd += _T("\"");
1272 break;
1273 case ShellMenuUpdate:
1274 tempfile = WriteFileListToTempFile();
1275 gitCmd += _T("update /pathfile:\"");
1276 gitCmd += tempfile;
1277 gitCmd += _T("\"");
1278 gitCmd += _T(" /deletepathfile");
1279 break;
1280 case ShellMenuSubSync:
1281 tempfile = WriteFileListToTempFile();
1282 gitCmd += _T("subsync /pathfile:\"");
1283 gitCmd += tempfile;
1284 gitCmd += _T("\"");
1285 gitCmd += _T(" /deletepathfile");
1286 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1288 gitCmd += _T(" /bkpath:\"");
1289 gitCmd += folder_;
1290 gitCmd += _T("\"");
1292 break;
1293 case ShellMenuUpdateExt:
1294 tempfile = WriteFileListToTempFile();
1295 gitCmd += _T("subupdate /pathfile:\"");
1296 gitCmd += tempfile;
1297 gitCmd += _T("\"");
1298 gitCmd += _T(" /deletepathfile");
1299 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1301 gitCmd += _T(" /bkpath:\"");
1302 gitCmd += folder_;
1303 gitCmd += _T("\"");
1305 break;
1306 case ShellMenuCommit:
1307 tempfile = WriteFileListToTempFile();
1308 gitCmd += _T("commit /pathfile:\"");
1309 gitCmd += tempfile;
1310 gitCmd += _T("\"");
1311 gitCmd += _T(" /deletepathfile");
1312 break;
1313 case ShellMenuAdd:
1314 case ShellMenuAddAsReplacement:
1315 tempfile = WriteFileListToTempFile();
1316 gitCmd += _T("add /pathfile:\"");
1317 gitCmd += tempfile;
1318 gitCmd += _T("\"");
1319 gitCmd += _T(" /deletepathfile");
1320 break;
1321 case ShellMenuIgnore:
1322 tempfile = WriteFileListToTempFile();
1323 gitCmd += _T("ignore /pathfile:\"");
1324 gitCmd += tempfile;
1325 gitCmd += _T("\"");
1326 gitCmd += _T(" /deletepathfile");
1327 break;
1328 case ShellMenuIgnoreCaseSensitive:
1329 tempfile = WriteFileListToTempFile();
1330 gitCmd += _T("ignore /pathfile:\"");
1331 gitCmd += tempfile;
1332 gitCmd += _T("\"");
1333 gitCmd += _T(" /deletepathfile");
1334 gitCmd += _T(" /onlymask");
1335 break;
1336 case ShellMenuDeleteIgnore:
1337 tempfile = WriteFileListToTempFile();
1338 gitCmd += _T("ignore /delete /pathfile:\"");
1339 gitCmd += tempfile;
1340 gitCmd += _T("\"");
1341 gitCmd += _T(" /deletepathfile");
1342 break;
1343 case ShellMenuDeleteIgnoreCaseSensitive:
1344 tempfile = WriteFileListToTempFile();
1345 gitCmd += _T("ignore /delete /pathfile:\"");
1346 gitCmd += tempfile;
1347 gitCmd += _T("\"");
1348 gitCmd += _T(" /deletepathfile");
1349 gitCmd += _T(" /onlymask");
1350 break;
1351 case ShellMenuUnIgnore:
1352 tempfile = WriteFileListToTempFile();
1353 gitCmd += _T("unignore /pathfile:\"");
1354 gitCmd += tempfile;
1355 gitCmd += _T("\"");
1356 gitCmd += _T(" /deletepathfile");
1357 break;
1358 case ShellMenuUnIgnoreCaseSensitive:
1359 tempfile = WriteFileListToTempFile();
1360 gitCmd += _T("unignore /pathfile:\"");
1361 gitCmd += tempfile;
1362 gitCmd += _T("\"");
1363 gitCmd += _T(" /deletepathfile");
1364 gitCmd += _T(" /onlymask");
1365 break;
1366 case ShellMenuRevert:
1367 tempfile = WriteFileListToTempFile();
1368 gitCmd += _T("revert /pathfile:\"");
1369 gitCmd += tempfile;
1370 gitCmd += _T("\"");
1371 gitCmd += _T(" /deletepathfile");
1372 break;
1373 case ShellMenuCleanup:
1374 tempfile = WriteFileListToTempFile();
1375 gitCmd += _T("cleanup /pathfile:\"");
1376 gitCmd += tempfile;
1377 gitCmd += _T("\"");
1378 gitCmd += _T(" /deletepathfile");
1379 break;
1380 case ShellMenuSendMail:
1381 tempfile = WriteFileListToTempFile();
1382 gitCmd += _T("sendmail /pathfile:\"");
1383 gitCmd += tempfile;
1384 gitCmd += _T("\"");
1385 gitCmd += _T(" /deletepathfile");
1386 break;
1387 case ShellMenuResolve:
1388 tempfile = WriteFileListToTempFile();
1389 gitCmd += _T("resolve /pathfile:\"");
1390 gitCmd += tempfile;
1391 gitCmd += _T("\"");
1392 gitCmd += _T(" /deletepathfile");
1393 break;
1394 case ShellMenuSwitch:
1395 gitCmd += _T("switch /path:\"");
1396 if (files_.size() > 0)
1397 gitCmd += files_.front();
1398 else
1399 gitCmd += folder_;
1400 gitCmd += _T("\"");
1401 break;
1402 case ShellMenuExport:
1403 gitCmd += _T("export /path:\"");
1404 if (files_.size() > 0)
1405 gitCmd += files_.front();
1406 else
1407 gitCmd += folder_;
1408 gitCmd += _T("\"");
1409 break;
1410 case ShellMenuAbout:
1411 gitCmd += _T("about");
1412 break;
1413 case ShellMenuCreateRepos:
1414 gitCmd += _T("repocreate /path:\"");
1415 if (files_.size() > 0)
1416 gitCmd += files_.front();
1417 else
1418 gitCmd += folder_;
1419 gitCmd += _T("\"");
1420 break;
1421 case ShellMenuMerge:
1422 gitCmd += _T("merge /path:\"");
1423 if (files_.size() > 0)
1424 gitCmd += files_.front();
1425 else
1426 gitCmd += folder_;
1427 gitCmd += _T("\"");
1428 break;
1429 case ShellMenuCopy:
1430 gitCmd += _T("copy /path:\"");
1431 if (files_.size() > 0)
1432 gitCmd += files_.front();
1433 else
1434 gitCmd += folder_;
1435 gitCmd += _T("\"");
1436 break;
1437 case ShellMenuSettings:
1438 gitCmd += _T("settings /path:\"");
1439 if (files_.size() > 0)
1440 gitCmd += files_.front();
1441 else
1442 gitCmd += folder_;
1443 gitCmd += _T("\"");
1444 break;
1445 case ShellMenuHelp:
1446 gitCmd += _T("help");
1447 break;
1448 case ShellMenuRename:
1449 gitCmd += _T("rename /path:\"");
1450 if (files_.size() > 0)
1451 gitCmd += files_.front();
1452 else
1453 gitCmd += folder_;
1454 gitCmd += _T("\"");
1455 break;
1456 case ShellMenuRemove:
1457 tempfile = WriteFileListToTempFile();
1458 gitCmd += _T("remove /pathfile:\"");
1459 gitCmd += tempfile;
1460 gitCmd += _T("\"");
1461 gitCmd += _T(" /deletepathfile");
1462 break;
1463 case ShellMenuRemoveKeep:
1464 tempfile = WriteFileListToTempFile();
1465 gitCmd += _T("remove /pathfile:\"");
1466 gitCmd += tempfile;
1467 gitCmd += _T("\"");
1468 gitCmd += _T(" /deletepathfile");
1469 gitCmd += _T(" /keep");
1470 break;
1471 case ShellMenuDiff:
1472 gitCmd += _T("diff /path:\"");
1473 if (files_.size() == 1)
1474 gitCmd += files_.front();
1475 else if (files_.size() == 2)
1477 std::vector<stdstring>::iterator I = files_.begin();
1478 gitCmd += *I;
1479 I++;
1480 gitCmd += _T("\" /path2:\"");
1481 gitCmd += *I;
1483 else
1484 gitCmd += folder_;
1485 gitCmd += _T("\"");
1486 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1487 gitCmd += _T(" /alternative");
1488 break;
1489 case ShellMenuPrevDiff:
1490 gitCmd += _T("prevdiff /path:\"");
1491 if (files_.size() == 1)
1492 gitCmd += files_.front();
1493 else
1494 gitCmd += folder_;
1495 gitCmd += _T("\"");
1496 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1497 gitCmd += _T(" /alternative");
1498 break;
1499 case ShellMenuDiffTwo:
1500 gitCmd += _T("diffcommits /path:\"");
1501 if (files_.size() == 1)
1502 gitCmd += files_.front();
1503 else
1504 gitCmd += folder_;
1505 gitCmd += _T("\"");
1506 break;
1507 case ShellMenuDropCopyAdd:
1508 tempfile = WriteFileListToTempFile();
1509 gitCmd += _T("dropcopyadd /pathfile:\"");
1510 gitCmd += tempfile;
1511 gitCmd += _T("\"");
1512 gitCmd += _T(" /deletepathfile");
1513 gitCmd += _T(" /droptarget:\"");
1514 gitCmd += folder_;
1515 gitCmd += _T("\"";)
1516 break;
1517 case ShellMenuDropCopy:
1518 tempfile = WriteFileListToTempFile();
1519 gitCmd += _T("dropcopy /pathfile:\"");
1520 gitCmd += tempfile;
1521 gitCmd += _T("\"");
1522 gitCmd += _T(" /deletepathfile");
1523 gitCmd += _T(" /droptarget:\"");
1524 gitCmd += folder_;
1525 gitCmd += _T("\"";)
1526 break;
1527 case ShellMenuDropCopyRename:
1528 tempfile = WriteFileListToTempFile();
1529 gitCmd += _T("dropcopy /pathfile:\"");
1530 gitCmd += tempfile;
1531 gitCmd += _T("\"");
1532 gitCmd += _T(" /deletepathfile");
1533 gitCmd += _T(" /droptarget:\"");
1534 gitCmd += folder_;
1535 gitCmd += _T("\" /rename";)
1536 break;
1537 case ShellMenuDropMove:
1538 tempfile = WriteFileListToTempFile();
1539 gitCmd += _T("dropmove /pathfile:\"");
1540 gitCmd += tempfile;
1541 gitCmd += _T("\"");
1542 gitCmd += _T(" /deletepathfile");
1543 gitCmd += _T(" /droptarget:\"");
1544 gitCmd += folder_;
1545 gitCmd += _T("\"");
1546 break;
1547 case ShellMenuDropMoveRename:
1548 tempfile = WriteFileListToTempFile();
1549 gitCmd += _T("dropmove /pathfile:\"");
1550 gitCmd += tempfile;
1551 gitCmd += _T("\"");
1552 gitCmd += _T(" /deletepathfile");
1553 gitCmd += _T(" /droptarget:\"");
1554 gitCmd += folder_;
1555 gitCmd += _T("\" /rename";)
1556 break;
1557 case ShellMenuDropExport:
1558 tempfile = WriteFileListToTempFile();
1559 gitCmd += _T("dropexport /pathfile:\"");
1560 gitCmd += tempfile;
1561 gitCmd += _T("\"");
1562 gitCmd += _T(" /deletepathfile");
1563 gitCmd += _T(" /droptarget:\"");
1564 gitCmd += folder_;
1565 gitCmd += _T("\"");
1566 break;
1567 case ShellMenuDropExportExtended:
1568 tempfile = WriteFileListToTempFile();
1569 gitCmd += _T("dropexport /pathfile:\"");
1570 gitCmd += tempfile;
1571 gitCmd += _T("\"");
1572 gitCmd += _T(" /deletepathfile");
1573 gitCmd += _T(" /droptarget:\"");
1574 gitCmd += folder_;
1575 gitCmd += _T("\"");
1576 gitCmd += _T(" /extended");
1577 break;
1578 case ShellMenuLog:
1579 gitCmd += _T("log /path:\"");
1580 if (files_.size() > 0)
1581 gitCmd += files_.front();
1582 else
1583 gitCmd += folder_;
1584 gitCmd += _T("\"");
1585 break;
1586 case ShellMenuConflictEditor:
1587 gitCmd += _T("conflicteditor /path:\"");
1588 if (files_.size() > 0)
1589 gitCmd += files_.front();
1590 else
1591 gitCmd += folder_;
1592 gitCmd += _T("\"");
1593 break;
1594 case ShellMenuGitSVNRebase:
1595 gitCmd += _T("svnrebase /path:\"");
1596 if (files_.size() > 0)
1597 gitCmd += files_.front();
1598 else
1599 gitCmd += folder_;
1600 gitCmd += _T("\"");
1601 break;
1602 case ShellMenuGitSVNDCommit:
1603 gitCmd += _T("svndcommit /path:\"");
1604 if (files_.size() > 0)
1605 gitCmd += files_.front();
1606 else
1607 gitCmd += folder_;
1608 gitCmd += _T("\"");
1609 break;
1610 case ShellMenuGitSVNDFetch:
1611 gitCmd += _T("svnfetch /path:\"");
1612 if (files_.size() > 0)
1613 gitCmd += files_.front();
1614 else
1615 gitCmd += folder_;
1616 gitCmd += _T("\"");
1617 break;
1618 case ShellMenuGitSVNIgnore:
1619 gitCmd += _T("svnignore /path:\"");
1620 if (files_.size() > 0)
1621 gitCmd += files_.front();
1622 else
1623 gitCmd += folder_;
1624 gitCmd += _T("\"");
1625 break;
1626 case ShellMenuRebase:
1627 gitCmd += _T("rebase /path:\"");
1628 if (files_.size() > 0)
1629 gitCmd += files_.front();
1630 else
1631 gitCmd += folder_;
1632 gitCmd += _T("\"");
1633 break;
1634 case ShellMenuShowChanged:
1635 if (files_.size() > 1)
1637 tempfile = WriteFileListToTempFile();
1638 gitCmd += _T("repostatus /pathfile:\"");
1639 gitCmd += tempfile;
1640 gitCmd += _T("\"");
1641 gitCmd += _T(" /deletepathfile");
1643 else
1645 gitCmd += _T("repostatus /path:\"");
1646 if (files_.size() > 0)
1647 gitCmd += files_.front();
1648 else
1649 gitCmd += folder_;
1650 gitCmd += _T("\"");
1652 break;
1653 case ShellMenuRefBrowse:
1654 gitCmd += _T("refbrowse /path:\"");
1655 if (files_.size() > 0)
1656 gitCmd += files_.front();
1657 else
1658 gitCmd += folder_;
1659 gitCmd += _T("\"");
1660 break;
1661 case ShellMenuRefLog:
1662 gitCmd += _T("reflog /path:\"");
1663 if (files_.size() > 0)
1664 gitCmd += files_.front();
1665 else
1666 gitCmd += folder_;
1667 gitCmd += _T("\"");
1668 break;
1670 case ShellMenuStashSave:
1671 gitCmd += _T("stashsave /path:\"");
1672 if (files_.size() > 0)
1673 gitCmd += files_.front();
1674 else
1675 gitCmd += folder_;
1676 gitCmd += _T("\"");
1677 break;
1679 case ShellMenuStashApply:
1680 gitCmd += _T("stashapply /path:\"");
1681 if (files_.size() > 0)
1682 gitCmd += files_.front();
1683 else
1684 gitCmd += folder_;
1685 gitCmd += _T("\"");
1686 break;
1688 case ShellMenuStashPop:
1689 gitCmd += _T("stashpop /path:\"");
1690 if (files_.size() > 0)
1691 gitCmd += files_.front();
1692 else
1693 gitCmd += folder_;
1694 gitCmd += _T("\"");
1695 break;
1698 case ShellMenuStashList:
1699 gitCmd += _T("reflog /path:\"");
1700 if (files_.size() > 0)
1701 gitCmd += files_.front();
1702 else
1703 gitCmd += folder_;
1704 gitCmd += _T("\" /ref:refs/stash");
1705 break;
1707 case ShellMenuBisectStart:
1708 gitCmd += _T("bisect /path:\"");
1709 if (files_.size() > 0)
1710 gitCmd += files_.front();
1711 else
1712 gitCmd += folder_;
1713 gitCmd += _T("\" /start");
1714 break;
1716 case ShellMenuBisectGood:
1717 gitCmd += _T("bisect /path:\"");
1718 if (files_.size() > 0)
1719 gitCmd += files_.front();
1720 else
1721 gitCmd += folder_;
1722 gitCmd += _T("\" /good");
1723 break;
1726 case ShellMenuBisectBad:
1727 gitCmd += _T("bisect /path:\"");
1728 if (files_.size() > 0)
1729 gitCmd += files_.front();
1730 else
1731 gitCmd += folder_;
1732 gitCmd += _T("\" /bad");
1733 break;
1735 case ShellMenuBisectReset:
1736 gitCmd += _T("bisect /path:\"");
1737 if (files_.size() > 0)
1738 gitCmd += files_.front();
1739 else
1740 gitCmd += folder_;
1741 gitCmd += _T("\" /reset");
1742 break;
1744 case ShellMenuSubAdd:
1745 gitCmd += _T("subadd /path:\"");
1746 if (files_.size() > 0)
1747 gitCmd += files_.front();
1748 else
1749 gitCmd += folder_;
1750 gitCmd += _T("\"");
1751 break;
1753 case ShellMenuBlame:
1754 gitCmd += _T("blame /path:\"");
1755 if (files_.size() > 0)
1756 gitCmd += files_.front();
1757 else
1758 gitCmd += folder_;
1759 gitCmd += _T("\"");
1760 break;
1761 case ShellMenuApplyPatch:
1762 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1764 // if there's a patch file in the clipboard, we save it
1765 // to a temporary file and tell TortoiseMerge to use that one
1766 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1767 if ((cFormat)&&(OpenClipboard(NULL)))
1769 HGLOBAL hglb = GetClipboardData(cFormat);
1770 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1772 DWORD len = GetTempPath(0, NULL);
1773 TCHAR * path = new TCHAR[len+1];
1774 TCHAR * tempF = new TCHAR[len+100];
1775 GetTempPath (len+1, path);
1776 GetTempFileName (path, TEXT("git"), 0, tempF);
1777 std::wstring sTempFile = std::wstring(tempF);
1778 delete [] path;
1779 delete [] tempF;
1781 FILE * outFile;
1782 size_t patchlen = strlen(lpstr);
1783 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1784 if(outFile)
1786 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1787 if (size == patchlen)
1789 itemStates |= ITEMIS_PATCHFILE;
1790 files_.clear();
1791 files_.push_back(sTempFile);
1793 fclose(outFile);
1795 GlobalUnlock(hglb);
1796 CloseClipboard();
1799 if (itemStates & ITEMIS_PATCHFILE)
1801 gitCmd = _T(" /diff:\"");
1802 if (files_.size() > 0)
1804 gitCmd += files_.front();
1805 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1807 gitCmd += _T("\" /patchpath:\"");
1808 gitCmd += folder_;
1811 else
1812 gitCmd += folder_;
1813 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1814 gitCmd += _T("\" /wc");
1815 else
1816 gitCmd += _T("\"");
1818 else
1820 gitCmd = _T(" /patchpath:\"");
1821 if (files_.size() > 0)
1822 gitCmd += files_.front();
1823 else
1824 gitCmd += folder_;
1825 gitCmd += _T("\"");
1827 myIDMap.clear();
1828 myVerbsIDMap.clear();
1829 myVerbsMap.clear();
1830 RunCommand(tortoiseMergePath, gitCmd, _T("TortoiseMerge launch failed"));
1831 return NOERROR;
1832 break;
1833 case ShellMenuProperties:
1834 tempfile = WriteFileListToTempFile();
1835 gitCmd += _T("properties /pathfile:\"");
1836 gitCmd += tempfile;
1837 gitCmd += _T("\"");
1838 gitCmd += _T(" /deletepathfile");
1839 break;
1840 case ShellMenuClipPaste:
1841 if (WriteClipboardPathsToTempFile(tempfile))
1843 bool bCopy = true;
1844 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1845 if (cPrefDropFormat)
1847 if (OpenClipboard(lpcmi->hwnd))
1849 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1850 if (hglb)
1852 DWORD* effect = (DWORD*) GlobalLock(hglb);
1853 if (*effect == DROPEFFECT_MOVE)
1854 bCopy = false;
1855 GlobalUnlock(hglb);
1857 CloseClipboard();
1861 if (bCopy)
1862 gitCmd += _T("pastecopy /pathfile:\"");
1863 else
1864 gitCmd += _T("pastemove /pathfile:\"");
1865 gitCmd += tempfile;
1866 gitCmd += _T("\"");
1867 gitCmd += _T(" /deletepathfile");
1868 gitCmd += _T(" /droptarget:\"");
1869 gitCmd += folder_;
1870 gitCmd += _T("\"");
1872 else return NOERROR;
1873 break;
1874 case ShellMenuClone:
1875 gitCmd += _T("clone /path:\"");
1876 if (files_.size() > 0)
1877 gitCmd += files_.front();
1878 else
1879 gitCmd += folder_;
1880 gitCmd += _T("\"");
1881 break;
1882 case ShellMenuPull:
1883 gitCmd += _T("pull /path:\"");
1884 if (files_.size() > 0)
1885 gitCmd += files_.front();
1886 else
1887 gitCmd += folder_;
1888 gitCmd += _T("\"");
1889 break;
1890 case ShellMenuPush:
1891 gitCmd += _T("push /path:\"");
1892 if (files_.size() > 0)
1893 gitCmd += files_.front();
1894 else
1895 gitCmd += folder_;
1896 gitCmd += _T("\"");
1897 break;
1898 case ShellMenuBranch:
1899 gitCmd += _T("branch /path:\"");
1900 if (files_.size() > 0)
1901 gitCmd += files_.front();
1902 else
1903 gitCmd += folder_;
1904 gitCmd += _T("\"");
1905 break;
1907 case ShellMenuTag:
1908 gitCmd += _T("tag /path:\"");
1909 if (files_.size() > 0)
1910 gitCmd += files_.front();
1911 else
1912 gitCmd += folder_;
1913 gitCmd += _T("\"");
1914 break;
1916 case ShellMenuFormatPatch:
1917 gitCmd += _T("formatpatch /path:\"");
1918 if (files_.size() > 0)
1919 gitCmd += files_.front();
1920 else
1921 gitCmd += folder_;
1922 gitCmd += _T("\"");
1923 break;
1925 case ShellMenuImportPatch:
1926 tempfile = WriteFileListToTempFile();
1927 gitCmd += _T("importpatch /pathfile:\"");
1928 gitCmd += tempfile;
1929 gitCmd += _T("\"");
1930 gitCmd += _T(" /deletepathfile");
1931 break;
1933 case ShellMenuCherryPick:
1934 gitCmd += _T("cherrypick /path:\"");
1935 if (files_.size() > 0)
1936 gitCmd += files_.front();
1937 else
1938 gitCmd += folder_;
1939 gitCmd += _T("\"");
1940 break;
1941 case ShellMenuFetch:
1942 gitCmd += _T("fetch /path:\"");
1943 if (files_.size() > 0)
1944 gitCmd += files_.front();
1945 else
1946 gitCmd += folder_;
1947 gitCmd += _T("\"");
1948 break;
1950 default:
1951 break;
1952 //#endregion
1953 } // switch (id_it->second)
1954 gitCmd += _T(" /hwnd:");
1955 TCHAR buf[30];
1956 _stprintf_s(buf, 30, _T("%d"), lpcmi->hwnd);
1957 gitCmd += buf;
1958 myIDMap.clear();
1959 myVerbsIDMap.clear();
1960 myVerbsMap.clear();
1961 RunCommand(tortoiseProcPath, gitCmd, _T("TortoiseProc launch failed"));
1962 hr = NOERROR;
1963 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
1964 } // if ((files_.size() > 0)||(folder_.size() > 0))
1965 return hr;
1969 // This is for the status bar and things like that:
1970 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
1971 UINT uFlags,
1972 UINT FAR * /*reserved*/,
1973 LPSTR pszName,
1974 UINT cchMax)
1976 PreserveChdir preserveChdir;
1977 //do we know the id?
1978 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1979 if (id_it == myIDMap.end() || id_it->first != idCmd)
1981 return E_INVALIDARG; //no, we don't
1984 LoadLangDll();
1985 HRESULT hr = E_INVALIDARG;
1987 MAKESTRING(IDS_MENUDESCDEFAULT);
1988 int menuIndex = 0;
1989 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1991 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
1993 MAKESTRING(menuInfo[menuIndex].menuDescID);
1994 break;
1996 menuIndex++;
1999 const TCHAR * desc = stringtablebuffer;
2000 switch(uFlags)
2002 case GCS_HELPTEXTA:
2004 std::string help = WideToMultibyte(desc);
2005 lstrcpynA(pszName, help.c_str(), cchMax);
2006 hr = S_OK;
2007 break;
2009 case GCS_HELPTEXTW:
2011 wide_string help = desc;
2012 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2013 hr = S_OK;
2014 break;
2016 case GCS_VERBA:
2018 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2019 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2021 std::string help = WideToMultibyte(verb_id_it->second);
2022 lstrcpynA(pszName, help.c_str(), cchMax);
2023 hr = S_OK;
2026 break;
2027 case GCS_VERBW:
2029 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2030 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2032 wide_string help = verb_id_it->second;
2033 ATLTRACE("verb : %ws\n", help.c_str());
2034 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2035 hr = S_OK;
2038 break;
2040 return hr;
2043 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
2045 LRESULT res;
2046 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
2049 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
2051 PreserveChdir preserveChdir;
2053 LRESULT res;
2054 if (pResult == NULL)
2055 pResult = &res;
2056 *pResult = FALSE;
2058 LoadLangDll();
2059 switch (uMsg)
2061 case WM_MEASUREITEM:
2063 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
2064 if (lpmis==NULL||lpmis->CtlType!=ODT_MENU)
2065 break;
2066 lpmis->itemWidth = 16;
2067 lpmis->itemHeight = 16;
2068 *pResult = TRUE;
2070 break;
2071 case WM_DRAWITEM:
2073 LPCTSTR resource;
2074 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
2075 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
2076 return S_OK; //not for a menu
2077 resource = GetMenuTextFromResource(myIDMap[lpdis->itemID]);
2078 if (resource == NULL)
2079 return S_OK;
2080 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2081 if (hIcon == NULL)
2082 return S_OK;
2083 DrawIconEx(lpdis->hDC,
2084 lpdis->rcItem.left,
2085 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
2086 hIcon, 16, 16,
2087 0, NULL, DI_NORMAL);
2088 DestroyIcon(hIcon);
2089 *pResult = TRUE;
2091 break;
2092 case WM_MENUCHAR:
2094 LPCTSTR resource;
2095 TCHAR *szItem;
2096 if (HIWORD(wParam) != MF_POPUP)
2097 return NOERROR;
2098 int nChar = LOWORD(wParam);
2099 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
2100 nChar = tolower(nChar);
2101 // we have the char the user pressed, now search that char in all our
2102 // menu items
2103 std::vector<int> accmenus;
2104 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
2106 resource = GetMenuTextFromResource(mySubMenuMap[It->first]);
2107 if (resource == NULL)
2108 continue;
2109 szItem = stringtablebuffer;
2110 TCHAR * amp = _tcschr(szItem, '&');
2111 if (amp == NULL)
2112 continue;
2113 amp++;
2114 int ampChar = LOWORD(*amp);
2115 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
2116 ampChar = tolower(ampChar);
2117 if (ampChar == nChar)
2119 // yep, we found a menu which has the pressed key
2120 // as an accelerator. Add that menu to the list to
2121 // process later.
2122 accmenus.push_back(It->first);
2125 if (accmenus.size() == 0)
2127 // no menu with that accelerator key.
2128 *pResult = MAKELONG(0, MNC_IGNORE);
2129 return NOERROR;
2131 if (accmenus.size() == 1)
2133 // Only one menu with that accelerator key. We're lucky!
2134 // So just execute that menu entry.
2135 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
2136 return NOERROR;
2138 if (accmenus.size() > 1)
2140 // we have more than one menu item with this accelerator key!
2141 MENUITEMINFO mif;
2142 mif.cbSize = sizeof(MENUITEMINFO);
2143 mif.fMask = MIIM_STATE;
2144 for (std::vector<int>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
2146 GetMenuItemInfo((HMENU)lParam, *it, TRUE, &mif);
2147 if (mif.fState == MFS_HILITE)
2149 // this is the selected item, so select the next one
2150 ++it;
2151 if (it == accmenus.end())
2152 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2153 else
2154 *pResult = MAKELONG(*it, MNC_SELECT);
2155 return NOERROR;
2158 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2161 break;
2162 default:
2163 return NOERROR;
2166 return NOERROR;
2169 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
2171 TCHAR textbuf[255];
2172 LPCTSTR resource = NULL;
2173 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
2174 space = 6;
2176 int menuIndex = 0;
2177 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2179 if (menuInfo[menuIndex].command == id)
2181 MAKESTRING(menuInfo[menuIndex].menuTextID);
2182 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
2183 switch (id)
2185 case ShellSubMenuMultiple:
2186 case ShellSubMenuLink:
2187 case ShellSubMenuFolder:
2188 case ShellSubMenuFile:
2189 case ShellSubMenu:
2190 space = 0;
2191 break;
2192 default:
2193 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
2194 if (layout & (menuInfo[menuIndex].menuID))
2196 _tcscpy_s(textbuf, 255, _T("Git "));
2197 _tcscat_s(textbuf, 255, stringtablebuffer);
2198 _tcscpy_s(stringtablebuffer, 255, textbuf);
2200 break;
2202 return resource;
2204 menuIndex++;
2206 return NULL;
2209 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
2211 int i=0;
2212 TCHAR buf[MAX_PATH]; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
2213 LPITEMIDLIST pidl = NULL;
2214 while (cslidarray[i])
2216 ++i;
2217 pidl = NULL;
2218 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
2219 continue;
2220 if (!SHGetPathFromIDList(pidl, buf))
2222 // not a file system path, definitely illegal for our use
2223 CoTaskMemFree(pidl);
2224 continue;
2226 CoTaskMemFree(pidl);
2227 if (_tcslen(buf)==0)
2228 continue;
2229 if (_tcscmp(buf, folder.c_str())==0)
2230 return true;
2232 return false;
2235 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT uFlags)
2237 HMENU ignoresubmenu = NULL;
2238 int indexignoresub = 0;
2239 bool bShowIgnoreMenu = false;
2240 TCHAR maskbuf[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2241 TCHAR ignorepath[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2242 if (files_.size() == 0)
2243 return false;
2244 UINT icon = bShowIcons ? IDI_IGNORE : 0;
2246 std::vector<stdstring>::iterator I = files_.begin();
2247 if (_tcsrchr(I->c_str(), '\\'))
2248 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
2249 else
2250 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
2251 if ((itemStates & ITEMIS_IGNORED)&&(ignoredprops.size() > 0))
2253 // check if the item name is ignored or the mask
2254 size_t p = 0;
2255 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
2257 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
2258 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
2260 break;
2262 p++;
2264 if (p!=-1)
2266 ignoresubmenu = CreateMenu();
2267 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2268 stdstring verb = stdstring(ignorepath);
2269 myVerbsMap[verb] = idCmd - idCmdFirst;
2270 myVerbsMap[verb] = idCmd;
2271 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2272 myVerbsIDMap[idCmd] = verb;
2273 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
2274 myIDMap[idCmd++] = ShellMenuUnIgnore;
2275 bShowIgnoreMenu = true;
2277 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2278 if (_tcsrchr(ignorepath, '.'))
2280 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2281 p = ignoredprops.find(maskbuf);
2282 if ((p!=-1) &&
2283 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
2285 if (ignoresubmenu==NULL)
2286 ignoresubmenu = CreateMenu();
2288 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2289 stdstring verb = stdstring(maskbuf);
2290 myVerbsMap[verb] = idCmd - idCmdFirst;
2291 myVerbsMap[verb] = idCmd;
2292 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2293 myVerbsIDMap[idCmd] = verb;
2294 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
2295 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
2296 bShowIgnoreMenu = true;
2300 else if ((itemStates & ITEMIS_IGNORED) == 0)
2302 bShowIgnoreMenu = true;
2303 ignoresubmenu = CreateMenu();
2304 if (itemStates & ITEMIS_ONLYONE)
2306 if (itemStates & ITEMIS_INGIT)
2308 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2309 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2310 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2312 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2313 if (_tcsrchr(ignorepath, '.'))
2315 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2316 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2317 stdstring verb = stdstring(maskbuf);
2318 myVerbsMap[verb] = idCmd - idCmdFirst;
2319 myVerbsMap[verb] = idCmd;
2320 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2321 myVerbsIDMap[idCmd] = verb;
2322 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2323 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2326 else
2328 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2329 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2330 myIDMap[idCmd++] = ShellMenuIgnore;
2332 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2333 if (_tcsrchr(ignorepath, '.'))
2335 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2336 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2337 stdstring verb = stdstring(maskbuf);
2338 myVerbsMap[verb] = idCmd - idCmdFirst;
2339 myVerbsMap[verb] = idCmd;
2340 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2341 myVerbsIDMap[idCmd] = verb;
2342 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2343 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2347 else
2349 if (itemStates & ITEMIS_INGIT)
2351 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
2352 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2353 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2354 stdstring verb = stdstring(ignorepath);
2355 myVerbsMap[verb] = idCmd - idCmdFirst;
2356 myVerbsMap[verb] = idCmd;
2357 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2358 myVerbsIDMap[idCmd] = verb;
2359 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2360 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2362 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
2363 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2364 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2365 verb = stdstring(ignorepath);
2366 myVerbsMap[verb] = idCmd - idCmdFirst;
2367 myVerbsMap[verb] = idCmd;
2368 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2369 myVerbsIDMap[idCmd] = verb;
2370 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2371 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2373 else
2375 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2376 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2377 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2378 stdstring verb = stdstring(ignorepath);
2379 myVerbsMap[verb] = idCmd - idCmdFirst;
2380 myVerbsMap[verb] = idCmd;
2381 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2382 myVerbsIDMap[idCmd] = verb;
2383 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2384 myIDMap[idCmd++] = ShellMenuIgnore;
2386 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2387 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2388 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2389 verb = stdstring(ignorepath);
2390 myVerbsMap[verb] = idCmd - idCmdFirst;
2391 myVerbsMap[verb] = idCmd;
2392 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2393 myVerbsIDMap[idCmd] = verb;
2394 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2395 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2400 if (bShowIgnoreMenu)
2402 MENUITEMINFO menuiteminfo;
2403 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2404 menuiteminfo.cbSize = sizeof(menuiteminfo);
2405 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2406 if (icon)
2408 menuiteminfo.fMask |= MIIM_BITMAP;
2409 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
2411 menuiteminfo.fType = MFT_STRING;
2412 menuiteminfo.hSubMenu = ignoresubmenu;
2413 menuiteminfo.wID = idCmd;
2414 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2415 if (itemStates & ITEMIS_IGNORED)
2416 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2417 else if (itemStates & ITEMIS_INGIT)
2418 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2419 else
2420 GetMenuTextFromResource(ShellMenuIgnoreSub);
2421 menuiteminfo.dwTypeData = stringtablebuffer;
2422 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2424 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2425 if (itemStates & ITEMIS_IGNORED)
2427 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2428 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2430 else
2432 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2433 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2436 return bShowIgnoreMenu;
2439 HBITMAP CShellExt::IconToBitmapPARGB32(UINT uIcon)
2441 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
2442 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
2443 return bitmap_it->second;
2445 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2446 if (!hIcon)
2447 return NULL;
2449 if (pfnBeginBufferedPaint == NULL || pfnEndBufferedPaint == NULL || pfnGetBufferedPaintBits == NULL)
2450 return NULL;
2452 SIZE sizIcon;
2453 sizIcon.cx = GetSystemMetrics(SM_CXSMICON);
2454 sizIcon.cy = GetSystemMetrics(SM_CYSMICON);
2456 RECT rcIcon;
2457 SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy);
2458 HBITMAP hBmp = NULL;
2460 HDC hdcDest = CreateCompatibleDC(NULL);
2461 if (hdcDest)
2463 if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp)))
2465 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp);
2466 if (hbmpOld)
2468 BLENDFUNCTION bfAlpha = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2469 BP_PAINTPARAMS paintParams = {0};
2470 paintParams.cbSize = sizeof(paintParams);
2471 paintParams.dwFlags = BPPF_ERASE;
2472 paintParams.pBlendFunction = &bfAlpha;
2474 HDC hdcBuffer;
2475 HPAINTBUFFER hPaintBuffer = pfnBeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer);
2476 if (hPaintBuffer)
2478 if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL))
2480 // If icon did not have an alpha channel we need to convert buffer to PARGB
2481 ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon);
2484 // This will write the buffer contents to the destination bitmap
2485 pfnEndBufferedPaint(hPaintBuffer, TRUE);
2488 SelectObject(hdcDest, hbmpOld);
2492 DeleteDC(hdcDest);
2495 DestroyIcon(hIcon);
2497 if(hBmp)
2498 bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp));
2499 return hBmp;
2502 HRESULT CShellExt::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP* phBmp)
2504 *phBmp = NULL;
2506 BITMAPINFO bmi;
2507 ZeroMemory(&bmi, sizeof(bmi));
2508 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2509 bmi.bmiHeader.biPlanes = 1;
2510 bmi.bmiHeader.biCompression = BI_RGB;
2512 bmi.bmiHeader.biWidth = psize->cx;
2513 bmi.bmiHeader.biHeight = psize->cy;
2514 bmi.bmiHeader.biBitCount = 32;
2516 HDC hdcUsed = hdc ? hdc : GetDC(NULL);
2517 if (hdcUsed)
2519 *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0);
2520 if (hdc != hdcUsed)
2522 ReleaseDC(NULL, hdcUsed);
2525 return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK;
2528 HRESULT CShellExt::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon)
2530 RGBQUAD *prgbQuad;
2531 int cxRow;
2532 HRESULT hr = pfnGetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow);
2533 if (SUCCEEDED(hr))
2535 ARGB *pargb = reinterpret_cast<ARGB *>(prgbQuad);
2536 if (!HasAlpha(pargb, sizIcon, cxRow))
2538 ICONINFO info;
2539 if (GetIconInfo(hicon, &info))
2541 if (info.hbmMask)
2543 hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow);
2546 DeleteObject(info.hbmColor);
2547 DeleteObject(info.hbmMask);
2552 return hr;
2555 bool CShellExt::HasAlpha(__in ARGB *pargb, SIZE& sizImage, int cxRow)
2557 ULONG cxDelta = cxRow - sizImage.cx;
2558 for (ULONG y = sizImage.cy; y; --y)
2560 for (ULONG x = sizImage.cx; x; --x)
2562 if (*pargb++ & 0xFF000000)
2564 return true;
2568 pargb += cxDelta;
2571 return false;
2574 HRESULT CShellExt::ConvertToPARGB32(HDC hdc, __inout ARGB *pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow)
2576 BITMAPINFO bmi;
2577 ZeroMemory(&bmi, sizeof(bmi));
2578 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2579 bmi.bmiHeader.biPlanes = 1;
2580 bmi.bmiHeader.biCompression = BI_RGB;
2582 bmi.bmiHeader.biWidth = sizImage.cx;
2583 bmi.bmiHeader.biHeight = sizImage.cy;
2584 bmi.bmiHeader.biBitCount = 32;
2586 HRESULT hr = E_OUTOFMEMORY;
2587 HANDLE hHeap = GetProcessHeap();
2588 void *pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight);
2589 if (pvBits)
2591 hr = E_UNEXPECTED;
2592 if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight)
2594 ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth;
2595 ARGB *pargbMask = static_cast<ARGB *>(pvBits);
2597 for (ULONG y = bmi.bmiHeader.biHeight; y; --y)
2599 for (ULONG x = bmi.bmiHeader.biWidth; x; --x)
2601 if (*pargbMask++)
2603 // transparent pixel
2604 *pargb++ = 0;
2606 else
2608 // opaque pixel
2609 *pargb++ |= 0xFF000000;
2613 pargb += cxDelta;
2616 hr = S_OK;
2619 HeapFree(hHeap, 0, pvBits);
2622 return hr;
2625 void CShellExt::RunCommand(const tstring& path, const tstring& command, LPCTSTR errorMessage)
2627 if (CCreateProcessHelper::CreateProcessDetached(path.c_str(), const_cast<TCHAR*>(command.c_str())))
2629 // process started - exit
2630 return;
2633 MessageBox(NULL, CFormatMessageWrapper(), errorMessage, MB_OK | MB_ICONINFORMATION);