Rename a lot of SVN references to GIT
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blob6ab7e63c7517139a0bef136e6ce4898bf4a7e5a6
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"
29 #define GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
30 #define GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
32 int g_shellidlist=RegisterClipboardFormat(CFSTR_SHELLIDLIST);
34 extern MenuInfo menuInfo[];
37 STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST pIDFolder,
38 LPDATAOBJECT pDataObj,
39 HKEY /* hRegKey */)
42 ATLTRACE("Shell :: Initialize\n");
43 PreserveChdir preserveChdir;
44 files_.clear();
45 folder_.erase();
46 uuidSource.erase();
47 uuidTarget.erase();
48 itemStates = 0;
49 itemStatesFolder = 0;
50 stdstring statuspath;
51 git_wc_status_kind fetchedstatus = git_wc_status_none;
52 // get selected files/folders
53 if (pDataObj)
55 STGMEDIUM medium;
56 FORMATETC fmte = {(CLIPFORMAT)g_shellidlist,
57 (DVTARGETDEVICE FAR *)NULL,
58 DVASPECT_CONTENT,
59 -1,
60 TYMED_HGLOBAL};
61 HRESULT hres = pDataObj->GetData(&fmte, &medium);
63 if (SUCCEEDED(hres) && medium.hGlobal)
65 if (m_State == FileStateDropHandler)
68 FORMATETC etc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
69 STGMEDIUM stg = { TYMED_HGLOBAL };
70 if ( FAILED( pDataObj->GetData ( &etc, &stg )))
72 ReleaseStgMedium ( &medium );
73 return E_INVALIDARG;
77 HDROP drop = (HDROP)GlobalLock(stg.hGlobal);
78 if ( NULL == drop )
80 ReleaseStgMedium ( &stg );
81 ReleaseStgMedium ( &medium );
82 return E_INVALIDARG;
85 int count = DragQueryFile(drop, (UINT)-1, NULL, 0);
86 if (count == 1)
87 itemStates |= ITEMIS_ONLYONE;
88 for (int i = 0; i < count; i++)
90 // find the path length in chars
91 UINT len = DragQueryFile(drop, i, NULL, 0);
92 if (len == 0)
93 continue;
94 TCHAR * szFileName = new TCHAR[len+1];
95 if (0 == DragQueryFile(drop, i, szFileName, len+1))
97 delete [] szFileName;
98 continue;
100 stdstring str = stdstring(szFileName);
101 delete [] szFileName;
102 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(szFileName)))
104 if (itemStates & ITEMIS_ONLYONE)
106 CTGitPath strpath;
107 strpath.SetFromWin(str.c_str());
108 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
109 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
111 files_.push_back(str);
112 if (i == 0)
114 //get the Subversion status of the item
115 git_wc_status_kind status = git_wc_status_none;
116 CTGitPath askedpath;
117 askedpath.SetFromWin(str.c_str());
120 GitStatus stat;
121 stat.GetStatus(CTGitPath(str.c_str()), false, false, true);
122 if (stat.status)
124 statuspath = str;
125 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
126 fetchedstatus = status;
127 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
128 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
129 if ( askedpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
131 itemStates |= ITEMIS_FOLDER;
132 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
133 itemStates |= ITEMIS_FOLDERINGIT;
135 //if ((stat.status->entry)&&(stat.status->entry->present_props))
137 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
138 // itemStates |= ITEMIS_NEEDSLOCK;
140 //if ((stat.status->entry)&&(stat.status->entry->uuid))
141 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
143 else
145 // sometimes, git_client_status() returns with an error.
146 // in that case, we have to check if the working copy is versioned
147 // anyway to show the 'correct' context menu
148 if (askedpath.HasAdminDir())
149 status = git_wc_status_normal;
152 catch ( ... )
154 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
157 // TODO: should we really assume any sub-directory to be versioned
158 // or only if it contains versioned files
159 itemStates |= askedpath.GetAdminDirMask();
161 if ((status == git_wc_status_unversioned) || (status == git_wc_status_ignored) || (status == git_wc_status_none))
162 itemStates &= ~ITEMIS_INGIT;
164 if (status == git_wc_status_ignored)
165 itemStates |= ITEMIS_IGNORED;
166 if (status == git_wc_status_normal)
167 itemStates |= ITEMIS_NORMAL;
168 if (status == git_wc_status_conflicted)
169 itemStates |= ITEMIS_CONFLICTED;
170 if (status == git_wc_status_added)
171 itemStates |= ITEMIS_ADDED;
172 if (status == git_wc_status_deleted)
173 itemStates |= ITEMIS_DELETED;
176 } // for (int i = 0; i < count; i++)
177 GlobalUnlock ( drop );
178 ReleaseStgMedium ( &stg );
180 } // if (m_State == FileStateDropHandler)
181 else
184 //Enumerate PIDLs which the user has selected
185 CIDA* cida = (CIDA*)GlobalLock(medium.hGlobal);
186 ItemIDList parent( GetPIDLFolder (cida));
188 int count = cida->cidl;
189 BOOL statfetched = FALSE;
190 for (int i = 0; i < count; ++i)
192 ItemIDList child (GetPIDLItem (cida, i), &parent);
193 stdstring str = child.toString();
194 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(str.c_str())))
196 //check if our menu is requested for a subversion admin directory
197 if (g_GitAdminDir.IsAdminDirPath(str.c_str()))
198 continue;
200 files_.push_back(str);
201 CTGitPath strpath;
202 strpath.SetFromWin(str.c_str());
203 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
204 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
205 if (!statfetched)
207 //get the Subversion status of the item
208 git_wc_status_kind status = git_wc_status_none;
209 if ((g_ShellCache.IsSimpleContext())&&(strpath.IsDirectory()))
211 if (strpath.HasAdminDir())
212 status = git_wc_status_normal;
214 else
218 GitStatus stat;
219 if (strpath.HasAdminDir())
220 stat.GetStatus(strpath, false, false, true);
221 statuspath = str;
222 if (stat.status)
224 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
225 fetchedstatus = status;
226 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
227 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
228 if ( strpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
230 itemStates |= ITEMIS_FOLDER;
231 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
232 itemStates |= ITEMIS_FOLDERINGIT;
234 // TODO: do we need to check that it's not a dir? does conflict options makes sense for dir in git?
235 if (status == git_wc_status_conflicted)//if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
236 itemStates |= ITEMIS_CONFLICTED;
237 //if ((stat.status->entry)&&(stat.status->entry->present_props))
239 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
240 // itemStates |= ITEMIS_NEEDSLOCK;
242 //if ((stat.status->entry)&&(stat.status->entry->uuid))
243 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
245 else
247 // sometimes, git_client_status() returns with an error.
248 // in that case, we have to check if the working copy is versioned
249 // anyway to show the 'correct' context menu
250 if (strpath.HasAdminDir())
252 status = git_wc_status_normal;
253 fetchedstatus = status;
256 statfetched = TRUE;
258 catch ( ... )
260 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
264 itemStates |= strpath.GetAdminDirMask();
266 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
267 itemStates &= ~ITEMIS_INGIT;
268 if (status == git_wc_status_ignored)
270 itemStates |= ITEMIS_IGNORED;
271 // the item is ignored. Get the svn:ignored properties so we can (maybe) later
272 // offer a 'remove from ignored list' entry
273 // GitProperties props(strpath.GetContainingDirectory(), false);
274 // ignoredprops.empty();
275 // for (int p=0; p<props.GetCount(); ++p)
276 // {
277 // if (props.GetItemName(p).compare(stdstring(_T("svn:ignore")))==0)
278 // {
279 // std::string st = props.GetItemValue(p);
280 // ignoredprops = MultibyteToWide(st.c_str());
281 // // remove all escape chars ('\\')
282 // std::remove(ignoredprops.begin(), ignoredprops.end(), '\\');
283 // break;
284 // }
285 // }
288 if (status == git_wc_status_normal)
289 itemStates |= ITEMIS_NORMAL;
290 if (status == git_wc_status_conflicted)
291 itemStates |= ITEMIS_CONFLICTED;
292 if (status == git_wc_status_added)
293 itemStates |= ITEMIS_ADDED;
294 if (status == git_wc_status_deleted)
295 itemStates |= ITEMIS_DELETED;
298 } // for (int i = 0; i < count; ++i)
299 ItemIDList child (GetPIDLItem (cida, 0), &parent);
300 if (g_ShellCache.HasGITAdminDir(child.toString().c_str(), FALSE))
301 itemStates |= ITEMIS_INVERSIONEDFOLDER;
302 GlobalUnlock(medium.hGlobal);
304 // if the item is a versioned folder, check if there's a patch file
305 // in the clipboard to be used in "Apply Patch"
306 UINT cFormatDiff = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
307 if (cFormatDiff)
309 if (IsClipboardFormatAvailable(cFormatDiff))
310 itemStates |= ITEMIS_PATCHINCLIPBOARD;
312 if (IsClipboardFormatAvailable(CF_HDROP))
313 itemStates |= ITEMIS_PATHINCLIPBOARD;
317 ReleaseStgMedium ( &medium );
318 if (medium.pUnkForRelease)
320 IUnknown* relInterface = (IUnknown*)medium.pUnkForRelease;
321 relInterface->Release();
326 // get folder background
327 if (pIDFolder)
330 ItemIDList list(pIDFolder);
331 folder_ = list.toString();
332 git_wc_status_kind status = git_wc_status_none;
333 if (IsClipboardFormatAvailable(CF_HDROP))
334 itemStatesFolder |= ITEMIS_PATHINCLIPBOARD;
336 CTGitPath askedpath;
337 askedpath.SetFromWin(folder_.c_str());
339 if (g_ShellCache.IsContextPathAllowed(folder_.c_str()))
341 if (folder_.compare(statuspath)!=0)
346 GitStatus stat;
347 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
348 if (stat.status)
350 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
351 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
352 // itemStatesFolder |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
353 // if ((stat.status->entry)&&(stat.status->entry->present_props))
354 // {
355 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
356 // itemStatesFolder |= ITEMIS_NEEDSLOCK;
357 // }
358 // if ((stat.status->entry)&&(stat.status->entry->uuid))
359 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
362 else
364 // sometimes, git_client_status() returns with an error.
365 // in that case, we have to check if the working copy is versioned
366 // anyway to show the 'correct' context menu
367 if (askedpath.HasAdminDir())
368 status = git_wc_status_normal;
371 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
372 itemStatesFolder |= askedpath.GetAdminDirMask();
374 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
375 itemStates &= ~ITEMIS_INGIT;
377 if (status == git_wc_status_normal)
378 itemStatesFolder |= ITEMIS_NORMAL;
379 if (status == git_wc_status_conflicted)
380 itemStatesFolder |= ITEMIS_CONFLICTED;
381 if (status == git_wc_status_added)
382 itemStatesFolder |= ITEMIS_ADDED;
383 if (status == git_wc_status_deleted)
384 itemStatesFolder |= ITEMIS_DELETED;
387 catch ( ... )
389 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
392 else
394 status = fetchedstatus;
396 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
397 itemStatesFolder |= askedpath.GetAdminDirMask();
399 if (status == git_wc_status_ignored)
400 itemStatesFolder |= ITEMIS_IGNORED;
401 itemStatesFolder |= ITEMIS_FOLDER;
402 if (files_.size() == 0)
403 itemStates |= ITEMIS_ONLYONE;
404 if (m_State != FileStateDropHandler)
405 itemStates |= itemStatesFolder;
407 else
409 folder_.clear();
410 status = fetchedstatus;
413 if (files_.size() == 2)
414 itemStates |= ITEMIS_TWO;
415 if ((files_.size() == 1)&&(g_ShellCache.IsContextPathAllowed(files_.front().c_str())))
418 itemStates |= ITEMIS_ONLYONE;
419 if (m_State != FileStateDropHandler)
421 if (PathIsDirectory(files_.front().c_str()))
423 folder_ = files_.front();
424 git_wc_status_kind status = git_wc_status_none;
425 CTGitPath askedpath;
426 askedpath.SetFromWin(folder_.c_str());
428 if (folder_.compare(statuspath)!=0)
432 GitStatus stat;
433 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
434 if (stat.status)
436 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
437 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
438 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
439 // if ((stat.status->entry)&&(stat.status->entry->present_props))
440 // {
441 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
442 // itemStates |= ITEMIS_NEEDSLOCK;
443 // }
444 // if ((stat.status->entry)&&(stat.status->entry->uuid))
445 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
448 catch ( ... )
450 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
453 else
455 status = fetchedstatus;
457 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
458 itemStates |= askedpath.GetAdminDirMask();
460 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
461 itemStates &= ~ITEMIS_INGIT;
463 if (status == git_wc_status_ignored)
464 itemStates |= ITEMIS_IGNORED;
465 itemStates |= ITEMIS_FOLDER;
466 if (status == git_wc_status_added)
467 itemStates |= ITEMIS_ADDED;
468 if (status == git_wc_status_deleted)
469 itemStates |= ITEMIS_DELETED;
476 return NOERROR;
479 void CShellExt::InsertGitMenu(BOOL istop, HMENU menu, UINT pos, UINT_PTR id, UINT stringid, UINT icon, UINT idCmdFirst, GitCommands com, UINT /*uFlags*/)
481 TCHAR menutextbuffer[512] = {0};
482 TCHAR verbsbuffer[255] = {0};
483 MAKESTRING(stringid);
485 if (istop)
487 //menu entry for the top context menu, so append an "Git " before
488 //the menu text to indicate where the entry comes from
489 _tcscpy_s(menutextbuffer, 255, _T("Git "));
491 _tcscat_s(menutextbuffer, 255, stringtablebuffer);
492 #if 1
493 // insert branch name into "Git Commit..." entry, so it looks like "Git Commit "master"..."
494 // so we have an easy and fast way to check the current branch
495 // (the other alternative is using a separate disabled menu entry, the code is already done but commented out)
496 if (com == ShellMenuCommit)
498 // get branch name
499 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
500 CString sProjectRoot;
501 CString sBranchName;
503 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
505 if (sBranchName.GetLength() == 40)
507 // if SHA1 only show 4 first bytes
508 BOOL bIsSha1 = TRUE;
509 for (int i=0; i<40; i++)
510 if ( !iswxdigit(sBranchName[i]) )
512 bIsSha1 = FALSE;
513 break;
515 if (bIsSha1)
516 sBranchName = sBranchName.Left(8) + _T("....");
519 // sanity check
520 if (sBranchName.GetLength() > 64)
521 sBranchName = sBranchName.Left(64) + _T("...");
523 // scan to before "..."
524 LPTSTR s = menutextbuffer + _tcslen(menutextbuffer)-1;
525 if (s > menutextbuffer)
527 while (s > menutextbuffer)
529 if (*s != _T('.'))
531 s++;
532 break;
534 s--;
537 else
539 s = menutextbuffer;
542 // append branch name and end with ...
543 _tcscpy(s, _T(" -> \"") + sBranchName + _T("\"..."));
546 #endif
547 MENUITEMINFO menuiteminfo;
548 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
549 menuiteminfo.cbSize = sizeof(menuiteminfo);
550 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
551 menuiteminfo.fType = MFT_STRING;
552 menuiteminfo.dwTypeData = menutextbuffer;
553 if (icon)
555 menuiteminfo.fMask |= MIIM_BITMAP;
556 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
558 menuiteminfo.wID = id;
559 InsertMenuItem(menu, pos, TRUE, &menuiteminfo);
561 if (istop)
563 //menu entry for the top context menu, so append an "Git " before
564 //the menu text to indicate where the entry comes from
565 _tcscpy_s(menutextbuffer, 255, _T("Git "));
567 LoadString(g_hResInst, stringid, verbsbuffer, sizeof(verbsbuffer));
568 _tcscat_s(menutextbuffer, 255, verbsbuffer);
569 stdstring verb = stdstring(menutextbuffer);
570 if (verb.find('&') != -1)
572 verb.erase(verb.find('&'),1);
574 myVerbsMap[verb] = id - idCmdFirst;
575 myVerbsMap[verb] = id;
576 myVerbsIDMap[id - idCmdFirst] = verb;
577 myVerbsIDMap[id] = verb;
578 // We store the relative and absolute diameter
579 // (drawitem callback uses absolute, others relative)
580 myIDMap[id - idCmdFirst] = com;
581 myIDMap[id] = com;
582 if (!istop)
583 mySubMenuMap[pos] = com;
586 HBITMAP CShellExt::IconToBitmap(UINT uIcon)
588 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
589 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
590 return bitmap_it->second;
592 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 12, 12, LR_DEFAULTCOLOR);
593 if (!hIcon)
594 return NULL;
596 RECT rect;
598 rect.right = ::GetSystemMetrics(SM_CXMENUCHECK);
599 rect.bottom = ::GetSystemMetrics(SM_CYMENUCHECK);
601 rect.left = rect.top = 0;
603 HWND desktop = ::GetDesktopWindow();
604 if (desktop == NULL)
606 DestroyIcon(hIcon);
607 return NULL;
610 HDC screen_dev = ::GetDC(desktop);
611 if (screen_dev == NULL)
613 DestroyIcon(hIcon);
614 return NULL;
617 // Create a compatible DC
618 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
619 if (dst_hdc == NULL)
621 DestroyIcon(hIcon);
622 ::ReleaseDC(desktop, screen_dev);
623 return NULL;
626 // Create a new bitmap of icon size
627 HBITMAP bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
628 if (bmp == NULL)
630 DestroyIcon(hIcon);
631 ::DeleteDC(dst_hdc);
632 ::ReleaseDC(desktop, screen_dev);
633 return NULL;
636 // Select it into the compatible DC
637 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
638 if (old_dst_bmp == NULL)
640 DestroyIcon(hIcon);
641 return NULL;
644 // Fill the background of the compatible DC with the white color
645 // that is taken by menu routines as transparent
646 ::SetBkColor(dst_hdc, RGB(255, 255, 255));
647 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
649 // Draw the icon into the compatible DC
650 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
652 // Restore settings
653 ::SelectObject(dst_hdc, old_dst_bmp);
654 ::DeleteDC(dst_hdc);
655 ::ReleaseDC(desktop, screen_dev);
656 DestroyIcon(hIcon);
657 if (bmp)
658 bitmaps.insert(bitmap_it, std::make_pair(uIcon, bmp));
659 return bmp;
662 bool CShellExt::WriteClipboardPathsToTempFile(stdstring& tempfile)
664 bool bRet = true;
665 tempfile = stdstring();
666 //write all selected files and paths to a temporary file
667 //for TortoiseProc.exe to read out again.
668 DWORD written = 0;
669 DWORD pathlength = GetTempPath(0, NULL);
670 TCHAR * path = new TCHAR[pathlength+1];
671 TCHAR * tempFile = new TCHAR[pathlength + 100];
672 GetTempPath (pathlength+1, path);
673 GetTempFileName (path, _T("git"), 0, tempFile);
674 tempfile = stdstring(tempFile);
676 HANDLE file = ::CreateFile (tempFile,
677 GENERIC_WRITE,
678 FILE_SHARE_READ,
680 CREATE_ALWAYS,
681 FILE_ATTRIBUTE_TEMPORARY,
684 delete [] path;
685 delete [] tempFile;
686 if (file == INVALID_HANDLE_VALUE)
687 return false;
689 if (!IsClipboardFormatAvailable(CF_HDROP))
690 return false;
691 if (!OpenClipboard(NULL))
692 return false;
694 stdstring sClipboardText;
695 HGLOBAL hglb = GetClipboardData(CF_HDROP);
696 HDROP hDrop = (HDROP)GlobalLock(hglb);
697 if(hDrop != NULL)
699 TCHAR szFileName[MAX_PATH];
700 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
701 for(UINT i = 0; i < cFiles; ++i)
703 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
704 stdstring filename = szFileName;
705 ::WriteFile (file, filename.c_str(), filename.size()*sizeof(TCHAR), &written, 0);
706 ::WriteFile (file, _T("\n"), 2, &written, 0);
708 GlobalUnlock(hDrop);
710 else bRet = false;
711 GlobalUnlock(hglb);
713 CloseClipboard();
714 ::CloseHandle(file);
716 return bRet;
719 stdstring CShellExt::WriteFileListToTempFile()
721 //write all selected files and paths to a temporary file
722 //for TortoiseProc.exe to read out again.
723 DWORD pathlength = GetTempPath(0, NULL);
724 TCHAR * path = new TCHAR[pathlength+1];
725 TCHAR * tempFile = new TCHAR[pathlength + 100];
726 GetTempPath (pathlength+1, path);
727 GetTempFileName (path, _T("git"), 0, tempFile);
728 stdstring retFilePath = stdstring(tempFile);
730 HANDLE file = ::CreateFile (tempFile,
731 GENERIC_WRITE,
732 FILE_SHARE_READ,
734 CREATE_ALWAYS,
735 FILE_ATTRIBUTE_TEMPORARY,
738 delete [] path;
739 delete [] tempFile;
740 if (file == INVALID_HANDLE_VALUE)
741 return stdstring();
743 DWORD written = 0;
744 if (files_.empty())
746 ::WriteFile (file, folder_.c_str(), folder_.size()*sizeof(TCHAR), &written, 0);
747 ::WriteFile (file, _T("\n"), 2, &written, 0);
750 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
752 ::WriteFile (file, I->c_str(), I->size()*sizeof(TCHAR), &written, 0);
753 ::WriteFile (file, _T("\n"), 2, &written, 0);
755 ::CloseHandle(file);
756 return retFilePath;
759 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
761 PreserveChdir preserveChdir;
762 LoadLangDll();
764 if ((uFlags & CMF_DEFAULTONLY)!=0)
765 return NOERROR; //we don't change the default action
767 if ((files_.size() == 0)||(folder_.size() == 0))
768 return NOERROR;
770 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
771 return NOERROR;
773 if (itemStatesFolder & ITEMIS_FOLDER) // we do not support folders atm, see issue #963
774 return NOERROR;
776 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
778 //the drop handler only has eight commands, but not all are visible at the same time:
779 //if the source file(s) are under version control then those files can be moved
780 //to the new location or they can be moved with a rename,
781 //if they are unversioned then they can be added to the working copy
782 //if they are versioned, they also can be exported to an unversioned location
783 UINT idCmd = idCmdFirst;
785 // Git move here
786 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
787 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
788 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
790 // Git move and rename here
791 // 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
792 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
793 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
795 // Git copy here
796 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
797 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
798 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
800 // Git copy and rename here, source and target from same repository
801 // available if source is a single, versioned but not added item, target is versioned or target folder is added
802 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
803 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
805 // Git add here
806 // available if target is versioned and source is either unversioned or from another repository
807 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
808 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
810 // Git export here
811 // available if source is versioned and a folder
812 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
813 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
815 // Git export all here
816 // available if source is versioned and a folder
817 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
818 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
820 // apply patch
821 // available if source is a patchfile
822 if (itemStates & ITEMIS_PATCHFILE)
823 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
825 // separator
826 if (idCmd != idCmdFirst)
827 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
829 TweakMenu(hMenu);
831 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
834 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
835 UINT indexMenu,
836 UINT idCmdFirst,
837 UINT /*idCmdLast*/,
838 UINT uFlags)
840 ATLTRACE("Shell :: QueryContextMenu\n");
841 PreserveChdir preserveChdir;
843 //first check if our drop handler is called
844 //and then (if true) provide the context menu for the
845 //drop handler
846 if (m_State == FileStateDropHandler)
848 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
851 if ((uFlags & CMF_DEFAULTONLY)!=0)
852 return NOERROR; //we don't change the default action
854 if ((files_.size() == 0)&&(folder_.size() == 0))
855 return NOERROR;
857 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
858 return NOERROR;
860 int csidlarray[] =
862 CSIDL_BITBUCKET,
863 CSIDL_CDBURN_AREA,
864 CSIDL_COMMON_FAVORITES,
865 CSIDL_COMMON_STARTMENU,
866 CSIDL_COMPUTERSNEARME,
867 CSIDL_CONNECTIONS,
868 CSIDL_CONTROLS,
869 CSIDL_COOKIES,
870 CSIDL_FAVORITES,
871 CSIDL_FONTS,
872 CSIDL_HISTORY,
873 CSIDL_INTERNET,
874 CSIDL_INTERNET_CACHE,
875 CSIDL_NETHOOD,
876 CSIDL_NETWORK,
877 CSIDL_PRINTERS,
878 CSIDL_PRINTHOOD,
879 CSIDL_RECENT,
880 CSIDL_SENDTO,
881 CSIDL_STARTMENU,
884 if (IsIllegalFolder(folder_, csidlarray))
885 return NOERROR;
887 if (folder_.empty())
889 // folder is empty, but maybe files are selected
890 if (files_.size() == 0)
891 return NOERROR; // nothing selected - we don't have a menu to show
892 // check whether a selected entry is an UID - those are namespace extensions
893 // which we can't handle
894 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
896 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
897 return NOERROR;
901 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
903 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT))==0)
904 return S_OK;
907 //check if our menu is requested for a subversion admin directory
908 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
909 return NOERROR;
911 if (uFlags & CMF_EXTENDEDVERBS)
912 itemStates |= ITEMIS_EXTENDED;
914 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
915 if ( bShortcut && (files_.size()==1))
917 // Don't show the context menu for a link if the
918 // destination is not part of a working copy.
919 // It would only show the standard menu items
920 // which are already shown for the lnk-file.
921 CString path = files_.front().c_str();
922 if ( !g_GitAdminDir.HasAdminDir(path) )
924 return NOERROR;
928 //check if we already added our menu entry for a folder.
929 //we check that by iterating through all menu entries and check if
930 //the dwItemData member points to our global ID string. That string is set
931 //by our shell extension when the folder menu is inserted.
932 TCHAR menubuf[MAX_PATH];
933 int count = GetMenuItemCount(hMenu);
934 for (int i=0; i<count; ++i)
936 MENUITEMINFO miif;
937 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
938 miif.cbSize = sizeof(MENUITEMINFO);
939 miif.fMask = MIIM_DATA;
940 miif.dwTypeData = menubuf;
941 miif.cch = _countof(menubuf);
942 GetMenuItemInfo(hMenu, i, TRUE, &miif);
943 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
944 return NOERROR;
947 LoadLangDll();
948 UINT idCmd = idCmdFirst;
950 //create the sub menu
951 HMENU subMenu = CreateMenu();
952 int indexSubMenu = 0;
954 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
955 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
956 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
958 int menuIndex = 0;
959 bool bAddSeparator = false;
960 bool bMenuEntryAdded = false;
961 bool bMenuEmpty = true;
962 // insert separator at start
963 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
964 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
966 #if 0
967 if (itemStates & (ITEMIS_INSVN|ITEMIS_FOLDERINSVN))
969 // show current branch name (as a "read-only" menu entry)
971 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
972 CString sProjectRoot;
973 CString sBranchName;
975 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
977 if (sBranchName.GetLength() == 40)
979 // if SHA1 only show 4 first bytes
980 BOOL bIsSha1 = TRUE;
981 for (int i=0; i<40; i++)
982 if ( !iswxdigit(sBranchName[i]) )
984 bIsSha1 = FALSE;
985 break;
987 if (bIsSha1)
988 sBranchName = sBranchName.Left(8) + _T("....");
991 sBranchName = _T('"') + sBranchName + _T('"');
993 const int icon = IDI_COPY;
994 const int pos = indexMenu++;
995 const int id = idCmd++;
997 MENUITEMINFO menuiteminfo;
998 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
999 menuiteminfo.cbSize = sizeof(menuiteminfo);
1000 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_STATE;
1001 menuiteminfo.fState = MFS_DISABLED;
1002 menuiteminfo.fType = MFT_STRING;
1003 menuiteminfo.dwTypeData = (LPWSTR)sBranchName.GetString();
1004 if (icon)
1006 menuiteminfo.fMask |= MIIM_BITMAP;
1007 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
1009 if (menuiteminfo.hbmpItem == HBMMENU_CALLBACK)
1011 // WM_DRAWITEM uses myIDMap to get icon, we use the same icon as create branch
1012 myIDMap[id - idCmdFirst] = ShellMenuBranch;
1013 myIDMap[id] = ShellMenuBranch;
1016 menuiteminfo.wID = id;
1017 InsertMenuItem(hMenu, pos, TRUE, &menuiteminfo);
1020 #endif
1022 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1024 if (menuInfo[menuIndex].command == ShellSeparator)
1026 // we don't add a separator immediately. Because there might not be
1027 // another 'normal' menu entry after we insert a separator.
1028 // we simply set a flag here, indicating that before the next
1029 // 'normal' menu entry, a separator should be added.
1030 if (!bMenuEmpty)
1031 bAddSeparator = true;
1033 else
1035 // check the conditions whether to show the menu entry or not
1036 bool bInsertMenu = false;
1038 if (menuInfo[menuIndex].firstyes && menuInfo[menuIndex].firstno)
1040 if (((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes)
1042 ((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1043 bInsertMenu = true;
1045 else if ((menuInfo[menuIndex].firstyes)&&((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes))
1046 bInsertMenu = true;
1047 else if ((menuInfo[menuIndex].firstno)&&((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1048 bInsertMenu = true;
1050 if (menuInfo[menuIndex].secondyes && menuInfo[menuIndex].secondno)
1052 if (((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes)
1054 ((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1055 bInsertMenu = true;
1057 else if ((menuInfo[menuIndex].secondyes)&&((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes))
1058 bInsertMenu = true;
1059 else if ((menuInfo[menuIndex].secondno)&&((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1060 bInsertMenu = true;
1062 if (menuInfo[menuIndex].thirdyes && menuInfo[menuIndex].thirdno)
1064 if (((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes)
1066 ((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1067 bInsertMenu = true;
1069 else if ((menuInfo[menuIndex].thirdyes)&&((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes))
1070 bInsertMenu = true;
1071 else if ((menuInfo[menuIndex].thirdno)&&((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1072 bInsertMenu = true;
1074 if (menuInfo[menuIndex].fourthyes && menuInfo[menuIndex].fourthno)
1076 if (((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes)
1078 ((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1079 bInsertMenu = true;
1081 else if ((menuInfo[menuIndex].fourthyes)&&((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes))
1082 bInsertMenu = true;
1083 else if ((menuInfo[menuIndex].fourthno)&&((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1084 bInsertMenu = true;
1086 if (menuInfo[menuIndex].menuID & menuex)
1088 if( !(itemStates & ITEMIS_EXTENDED) )
1090 bInsertMenu = false;
1094 if (menuInfo[menuIndex].menuID & (~menumask))
1096 if (bInsertMenu)
1098 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1099 // insert a separator
1100 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1102 bAddSeparator = false;
1103 bMenuEntryAdded = false;
1104 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1105 idCmd++;
1108 // handle special cases (sub menus)
1109 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1111 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1113 bMenuEntryAdded = true;
1114 bMenuEmpty = false;
1117 else
1119 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1121 // insert the menu entry
1122 InsertGitMenu( bIsTop,
1123 bIsTop ? hMenu : subMenu,
1124 bIsTop ? indexMenu++ : indexSubMenu++,
1125 idCmd++,
1126 menuInfo[menuIndex].menuTextID,
1127 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1128 idCmdFirst,
1129 menuInfo[menuIndex].command,
1130 uFlags);
1131 if (!bIsTop)
1133 bMenuEntryAdded = true;
1134 bMenuEmpty = false;
1135 bAddSeparator = false;
1141 menuIndex++;
1144 //add sub menu to main context menu
1145 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1146 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1147 MAKESTRING(IDS_MENUSUBMENU);
1148 MENUITEMINFO menuiteminfo;
1149 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1150 menuiteminfo.cbSize = sizeof(menuiteminfo);
1151 menuiteminfo.fType = MFT_STRING;
1152 menuiteminfo.dwTypeData = stringtablebuffer;
1154 UINT uIcon = bShowIcons ? IDI_APP : 0;
1155 if (folder_.size())
1157 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1158 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1159 myIDMap[idCmd] = ShellSubMenuFolder;
1160 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1162 else if (!bShortcut && (files_.size()==1))
1164 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1165 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1166 myIDMap[idCmd] = ShellSubMenuFile;
1168 else if (bShortcut && (files_.size()==1))
1170 uIcon = bShowIcons ? IDI_MENULINK : 0;
1171 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1172 myIDMap[idCmd] = ShellSubMenuLink;
1174 else if (files_.size() > 1)
1176 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1177 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1178 myIDMap[idCmd] = ShellSubMenuMultiple;
1180 else
1182 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1183 myIDMap[idCmd] = ShellSubMenu;
1185 HBITMAP bmp = NULL;
1186 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1187 if (uIcon)
1189 menuiteminfo.fMask |= MIIM_BITMAP;
1190 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(uIcon) : HBMMENU_CALLBACK;
1192 menuiteminfo.hSubMenu = subMenu;
1193 menuiteminfo.wID = idCmd++;
1194 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1196 //separator after
1197 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1199 TweakMenu(hMenu);
1201 //return number of menu items added
1202 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1205 void CShellExt::TweakMenu(HMENU hMenu)
1207 MENUINFO MenuInfo = {};
1208 MenuInfo.cbSize = sizeof(MenuInfo);
1209 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1210 MenuInfo.dwStyle = MNS_CHECKORBMP;
1211 SetMenuInfo(hMenu, &MenuInfo);
1214 // This is called when you invoke a command on the menu:
1215 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1217 PreserveChdir preserveChdir;
1218 HRESULT hr = E_INVALIDARG;
1219 if (lpcmi == NULL)
1220 return hr;
1222 std::string command;
1223 std::string parent;
1224 std::string file;
1226 if ((files_.size() > 0)||(folder_.size() > 0))
1228 UINT idCmd = LOWORD(lpcmi->lpVerb);
1230 if (HIWORD(lpcmi->lpVerb))
1232 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1233 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1234 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1235 idCmd = verb_it->second;
1236 else
1237 return hr;
1240 // See if we have a handler interface for this id
1241 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1242 if (id_it != myIDMap.end() && id_it->first == idCmd)
1244 STARTUPINFO startup;
1245 PROCESS_INFORMATION process;
1246 memset(&startup, 0, sizeof(startup));
1247 startup.cb = sizeof(startup);
1248 memset(&process, 0, sizeof(process));
1249 CRegStdString tortoiseProcPath(_T("Software\\TortoiseGit\\ProcPath"), _T("TortoiseProc.exe"), false, HKEY_LOCAL_MACHINE);
1250 CRegStdString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T("TortoiseMerge.exe"), false, HKEY_LOCAL_MACHINE);
1252 //TortoiseProc expects a command line of the form:
1253 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1254 // or
1255 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1257 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1258 //* pathfile is a path to a temporary file which contains a list of file paths
1259 stdstring gitCmd = _T(" /command:");
1260 stdstring tempfile;
1261 switch (id_it->second)
1263 //#region case
1264 case ShellMenuSync:
1265 gitCmd += _T("sync /path:\"");
1266 if (files_.size() > 0)
1267 gitCmd += files_.front();
1268 else
1269 gitCmd += folder_;
1270 gitCmd += _T("\"");
1271 break;
1272 case ShellMenuUpdate:
1273 tempfile = WriteFileListToTempFile();
1274 gitCmd += _T("update /pathfile:\"");
1275 gitCmd += tempfile;
1276 gitCmd += _T("\"");
1277 gitCmd += _T(" /deletepathfile");
1278 break;
1279 case ShellMenuSubSync:
1280 tempfile = WriteFileListToTempFile();
1281 gitCmd += _T("subsync /pathfile:\"");
1282 gitCmd += tempfile;
1283 gitCmd += _T("\"");
1284 gitCmd += _T(" /deletepathfile");
1285 if(itemStatesFolder&ITEMIS_SUBMODULECONTAINER)
1287 gitCmd += _T(" /bkpath:\"");
1288 gitCmd += folder_;
1289 gitCmd += _T("\"");
1291 break;
1292 case ShellMenuUpdateExt:
1293 tempfile = WriteFileListToTempFile();
1294 gitCmd += _T("subupdate /pathfile:\"");
1295 gitCmd += tempfile;
1296 gitCmd += _T("\"");
1297 gitCmd += _T(" /deletepathfile");
1298 if(itemStatesFolder&ITEMIS_SUBMODULECONTAINER)
1300 gitCmd += _T(" /bkpath:\"");
1301 gitCmd += folder_;
1302 gitCmd += _T("\"");
1304 break;
1305 case ShellMenuCommit:
1306 tempfile = WriteFileListToTempFile();
1307 gitCmd += _T("commit /pathfile:\"");
1308 gitCmd += tempfile;
1309 gitCmd += _T("\"");
1310 gitCmd += _T(" /deletepathfile");
1311 break;
1312 case ShellMenuAdd:
1313 case ShellMenuAddAsReplacement:
1314 tempfile = WriteFileListToTempFile();
1315 gitCmd += _T("add /pathfile:\"");
1316 gitCmd += tempfile;
1317 gitCmd += _T("\"");
1318 gitCmd += _T(" /deletepathfile");
1319 break;
1320 case ShellMenuIgnore:
1321 tempfile = WriteFileListToTempFile();
1322 gitCmd += _T("ignore /pathfile:\"");
1323 gitCmd += tempfile;
1324 gitCmd += _T("\"");
1325 gitCmd += _T(" /deletepathfile");
1326 break;
1327 case ShellMenuIgnoreCaseSensitive:
1328 tempfile = WriteFileListToTempFile();
1329 gitCmd += _T("ignore /pathfile:\"");
1330 gitCmd += tempfile;
1331 gitCmd += _T("\"");
1332 gitCmd += _T(" /deletepathfile");
1333 gitCmd += _T(" /onlymask");
1334 break;
1335 case ShellMenuDeleteIgnore:
1336 tempfile = WriteFileListToTempFile();
1337 gitCmd += _T("ignore /delete /pathfile:\"");
1338 gitCmd += tempfile;
1339 gitCmd += _T("\"");
1340 gitCmd += _T(" /deletepathfile");
1341 break;
1342 case ShellMenuDeleteIgnoreCaseSensitive:
1343 tempfile = WriteFileListToTempFile();
1344 gitCmd += _T("ignore /delete /pathfile:\"");
1345 gitCmd += tempfile;
1346 gitCmd += _T("\"");
1347 gitCmd += _T(" /deletepathfile");
1348 gitCmd += _T(" /onlymask");
1349 break;
1350 case ShellMenuUnIgnore:
1351 tempfile = WriteFileListToTempFile();
1352 gitCmd += _T("unignore /pathfile:\"");
1353 gitCmd += tempfile;
1354 gitCmd += _T("\"");
1355 gitCmd += _T(" /deletepathfile");
1356 break;
1357 case ShellMenuUnIgnoreCaseSensitive:
1358 tempfile = WriteFileListToTempFile();
1359 gitCmd += _T("unignore /pathfile:\"");
1360 gitCmd += tempfile;
1361 gitCmd += _T("\"");
1362 gitCmd += _T(" /deletepathfile");
1363 gitCmd += _T(" /onlymask");
1364 break;
1365 case ShellMenuRevert:
1366 tempfile = WriteFileListToTempFile();
1367 gitCmd += _T("revert /pathfile:\"");
1368 gitCmd += tempfile;
1369 gitCmd += _T("\"");
1370 gitCmd += _T(" /deletepathfile");
1371 break;
1372 case ShellMenuCleanup:
1373 tempfile = WriteFileListToTempFile();
1374 gitCmd += _T("cleanup /pathfile:\"");
1375 gitCmd += tempfile;
1376 gitCmd += _T("\"");
1377 gitCmd += _T(" /deletepathfile");
1378 break;
1379 case ShellMenuSendMail:
1380 tempfile = WriteFileListToTempFile();
1381 gitCmd += _T("sendmail /pathfile:\"");
1382 gitCmd += tempfile;
1383 gitCmd += _T("\"");
1384 gitCmd += _T(" /deletepathfile");
1385 break;
1386 case ShellMenuResolve:
1387 tempfile = WriteFileListToTempFile();
1388 gitCmd += _T("resolve /pathfile:\"");
1389 gitCmd += tempfile;
1390 gitCmd += _T("\"");
1391 gitCmd += _T(" /deletepathfile");
1392 break;
1393 case ShellMenuSwitch:
1394 gitCmd += _T("switch /path:\"");
1395 if (files_.size() > 0)
1396 gitCmd += files_.front();
1397 else
1398 gitCmd += folder_;
1399 gitCmd += _T("\"");
1400 break;
1401 case ShellMenuExport:
1402 gitCmd += _T("export /path:\"");
1403 if (files_.size() > 0)
1404 gitCmd += files_.front();
1405 else
1406 gitCmd += folder_;
1407 gitCmd += _T("\"");
1408 break;
1409 case ShellMenuAbout:
1410 gitCmd += _T("about");
1411 break;
1412 case ShellMenuCreateRepos:
1413 gitCmd += _T("repocreate /path:\"");
1414 if (files_.size() > 0)
1415 gitCmd += files_.front();
1416 else
1417 gitCmd += folder_;
1418 gitCmd += _T("\"");
1419 break;
1420 case ShellMenuMerge:
1421 gitCmd += _T("merge /path:\"");
1422 if (files_.size() > 0)
1423 gitCmd += files_.front();
1424 else
1425 gitCmd += folder_;
1426 gitCmd += _T("\"");
1427 break;
1428 case ShellMenuCopy:
1429 gitCmd += _T("copy /path:\"");
1430 if (files_.size() > 0)
1431 gitCmd += files_.front();
1432 else
1433 gitCmd += folder_;
1434 gitCmd += _T("\"");
1435 break;
1436 case ShellMenuSettings:
1437 gitCmd += _T("settings /path:\"");
1438 if (files_.size() > 0)
1439 gitCmd += files_.front();
1440 else
1441 gitCmd += folder_;
1442 gitCmd += _T("\"");
1443 break;
1444 case ShellMenuHelp:
1445 gitCmd += _T("help");
1446 break;
1447 case ShellMenuRename:
1448 gitCmd += _T("rename /path:\"");
1449 if (files_.size() > 0)
1450 gitCmd += files_.front();
1451 else
1452 gitCmd += folder_;
1453 gitCmd += _T("\"");
1454 break;
1455 case ShellMenuRemove:
1456 tempfile = WriteFileListToTempFile();
1457 gitCmd += _T("remove /pathfile:\"");
1458 gitCmd += tempfile;
1459 gitCmd += _T("\"");
1460 gitCmd += _T(" /deletepathfile");
1461 break;
1462 case ShellMenuRemoveKeep:
1463 tempfile = WriteFileListToTempFile();
1464 gitCmd += _T("remove /pathfile:\"");
1465 gitCmd += tempfile;
1466 gitCmd += _T("\"");
1467 gitCmd += _T(" /deletepathfile");
1468 gitCmd += _T(" /keep");
1469 break;
1470 case ShellMenuDiff:
1471 gitCmd += _T("diff /path:\"");
1472 if (files_.size() == 1)
1473 gitCmd += files_.front();
1474 else if (files_.size() == 2)
1476 std::vector<stdstring>::iterator I = files_.begin();
1477 gitCmd += *I;
1478 I++;
1479 gitCmd += _T("\" /path2:\"");
1480 gitCmd += *I;
1482 else
1483 gitCmd += folder_;
1484 gitCmd += _T("\"");
1485 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1486 gitCmd += _T(" /alternative");
1487 break;
1488 case ShellMenuPrevDiff:
1489 gitCmd += _T("prevdiff /path:\"");
1490 if (files_.size() == 1)
1491 gitCmd += files_.front();
1492 else
1493 gitCmd += folder_;
1494 gitCmd += _T("\"");
1495 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1496 gitCmd += _T(" /alternative");
1497 break;
1498 case ShellMenuDiffTwo:
1499 gitCmd += _T("diffcommits /path:\"");
1500 if (files_.size() == 1)
1501 gitCmd += files_.front();
1502 else
1503 gitCmd += folder_;
1504 gitCmd += _T("\"");
1505 break;
1506 case ShellMenuDropCopyAdd:
1507 tempfile = WriteFileListToTempFile();
1508 gitCmd += _T("dropcopyadd /pathfile:\"");
1509 gitCmd += tempfile;
1510 gitCmd += _T("\"");
1511 gitCmd += _T(" /deletepathfile");
1512 gitCmd += _T(" /droptarget:\"");
1513 gitCmd += folder_;
1514 gitCmd += _T("\"";)
1515 break;
1516 case ShellMenuDropCopy:
1517 tempfile = WriteFileListToTempFile();
1518 gitCmd += _T("dropcopy /pathfile:\"");
1519 gitCmd += tempfile;
1520 gitCmd += _T("\"");
1521 gitCmd += _T(" /deletepathfile");
1522 gitCmd += _T(" /droptarget:\"");
1523 gitCmd += folder_;
1524 gitCmd += _T("\"";)
1525 break;
1526 case ShellMenuDropCopyRename:
1527 tempfile = WriteFileListToTempFile();
1528 gitCmd += _T("dropcopy /pathfile:\"");
1529 gitCmd += tempfile;
1530 gitCmd += _T("\"");
1531 gitCmd += _T(" /deletepathfile");
1532 gitCmd += _T(" /droptarget:\"");
1533 gitCmd += folder_;
1534 gitCmd += _T("\" /rename";)
1535 break;
1536 case ShellMenuDropMove:
1537 tempfile = WriteFileListToTempFile();
1538 gitCmd += _T("dropmove /pathfile:\"");
1539 gitCmd += tempfile;
1540 gitCmd += _T("\"");
1541 gitCmd += _T(" /deletepathfile");
1542 gitCmd += _T(" /droptarget:\"");
1543 gitCmd += folder_;
1544 gitCmd += _T("\"");
1545 break;
1546 case ShellMenuDropMoveRename:
1547 tempfile = WriteFileListToTempFile();
1548 gitCmd += _T("dropmove /pathfile:\"");
1549 gitCmd += tempfile;
1550 gitCmd += _T("\"");
1551 gitCmd += _T(" /deletepathfile");
1552 gitCmd += _T(" /droptarget:\"");
1553 gitCmd += folder_;
1554 gitCmd += _T("\" /rename";)
1555 break;
1556 case ShellMenuDropExport:
1557 tempfile = WriteFileListToTempFile();
1558 gitCmd += _T("dropexport /pathfile:\"");
1559 gitCmd += tempfile;
1560 gitCmd += _T("\"");
1561 gitCmd += _T(" /deletepathfile");
1562 gitCmd += _T(" /droptarget:\"");
1563 gitCmd += folder_;
1564 gitCmd += _T("\"");
1565 break;
1566 case ShellMenuDropExportExtended:
1567 tempfile = WriteFileListToTempFile();
1568 gitCmd += _T("dropexport /pathfile:\"");
1569 gitCmd += tempfile;
1570 gitCmd += _T("\"");
1571 gitCmd += _T(" /deletepathfile");
1572 gitCmd += _T(" /droptarget:\"");
1573 gitCmd += folder_;
1574 gitCmd += _T("\"");
1575 gitCmd += _T(" /extended");
1576 break;
1577 case ShellMenuLog:
1578 gitCmd += _T("log /path:\"");
1579 if (files_.size() > 0)
1580 gitCmd += files_.front();
1581 else
1582 gitCmd += folder_;
1583 gitCmd += _T("\"");
1584 break;
1585 case ShellMenuConflictEditor:
1586 gitCmd += _T("conflicteditor /path:\"");
1587 if (files_.size() > 0)
1588 gitCmd += files_.front();
1589 else
1590 gitCmd += folder_;
1591 gitCmd += _T("\"");
1592 break;
1593 case ShellMenuGitSVNRebase:
1594 gitCmd += _T("svnrebase /path:\"");
1595 if (files_.size() > 0)
1596 gitCmd += files_.front();
1597 else
1598 gitCmd += folder_;
1599 gitCmd += _T("\"");
1600 break;
1601 case ShellMenuGitSVNDCommit:
1602 gitCmd += _T("svndcommit /path:\"");
1603 if (files_.size() > 0)
1604 gitCmd += files_.front();
1605 else
1606 gitCmd += folder_;
1607 gitCmd += _T("\"");
1608 break;
1609 case ShellMenuGitSVNIgnore:
1610 gitCmd += _T("svnignore /path:\"");
1611 if (files_.size() > 0)
1612 gitCmd += files_.front();
1613 else
1614 gitCmd += folder_;
1615 gitCmd += _T("\"");
1616 break;
1617 case ShellMenuRebase:
1618 gitCmd += _T("rebase /path:\"");
1619 if (files_.size() > 0)
1620 gitCmd += files_.front();
1621 else
1622 gitCmd += folder_;
1623 gitCmd += _T("\"");
1624 break;
1625 case ShellMenuShowChanged:
1626 if (files_.size() > 1)
1628 tempfile = WriteFileListToTempFile();
1629 gitCmd += _T("repostatus /pathfile:\"");
1630 gitCmd += tempfile;
1631 gitCmd += _T("\"");
1632 gitCmd += _T(" /deletepathfile");
1634 else
1636 gitCmd += _T("repostatus /path:\"");
1637 if (files_.size() > 0)
1638 gitCmd += files_.front();
1639 else
1640 gitCmd += folder_;
1641 gitCmd += _T("\"");
1643 break;
1644 case ShellMenuRefBrowse:
1645 gitCmd += _T("refbrowse /path:\"");
1646 if (files_.size() > 0)
1647 gitCmd += files_.front();
1648 else
1649 gitCmd += folder_;
1650 gitCmd += _T("\"");
1651 break;
1652 case ShellMenuRefLog:
1653 gitCmd += _T("reflog /path:\"");
1654 if (files_.size() > 0)
1655 gitCmd += files_.front();
1656 else
1657 gitCmd += folder_;
1658 gitCmd += _T("\"");
1659 break;
1661 case ShellMenuStashSave:
1662 gitCmd += _T("stashsave /path:\"");
1663 if (files_.size() > 0)
1664 gitCmd += files_.front();
1665 else
1666 gitCmd += folder_;
1667 gitCmd += _T("\"");
1668 break;
1670 case ShellMenuStashApply:
1671 gitCmd += _T("stashapply /path:\"");
1672 if (files_.size() > 0)
1673 gitCmd += files_.front();
1674 else
1675 gitCmd += folder_;
1676 gitCmd += _T("\"");
1677 break;
1679 case ShellMenuStashPop:
1680 gitCmd += _T("stashpop /path:\"");
1681 if (files_.size() > 0)
1682 gitCmd += files_.front();
1683 else
1684 gitCmd += folder_;
1685 gitCmd += _T("\"");
1686 break;
1689 case ShellMenuStashList:
1690 gitCmd += _T("reflog /path:\"");
1691 if (files_.size() > 0)
1692 gitCmd += files_.front();
1693 else
1694 gitCmd += folder_;
1695 gitCmd += _T("\" /ref:refs/stash");
1696 break;
1698 case ShellMenuBisectStart:
1699 gitCmd += _T("bisect /path:\"");
1700 if (files_.size() > 0)
1701 gitCmd += files_.front();
1702 else
1703 gitCmd += folder_;
1704 gitCmd += _T("\" /start");
1705 break;
1707 case ShellMenuBisectGood:
1708 gitCmd += _T("bisect /path:\"");
1709 if (files_.size() > 0)
1710 gitCmd += files_.front();
1711 else
1712 gitCmd += folder_;
1713 gitCmd += _T("\" /good");
1714 break;
1717 case ShellMenuBisectBad:
1718 gitCmd += _T("bisect /path:\"");
1719 if (files_.size() > 0)
1720 gitCmd += files_.front();
1721 else
1722 gitCmd += folder_;
1723 gitCmd += _T("\" /bad");
1724 break;
1726 case ShellMenuBisectReset:
1727 gitCmd += _T("bisect /path:\"");
1728 if (files_.size() > 0)
1729 gitCmd += files_.front();
1730 else
1731 gitCmd += folder_;
1732 gitCmd += _T("\" /reset");
1733 break;
1735 case ShellMenuSubAdd:
1736 gitCmd += _T("subadd /path:\"");
1737 if (files_.size() > 0)
1738 gitCmd += files_.front();
1739 else
1740 gitCmd += folder_;
1741 gitCmd += _T("\"");
1742 break;
1744 case ShellMenuBlame:
1745 gitCmd += _T("blame /path:\"");
1746 if (files_.size() > 0)
1747 gitCmd += files_.front();
1748 else
1749 gitCmd += folder_;
1750 gitCmd += _T("\"");
1751 break;
1752 case ShellMenuApplyPatch:
1753 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1755 // if there's a patch file in the clipboard, we save it
1756 // to a temporary file and tell TortoiseMerge to use that one
1757 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1758 if ((cFormat)&&(OpenClipboard(NULL)))
1760 HGLOBAL hglb = GetClipboardData(cFormat);
1761 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1763 DWORD len = GetTempPath(0, NULL);
1764 TCHAR * path = new TCHAR[len+1];
1765 TCHAR * tempF = new TCHAR[len+100];
1766 GetTempPath (len+1, path);
1767 GetTempFileName (path, TEXT("git"), 0, tempF);
1768 std::wstring sTempFile = std::wstring(tempF);
1769 delete [] path;
1770 delete [] tempF;
1772 FILE * outFile;
1773 size_t patchlen = strlen(lpstr);
1774 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1775 if(outFile)
1777 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1778 if (size == patchlen)
1780 itemStates |= ITEMIS_PATCHFILE;
1781 files_.clear();
1782 files_.push_back(sTempFile);
1784 fclose(outFile);
1786 GlobalUnlock(hglb);
1787 CloseClipboard();
1790 if (itemStates & ITEMIS_PATCHFILE)
1792 gitCmd = _T(" /diff:\"");
1793 if (files_.size() > 0)
1795 gitCmd += files_.front();
1796 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1798 gitCmd += _T("\" /patchpath:\"");
1799 gitCmd += folder_;
1802 else
1803 gitCmd += folder_;
1804 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1805 gitCmd += _T("\" /wc");
1806 else
1807 gitCmd += _T("\"");
1809 else
1811 gitCmd = _T(" /patchpath:\"");
1812 if (files_.size() > 0)
1813 gitCmd += files_.front();
1814 else
1815 gitCmd += folder_;
1816 gitCmd += _T("\"");
1818 myIDMap.clear();
1819 myVerbsIDMap.clear();
1820 myVerbsMap.clear();
1821 if (CreateProcess(((stdstring)tortoiseMergePath).c_str(), const_cast<TCHAR*>(gitCmd.c_str()), NULL, NULL, FALSE, 0, 0, 0, &startup, &process)==0)
1823 LPVOID lpMsgBuf;
1824 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1825 FORMAT_MESSAGE_FROM_SYSTEM |
1826 FORMAT_MESSAGE_IGNORE_INSERTS,
1827 NULL,
1828 GetLastError(),
1829 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
1830 (LPTSTR) &lpMsgBuf,
1832 NULL
1834 MessageBox( NULL, (LPCTSTR)lpMsgBuf, _T("TortoiseMerge launch failed"), MB_OK | MB_ICONINFORMATION );
1835 LocalFree( lpMsgBuf );
1837 CloseHandle(process.hThread);
1838 CloseHandle(process.hProcess);
1839 return NOERROR;
1840 break;
1841 case ShellMenuProperties:
1842 tempfile = WriteFileListToTempFile();
1843 gitCmd += _T("properties /pathfile:\"");
1844 gitCmd += tempfile;
1845 gitCmd += _T("\"");
1846 gitCmd += _T(" /deletepathfile");
1847 break;
1848 case ShellMenuClipPaste:
1849 if (WriteClipboardPathsToTempFile(tempfile))
1851 bool bCopy = true;
1852 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1853 if (cPrefDropFormat)
1855 if (OpenClipboard(lpcmi->hwnd))
1857 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1858 if (hglb)
1860 DWORD* effect = (DWORD*) GlobalLock(hglb);
1861 if (*effect == DROPEFFECT_MOVE)
1862 bCopy = false;
1863 GlobalUnlock(hglb);
1865 CloseClipboard();
1869 if (bCopy)
1870 gitCmd += _T("pastecopy /pathfile:\"");
1871 else
1872 gitCmd += _T("pastemove /pathfile:\"");
1873 gitCmd += tempfile;
1874 gitCmd += _T("\"");
1875 gitCmd += _T(" /deletepathfile");
1876 gitCmd += _T(" /droptarget:\"");
1877 gitCmd += folder_;
1878 gitCmd += _T("\"");
1880 else return NOERROR;
1881 break;
1882 case ShellMenuClone:
1883 gitCmd += _T("clone /path:\"");
1884 if (files_.size() > 0)
1885 gitCmd += files_.front();
1886 else
1887 gitCmd += folder_;
1888 gitCmd += _T("\"");
1889 break;
1890 case ShellMenuPull:
1891 gitCmd += _T("pull /path:\"");
1892 if (files_.size() > 0)
1893 gitCmd += files_.front();
1894 else
1895 gitCmd += folder_;
1896 gitCmd += _T("\"");
1897 break;
1898 case ShellMenuPush:
1899 gitCmd += _T("push /path:\"");
1900 if (files_.size() > 0)
1901 gitCmd += files_.front();
1902 else
1903 gitCmd += folder_;
1904 gitCmd += _T("\"");
1905 break;
1906 case ShellMenuBranch:
1907 gitCmd += _T("branch /path:\"");
1908 if (files_.size() > 0)
1909 gitCmd += files_.front();
1910 else
1911 gitCmd += folder_;
1912 gitCmd += _T("\"");
1913 break;
1915 case ShellMenuTag:
1916 gitCmd += _T("tag /path:\"");
1917 if (files_.size() > 0)
1918 gitCmd += files_.front();
1919 else
1920 gitCmd += folder_;
1921 gitCmd += _T("\"");
1922 break;
1924 case ShellMenuFormatPatch:
1925 gitCmd += _T("formatpatch /path:\"");
1926 if (files_.size() > 0)
1927 gitCmd += files_.front();
1928 else
1929 gitCmd += folder_;
1930 gitCmd += _T("\"");
1931 break;
1933 case ShellMenuImportPatch:
1934 tempfile = WriteFileListToTempFile();
1935 gitCmd += _T("importpatch /pathfile:\"");
1936 gitCmd += tempfile;
1937 gitCmd += _T("\"");
1938 gitCmd += _T(" /deletepathfile");
1939 break;
1941 case ShellMenuCherryPick:
1942 gitCmd += _T("cherrypick /path:\"");
1943 if (files_.size() > 0)
1944 gitCmd += files_.front();
1945 else
1946 gitCmd += folder_;
1947 gitCmd += _T("\"");
1948 break;
1949 case ShellMenuFetch:
1950 gitCmd += _T("fetch /path:\"");
1951 if (files_.size() > 0)
1952 gitCmd += files_.front();
1953 else
1954 gitCmd += folder_;
1955 gitCmd += _T("\"");
1956 break;
1958 default:
1959 break;
1960 //#endregion
1961 } // switch (id_it->second)
1962 gitCmd += _T(" /hwnd:");
1963 TCHAR buf[30];
1964 _stprintf_s(buf, 30, _T("%d"), lpcmi->hwnd);
1965 gitCmd += buf;
1966 myIDMap.clear();
1967 myVerbsIDMap.clear();
1968 myVerbsMap.clear();
1969 if (CreateProcess(((stdstring)tortoiseProcPath).c_str(), const_cast<TCHAR*>(gitCmd.c_str()), NULL, NULL, FALSE, 0, 0, 0, &startup, &process)==0)
1971 LPVOID lpMsgBuf;
1972 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1973 FORMAT_MESSAGE_FROM_SYSTEM |
1974 FORMAT_MESSAGE_IGNORE_INSERTS,
1975 NULL,
1976 GetLastError(),
1977 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
1978 (LPTSTR) &lpMsgBuf,
1980 NULL
1982 MessageBox( NULL, (LPCTSTR)lpMsgBuf, _T("TortoiseProc Launch failed"), MB_OK | MB_ICONINFORMATION );
1983 LocalFree( lpMsgBuf );
1985 CloseHandle(process.hThread);
1986 CloseHandle(process.hProcess);
1987 hr = NOERROR;
1988 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
1989 } // if ((files_.size() > 0)||(folder_.size() > 0))
1990 return hr;
1994 // This is for the status bar and things like that:
1995 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
1996 UINT uFlags,
1997 UINT FAR * /*reserved*/,
1998 LPSTR pszName,
1999 UINT cchMax)
2001 PreserveChdir preserveChdir;
2002 //do we know the id?
2003 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
2004 if (id_it == myIDMap.end() || id_it->first != idCmd)
2006 return E_INVALIDARG; //no, we don't
2009 LoadLangDll();
2010 HRESULT hr = E_INVALIDARG;
2012 MAKESTRING(IDS_MENUDESCDEFAULT);
2013 int menuIndex = 0;
2014 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2016 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
2018 MAKESTRING(menuInfo[menuIndex].menuDescID);
2019 break;
2021 menuIndex++;
2024 const TCHAR * desc = stringtablebuffer;
2025 switch(uFlags)
2027 case GCS_HELPTEXTA:
2029 std::string help = WideToMultibyte(desc);
2030 lstrcpynA(pszName, help.c_str(), cchMax);
2031 hr = S_OK;
2032 break;
2034 case GCS_HELPTEXTW:
2036 wide_string help = desc;
2037 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2038 hr = S_OK;
2039 break;
2041 case GCS_VERBA:
2043 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2044 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2046 std::string help = WideToMultibyte(verb_id_it->second);
2047 lstrcpynA(pszName, help.c_str(), cchMax);
2048 hr = S_OK;
2051 break;
2052 case GCS_VERBW:
2054 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2055 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2057 wide_string help = verb_id_it->second;
2058 ATLTRACE("verb : %ws\n", help.c_str());
2059 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2060 hr = S_OK;
2063 break;
2065 return hr;
2068 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
2070 LRESULT res;
2071 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
2074 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
2076 PreserveChdir preserveChdir;
2078 LRESULT res;
2079 if (pResult == NULL)
2080 pResult = &res;
2081 *pResult = FALSE;
2083 LoadLangDll();
2084 switch (uMsg)
2086 case WM_MEASUREITEM:
2088 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
2089 if (lpmis==NULL||lpmis->CtlType!=ODT_MENU)
2090 break;
2091 lpmis->itemWidth = 16;
2092 lpmis->itemHeight = 16;
2093 *pResult = TRUE;
2095 break;
2096 case WM_DRAWITEM:
2098 LPCTSTR resource;
2099 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
2100 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
2101 return S_OK; //not for a menu
2102 resource = GetMenuTextFromResource(myIDMap[lpdis->itemID]);
2103 if (resource == NULL)
2104 return S_OK;
2105 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2106 if (hIcon == NULL)
2107 return S_OK;
2108 DrawIconEx(lpdis->hDC,
2109 lpdis->rcItem.left,
2110 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
2111 hIcon, 16, 16,
2112 0, NULL, DI_NORMAL);
2113 DestroyIcon(hIcon);
2114 *pResult = TRUE;
2116 break;
2117 case WM_MENUCHAR:
2119 LPCTSTR resource;
2120 TCHAR *szItem;
2121 if (HIWORD(wParam) != MF_POPUP)
2122 return NOERROR;
2123 int nChar = LOWORD(wParam);
2124 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
2125 nChar = tolower(nChar);
2126 // we have the char the user pressed, now search that char in all our
2127 // menu items
2128 std::vector<int> accmenus;
2129 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
2131 resource = GetMenuTextFromResource(mySubMenuMap[It->first]);
2132 if (resource == NULL)
2133 continue;
2134 szItem = stringtablebuffer;
2135 TCHAR * amp = _tcschr(szItem, '&');
2136 if (amp == NULL)
2137 continue;
2138 amp++;
2139 int ampChar = LOWORD(*amp);
2140 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
2141 ampChar = tolower(ampChar);
2142 if (ampChar == nChar)
2144 // yep, we found a menu which has the pressed key
2145 // as an accelerator. Add that menu to the list to
2146 // process later.
2147 accmenus.push_back(It->first);
2150 if (accmenus.size() == 0)
2152 // no menu with that accelerator key.
2153 *pResult = MAKELONG(0, MNC_IGNORE);
2154 return NOERROR;
2156 if (accmenus.size() == 1)
2158 // Only one menu with that accelerator key. We're lucky!
2159 // So just execute that menu entry.
2160 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
2161 return NOERROR;
2163 if (accmenus.size() > 1)
2165 // we have more than one menu item with this accelerator key!
2166 MENUITEMINFO mif;
2167 mif.cbSize = sizeof(MENUITEMINFO);
2168 mif.fMask = MIIM_STATE;
2169 for (std::vector<int>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
2171 GetMenuItemInfo((HMENU)lParam, *it, TRUE, &mif);
2172 if (mif.fState == MFS_HILITE)
2174 // this is the selected item, so select the next one
2175 ++it;
2176 if (it == accmenus.end())
2177 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2178 else
2179 *pResult = MAKELONG(*it, MNC_SELECT);
2180 return NOERROR;
2183 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2186 break;
2187 default:
2188 return NOERROR;
2191 return NOERROR;
2194 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
2196 TCHAR textbuf[255];
2197 LPCTSTR resource = NULL;
2198 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
2199 space = 6;
2201 int menuIndex = 0;
2202 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2204 if (menuInfo[menuIndex].command == id)
2206 MAKESTRING(menuInfo[menuIndex].menuTextID);
2207 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
2208 switch (id)
2210 case ShellSubMenuMultiple:
2211 case ShellSubMenuLink:
2212 case ShellSubMenuFolder:
2213 case ShellSubMenuFile:
2214 case ShellSubMenu:
2215 space = 0;
2216 break;
2217 default:
2218 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
2219 if (layout & (menuInfo[menuIndex].menuID))
2221 _tcscpy_s(textbuf, 255, _T("Git "));
2222 _tcscat_s(textbuf, 255, stringtablebuffer);
2223 _tcscpy_s(stringtablebuffer, 255, textbuf);
2225 break;
2227 return resource;
2229 menuIndex++;
2231 return NULL;
2234 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
2236 int i=0;
2237 TCHAR buf[MAX_PATH]; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
2238 LPITEMIDLIST pidl = NULL;
2239 while (cslidarray[i])
2241 ++i;
2242 pidl = NULL;
2243 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
2244 continue;
2245 if (!SHGetPathFromIDList(pidl, buf))
2247 // not a file system path, definitely illegal for our use
2248 CoTaskMemFree(pidl);
2249 continue;
2251 CoTaskMemFree(pidl);
2252 if (_tcslen(buf)==0)
2253 continue;
2254 if (_tcscmp(buf, folder.c_str())==0)
2255 return true;
2257 return false;
2260 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT uFlags)
2262 HMENU ignoresubmenu = NULL;
2263 int indexignoresub = 0;
2264 bool bShowIgnoreMenu = false;
2265 TCHAR maskbuf[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2266 TCHAR ignorepath[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2267 if (files_.size() == 0)
2268 return false;
2269 UINT icon = bShowIcons ? IDI_IGNORE : 0;
2271 std::vector<stdstring>::iterator I = files_.begin();
2272 if (_tcsrchr(I->c_str(), '\\'))
2273 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
2274 else
2275 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
2276 if ((itemStates & ITEMIS_IGNORED)&&(ignoredprops.size() > 0))
2278 // check if the item name is ignored or the mask
2279 size_t p = 0;
2280 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
2282 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
2283 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
2285 break;
2287 p++;
2289 if (p!=-1)
2291 ignoresubmenu = CreateMenu();
2292 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2293 stdstring verb = stdstring(ignorepath);
2294 myVerbsMap[verb] = idCmd - idCmdFirst;
2295 myVerbsMap[verb] = idCmd;
2296 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2297 myVerbsIDMap[idCmd] = verb;
2298 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
2299 myIDMap[idCmd++] = ShellMenuUnIgnore;
2300 bShowIgnoreMenu = true;
2302 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2303 if (_tcsrchr(ignorepath, '.'))
2305 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2306 p = ignoredprops.find(maskbuf);
2307 if ((p!=-1) &&
2308 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
2310 if (ignoresubmenu==NULL)
2311 ignoresubmenu = CreateMenu();
2313 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2314 stdstring verb = stdstring(maskbuf);
2315 myVerbsMap[verb] = idCmd - idCmdFirst;
2316 myVerbsMap[verb] = idCmd;
2317 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2318 myVerbsIDMap[idCmd] = verb;
2319 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
2320 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
2321 bShowIgnoreMenu = true;
2325 else if ((itemStates & ITEMIS_IGNORED) == 0)
2327 bShowIgnoreMenu = true;
2328 ignoresubmenu = CreateMenu();
2329 if (itemStates & ITEMIS_ONLYONE)
2331 if (itemStates & ITEMIS_INGIT)
2333 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2334 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2335 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2337 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2338 if (_tcsrchr(ignorepath, '.'))
2340 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2341 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2342 stdstring verb = stdstring(maskbuf);
2343 myVerbsMap[verb] = idCmd - idCmdFirst;
2344 myVerbsMap[verb] = idCmd;
2345 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2346 myVerbsIDMap[idCmd] = verb;
2347 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2348 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2351 else
2353 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2354 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2355 myIDMap[idCmd++] = ShellMenuIgnore;
2357 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2358 if (_tcsrchr(ignorepath, '.'))
2360 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2361 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2362 stdstring verb = stdstring(maskbuf);
2363 myVerbsMap[verb] = idCmd - idCmdFirst;
2364 myVerbsMap[verb] = idCmd;
2365 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2366 myVerbsIDMap[idCmd] = verb;
2367 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2368 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2372 else
2374 if (itemStates & ITEMIS_INGIT)
2376 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
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] = ShellMenuDeleteIgnore;
2385 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2387 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
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] = ShellMenuDeleteIgnoreCaseSensitive;
2396 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2398 else
2400 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2401 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2402 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2403 stdstring verb = stdstring(ignorepath);
2404 myVerbsMap[verb] = idCmd - idCmdFirst;
2405 myVerbsMap[verb] = idCmd;
2406 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2407 myVerbsIDMap[idCmd] = verb;
2408 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2409 myIDMap[idCmd++] = ShellMenuIgnore;
2411 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2412 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2413 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2414 verb = stdstring(ignorepath);
2415 myVerbsMap[verb] = idCmd - idCmdFirst;
2416 myVerbsMap[verb] = idCmd;
2417 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2418 myVerbsIDMap[idCmd] = verb;
2419 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2420 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2425 if (bShowIgnoreMenu)
2427 MENUITEMINFO menuiteminfo;
2428 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2429 menuiteminfo.cbSize = sizeof(menuiteminfo);
2430 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2431 if (icon)
2433 menuiteminfo.fMask |= MIIM_BITMAP;
2434 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
2436 menuiteminfo.fType = MFT_STRING;
2437 menuiteminfo.hSubMenu = ignoresubmenu;
2438 menuiteminfo.wID = idCmd;
2439 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2440 if (itemStates & ITEMIS_IGNORED)
2441 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2442 else if (itemStates & ITEMIS_INGIT)
2443 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2444 else
2445 GetMenuTextFromResource(ShellMenuIgnoreSub);
2446 menuiteminfo.dwTypeData = stringtablebuffer;
2447 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2449 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2450 if (itemStates & ITEMIS_IGNORED)
2452 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2453 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2455 else
2457 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2458 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2461 return bShowIgnoreMenu;
2464 HBITMAP CShellExt::IconToBitmapPARGB32(UINT uIcon)
2466 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
2467 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
2468 return bitmap_it->second;
2470 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2471 if (!hIcon)
2472 return NULL;
2474 if (pfnBeginBufferedPaint == NULL || pfnEndBufferedPaint == NULL || pfnGetBufferedPaintBits == NULL)
2475 return NULL;
2477 SIZE sizIcon;
2478 sizIcon.cx = GetSystemMetrics(SM_CXSMICON);
2479 sizIcon.cy = GetSystemMetrics(SM_CYSMICON);
2481 RECT rcIcon;
2482 SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy);
2483 HBITMAP hBmp = NULL;
2485 HDC hdcDest = CreateCompatibleDC(NULL);
2486 if (hdcDest)
2488 if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp)))
2490 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp);
2491 if (hbmpOld)
2493 BLENDFUNCTION bfAlpha = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2494 BP_PAINTPARAMS paintParams = {0};
2495 paintParams.cbSize = sizeof(paintParams);
2496 paintParams.dwFlags = BPPF_ERASE;
2497 paintParams.pBlendFunction = &bfAlpha;
2499 HDC hdcBuffer;
2500 HPAINTBUFFER hPaintBuffer = pfnBeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer);
2501 if (hPaintBuffer)
2503 if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL))
2505 // If icon did not have an alpha channel we need to convert buffer to PARGB
2506 ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon);
2509 // This will write the buffer contents to the destination bitmap
2510 pfnEndBufferedPaint(hPaintBuffer, TRUE);
2513 SelectObject(hdcDest, hbmpOld);
2517 DeleteDC(hdcDest);
2520 DestroyIcon(hIcon);
2522 if(hBmp)
2523 bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp));
2524 return hBmp;
2527 HRESULT CShellExt::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP* phBmp)
2529 *phBmp = NULL;
2531 BITMAPINFO bmi;
2532 ZeroMemory(&bmi, sizeof(bmi));
2533 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2534 bmi.bmiHeader.biPlanes = 1;
2535 bmi.bmiHeader.biCompression = BI_RGB;
2537 bmi.bmiHeader.biWidth = psize->cx;
2538 bmi.bmiHeader.biHeight = psize->cy;
2539 bmi.bmiHeader.biBitCount = 32;
2541 HDC hdcUsed = hdc ? hdc : GetDC(NULL);
2542 if (hdcUsed)
2544 *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0);
2545 if (hdc != hdcUsed)
2547 ReleaseDC(NULL, hdcUsed);
2550 return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK;
2553 HRESULT CShellExt::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon)
2555 RGBQUAD *prgbQuad;
2556 int cxRow;
2557 HRESULT hr = pfnGetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow);
2558 if (SUCCEEDED(hr))
2560 ARGB *pargb = reinterpret_cast<ARGB *>(prgbQuad);
2561 if (!HasAlpha(pargb, sizIcon, cxRow))
2563 ICONINFO info;
2564 if (GetIconInfo(hicon, &info))
2566 if (info.hbmMask)
2568 hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow);
2571 DeleteObject(info.hbmColor);
2572 DeleteObject(info.hbmMask);
2577 return hr;
2580 bool CShellExt::HasAlpha(__in ARGB *pargb, SIZE& sizImage, int cxRow)
2582 ULONG cxDelta = cxRow - sizImage.cx;
2583 for (ULONG y = sizImage.cy; y; --y)
2585 for (ULONG x = sizImage.cx; x; --x)
2587 if (*pargb++ & 0xFF000000)
2589 return true;
2593 pargb += cxDelta;
2596 return false;
2599 HRESULT CShellExt::ConvertToPARGB32(HDC hdc, __inout ARGB *pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow)
2601 BITMAPINFO bmi;
2602 ZeroMemory(&bmi, sizeof(bmi));
2603 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2604 bmi.bmiHeader.biPlanes = 1;
2605 bmi.bmiHeader.biCompression = BI_RGB;
2607 bmi.bmiHeader.biWidth = sizImage.cx;
2608 bmi.bmiHeader.biHeight = sizImage.cy;
2609 bmi.bmiHeader.biBitCount = 32;
2611 HRESULT hr = E_OUTOFMEMORY;
2612 HANDLE hHeap = GetProcessHeap();
2613 void *pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight);
2614 if (pvBits)
2616 hr = E_UNEXPECTED;
2617 if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight)
2619 ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth;
2620 ARGB *pargbMask = static_cast<ARGB *>(pvBits);
2622 for (ULONG y = bmi.bmiHeader.biHeight; y; --y)
2624 for (ULONG x = bmi.bmiHeader.biWidth; x; --x)
2626 if (*pargbMask++)
2628 // transparent pixel
2629 *pargb++ = 0;
2631 else
2633 // opaque pixel
2634 *pargb++ |= 0xFF000000;
2638 pargb += cxDelta;
2641 hr = S_OK;
2644 HeapFree(hHeap, 0, pvBits);
2647 return hr;