Merge branch 'bare-repo'
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blobd4989c56ca93a9ed0e03ad6641bd80f49be41c51
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;
303 if (itemStates == 0 && g_GitAdminDir.IsBareRepo(child.toString().c_str()))
304 itemStates = ITEMIS_BAREREPO;
306 GlobalUnlock(medium.hGlobal);
308 // if the item is a versioned folder, check if there's a patch file
309 // in the clipboard to be used in "Apply Patch"
310 UINT cFormatDiff = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
311 if (cFormatDiff)
313 if (IsClipboardFormatAvailable(cFormatDiff))
314 itemStates |= ITEMIS_PATCHINCLIPBOARD;
316 if (IsClipboardFormatAvailable(CF_HDROP))
317 itemStates |= ITEMIS_PATHINCLIPBOARD;
321 ReleaseStgMedium ( &medium );
322 if (medium.pUnkForRelease)
324 IUnknown* relInterface = (IUnknown*)medium.pUnkForRelease;
325 relInterface->Release();
330 // get folder background
331 if (pIDFolder)
334 ItemIDList list(pIDFolder);
335 folder_ = list.toString();
336 git_wc_status_kind status = git_wc_status_none;
337 if (IsClipboardFormatAvailable(CF_HDROP))
338 itemStatesFolder |= ITEMIS_PATHINCLIPBOARD;
340 CTGitPath askedpath;
341 askedpath.SetFromWin(folder_.c_str());
343 if (g_ShellCache.IsContextPathAllowed(folder_.c_str()))
345 if (folder_.compare(statuspath)!=0)
350 GitStatus stat;
351 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
352 if (stat.status)
354 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
355 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
356 // itemStatesFolder |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
357 // if ((stat.status->entry)&&(stat.status->entry->present_props))
358 // {
359 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
360 // itemStatesFolder |= ITEMIS_NEEDSLOCK;
361 // }
362 // if ((stat.status->entry)&&(stat.status->entry->uuid))
363 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
366 else
368 // sometimes, git_client_status() returns with an error.
369 // in that case, we have to check if the working copy is versioned
370 // anyway to show the 'correct' context menu
371 if (askedpath.HasAdminDir())
372 status = git_wc_status_normal;
375 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
376 itemStatesFolder |= askedpath.GetAdminDirMask();
378 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
379 itemStates &= ~ITEMIS_INGIT;
381 if (status == git_wc_status_normal)
382 itemStatesFolder |= ITEMIS_NORMAL;
383 if (status == git_wc_status_conflicted)
384 itemStatesFolder |= ITEMIS_CONFLICTED;
385 if (status == git_wc_status_added)
386 itemStatesFolder |= ITEMIS_ADDED;
387 if (status == git_wc_status_deleted)
388 itemStatesFolder |= ITEMIS_DELETED;
391 catch ( ... )
393 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
396 else
398 status = fetchedstatus;
400 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
401 itemStatesFolder |= askedpath.GetAdminDirMask();
403 if (status == git_wc_status_ignored)
404 itemStatesFolder |= ITEMIS_IGNORED;
405 itemStatesFolder |= ITEMIS_FOLDER;
406 if (files_.size() == 0)
407 itemStates |= ITEMIS_ONLYONE;
408 if (m_State != FileStateDropHandler)
409 itemStates |= itemStatesFolder;
411 else
413 folder_.clear();
414 status = fetchedstatus;
417 if (files_.size() == 2)
418 itemStates |= ITEMIS_TWO;
419 if ((files_.size() == 1)&&(g_ShellCache.IsContextPathAllowed(files_.front().c_str())))
422 itemStates |= ITEMIS_ONLYONE;
423 if (m_State != FileStateDropHandler)
425 if (PathIsDirectory(files_.front().c_str()))
427 folder_ = files_.front();
428 git_wc_status_kind status = git_wc_status_none;
429 CTGitPath askedpath;
430 askedpath.SetFromWin(folder_.c_str());
432 if (folder_.compare(statuspath)!=0)
436 GitStatus stat;
437 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
438 if (stat.status)
440 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
441 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
442 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
443 // if ((stat.status->entry)&&(stat.status->entry->present_props))
444 // {
445 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
446 // itemStates |= ITEMIS_NEEDSLOCK;
447 // }
448 // if ((stat.status->entry)&&(stat.status->entry->uuid))
449 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
452 catch ( ... )
454 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
457 else
459 status = fetchedstatus;
461 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
462 itemStates |= askedpath.GetAdminDirMask();
464 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
465 itemStates &= ~ITEMIS_INGIT;
467 if (status == git_wc_status_ignored)
468 itemStates |= ITEMIS_IGNORED;
469 itemStates |= ITEMIS_FOLDER;
470 if (status == git_wc_status_added)
471 itemStates |= ITEMIS_ADDED;
472 if (status == git_wc_status_deleted)
473 itemStates |= ITEMIS_DELETED;
480 return NOERROR;
483 void CShellExt::InsertGitMenu(BOOL istop, HMENU menu, UINT pos, UINT_PTR id, UINT stringid, UINT icon, UINT idCmdFirst, GitCommands com, UINT /*uFlags*/)
485 TCHAR menutextbuffer[512] = {0};
486 TCHAR verbsbuffer[255] = {0};
487 MAKESTRING(stringid);
489 if (istop)
491 //menu entry for the top context menu, so append an "Git " before
492 //the menu text to indicate where the entry comes from
493 _tcscpy_s(menutextbuffer, 255, _T("Git "));
495 _tcscat_s(menutextbuffer, 255, stringtablebuffer);
496 #if 1
497 // insert branch name into "Git Commit..." entry, so it looks like "Git Commit "master"..."
498 // so we have an easy and fast way to check the current branch
499 // (the other alternative is using a separate disabled menu entry, the code is already done but commented out)
500 if (com == ShellMenuCommit)
502 // get branch name
503 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
504 CString sProjectRoot;
505 CString sBranchName;
507 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
509 if (sBranchName.GetLength() == 40)
511 // if SHA1 only show 4 first bytes
512 BOOL bIsSha1 = TRUE;
513 for (int i=0; i<40; i++)
514 if ( !iswxdigit(sBranchName[i]) )
516 bIsSha1 = FALSE;
517 break;
519 if (bIsSha1)
520 sBranchName = sBranchName.Left(8) + _T("....");
523 // sanity check
524 if (sBranchName.GetLength() > 64)
525 sBranchName = sBranchName.Left(64) + _T("...");
527 // scan to before "..."
528 LPTSTR s = menutextbuffer + _tcslen(menutextbuffer)-1;
529 if (s > menutextbuffer)
531 while (s > menutextbuffer)
533 if (*s != _T('.'))
535 s++;
536 break;
538 s--;
541 else
543 s = menutextbuffer;
546 // append branch name and end with ...
547 _tcscpy(s, _T(" -> \"") + sBranchName + _T("\"..."));
550 #endif
551 MENUITEMINFO menuiteminfo;
552 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
553 menuiteminfo.cbSize = sizeof(menuiteminfo);
554 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
555 menuiteminfo.fType = MFT_STRING;
556 menuiteminfo.dwTypeData = menutextbuffer;
557 if (icon)
559 menuiteminfo.fMask |= MIIM_BITMAP;
560 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
562 menuiteminfo.wID = id;
563 InsertMenuItem(menu, pos, TRUE, &menuiteminfo);
565 if (istop)
567 //menu entry for the top context menu, so append an "Git " before
568 //the menu text to indicate where the entry comes from
569 _tcscpy_s(menutextbuffer, 255, _T("Git "));
571 LoadString(g_hResInst, stringid, verbsbuffer, sizeof(verbsbuffer));
572 _tcscat_s(menutextbuffer, 255, verbsbuffer);
573 stdstring verb = stdstring(menutextbuffer);
574 if (verb.find('&') != -1)
576 verb.erase(verb.find('&'),1);
578 myVerbsMap[verb] = id - idCmdFirst;
579 myVerbsMap[verb] = id;
580 myVerbsIDMap[id - idCmdFirst] = verb;
581 myVerbsIDMap[id] = verb;
582 // We store the relative and absolute diameter
583 // (drawitem callback uses absolute, others relative)
584 myIDMap[id - idCmdFirst] = com;
585 myIDMap[id] = com;
586 if (!istop)
587 mySubMenuMap[pos] = com;
590 HBITMAP CShellExt::IconToBitmap(UINT uIcon)
592 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
593 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
594 return bitmap_it->second;
596 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 12, 12, LR_DEFAULTCOLOR);
597 if (!hIcon)
598 return NULL;
600 RECT rect;
602 rect.right = ::GetSystemMetrics(SM_CXMENUCHECK);
603 rect.bottom = ::GetSystemMetrics(SM_CYMENUCHECK);
605 rect.left = rect.top = 0;
607 HWND desktop = ::GetDesktopWindow();
608 if (desktop == NULL)
610 DestroyIcon(hIcon);
611 return NULL;
614 HDC screen_dev = ::GetDC(desktop);
615 if (screen_dev == NULL)
617 DestroyIcon(hIcon);
618 return NULL;
621 // Create a compatible DC
622 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
623 if (dst_hdc == NULL)
625 DestroyIcon(hIcon);
626 ::ReleaseDC(desktop, screen_dev);
627 return NULL;
630 // Create a new bitmap of icon size
631 HBITMAP bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
632 if (bmp == NULL)
634 DestroyIcon(hIcon);
635 ::DeleteDC(dst_hdc);
636 ::ReleaseDC(desktop, screen_dev);
637 return NULL;
640 // Select it into the compatible DC
641 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
642 if (old_dst_bmp == NULL)
644 DestroyIcon(hIcon);
645 return NULL;
648 // Fill the background of the compatible DC with the white color
649 // that is taken by menu routines as transparent
650 ::SetBkColor(dst_hdc, RGB(255, 255, 255));
651 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
653 // Draw the icon into the compatible DC
654 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
656 // Restore settings
657 ::SelectObject(dst_hdc, old_dst_bmp);
658 ::DeleteDC(dst_hdc);
659 ::ReleaseDC(desktop, screen_dev);
660 DestroyIcon(hIcon);
661 if (bmp)
662 bitmaps.insert(bitmap_it, std::make_pair(uIcon, bmp));
663 return bmp;
666 bool CShellExt::WriteClipboardPathsToTempFile(stdstring& tempfile)
668 bool bRet = true;
669 tempfile = stdstring();
670 //write all selected files and paths to a temporary file
671 //for TortoiseProc.exe to read out again.
672 DWORD written = 0;
673 DWORD pathlength = GetTempPath(0, NULL);
674 TCHAR * path = new TCHAR[pathlength+1];
675 TCHAR * tempFile = new TCHAR[pathlength + 100];
676 GetTempPath (pathlength+1, path);
677 GetTempFileName (path, _T("git"), 0, tempFile);
678 tempfile = stdstring(tempFile);
680 HANDLE file = ::CreateFile (tempFile,
681 GENERIC_WRITE,
682 FILE_SHARE_READ,
684 CREATE_ALWAYS,
685 FILE_ATTRIBUTE_TEMPORARY,
688 delete [] path;
689 delete [] tempFile;
690 if (file == INVALID_HANDLE_VALUE)
691 return false;
693 if (!IsClipboardFormatAvailable(CF_HDROP))
694 return false;
695 if (!OpenClipboard(NULL))
696 return false;
698 stdstring sClipboardText;
699 HGLOBAL hglb = GetClipboardData(CF_HDROP);
700 HDROP hDrop = (HDROP)GlobalLock(hglb);
701 if(hDrop != NULL)
703 TCHAR szFileName[MAX_PATH];
704 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
705 for(UINT i = 0; i < cFiles; ++i)
707 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
708 stdstring filename = szFileName;
709 ::WriteFile (file, filename.c_str(), filename.size()*sizeof(TCHAR), &written, 0);
710 ::WriteFile (file, _T("\n"), 2, &written, 0);
712 GlobalUnlock(hDrop);
714 else bRet = false;
715 GlobalUnlock(hglb);
717 CloseClipboard();
718 ::CloseHandle(file);
720 return bRet;
723 stdstring CShellExt::WriteFileListToTempFile()
725 //write all selected files and paths to a temporary file
726 //for TortoiseProc.exe to read out again.
727 DWORD pathlength = GetTempPath(0, NULL);
728 TCHAR * path = new TCHAR[pathlength+1];
729 TCHAR * tempFile = new TCHAR[pathlength + 100];
730 GetTempPath (pathlength+1, path);
731 GetTempFileName (path, _T("git"), 0, tempFile);
732 stdstring retFilePath = stdstring(tempFile);
734 HANDLE file = ::CreateFile (tempFile,
735 GENERIC_WRITE,
736 FILE_SHARE_READ,
738 CREATE_ALWAYS,
739 FILE_ATTRIBUTE_TEMPORARY,
742 delete [] path;
743 delete [] tempFile;
744 if (file == INVALID_HANDLE_VALUE)
745 return stdstring();
747 DWORD written = 0;
748 if (files_.empty())
750 ::WriteFile (file, folder_.c_str(), folder_.size()*sizeof(TCHAR), &written, 0);
751 ::WriteFile (file, _T("\n"), 2, &written, 0);
754 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
756 ::WriteFile (file, I->c_str(), I->size()*sizeof(TCHAR), &written, 0);
757 ::WriteFile (file, _T("\n"), 2, &written, 0);
759 ::CloseHandle(file);
760 return retFilePath;
763 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
765 PreserveChdir preserveChdir;
766 LoadLangDll();
768 if ((uFlags & CMF_DEFAULTONLY)!=0)
769 return NOERROR; //we don't change the default action
771 if ((files_.size() == 0)||(folder_.size() == 0))
772 return NOERROR;
774 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
775 return NOERROR;
777 if (itemStatesFolder & ITEMIS_FOLDER) // we do not support folders atm, see issue #963
778 return NOERROR;
780 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
782 //the drop handler only has eight commands, but not all are visible at the same time:
783 //if the source file(s) are under version control then those files can be moved
784 //to the new location or they can be moved with a rename,
785 //if they are unversioned then they can be added to the working copy
786 //if they are versioned, they also can be exported to an unversioned location
787 UINT idCmd = idCmdFirst;
789 // Git move here
790 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
791 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
792 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
794 // Git move and rename here
795 // available if source is a single, versioned but not added item, target is versioned, source and target from same repository or target folder is added
796 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
797 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
799 // Git copy here
800 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
801 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
802 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
804 // Git copy and rename here, source and target from same repository
805 // available if source is a single, versioned but not added item, target is versioned or target folder is added
806 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
807 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
809 // Git add here
810 // available if target is versioned and source is either unversioned or from another repository
811 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
812 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
814 // Git export here
815 // available if source is versioned and a folder
816 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
817 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
819 // Git export all here
820 // available if source is versioned and a folder
821 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
822 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
824 // apply patch
825 // available if source is a patchfile
826 if (itemStates & ITEMIS_PATCHFILE)
827 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
829 // separator
830 if (idCmd != idCmdFirst)
831 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
833 TweakMenu(hMenu);
835 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
838 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
839 UINT indexMenu,
840 UINT idCmdFirst,
841 UINT /*idCmdLast*/,
842 UINT uFlags)
844 ATLTRACE("Shell :: QueryContextMenu\n");
845 PreserveChdir preserveChdir;
847 //first check if our drop handler is called
848 //and then (if true) provide the context menu for the
849 //drop handler
850 if (m_State == FileStateDropHandler)
852 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
855 if ((uFlags & CMF_DEFAULTONLY)!=0)
856 return NOERROR; //we don't change the default action
858 if ((files_.size() == 0)&&(folder_.size() == 0))
859 return NOERROR;
861 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
862 return NOERROR;
864 int csidlarray[] =
866 CSIDL_BITBUCKET,
867 CSIDL_CDBURN_AREA,
868 CSIDL_COMMON_FAVORITES,
869 CSIDL_COMMON_STARTMENU,
870 CSIDL_COMPUTERSNEARME,
871 CSIDL_CONNECTIONS,
872 CSIDL_CONTROLS,
873 CSIDL_COOKIES,
874 CSIDL_FAVORITES,
875 CSIDL_FONTS,
876 CSIDL_HISTORY,
877 CSIDL_INTERNET,
878 CSIDL_INTERNET_CACHE,
879 CSIDL_NETHOOD,
880 CSIDL_NETWORK,
881 CSIDL_PRINTERS,
882 CSIDL_PRINTHOOD,
883 CSIDL_RECENT,
884 CSIDL_SENDTO,
885 CSIDL_STARTMENU,
888 if (IsIllegalFolder(folder_, csidlarray))
889 return NOERROR;
891 if (folder_.empty())
893 // folder is empty, but maybe files are selected
894 if (files_.size() == 0)
895 return NOERROR; // nothing selected - we don't have a menu to show
896 // check whether a selected entry is an UID - those are namespace extensions
897 // which we can't handle
898 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
900 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
901 return NOERROR;
905 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
907 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT|ITEMIS_BAREREPO))==0)
908 return S_OK;
911 //check if our menu is requested for a subversion admin directory
912 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
913 return NOERROR;
915 if (uFlags & CMF_EXTENDEDVERBS)
916 itemStates |= ITEMIS_EXTENDED;
918 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
919 if ( bShortcut && (files_.size()==1))
921 // Don't show the context menu for a link if the
922 // destination is not part of a working copy.
923 // It would only show the standard menu items
924 // which are already shown for the lnk-file.
925 CString path = files_.front().c_str();
926 if ( !g_GitAdminDir.HasAdminDir(path) )
928 return NOERROR;
932 //check if we already added our menu entry for a folder.
933 //we check that by iterating through all menu entries and check if
934 //the dwItemData member points to our global ID string. That string is set
935 //by our shell extension when the folder menu is inserted.
936 TCHAR menubuf[MAX_PATH];
937 int count = GetMenuItemCount(hMenu);
938 for (int i=0; i<count; ++i)
940 MENUITEMINFO miif;
941 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
942 miif.cbSize = sizeof(MENUITEMINFO);
943 miif.fMask = MIIM_DATA;
944 miif.dwTypeData = menubuf;
945 miif.cch = _countof(menubuf);
946 GetMenuItemInfo(hMenu, i, TRUE, &miif);
947 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
948 return NOERROR;
951 LoadLangDll();
952 UINT idCmd = idCmdFirst;
954 //create the sub menu
955 HMENU subMenu = CreateMenu();
956 int indexSubMenu = 0;
958 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
959 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
960 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
962 int menuIndex = 0;
963 bool bAddSeparator = false;
964 bool bMenuEntryAdded = false;
965 bool bMenuEmpty = true;
966 // insert separator at start
967 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
968 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
970 #if 0
971 if (itemStates & (ITEMIS_INSVN|ITEMIS_FOLDERINSVN))
973 // show current branch name (as a "read-only" menu entry)
975 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
976 CString sProjectRoot;
977 CString sBranchName;
979 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
981 if (sBranchName.GetLength() == 40)
983 // if SHA1 only show 4 first bytes
984 BOOL bIsSha1 = TRUE;
985 for (int i=0; i<40; i++)
986 if ( !iswxdigit(sBranchName[i]) )
988 bIsSha1 = FALSE;
989 break;
991 if (bIsSha1)
992 sBranchName = sBranchName.Left(8) + _T("....");
995 sBranchName = _T('"') + sBranchName + _T('"');
997 const int icon = IDI_COPY;
998 const int pos = indexMenu++;
999 const int id = idCmd++;
1001 MENUITEMINFO menuiteminfo;
1002 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1003 menuiteminfo.cbSize = sizeof(menuiteminfo);
1004 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_STATE;
1005 menuiteminfo.fState = MFS_DISABLED;
1006 menuiteminfo.fType = MFT_STRING;
1007 menuiteminfo.dwTypeData = (LPWSTR)sBranchName.GetString();
1008 if (icon)
1010 menuiteminfo.fMask |= MIIM_BITMAP;
1011 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
1013 if (menuiteminfo.hbmpItem == HBMMENU_CALLBACK)
1015 // WM_DRAWITEM uses myIDMap to get icon, we use the same icon as create branch
1016 myIDMap[id - idCmdFirst] = ShellMenuBranch;
1017 myIDMap[id] = ShellMenuBranch;
1020 menuiteminfo.wID = id;
1021 InsertMenuItem(hMenu, pos, TRUE, &menuiteminfo);
1024 #endif
1026 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1028 if (menuInfo[menuIndex].command == ShellSeparator)
1030 // we don't add a separator immediately. Because there might not be
1031 // another 'normal' menu entry after we insert a separator.
1032 // we simply set a flag here, indicating that before the next
1033 // 'normal' menu entry, a separator should be added.
1034 if (!bMenuEmpty)
1035 bAddSeparator = true;
1037 else
1039 // check the conditions whether to show the menu entry or not
1040 bool bInsertMenu = false;
1042 if (menuInfo[menuIndex].firstyes && menuInfo[menuIndex].firstno)
1044 if (((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes)
1046 ((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1047 bInsertMenu = true;
1049 else if ((menuInfo[menuIndex].firstyes)&&((menuInfo[menuIndex].firstyes & itemStates) == menuInfo[menuIndex].firstyes))
1050 bInsertMenu = true;
1051 else if ((menuInfo[menuIndex].firstno)&&((menuInfo[menuIndex].firstno & (~itemStates)) == menuInfo[menuIndex].firstno))
1052 bInsertMenu = true;
1054 if (menuInfo[menuIndex].secondyes && menuInfo[menuIndex].secondno)
1056 if (((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes)
1058 ((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1059 bInsertMenu = true;
1061 else if ((menuInfo[menuIndex].secondyes)&&((menuInfo[menuIndex].secondyes & itemStates) == menuInfo[menuIndex].secondyes))
1062 bInsertMenu = true;
1063 else if ((menuInfo[menuIndex].secondno)&&((menuInfo[menuIndex].secondno & (~itemStates)) == menuInfo[menuIndex].secondno))
1064 bInsertMenu = true;
1066 if (menuInfo[menuIndex].thirdyes && menuInfo[menuIndex].thirdno)
1068 if (((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes)
1070 ((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1071 bInsertMenu = true;
1073 else if ((menuInfo[menuIndex].thirdyes)&&((menuInfo[menuIndex].thirdyes & itemStates) == menuInfo[menuIndex].thirdyes))
1074 bInsertMenu = true;
1075 else if ((menuInfo[menuIndex].thirdno)&&((menuInfo[menuIndex].thirdno & (~itemStates)) == menuInfo[menuIndex].thirdno))
1076 bInsertMenu = true;
1078 if (menuInfo[menuIndex].fourthyes && menuInfo[menuIndex].fourthno)
1080 if (((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes)
1082 ((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1083 bInsertMenu = true;
1085 else if ((menuInfo[menuIndex].fourthyes)&&((menuInfo[menuIndex].fourthyes & itemStates) == menuInfo[menuIndex].fourthyes))
1086 bInsertMenu = true;
1087 else if ((menuInfo[menuIndex].fourthno)&&((menuInfo[menuIndex].fourthno & (~itemStates)) == menuInfo[menuIndex].fourthno))
1088 bInsertMenu = true;
1090 if (menuInfo[menuIndex].menuID & menuex)
1092 if( !(itemStates & ITEMIS_EXTENDED) )
1094 bInsertMenu = false;
1098 if (menuInfo[menuIndex].menuID & (~menumask))
1100 if (bInsertMenu)
1102 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1103 // insert a separator
1104 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1106 bAddSeparator = false;
1107 bMenuEntryAdded = false;
1108 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1109 idCmd++;
1112 // handle special cases (sub menus)
1113 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1115 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1117 bMenuEntryAdded = true;
1118 bMenuEmpty = false;
1121 else
1123 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1125 // insert the menu entry
1126 InsertGitMenu( bIsTop,
1127 bIsTop ? hMenu : subMenu,
1128 bIsTop ? indexMenu++ : indexSubMenu++,
1129 idCmd++,
1130 menuInfo[menuIndex].menuTextID,
1131 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1132 idCmdFirst,
1133 menuInfo[menuIndex].command,
1134 uFlags);
1135 if (!bIsTop)
1137 bMenuEntryAdded = true;
1138 bMenuEmpty = false;
1139 bAddSeparator = false;
1145 menuIndex++;
1148 //add sub menu to main context menu
1149 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1150 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1151 MAKESTRING(IDS_MENUSUBMENU);
1152 MENUITEMINFO menuiteminfo;
1153 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1154 menuiteminfo.cbSize = sizeof(menuiteminfo);
1155 menuiteminfo.fType = MFT_STRING;
1156 menuiteminfo.dwTypeData = stringtablebuffer;
1158 UINT uIcon = bShowIcons ? IDI_APP : 0;
1159 if (folder_.size())
1161 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1162 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1163 myIDMap[idCmd] = ShellSubMenuFolder;
1164 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1166 else if (!bShortcut && (files_.size()==1))
1168 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1169 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1170 myIDMap[idCmd] = ShellSubMenuFile;
1172 else if (bShortcut && (files_.size()==1))
1174 uIcon = bShowIcons ? IDI_MENULINK : 0;
1175 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1176 myIDMap[idCmd] = ShellSubMenuLink;
1178 else if (files_.size() > 1)
1180 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1181 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1182 myIDMap[idCmd] = ShellSubMenuMultiple;
1184 else
1186 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1187 myIDMap[idCmd] = ShellSubMenu;
1189 HBITMAP bmp = NULL;
1190 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1191 if (uIcon)
1193 menuiteminfo.fMask |= MIIM_BITMAP;
1194 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(uIcon) : HBMMENU_CALLBACK;
1196 menuiteminfo.hSubMenu = subMenu;
1197 menuiteminfo.wID = idCmd++;
1198 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1200 //separator after
1201 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1203 TweakMenu(hMenu);
1205 //return number of menu items added
1206 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1209 void CShellExt::TweakMenu(HMENU hMenu)
1211 MENUINFO MenuInfo = {};
1212 MenuInfo.cbSize = sizeof(MenuInfo);
1213 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1214 MenuInfo.dwStyle = MNS_CHECKORBMP;
1215 SetMenuInfo(hMenu, &MenuInfo);
1218 // This is called when you invoke a command on the menu:
1219 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1221 PreserveChdir preserveChdir;
1222 HRESULT hr = E_INVALIDARG;
1223 if (lpcmi == NULL)
1224 return hr;
1226 std::string command;
1227 std::string parent;
1228 std::string file;
1230 if ((files_.size() > 0)||(folder_.size() > 0))
1232 UINT idCmd = LOWORD(lpcmi->lpVerb);
1234 if (HIWORD(lpcmi->lpVerb))
1236 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1237 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1238 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1239 idCmd = verb_it->second;
1240 else
1241 return hr;
1244 // See if we have a handler interface for this id
1245 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1246 if (id_it != myIDMap.end() && id_it->first == idCmd)
1248 STARTUPINFO startup;
1249 PROCESS_INFORMATION process;
1250 memset(&startup, 0, sizeof(startup));
1251 startup.cb = sizeof(startup);
1252 memset(&process, 0, sizeof(process));
1253 CRegStdString tortoiseProcPath(_T("Software\\TortoiseGit\\ProcPath"), _T("TortoiseProc.exe"), false, HKEY_LOCAL_MACHINE);
1254 CRegStdString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T("TortoiseMerge.exe"), false, HKEY_LOCAL_MACHINE);
1256 //TortoiseProc expects a command line of the form:
1257 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1258 // or
1259 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1261 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1262 //* pathfile is a path to a temporary file which contains a list of file paths
1263 stdstring gitCmd = _T(" /command:");
1264 stdstring tempfile;
1265 switch (id_it->second)
1267 //#region case
1268 case ShellMenuSync:
1269 gitCmd += _T("sync /path:\"");
1270 if (files_.size() > 0)
1271 gitCmd += files_.front();
1272 else
1273 gitCmd += folder_;
1274 gitCmd += _T("\"");
1275 break;
1276 case ShellMenuUpdate:
1277 tempfile = WriteFileListToTempFile();
1278 gitCmd += _T("update /pathfile:\"");
1279 gitCmd += tempfile;
1280 gitCmd += _T("\"");
1281 gitCmd += _T(" /deletepathfile");
1282 break;
1283 case ShellMenuSubSync:
1284 tempfile = WriteFileListToTempFile();
1285 gitCmd += _T("subsync /pathfile:\"");
1286 gitCmd += tempfile;
1287 gitCmd += _T("\"");
1288 gitCmd += _T(" /deletepathfile");
1289 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1291 gitCmd += _T(" /bkpath:\"");
1292 gitCmd += folder_;
1293 gitCmd += _T("\"");
1295 break;
1296 case ShellMenuUpdateExt:
1297 tempfile = WriteFileListToTempFile();
1298 gitCmd += _T("subupdate /pathfile:\"");
1299 gitCmd += tempfile;
1300 gitCmd += _T("\"");
1301 gitCmd += _T(" /deletepathfile");
1302 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1304 gitCmd += _T(" /bkpath:\"");
1305 gitCmd += folder_;
1306 gitCmd += _T("\"");
1308 break;
1309 case ShellMenuCommit:
1310 tempfile = WriteFileListToTempFile();
1311 gitCmd += _T("commit /pathfile:\"");
1312 gitCmd += tempfile;
1313 gitCmd += _T("\"");
1314 gitCmd += _T(" /deletepathfile");
1315 break;
1316 case ShellMenuAdd:
1317 case ShellMenuAddAsReplacement:
1318 tempfile = WriteFileListToTempFile();
1319 gitCmd += _T("add /pathfile:\"");
1320 gitCmd += tempfile;
1321 gitCmd += _T("\"");
1322 gitCmd += _T(" /deletepathfile");
1323 break;
1324 case ShellMenuIgnore:
1325 tempfile = WriteFileListToTempFile();
1326 gitCmd += _T("ignore /pathfile:\"");
1327 gitCmd += tempfile;
1328 gitCmd += _T("\"");
1329 gitCmd += _T(" /deletepathfile");
1330 break;
1331 case ShellMenuIgnoreCaseSensitive:
1332 tempfile = WriteFileListToTempFile();
1333 gitCmd += _T("ignore /pathfile:\"");
1334 gitCmd += tempfile;
1335 gitCmd += _T("\"");
1336 gitCmd += _T(" /deletepathfile");
1337 gitCmd += _T(" /onlymask");
1338 break;
1339 case ShellMenuDeleteIgnore:
1340 tempfile = WriteFileListToTempFile();
1341 gitCmd += _T("ignore /delete /pathfile:\"");
1342 gitCmd += tempfile;
1343 gitCmd += _T("\"");
1344 gitCmd += _T(" /deletepathfile");
1345 break;
1346 case ShellMenuDeleteIgnoreCaseSensitive:
1347 tempfile = WriteFileListToTempFile();
1348 gitCmd += _T("ignore /delete /pathfile:\"");
1349 gitCmd += tempfile;
1350 gitCmd += _T("\"");
1351 gitCmd += _T(" /deletepathfile");
1352 gitCmd += _T(" /onlymask");
1353 break;
1354 case ShellMenuUnIgnore:
1355 tempfile = WriteFileListToTempFile();
1356 gitCmd += _T("unignore /pathfile:\"");
1357 gitCmd += tempfile;
1358 gitCmd += _T("\"");
1359 gitCmd += _T(" /deletepathfile");
1360 break;
1361 case ShellMenuUnIgnoreCaseSensitive:
1362 tempfile = WriteFileListToTempFile();
1363 gitCmd += _T("unignore /pathfile:\"");
1364 gitCmd += tempfile;
1365 gitCmd += _T("\"");
1366 gitCmd += _T(" /deletepathfile");
1367 gitCmd += _T(" /onlymask");
1368 break;
1369 case ShellMenuRevert:
1370 tempfile = WriteFileListToTempFile();
1371 gitCmd += _T("revert /pathfile:\"");
1372 gitCmd += tempfile;
1373 gitCmd += _T("\"");
1374 gitCmd += _T(" /deletepathfile");
1375 break;
1376 case ShellMenuCleanup:
1377 tempfile = WriteFileListToTempFile();
1378 gitCmd += _T("cleanup /pathfile:\"");
1379 gitCmd += tempfile;
1380 gitCmd += _T("\"");
1381 gitCmd += _T(" /deletepathfile");
1382 break;
1383 case ShellMenuSendMail:
1384 tempfile = WriteFileListToTempFile();
1385 gitCmd += _T("sendmail /pathfile:\"");
1386 gitCmd += tempfile;
1387 gitCmd += _T("\"");
1388 gitCmd += _T(" /deletepathfile");
1389 break;
1390 case ShellMenuResolve:
1391 tempfile = WriteFileListToTempFile();
1392 gitCmd += _T("resolve /pathfile:\"");
1393 gitCmd += tempfile;
1394 gitCmd += _T("\"");
1395 gitCmd += _T(" /deletepathfile");
1396 break;
1397 case ShellMenuSwitch:
1398 gitCmd += _T("switch /path:\"");
1399 if (files_.size() > 0)
1400 gitCmd += files_.front();
1401 else
1402 gitCmd += folder_;
1403 gitCmd += _T("\"");
1404 break;
1405 case ShellMenuExport:
1406 gitCmd += _T("export /path:\"");
1407 if (files_.size() > 0)
1408 gitCmd += files_.front();
1409 else
1410 gitCmd += folder_;
1411 gitCmd += _T("\"");
1412 break;
1413 case ShellMenuAbout:
1414 gitCmd += _T("about");
1415 break;
1416 case ShellMenuCreateRepos:
1417 gitCmd += _T("repocreate /path:\"");
1418 if (files_.size() > 0)
1419 gitCmd += files_.front();
1420 else
1421 gitCmd += folder_;
1422 gitCmd += _T("\"");
1423 break;
1424 case ShellMenuMerge:
1425 gitCmd += _T("merge /path:\"");
1426 if (files_.size() > 0)
1427 gitCmd += files_.front();
1428 else
1429 gitCmd += folder_;
1430 gitCmd += _T("\"");
1431 break;
1432 case ShellMenuCopy:
1433 gitCmd += _T("copy /path:\"");
1434 if (files_.size() > 0)
1435 gitCmd += files_.front();
1436 else
1437 gitCmd += folder_;
1438 gitCmd += _T("\"");
1439 break;
1440 case ShellMenuSettings:
1441 gitCmd += _T("settings /path:\"");
1442 if (files_.size() > 0)
1443 gitCmd += files_.front();
1444 else
1445 gitCmd += folder_;
1446 gitCmd += _T("\"");
1447 break;
1448 case ShellMenuHelp:
1449 gitCmd += _T("help");
1450 break;
1451 case ShellMenuRename:
1452 gitCmd += _T("rename /path:\"");
1453 if (files_.size() > 0)
1454 gitCmd += files_.front();
1455 else
1456 gitCmd += folder_;
1457 gitCmd += _T("\"");
1458 break;
1459 case ShellMenuRemove:
1460 tempfile = WriteFileListToTempFile();
1461 gitCmd += _T("remove /pathfile:\"");
1462 gitCmd += tempfile;
1463 gitCmd += _T("\"");
1464 gitCmd += _T(" /deletepathfile");
1465 break;
1466 case ShellMenuRemoveKeep:
1467 tempfile = WriteFileListToTempFile();
1468 gitCmd += _T("remove /pathfile:\"");
1469 gitCmd += tempfile;
1470 gitCmd += _T("\"");
1471 gitCmd += _T(" /deletepathfile");
1472 gitCmd += _T(" /keep");
1473 break;
1474 case ShellMenuDiff:
1475 gitCmd += _T("diff /path:\"");
1476 if (files_.size() == 1)
1477 gitCmd += files_.front();
1478 else if (files_.size() == 2)
1480 std::vector<stdstring>::iterator I = files_.begin();
1481 gitCmd += *I;
1482 I++;
1483 gitCmd += _T("\" /path2:\"");
1484 gitCmd += *I;
1486 else
1487 gitCmd += folder_;
1488 gitCmd += _T("\"");
1489 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1490 gitCmd += _T(" /alternative");
1491 break;
1492 case ShellMenuPrevDiff:
1493 gitCmd += _T("prevdiff /path:\"");
1494 if (files_.size() == 1)
1495 gitCmd += files_.front();
1496 else
1497 gitCmd += folder_;
1498 gitCmd += _T("\"");
1499 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1500 gitCmd += _T(" /alternative");
1501 break;
1502 case ShellMenuDiffTwo:
1503 gitCmd += _T("diffcommits /path:\"");
1504 if (files_.size() == 1)
1505 gitCmd += files_.front();
1506 else
1507 gitCmd += folder_;
1508 gitCmd += _T("\"");
1509 break;
1510 case ShellMenuDropCopyAdd:
1511 tempfile = WriteFileListToTempFile();
1512 gitCmd += _T("dropcopyadd /pathfile:\"");
1513 gitCmd += tempfile;
1514 gitCmd += _T("\"");
1515 gitCmd += _T(" /deletepathfile");
1516 gitCmd += _T(" /droptarget:\"");
1517 gitCmd += folder_;
1518 gitCmd += _T("\"";)
1519 break;
1520 case ShellMenuDropCopy:
1521 tempfile = WriteFileListToTempFile();
1522 gitCmd += _T("dropcopy /pathfile:\"");
1523 gitCmd += tempfile;
1524 gitCmd += _T("\"");
1525 gitCmd += _T(" /deletepathfile");
1526 gitCmd += _T(" /droptarget:\"");
1527 gitCmd += folder_;
1528 gitCmd += _T("\"";)
1529 break;
1530 case ShellMenuDropCopyRename:
1531 tempfile = WriteFileListToTempFile();
1532 gitCmd += _T("dropcopy /pathfile:\"");
1533 gitCmd += tempfile;
1534 gitCmd += _T("\"");
1535 gitCmd += _T(" /deletepathfile");
1536 gitCmd += _T(" /droptarget:\"");
1537 gitCmd += folder_;
1538 gitCmd += _T("\" /rename";)
1539 break;
1540 case ShellMenuDropMove:
1541 tempfile = WriteFileListToTempFile();
1542 gitCmd += _T("dropmove /pathfile:\"");
1543 gitCmd += tempfile;
1544 gitCmd += _T("\"");
1545 gitCmd += _T(" /deletepathfile");
1546 gitCmd += _T(" /droptarget:\"");
1547 gitCmd += folder_;
1548 gitCmd += _T("\"");
1549 break;
1550 case ShellMenuDropMoveRename:
1551 tempfile = WriteFileListToTempFile();
1552 gitCmd += _T("dropmove /pathfile:\"");
1553 gitCmd += tempfile;
1554 gitCmd += _T("\"");
1555 gitCmd += _T(" /deletepathfile");
1556 gitCmd += _T(" /droptarget:\"");
1557 gitCmd += folder_;
1558 gitCmd += _T("\" /rename";)
1559 break;
1560 case ShellMenuDropExport:
1561 tempfile = WriteFileListToTempFile();
1562 gitCmd += _T("dropexport /pathfile:\"");
1563 gitCmd += tempfile;
1564 gitCmd += _T("\"");
1565 gitCmd += _T(" /deletepathfile");
1566 gitCmd += _T(" /droptarget:\"");
1567 gitCmd += folder_;
1568 gitCmd += _T("\"");
1569 break;
1570 case ShellMenuDropExportExtended:
1571 tempfile = WriteFileListToTempFile();
1572 gitCmd += _T("dropexport /pathfile:\"");
1573 gitCmd += tempfile;
1574 gitCmd += _T("\"");
1575 gitCmd += _T(" /deletepathfile");
1576 gitCmd += _T(" /droptarget:\"");
1577 gitCmd += folder_;
1578 gitCmd += _T("\"");
1579 gitCmd += _T(" /extended");
1580 break;
1581 case ShellMenuLog:
1582 gitCmd += _T("log /path:\"");
1583 if (files_.size() > 0)
1584 gitCmd += files_.front();
1585 else
1586 gitCmd += folder_;
1587 gitCmd += _T("\"");
1588 break;
1589 case ShellMenuConflictEditor:
1590 gitCmd += _T("conflicteditor /path:\"");
1591 if (files_.size() > 0)
1592 gitCmd += files_.front();
1593 else
1594 gitCmd += folder_;
1595 gitCmd += _T("\"");
1596 break;
1597 case ShellMenuGitSVNRebase:
1598 gitCmd += _T("svnrebase /path:\"");
1599 if (files_.size() > 0)
1600 gitCmd += files_.front();
1601 else
1602 gitCmd += folder_;
1603 gitCmd += _T("\"");
1604 break;
1605 case ShellMenuGitSVNDCommit:
1606 gitCmd += _T("svndcommit /path:\"");
1607 if (files_.size() > 0)
1608 gitCmd += files_.front();
1609 else
1610 gitCmd += folder_;
1611 gitCmd += _T("\"");
1612 break;
1613 case ShellMenuGitSVNDFetch:
1614 gitCmd += _T("svnfetch /path:\"");
1615 if (files_.size() > 0)
1616 gitCmd += files_.front();
1617 else
1618 gitCmd += folder_;
1619 gitCmd += _T("\"");
1620 break;
1621 case ShellMenuGitSVNIgnore:
1622 gitCmd += _T("svnignore /path:\"");
1623 if (files_.size() > 0)
1624 gitCmd += files_.front();
1625 else
1626 gitCmd += folder_;
1627 gitCmd += _T("\"");
1628 break;
1629 case ShellMenuRebase:
1630 gitCmd += _T("rebase /path:\"");
1631 if (files_.size() > 0)
1632 gitCmd += files_.front();
1633 else
1634 gitCmd += folder_;
1635 gitCmd += _T("\"");
1636 break;
1637 case ShellMenuShowChanged:
1638 if (files_.size() > 1)
1640 tempfile = WriteFileListToTempFile();
1641 gitCmd += _T("repostatus /pathfile:\"");
1642 gitCmd += tempfile;
1643 gitCmd += _T("\"");
1644 gitCmd += _T(" /deletepathfile");
1646 else
1648 gitCmd += _T("repostatus /path:\"");
1649 if (files_.size() > 0)
1650 gitCmd += files_.front();
1651 else
1652 gitCmd += folder_;
1653 gitCmd += _T("\"");
1655 break;
1656 case ShellMenuRefBrowse:
1657 gitCmd += _T("refbrowse /path:\"");
1658 if (files_.size() > 0)
1659 gitCmd += files_.front();
1660 else
1661 gitCmd += folder_;
1662 gitCmd += _T("\"");
1663 break;
1664 case ShellMenuRefLog:
1665 gitCmd += _T("reflog /path:\"");
1666 if (files_.size() > 0)
1667 gitCmd += files_.front();
1668 else
1669 gitCmd += folder_;
1670 gitCmd += _T("\"");
1671 break;
1673 case ShellMenuStashSave:
1674 gitCmd += _T("stashsave /path:\"");
1675 if (files_.size() > 0)
1676 gitCmd += files_.front();
1677 else
1678 gitCmd += folder_;
1679 gitCmd += _T("\"");
1680 break;
1682 case ShellMenuStashApply:
1683 gitCmd += _T("stashapply /path:\"");
1684 if (files_.size() > 0)
1685 gitCmd += files_.front();
1686 else
1687 gitCmd += folder_;
1688 gitCmd += _T("\"");
1689 break;
1691 case ShellMenuStashPop:
1692 gitCmd += _T("stashpop /path:\"");
1693 if (files_.size() > 0)
1694 gitCmd += files_.front();
1695 else
1696 gitCmd += folder_;
1697 gitCmd += _T("\"");
1698 break;
1701 case ShellMenuStashList:
1702 gitCmd += _T("reflog /path:\"");
1703 if (files_.size() > 0)
1704 gitCmd += files_.front();
1705 else
1706 gitCmd += folder_;
1707 gitCmd += _T("\" /ref:refs/stash");
1708 break;
1710 case ShellMenuBisectStart:
1711 gitCmd += _T("bisect /path:\"");
1712 if (files_.size() > 0)
1713 gitCmd += files_.front();
1714 else
1715 gitCmd += folder_;
1716 gitCmd += _T("\" /start");
1717 break;
1719 case ShellMenuBisectGood:
1720 gitCmd += _T("bisect /path:\"");
1721 if (files_.size() > 0)
1722 gitCmd += files_.front();
1723 else
1724 gitCmd += folder_;
1725 gitCmd += _T("\" /good");
1726 break;
1729 case ShellMenuBisectBad:
1730 gitCmd += _T("bisect /path:\"");
1731 if (files_.size() > 0)
1732 gitCmd += files_.front();
1733 else
1734 gitCmd += folder_;
1735 gitCmd += _T("\" /bad");
1736 break;
1738 case ShellMenuBisectReset:
1739 gitCmd += _T("bisect /path:\"");
1740 if (files_.size() > 0)
1741 gitCmd += files_.front();
1742 else
1743 gitCmd += folder_;
1744 gitCmd += _T("\" /reset");
1745 break;
1747 case ShellMenuSubAdd:
1748 gitCmd += _T("subadd /path:\"");
1749 if (files_.size() > 0)
1750 gitCmd += files_.front();
1751 else
1752 gitCmd += folder_;
1753 gitCmd += _T("\"");
1754 break;
1756 case ShellMenuBlame:
1757 gitCmd += _T("blame /path:\"");
1758 if (files_.size() > 0)
1759 gitCmd += files_.front();
1760 else
1761 gitCmd += folder_;
1762 gitCmd += _T("\"");
1763 break;
1764 case ShellMenuApplyPatch:
1765 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1767 // if there's a patch file in the clipboard, we save it
1768 // to a temporary file and tell TortoiseMerge to use that one
1769 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1770 if ((cFormat)&&(OpenClipboard(NULL)))
1772 HGLOBAL hglb = GetClipboardData(cFormat);
1773 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1775 DWORD len = GetTempPath(0, NULL);
1776 TCHAR * path = new TCHAR[len+1];
1777 TCHAR * tempF = new TCHAR[len+100];
1778 GetTempPath (len+1, path);
1779 GetTempFileName (path, TEXT("git"), 0, tempF);
1780 std::wstring sTempFile = std::wstring(tempF);
1781 delete [] path;
1782 delete [] tempF;
1784 FILE * outFile;
1785 size_t patchlen = strlen(lpstr);
1786 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1787 if(outFile)
1789 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1790 if (size == patchlen)
1792 itemStates |= ITEMIS_PATCHFILE;
1793 files_.clear();
1794 files_.push_back(sTempFile);
1796 fclose(outFile);
1798 GlobalUnlock(hglb);
1799 CloseClipboard();
1802 if (itemStates & ITEMIS_PATCHFILE)
1804 gitCmd = _T(" /diff:\"");
1805 if (files_.size() > 0)
1807 gitCmd += files_.front();
1808 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1810 gitCmd += _T("\" /patchpath:\"");
1811 gitCmd += folder_;
1814 else
1815 gitCmd += folder_;
1816 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1817 gitCmd += _T("\" /wc");
1818 else
1819 gitCmd += _T("\"");
1821 else
1823 gitCmd = _T(" /patchpath:\"");
1824 if (files_.size() > 0)
1825 gitCmd += files_.front();
1826 else
1827 gitCmd += folder_;
1828 gitCmd += _T("\"");
1830 myIDMap.clear();
1831 myVerbsIDMap.clear();
1832 myVerbsMap.clear();
1833 if (CreateProcess(((stdstring)tortoiseMergePath).c_str(), const_cast<TCHAR*>(gitCmd.c_str()), NULL, NULL, FALSE, 0, 0, 0, &startup, &process)==0)
1835 LPVOID lpMsgBuf;
1836 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1837 FORMAT_MESSAGE_FROM_SYSTEM |
1838 FORMAT_MESSAGE_IGNORE_INSERTS,
1839 NULL,
1840 GetLastError(),
1841 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
1842 (LPTSTR) &lpMsgBuf,
1844 NULL
1846 MessageBox( NULL, (LPCTSTR)lpMsgBuf, _T("TortoiseMerge launch failed"), MB_OK | MB_ICONINFORMATION );
1847 LocalFree( lpMsgBuf );
1849 CloseHandle(process.hThread);
1850 CloseHandle(process.hProcess);
1851 return NOERROR;
1852 break;
1853 case ShellMenuProperties:
1854 tempfile = WriteFileListToTempFile();
1855 gitCmd += _T("properties /pathfile:\"");
1856 gitCmd += tempfile;
1857 gitCmd += _T("\"");
1858 gitCmd += _T(" /deletepathfile");
1859 break;
1860 case ShellMenuClipPaste:
1861 if (WriteClipboardPathsToTempFile(tempfile))
1863 bool bCopy = true;
1864 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1865 if (cPrefDropFormat)
1867 if (OpenClipboard(lpcmi->hwnd))
1869 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1870 if (hglb)
1872 DWORD* effect = (DWORD*) GlobalLock(hglb);
1873 if (*effect == DROPEFFECT_MOVE)
1874 bCopy = false;
1875 GlobalUnlock(hglb);
1877 CloseClipboard();
1881 if (bCopy)
1882 gitCmd += _T("pastecopy /pathfile:\"");
1883 else
1884 gitCmd += _T("pastemove /pathfile:\"");
1885 gitCmd += tempfile;
1886 gitCmd += _T("\"");
1887 gitCmd += _T(" /deletepathfile");
1888 gitCmd += _T(" /droptarget:\"");
1889 gitCmd += folder_;
1890 gitCmd += _T("\"");
1892 else return NOERROR;
1893 break;
1894 case ShellMenuClone:
1895 gitCmd += _T("clone /path:\"");
1896 if (files_.size() > 0)
1897 gitCmd += files_.front();
1898 else
1899 gitCmd += folder_;
1900 gitCmd += _T("\"");
1901 break;
1902 case ShellMenuPull:
1903 gitCmd += _T("pull /path:\"");
1904 if (files_.size() > 0)
1905 gitCmd += files_.front();
1906 else
1907 gitCmd += folder_;
1908 gitCmd += _T("\"");
1909 break;
1910 case ShellMenuPush:
1911 gitCmd += _T("push /path:\"");
1912 if (files_.size() > 0)
1913 gitCmd += files_.front();
1914 else
1915 gitCmd += folder_;
1916 gitCmd += _T("\"");
1917 break;
1918 case ShellMenuBranch:
1919 gitCmd += _T("branch /path:\"");
1920 if (files_.size() > 0)
1921 gitCmd += files_.front();
1922 else
1923 gitCmd += folder_;
1924 gitCmd += _T("\"");
1925 break;
1927 case ShellMenuTag:
1928 gitCmd += _T("tag /path:\"");
1929 if (files_.size() > 0)
1930 gitCmd += files_.front();
1931 else
1932 gitCmd += folder_;
1933 gitCmd += _T("\"");
1934 break;
1936 case ShellMenuFormatPatch:
1937 gitCmd += _T("formatpatch /path:\"");
1938 if (files_.size() > 0)
1939 gitCmd += files_.front();
1940 else
1941 gitCmd += folder_;
1942 gitCmd += _T("\"");
1943 break;
1945 case ShellMenuImportPatch:
1946 tempfile = WriteFileListToTempFile();
1947 gitCmd += _T("importpatch /pathfile:\"");
1948 gitCmd += tempfile;
1949 gitCmd += _T("\"");
1950 gitCmd += _T(" /deletepathfile");
1951 break;
1953 case ShellMenuCherryPick:
1954 gitCmd += _T("cherrypick /path:\"");
1955 if (files_.size() > 0)
1956 gitCmd += files_.front();
1957 else
1958 gitCmd += folder_;
1959 gitCmd += _T("\"");
1960 break;
1961 case ShellMenuFetch:
1962 gitCmd += _T("fetch /path:\"");
1963 if (files_.size() > 0)
1964 gitCmd += files_.front();
1965 else
1966 gitCmd += folder_;
1967 gitCmd += _T("\"");
1968 break;
1970 default:
1971 break;
1972 //#endregion
1973 } // switch (id_it->second)
1974 gitCmd += _T(" /hwnd:");
1975 TCHAR buf[30];
1976 _stprintf_s(buf, 30, _T("%d"), lpcmi->hwnd);
1977 gitCmd += buf;
1978 myIDMap.clear();
1979 myVerbsIDMap.clear();
1980 myVerbsMap.clear();
1981 if (CreateProcess(((stdstring)tortoiseProcPath).c_str(), const_cast<TCHAR*>(gitCmd.c_str()), NULL, NULL, FALSE, 0, 0, 0, &startup, &process)==0)
1983 LPVOID lpMsgBuf;
1984 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1985 FORMAT_MESSAGE_FROM_SYSTEM |
1986 FORMAT_MESSAGE_IGNORE_INSERTS,
1987 NULL,
1988 GetLastError(),
1989 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
1990 (LPTSTR) &lpMsgBuf,
1992 NULL
1994 MessageBox( NULL, (LPCTSTR)lpMsgBuf, _T("TortoiseProc Launch failed"), MB_OK | MB_ICONINFORMATION );
1995 LocalFree( lpMsgBuf );
1997 CloseHandle(process.hThread);
1998 CloseHandle(process.hProcess);
1999 hr = NOERROR;
2000 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
2001 } // if ((files_.size() > 0)||(folder_.size() > 0))
2002 return hr;
2006 // This is for the status bar and things like that:
2007 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
2008 UINT uFlags,
2009 UINT FAR * /*reserved*/,
2010 LPSTR pszName,
2011 UINT cchMax)
2013 PreserveChdir preserveChdir;
2014 //do we know the id?
2015 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
2016 if (id_it == myIDMap.end() || id_it->first != idCmd)
2018 return E_INVALIDARG; //no, we don't
2021 LoadLangDll();
2022 HRESULT hr = E_INVALIDARG;
2024 MAKESTRING(IDS_MENUDESCDEFAULT);
2025 int menuIndex = 0;
2026 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2028 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
2030 MAKESTRING(menuInfo[menuIndex].menuDescID);
2031 break;
2033 menuIndex++;
2036 const TCHAR * desc = stringtablebuffer;
2037 switch(uFlags)
2039 case GCS_HELPTEXTA:
2041 std::string help = WideToMultibyte(desc);
2042 lstrcpynA(pszName, help.c_str(), cchMax);
2043 hr = S_OK;
2044 break;
2046 case GCS_HELPTEXTW:
2048 wide_string help = desc;
2049 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2050 hr = S_OK;
2051 break;
2053 case GCS_VERBA:
2055 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2056 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2058 std::string help = WideToMultibyte(verb_id_it->second);
2059 lstrcpynA(pszName, help.c_str(), cchMax);
2060 hr = S_OK;
2063 break;
2064 case GCS_VERBW:
2066 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
2067 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
2069 wide_string help = verb_id_it->second;
2070 ATLTRACE("verb : %ws\n", help.c_str());
2071 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
2072 hr = S_OK;
2075 break;
2077 return hr;
2080 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
2082 LRESULT res;
2083 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
2086 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
2088 PreserveChdir preserveChdir;
2090 LRESULT res;
2091 if (pResult == NULL)
2092 pResult = &res;
2093 *pResult = FALSE;
2095 LoadLangDll();
2096 switch (uMsg)
2098 case WM_MEASUREITEM:
2100 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
2101 if (lpmis==NULL||lpmis->CtlType!=ODT_MENU)
2102 break;
2103 lpmis->itemWidth = 16;
2104 lpmis->itemHeight = 16;
2105 *pResult = TRUE;
2107 break;
2108 case WM_DRAWITEM:
2110 LPCTSTR resource;
2111 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
2112 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
2113 return S_OK; //not for a menu
2114 resource = GetMenuTextFromResource(myIDMap[lpdis->itemID]);
2115 if (resource == NULL)
2116 return S_OK;
2117 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2118 if (hIcon == NULL)
2119 return S_OK;
2120 DrawIconEx(lpdis->hDC,
2121 lpdis->rcItem.left,
2122 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
2123 hIcon, 16, 16,
2124 0, NULL, DI_NORMAL);
2125 DestroyIcon(hIcon);
2126 *pResult = TRUE;
2128 break;
2129 case WM_MENUCHAR:
2131 LPCTSTR resource;
2132 TCHAR *szItem;
2133 if (HIWORD(wParam) != MF_POPUP)
2134 return NOERROR;
2135 int nChar = LOWORD(wParam);
2136 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
2137 nChar = tolower(nChar);
2138 // we have the char the user pressed, now search that char in all our
2139 // menu items
2140 std::vector<int> accmenus;
2141 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
2143 resource = GetMenuTextFromResource(mySubMenuMap[It->first]);
2144 if (resource == NULL)
2145 continue;
2146 szItem = stringtablebuffer;
2147 TCHAR * amp = _tcschr(szItem, '&');
2148 if (amp == NULL)
2149 continue;
2150 amp++;
2151 int ampChar = LOWORD(*amp);
2152 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
2153 ampChar = tolower(ampChar);
2154 if (ampChar == nChar)
2156 // yep, we found a menu which has the pressed key
2157 // as an accelerator. Add that menu to the list to
2158 // process later.
2159 accmenus.push_back(It->first);
2162 if (accmenus.size() == 0)
2164 // no menu with that accelerator key.
2165 *pResult = MAKELONG(0, MNC_IGNORE);
2166 return NOERROR;
2168 if (accmenus.size() == 1)
2170 // Only one menu with that accelerator key. We're lucky!
2171 // So just execute that menu entry.
2172 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
2173 return NOERROR;
2175 if (accmenus.size() > 1)
2177 // we have more than one menu item with this accelerator key!
2178 MENUITEMINFO mif;
2179 mif.cbSize = sizeof(MENUITEMINFO);
2180 mif.fMask = MIIM_STATE;
2181 for (std::vector<int>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
2183 GetMenuItemInfo((HMENU)lParam, *it, TRUE, &mif);
2184 if (mif.fState == MFS_HILITE)
2186 // this is the selected item, so select the next one
2187 ++it;
2188 if (it == accmenus.end())
2189 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2190 else
2191 *pResult = MAKELONG(*it, MNC_SELECT);
2192 return NOERROR;
2195 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
2198 break;
2199 default:
2200 return NOERROR;
2203 return NOERROR;
2206 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
2208 TCHAR textbuf[255];
2209 LPCTSTR resource = NULL;
2210 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
2211 space = 6;
2213 int menuIndex = 0;
2214 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
2216 if (menuInfo[menuIndex].command == id)
2218 MAKESTRING(menuInfo[menuIndex].menuTextID);
2219 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
2220 switch (id)
2222 case ShellSubMenuMultiple:
2223 case ShellSubMenuLink:
2224 case ShellSubMenuFolder:
2225 case ShellSubMenuFile:
2226 case ShellSubMenu:
2227 space = 0;
2228 break;
2229 default:
2230 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
2231 if (layout & (menuInfo[menuIndex].menuID))
2233 _tcscpy_s(textbuf, 255, _T("Git "));
2234 _tcscat_s(textbuf, 255, stringtablebuffer);
2235 _tcscpy_s(stringtablebuffer, 255, textbuf);
2237 break;
2239 return resource;
2241 menuIndex++;
2243 return NULL;
2246 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
2248 int i=0;
2249 TCHAR buf[MAX_PATH]; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
2250 LPITEMIDLIST pidl = NULL;
2251 while (cslidarray[i])
2253 ++i;
2254 pidl = NULL;
2255 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
2256 continue;
2257 if (!SHGetPathFromIDList(pidl, buf))
2259 // not a file system path, definitely illegal for our use
2260 CoTaskMemFree(pidl);
2261 continue;
2263 CoTaskMemFree(pidl);
2264 if (_tcslen(buf)==0)
2265 continue;
2266 if (_tcscmp(buf, folder.c_str())==0)
2267 return true;
2269 return false;
2272 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT uFlags)
2274 HMENU ignoresubmenu = NULL;
2275 int indexignoresub = 0;
2276 bool bShowIgnoreMenu = false;
2277 TCHAR maskbuf[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2278 TCHAR ignorepath[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
2279 if (files_.size() == 0)
2280 return false;
2281 UINT icon = bShowIcons ? IDI_IGNORE : 0;
2283 std::vector<stdstring>::iterator I = files_.begin();
2284 if (_tcsrchr(I->c_str(), '\\'))
2285 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
2286 else
2287 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
2288 if ((itemStates & ITEMIS_IGNORED)&&(ignoredprops.size() > 0))
2290 // check if the item name is ignored or the mask
2291 size_t p = 0;
2292 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
2294 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
2295 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
2297 break;
2299 p++;
2301 if (p!=-1)
2303 ignoresubmenu = CreateMenu();
2304 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2305 stdstring verb = stdstring(ignorepath);
2306 myVerbsMap[verb] = idCmd - idCmdFirst;
2307 myVerbsMap[verb] = idCmd;
2308 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2309 myVerbsIDMap[idCmd] = verb;
2310 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
2311 myIDMap[idCmd++] = ShellMenuUnIgnore;
2312 bShowIgnoreMenu = true;
2314 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2315 if (_tcsrchr(ignorepath, '.'))
2317 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2318 p = ignoredprops.find(maskbuf);
2319 if ((p!=-1) &&
2320 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
2322 if (ignoresubmenu==NULL)
2323 ignoresubmenu = CreateMenu();
2325 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2326 stdstring verb = stdstring(maskbuf);
2327 myVerbsMap[verb] = idCmd - idCmdFirst;
2328 myVerbsMap[verb] = idCmd;
2329 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2330 myVerbsIDMap[idCmd] = verb;
2331 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
2332 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
2333 bShowIgnoreMenu = true;
2337 else if ((itemStates & ITEMIS_IGNORED) == 0)
2339 bShowIgnoreMenu = true;
2340 ignoresubmenu = CreateMenu();
2341 if (itemStates & ITEMIS_ONLYONE)
2343 if (itemStates & ITEMIS_INGIT)
2345 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2346 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2347 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2349 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2350 if (_tcsrchr(ignorepath, '.'))
2352 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2353 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2354 stdstring verb = stdstring(maskbuf);
2355 myVerbsMap[verb] = idCmd - idCmdFirst;
2356 myVerbsMap[verb] = idCmd;
2357 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2358 myVerbsIDMap[idCmd] = verb;
2359 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2360 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2363 else
2365 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2366 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2367 myIDMap[idCmd++] = ShellMenuIgnore;
2369 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2370 if (_tcsrchr(ignorepath, '.'))
2372 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2373 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2374 stdstring verb = stdstring(maskbuf);
2375 myVerbsMap[verb] = idCmd - idCmdFirst;
2376 myVerbsMap[verb] = idCmd;
2377 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2378 myVerbsIDMap[idCmd] = verb;
2379 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2380 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2384 else
2386 if (itemStates & ITEMIS_INGIT)
2388 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
2389 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2390 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2391 stdstring verb = stdstring(ignorepath);
2392 myVerbsMap[verb] = idCmd - idCmdFirst;
2393 myVerbsMap[verb] = idCmd;
2394 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2395 myVerbsIDMap[idCmd] = verb;
2396 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2397 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2399 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
2400 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2401 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2402 verb = stdstring(ignorepath);
2403 myVerbsMap[verb] = idCmd - idCmdFirst;
2404 myVerbsMap[verb] = idCmd;
2405 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2406 myVerbsIDMap[idCmd] = verb;
2407 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2408 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2410 else
2412 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2413 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2414 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2415 stdstring verb = stdstring(ignorepath);
2416 myVerbsMap[verb] = idCmd - idCmdFirst;
2417 myVerbsMap[verb] = idCmd;
2418 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2419 myVerbsIDMap[idCmd] = verb;
2420 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2421 myIDMap[idCmd++] = ShellMenuIgnore;
2423 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2424 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2425 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2426 verb = stdstring(ignorepath);
2427 myVerbsMap[verb] = idCmd - idCmdFirst;
2428 myVerbsMap[verb] = idCmd;
2429 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2430 myVerbsIDMap[idCmd] = verb;
2431 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2432 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2437 if (bShowIgnoreMenu)
2439 MENUITEMINFO menuiteminfo;
2440 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2441 menuiteminfo.cbSize = sizeof(menuiteminfo);
2442 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2443 if (icon)
2445 menuiteminfo.fMask |= MIIM_BITMAP;
2446 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
2448 menuiteminfo.fType = MFT_STRING;
2449 menuiteminfo.hSubMenu = ignoresubmenu;
2450 menuiteminfo.wID = idCmd;
2451 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2452 if (itemStates & ITEMIS_IGNORED)
2453 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2454 else if (itemStates & ITEMIS_INGIT)
2455 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2456 else
2457 GetMenuTextFromResource(ShellMenuIgnoreSub);
2458 menuiteminfo.dwTypeData = stringtablebuffer;
2459 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2461 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2462 if (itemStates & ITEMIS_IGNORED)
2464 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2465 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2467 else
2469 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2470 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2473 return bShowIgnoreMenu;
2476 HBITMAP CShellExt::IconToBitmapPARGB32(UINT uIcon)
2478 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
2479 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
2480 return bitmap_it->second;
2482 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2483 if (!hIcon)
2484 return NULL;
2486 if (pfnBeginBufferedPaint == NULL || pfnEndBufferedPaint == NULL || pfnGetBufferedPaintBits == NULL)
2487 return NULL;
2489 SIZE sizIcon;
2490 sizIcon.cx = GetSystemMetrics(SM_CXSMICON);
2491 sizIcon.cy = GetSystemMetrics(SM_CYSMICON);
2493 RECT rcIcon;
2494 SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy);
2495 HBITMAP hBmp = NULL;
2497 HDC hdcDest = CreateCompatibleDC(NULL);
2498 if (hdcDest)
2500 if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp)))
2502 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp);
2503 if (hbmpOld)
2505 BLENDFUNCTION bfAlpha = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2506 BP_PAINTPARAMS paintParams = {0};
2507 paintParams.cbSize = sizeof(paintParams);
2508 paintParams.dwFlags = BPPF_ERASE;
2509 paintParams.pBlendFunction = &bfAlpha;
2511 HDC hdcBuffer;
2512 HPAINTBUFFER hPaintBuffer = pfnBeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer);
2513 if (hPaintBuffer)
2515 if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL))
2517 // If icon did not have an alpha channel we need to convert buffer to PARGB
2518 ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon);
2521 // This will write the buffer contents to the destination bitmap
2522 pfnEndBufferedPaint(hPaintBuffer, TRUE);
2525 SelectObject(hdcDest, hbmpOld);
2529 DeleteDC(hdcDest);
2532 DestroyIcon(hIcon);
2534 if(hBmp)
2535 bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp));
2536 return hBmp;
2539 HRESULT CShellExt::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP* phBmp)
2541 *phBmp = NULL;
2543 BITMAPINFO bmi;
2544 ZeroMemory(&bmi, sizeof(bmi));
2545 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2546 bmi.bmiHeader.biPlanes = 1;
2547 bmi.bmiHeader.biCompression = BI_RGB;
2549 bmi.bmiHeader.biWidth = psize->cx;
2550 bmi.bmiHeader.biHeight = psize->cy;
2551 bmi.bmiHeader.biBitCount = 32;
2553 HDC hdcUsed = hdc ? hdc : GetDC(NULL);
2554 if (hdcUsed)
2556 *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0);
2557 if (hdc != hdcUsed)
2559 ReleaseDC(NULL, hdcUsed);
2562 return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK;
2565 HRESULT CShellExt::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon)
2567 RGBQUAD *prgbQuad;
2568 int cxRow;
2569 HRESULT hr = pfnGetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow);
2570 if (SUCCEEDED(hr))
2572 ARGB *pargb = reinterpret_cast<ARGB *>(prgbQuad);
2573 if (!HasAlpha(pargb, sizIcon, cxRow))
2575 ICONINFO info;
2576 if (GetIconInfo(hicon, &info))
2578 if (info.hbmMask)
2580 hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow);
2583 DeleteObject(info.hbmColor);
2584 DeleteObject(info.hbmMask);
2589 return hr;
2592 bool CShellExt::HasAlpha(__in ARGB *pargb, SIZE& sizImage, int cxRow)
2594 ULONG cxDelta = cxRow - sizImage.cx;
2595 for (ULONG y = sizImage.cy; y; --y)
2597 for (ULONG x = sizImage.cx; x; --x)
2599 if (*pargb++ & 0xFF000000)
2601 return true;
2605 pargb += cxDelta;
2608 return false;
2611 HRESULT CShellExt::ConvertToPARGB32(HDC hdc, __inout ARGB *pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow)
2613 BITMAPINFO bmi;
2614 ZeroMemory(&bmi, sizeof(bmi));
2615 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2616 bmi.bmiHeader.biPlanes = 1;
2617 bmi.bmiHeader.biCompression = BI_RGB;
2619 bmi.bmiHeader.biWidth = sizImage.cx;
2620 bmi.bmiHeader.biHeight = sizImage.cy;
2621 bmi.bmiHeader.biBitCount = 32;
2623 HRESULT hr = E_OUTOFMEMORY;
2624 HANDLE hHeap = GetProcessHeap();
2625 void *pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight);
2626 if (pvBits)
2628 hr = E_UNEXPECTED;
2629 if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight)
2631 ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth;
2632 ARGB *pargbMask = static_cast<ARGB *>(pvBits);
2634 for (ULONG y = bmi.bmiHeader.biHeight; y; --y)
2636 for (ULONG x = bmi.bmiHeader.biWidth; x; --x)
2638 if (*pargbMask++)
2640 // transparent pixel
2641 *pargb++ = 0;
2643 else
2645 // opaque pixel
2646 *pargb++ |= 0xFF000000;
2650 pargb += cxDelta;
2653 hr = S_OK;
2656 HeapFree(hHeap, 0, pvBits);
2659 return hr;