Dropped unused variables
[TortoiseGit.git] / src / TortoiseShell / ContextMenu.cpp
blob4f8c96264010990e1cd6461e46f58370d45d1fbe
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2012 - TortoiseSVN
4 // Copyright (C) 2008-2012 - TortoiseGit
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "ShellExt.h"
22 #include "ItemIDList.h"
23 #include "PreserveChdir.h"
24 #include "UnicodeUtils.h"
25 #include "GitStatus.h"
26 #include "TGitPath.h"
27 #include "PathUtils.h"
28 #include "CreateProcessHelper.h"
29 #include "FormatMessageWrapper.h"
30 #include "resource.h"
32 #define GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
33 #define GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
35 int g_shellidlist=RegisterClipboardFormat(CFSTR_SHELLIDLIST);
37 extern MenuInfo menuInfo[];
40 STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST pIDFolder,
41 LPDATAOBJECT pDataObj,
42 HKEY hRegKey)
44 __try
46 return Initialize_Wrap(pIDFolder, pDataObj, hRegKey);
48 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
51 return E_FAIL;
54 STDMETHODIMP CShellExt::Initialize_Wrap(LPCITEMIDLIST pIDFolder,
55 LPDATAOBJECT pDataObj,
56 HKEY /* hRegKey */)
58 ATLTRACE("Shell :: Initialize\n");
59 PreserveChdir preserveChdir;
60 files_.clear();
61 folder_.clear();
62 uuidSource.clear();
63 uuidTarget.clear();
64 itemStates = 0;
65 itemStatesFolder = 0;
66 stdstring statuspath;
67 git_wc_status_kind fetchedstatus = git_wc_status_none;
68 // get selected files/folders
69 if (pDataObj)
71 STGMEDIUM medium;
72 FORMATETC fmte = {(CLIPFORMAT)g_shellidlist,
73 (DVTARGETDEVICE FAR *)NULL,
74 DVASPECT_CONTENT,
75 -1,
76 TYMED_HGLOBAL};
77 HRESULT hres = pDataObj->GetData(&fmte, &medium);
79 if (SUCCEEDED(hres) && medium.hGlobal)
81 if (m_State == FileStateDropHandler)
84 FORMATETC etc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
85 STGMEDIUM stg = { TYMED_HGLOBAL };
86 if ( FAILED( pDataObj->GetData ( &etc, &stg )))
88 ReleaseStgMedium ( &medium );
89 return E_INVALIDARG;
93 HDROP drop = (HDROP)GlobalLock(stg.hGlobal);
94 if ( NULL == drop )
96 ReleaseStgMedium ( &stg );
97 ReleaseStgMedium ( &medium );
98 return E_INVALIDARG;
101 int count = DragQueryFile(drop, (UINT)-1, NULL, 0);
102 if (count == 1)
103 itemStates |= ITEMIS_ONLYONE;
104 for (int i = 0; i < count; i++)
106 // find the path length in chars
107 UINT len = DragQueryFile(drop, i, NULL, 0);
108 if (len == 0)
109 continue;
110 std::unique_ptr<TCHAR[]> szFileName(new TCHAR[len + 1]);
111 if (0 == DragQueryFile(drop, i, szFileName.get(), len + 1))
112 continue;
113 stdstring str = stdstring(szFileName.get());
114 if ((!str.empty()) && (g_ShellCache.IsContextPathAllowed(szFileName.get())))
116 if (itemStates & ITEMIS_ONLYONE)
118 CTGitPath strpath;
119 strpath.SetFromWin(str.c_str());
120 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
121 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
123 files_.push_back(str);
124 if (i == 0)
126 //get the Subversion status of the item
127 git_wc_status_kind status = git_wc_status_none;
128 CTGitPath askedpath;
129 askedpath.SetFromWin(str.c_str());
132 GitStatus stat;
133 stat.GetStatus(CTGitPath(str.c_str()), false, false, true);
134 if (stat.status)
136 statuspath = str;
137 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
138 fetchedstatus = status;
139 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
140 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
141 if ( askedpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
143 itemStates |= ITEMIS_FOLDER;
144 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
145 itemStates |= ITEMIS_FOLDERINGIT;
147 //if ((stat.status->entry)&&(stat.status->entry->present_props))
149 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
150 // itemStates |= ITEMIS_NEEDSLOCK;
152 //if ((stat.status->entry)&&(stat.status->entry->uuid))
153 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
155 else
157 // sometimes, git_client_status() returns with an error.
158 // in that case, we have to check if the working copy is versioned
159 // anyway to show the 'correct' context menu
160 if (askedpath.HasAdminDir())
161 status = git_wc_status_normal;
164 catch ( ... )
166 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
169 // TODO: should we really assume any sub-directory to be versioned
170 // or only if it contains versioned files
171 itemStates |= askedpath.GetAdminDirMask();
173 if ((status == git_wc_status_unversioned) || (status == git_wc_status_ignored) || (status == git_wc_status_none))
174 itemStates &= ~ITEMIS_INGIT;
176 if (status == git_wc_status_ignored)
177 itemStates |= ITEMIS_IGNORED;
178 if (status == git_wc_status_normal)
179 itemStates |= ITEMIS_NORMAL;
180 if (status == git_wc_status_conflicted)
181 itemStates |= ITEMIS_CONFLICTED;
182 if (status == git_wc_status_added)
183 itemStates |= ITEMIS_ADDED;
184 if (status == git_wc_status_deleted)
185 itemStates |= ITEMIS_DELETED;
188 } // for (int i = 0; i < count; i++)
189 GlobalUnlock ( drop );
190 ReleaseStgMedium ( &stg );
192 } // if (m_State == FileStateDropHandler)
193 else
196 //Enumerate PIDLs which the user has selected
197 CIDA* cida = (CIDA*)GlobalLock(medium.hGlobal);
198 ItemIDList parent( GetPIDLFolder (cida));
200 int count = cida->cidl;
201 BOOL statfetched = FALSE;
202 for (int i = 0; i < count; ++i)
204 ItemIDList child (GetPIDLItem (cida, i), &parent);
205 stdstring str = child.toString();
206 if ((str.empty() == false)&&(g_ShellCache.IsContextPathAllowed(str.c_str())))
208 //check if our menu is requested for a subversion admin directory
209 if (g_GitAdminDir.IsAdminDirPath(str.c_str()))
210 continue;
212 files_.push_back(str);
213 CTGitPath strpath;
214 strpath.SetFromWin(str.c_str());
215 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".diff"))==0) ? ITEMIS_PATCHFILE : 0;
216 itemStates |= (strpath.GetFileExtension().CompareNoCase(_T(".patch"))==0) ? ITEMIS_PATCHFILE : 0;
217 if (!statfetched)
219 //get the Subversion status of the item
220 git_wc_status_kind status = git_wc_status_none;
221 if ((g_ShellCache.IsSimpleContext())&&(strpath.IsDirectory()))
223 if (strpath.HasAdminDir())
224 status = git_wc_status_normal;
226 else
230 GitStatus stat;
231 if (strpath.HasAdminDir())
232 stat.GetStatus(strpath, false, false, true);
233 statuspath = str;
234 if (stat.status)
236 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
237 fetchedstatus = status;
238 //if ((stat.status->entry)&&(stat.status->entry->lock_token))
239 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
240 if ( strpath.IsDirectory() )//if ((stat.status->entry)&&(stat.status->entry->kind == git_node_dir))
242 itemStates |= ITEMIS_FOLDER;
243 if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
244 itemStates |= ITEMIS_FOLDERINGIT;
246 // TODO: do we need to check that it's not a dir? does conflict options makes sense for dir in git?
247 if (status == git_wc_status_conflicted)//if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
248 itemStates |= ITEMIS_CONFLICTED;
249 //if ((stat.status->entry)&&(stat.status->entry->present_props))
251 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
252 // itemStates |= ITEMIS_NEEDSLOCK;
254 //if ((stat.status->entry)&&(stat.status->entry->uuid))
255 // uuidSource = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
257 else
259 // sometimes, git_client_status() returns with an error.
260 // in that case, we have to check if the working copy is versioned
261 // anyway to show the 'correct' context menu
262 if (strpath.HasAdminDir())
264 status = git_wc_status_normal;
265 fetchedstatus = status;
268 statfetched = TRUE;
270 catch ( ... )
272 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
276 itemStates |= strpath.GetAdminDirMask();
278 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
279 itemStates &= ~ITEMIS_INGIT;
280 if (status == git_wc_status_ignored)
282 itemStates |= ITEMIS_IGNORED;
283 // the item is ignored. Get the svn:ignored properties so we can (maybe) later
284 // offer a 'remove from ignored list' entry
285 // GitProperties props(strpath.GetContainingDirectory(), false);
286 // ignoredprops.empty();
287 // for (int p=0; p<props.GetCount(); ++p)
288 // {
289 // if (props.GetItemName(p).compare(stdstring(_T("svn:ignore")))==0)
290 // {
291 // std::string st = props.GetItemValue(p);
292 // ignoredprops = MultibyteToWide(st.c_str());
293 // // remove all escape chars ('\\')
294 // std::remove(ignoredprops.begin(), ignoredprops.end(), '\\');
295 // break;
296 // }
297 // }
300 if (status == git_wc_status_normal)
301 itemStates |= ITEMIS_NORMAL;
302 if (status == git_wc_status_conflicted)
303 itemStates |= ITEMIS_CONFLICTED;
304 if (status == git_wc_status_added)
305 itemStates |= ITEMIS_ADDED;
306 if (status == git_wc_status_deleted)
307 itemStates |= ITEMIS_DELETED;
310 } // for (int i = 0; i < count; ++i)
311 ItemIDList child (GetPIDLItem (cida, 0), &parent);
312 if (g_ShellCache.HasGITAdminDir(child.toString().c_str(), FALSE))
313 itemStates |= ITEMIS_INVERSIONEDFOLDER;
315 if (itemStates == 0 && g_GitAdminDir.IsBareRepo(child.toString().c_str()))
316 itemStates = ITEMIS_BAREREPO;
318 GlobalUnlock(medium.hGlobal);
320 // if the item is a versioned folder, check if there's a patch file
321 // in the clipboard to be used in "Apply Patch"
322 UINT cFormatDiff = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
323 if (cFormatDiff)
325 if (IsClipboardFormatAvailable(cFormatDiff))
326 itemStates |= ITEMIS_PATCHINCLIPBOARD;
328 if (IsClipboardFormatAvailable(CF_HDROP))
329 itemStates |= ITEMIS_PATHINCLIPBOARD;
333 ReleaseStgMedium ( &medium );
334 if (medium.pUnkForRelease)
336 IUnknown* relInterface = (IUnknown*)medium.pUnkForRelease;
337 relInterface->Release();
342 // get folder background
343 if (pIDFolder)
346 ItemIDList list(pIDFolder);
347 folder_ = list.toString();
348 git_wc_status_kind status = git_wc_status_none;
349 if (IsClipboardFormatAvailable(CF_HDROP))
350 itemStatesFolder |= ITEMIS_PATHINCLIPBOARD;
352 CTGitPath askedpath;
353 askedpath.SetFromWin(folder_.c_str());
355 if (g_ShellCache.IsContextPathAllowed(folder_.c_str()))
357 if (folder_.compare(statuspath)!=0)
362 GitStatus stat;
363 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
364 if (stat.status)
366 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
367 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
368 // itemStatesFolder |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
369 // if ((stat.status->entry)&&(stat.status->entry->present_props))
370 // {
371 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
372 // itemStatesFolder |= ITEMIS_NEEDSLOCK;
373 // }
374 // if ((stat.status->entry)&&(stat.status->entry->uuid))
375 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
378 else
380 // sometimes, git_client_status() returns with an error.
381 // in that case, we have to check if the working copy is versioned
382 // anyway to show the 'correct' context menu
383 if (askedpath.HasAdminDir())
384 status = git_wc_status_normal;
387 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
388 itemStatesFolder |= askedpath.GetAdminDirMask();
390 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
391 itemStates &= ~ITEMIS_INGIT;
393 if (status == git_wc_status_normal)
394 itemStatesFolder |= ITEMIS_NORMAL;
395 if (status == git_wc_status_conflicted)
396 itemStatesFolder |= ITEMIS_CONFLICTED;
397 if (status == git_wc_status_added)
398 itemStatesFolder |= ITEMIS_ADDED;
399 if (status == git_wc_status_deleted)
400 itemStatesFolder |= ITEMIS_DELETED;
403 catch ( ... )
405 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
408 else
410 status = fetchedstatus;
412 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
413 itemStatesFolder |= askedpath.GetAdminDirMask();
415 if (status == git_wc_status_ignored)
416 itemStatesFolder |= ITEMIS_IGNORED;
417 itemStatesFolder |= ITEMIS_FOLDER;
418 if (files_.empty())
419 itemStates |= ITEMIS_ONLYONE;
420 if (m_State != FileStateDropHandler)
421 itemStates |= itemStatesFolder;
423 else
425 folder_.clear();
426 status = fetchedstatus;
429 if (files_.size() == 2)
430 itemStates |= ITEMIS_TWO;
431 if ((files_.size() == 1)&&(g_ShellCache.IsContextPathAllowed(files_.front().c_str())))
434 itemStates |= ITEMIS_ONLYONE;
435 if (m_State != FileStateDropHandler)
437 if (PathIsDirectory(files_.front().c_str()))
439 folder_ = files_.front();
440 git_wc_status_kind status = git_wc_status_none;
441 CTGitPath askedpath;
442 askedpath.SetFromWin(folder_.c_str());
444 if (folder_.compare(statuspath)!=0)
448 GitStatus stat;
449 stat.GetStatus(CTGitPath(folder_.c_str()), false, false, true);
450 if (stat.status)
452 status = GitStatus::GetMoreImportant(stat.status->text_status, stat.status->prop_status);
453 // if ((stat.status->entry)&&(stat.status->entry->lock_token))
454 // itemStates |= (stat.status->entry->lock_token[0] != 0) ? ITEMIS_LOCKED : 0;
455 // if ((stat.status->entry)&&(stat.status->entry->present_props))
456 // {
457 // if (strstr(stat.status->entry->present_props, "svn:needs-lock"))
458 // itemStates |= ITEMIS_NEEDSLOCK;
459 // }
460 // if ((stat.status->entry)&&(stat.status->entry->uuid))
461 // uuidTarget = CUnicodeUtils::StdGetUnicode(stat.status->entry->uuid);
464 catch ( ... )
466 ATLTRACE2(_T("Exception in GitStatus::GetStatus()\n"));
469 else
471 status = fetchedstatus;
473 //if ((status != git_wc_status_unversioned)&&(status != git_wc_status_ignored)&&(status != git_wc_status_none))
474 itemStates |= askedpath.GetAdminDirMask();
476 if ((status == git_wc_status_unversioned)||(status == git_wc_status_ignored)||(status == git_wc_status_none))
477 itemStates &= ~ITEMIS_INGIT;
479 if (status == git_wc_status_ignored)
480 itemStates |= ITEMIS_IGNORED;
481 itemStates |= ITEMIS_FOLDER;
482 if (status == git_wc_status_added)
483 itemStates |= ITEMIS_ADDED;
484 if (status == git_wc_status_deleted)
485 itemStates |= ITEMIS_DELETED;
492 return S_OK;
495 void CShellExt::InsertGitMenu(BOOL istop, HMENU menu, UINT pos, UINT_PTR id, UINT stringid, UINT icon, UINT idCmdFirst, GitCommands com, UINT /*uFlags*/)
497 TCHAR menutextbuffer[512] = {0};
498 TCHAR verbsbuffer[255] = {0};
499 MAKESTRING(stringid);
501 if (istop)
503 //menu entry for the top context menu, so append an "Git " before
504 //the menu text to indicate where the entry comes from
505 _tcscpy_s(menutextbuffer, 255, _T("Git "));
507 _tcscat_s(menutextbuffer, 255, stringtablebuffer);
508 #if 1
509 // insert branch name into "Git Commit..." entry, so it looks like "Git Commit "master"..."
510 // so we have an easy and fast way to check the current branch
511 // (the other alternative is using a separate disabled menu entry, the code is already done but commented out)
512 if (com == ShellMenuCommit)
514 // get branch name
515 CTGitPath path(folder_.empty() ? files_.front().c_str() : folder_.c_str());
516 CString sProjectRoot;
517 CString sBranchName;
519 if (path.GetAdminDirMask() & ITEMIS_SUBMODULE)
521 if (istop)
522 _tcscpy_s(menutextbuffer, 255, _T("Git "));
523 _tcscat_s(menutextbuffer, 255, CString(MAKEINTRESOURCE(IDS_MENUCOMMITSUBMODULE)));
526 if (path.HasAdminDir(&sProjectRoot) && !g_Git.GetCurrentBranchFromFile(sProjectRoot, sBranchName))
528 if (sBranchName.GetLength() == 40)
530 // if SHA1 only show 4 first bytes
531 BOOL bIsSha1 = TRUE;
532 for (int i=0; i<40; i++)
533 if ( !iswxdigit(sBranchName[i]) )
535 bIsSha1 = FALSE;
536 break;
538 if (bIsSha1)
539 sBranchName = sBranchName.Left(8) + _T("....");
542 // sanity check
543 if (sBranchName.GetLength() > 64)
544 sBranchName = sBranchName.Left(64) + _T("...");
546 // scan to before "..."
547 LPTSTR s = menutextbuffer + _tcslen(menutextbuffer)-1;
548 if (s > menutextbuffer)
550 while (s > menutextbuffer)
552 if (*s != _T('.'))
554 s++;
555 break;
557 s--;
560 else
562 s = menutextbuffer;
565 // append branch name and end with ...
566 _tcscpy(s, _T(" -> \"") + sBranchName + _T("\"..."));
569 #endif
570 MENUITEMINFO menuiteminfo;
571 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
572 menuiteminfo.cbSize = sizeof(menuiteminfo);
573 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
574 menuiteminfo.fType = MFT_STRING;
575 menuiteminfo.dwTypeData = menutextbuffer;
576 if (icon)
578 menuiteminfo.fMask |= MIIM_BITMAP;
579 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
581 menuiteminfo.wID = (UINT)id;
582 InsertMenuItem(menu, pos, TRUE, &menuiteminfo);
584 if (istop)
586 //menu entry for the top context menu, so append an "Git " before
587 //the menu text to indicate where the entry comes from
588 _tcscpy_s(menutextbuffer, 255, _T("Git "));
590 LoadString(g_hResInst, stringid, verbsbuffer, sizeof(verbsbuffer));
591 _tcscat_s(menutextbuffer, 255, verbsbuffer);
592 stdstring verb = stdstring(menutextbuffer);
593 if (verb.find('&') != -1)
595 verb.erase(verb.find('&'),1);
597 myVerbsMap[verb] = id - idCmdFirst;
598 myVerbsMap[verb] = id;
599 myVerbsIDMap[id - idCmdFirst] = verb;
600 myVerbsIDMap[id] = verb;
601 // We store the relative and absolute diameter
602 // (drawitem callback uses absolute, others relative)
603 myIDMap[id - idCmdFirst] = com;
604 myIDMap[id] = com;
605 if (!istop)
606 mySubMenuMap[pos] = com;
609 HBITMAP CShellExt::IconToBitmap(UINT uIcon)
611 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
612 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
613 return bitmap_it->second;
615 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 12, 12, LR_DEFAULTCOLOR);
616 if (!hIcon)
617 return NULL;
619 RECT rect;
621 rect.right = ::GetSystemMetrics(SM_CXMENUCHECK);
622 rect.bottom = ::GetSystemMetrics(SM_CYMENUCHECK);
624 rect.left = rect.top = 0;
626 HWND desktop = ::GetDesktopWindow();
627 if (desktop == NULL)
629 DestroyIcon(hIcon);
630 return NULL;
633 HDC screen_dev = ::GetDC(desktop);
634 if (screen_dev == NULL)
636 DestroyIcon(hIcon);
637 return NULL;
640 // Create a compatible DC
641 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
642 if (dst_hdc == NULL)
644 DestroyIcon(hIcon);
645 ::ReleaseDC(desktop, screen_dev);
646 return NULL;
649 // Create a new bitmap of icon size
650 HBITMAP bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
651 if (bmp == NULL)
653 DestroyIcon(hIcon);
654 ::DeleteDC(dst_hdc);
655 ::ReleaseDC(desktop, screen_dev);
656 return NULL;
659 // Select it into the compatible DC
660 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
661 if (old_dst_bmp == NULL)
663 DestroyIcon(hIcon);
664 return NULL;
667 // Fill the background of the compatible DC with the white color
668 // that is taken by menu routines as transparent
669 ::SetBkColor(dst_hdc, RGB(255, 255, 255));
670 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
672 // Draw the icon into the compatible DC
673 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
675 // Restore settings
676 ::SelectObject(dst_hdc, old_dst_bmp);
677 ::DeleteDC(dst_hdc);
678 ::ReleaseDC(desktop, screen_dev);
679 DestroyIcon(hIcon);
680 if (bmp)
681 bitmaps.insert(bitmap_it, std::make_pair(uIcon, bmp));
682 return bmp;
685 bool CShellExt::WriteClipboardPathsToTempFile(stdstring& tempfile)
687 bool bRet = true;
688 tempfile = stdstring();
689 //write all selected files and paths to a temporary file
690 //for TortoiseGitProc.exe to read out again.
691 DWORD written = 0;
692 DWORD pathlength = GetTortoiseGitTempPath(0, NULL);
693 std::unique_ptr<TCHAR[]> path(new TCHAR[pathlength + 1]);
694 std::unique_ptr<TCHAR[]> tempFile(new TCHAR[pathlength + 100]);
695 GetTortoiseGitTempPath(pathlength+1, path.get());
696 GetTempFileName(path.get(), _T("git"), 0, tempFile.get());
697 tempfile = stdstring(tempFile.get());
699 CAutoFile file = ::CreateFile(tempFile.get(),
700 GENERIC_WRITE,
701 FILE_SHARE_READ,
703 CREATE_ALWAYS,
704 FILE_ATTRIBUTE_TEMPORARY,
707 if (!file)
708 return false;
710 if (!IsClipboardFormatAvailable(CF_HDROP))
711 return false;
712 if (!OpenClipboard(NULL))
713 return false;
715 stdstring sClipboardText;
716 HGLOBAL hglb = GetClipboardData(CF_HDROP);
717 HDROP hDrop = (HDROP)GlobalLock(hglb);
718 if(hDrop != NULL)
720 TCHAR szFileName[MAX_PATH];
721 UINT cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
722 for(UINT i = 0; i < cFiles; ++i)
724 DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
725 stdstring filename = szFileName;
726 ::WriteFile (file, filename.c_str(), (DWORD)filename.size()*sizeof(TCHAR), &written, 0);
727 ::WriteFile (file, _T("\n"), 2, &written, 0);
729 GlobalUnlock(hDrop);
731 else bRet = false;
732 GlobalUnlock(hglb);
734 CloseClipboard();
736 return bRet;
739 stdstring CShellExt::WriteFileListToTempFile()
741 //write all selected files and paths to a temporary file
742 //for TortoiseGitProc.exe to read out again.
743 DWORD pathlength = GetTortoiseGitTempPath(0, NULL);
744 std::unique_ptr<TCHAR[]> path(new TCHAR[pathlength + 1]);
745 std::unique_ptr<TCHAR[]> tempFile(new TCHAR[pathlength + 100]);
746 GetTortoiseGitTempPath(pathlength + 1, path.get());
747 GetTempFileName(path.get(), _T("git"), 0, tempFile.get());
748 stdstring retFilePath = stdstring(tempFile.get());
750 CAutoFile file = ::CreateFile (tempFile.get(),
751 GENERIC_WRITE,
752 FILE_SHARE_READ,
754 CREATE_ALWAYS,
755 FILE_ATTRIBUTE_TEMPORARY,
758 if (!file)
759 return stdstring();
761 DWORD written = 0;
762 if (files_.empty())
764 ::WriteFile (file, folder_.c_str(), (DWORD)folder_.size()*sizeof(TCHAR), &written, 0);
765 ::WriteFile (file, _T("\n"), 2, &written, 0);
768 for (std::vector<stdstring>::iterator I = files_.begin(); I != files_.end(); ++I)
770 ::WriteFile (file, I->c_str(), (DWORD)I->size()*sizeof(TCHAR), &written, 0);
771 ::WriteFile (file, _T("\n"), 2, &written, 0);
773 return retFilePath;
776 STDMETHODIMP CShellExt::QueryDropContext(UINT uFlags, UINT idCmdFirst, HMENU hMenu, UINT &indexMenu)
778 PreserveChdir preserveChdir;
779 LoadLangDll();
781 if ((uFlags & CMF_DEFAULTONLY)!=0)
782 return S_OK; //we don't change the default action
784 if (files_.empty() || folder_.empty())
785 return S_OK;
787 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
788 return S_OK;
790 if (itemStatesFolder & ITEMIS_FOLDER) // we do not support folders atm, see issue #963
791 return S_OK;
793 bool bSourceAndTargetFromSameRepository = (uuidSource.compare(uuidTarget) == 0) || uuidSource.empty() || uuidTarget.empty();
795 //the drop handler only has eight commands, but not all are visible at the same time:
796 //if the source file(s) are under version control then those files can be moved
797 //to the new location or they can be moved with a rename,
798 //if they are unversioned then they can be added to the working copy
799 //if they are versioned, they also can be exported to an unversioned location
800 UINT idCmd = idCmdFirst;
802 // Git move here
803 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
804 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&((itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED)))
805 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVEMENU, 0, idCmdFirst, ShellMenuDropMove, uFlags);
807 // Git move and rename here
808 // 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
809 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
810 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPMOVERENAMEMENU, 0, idCmdFirst, ShellMenuDropMoveRename, uFlags);
812 // Git copy here
813 // available if source is versioned but not added, target is versioned, source and target from same repository or target folder is added
814 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&((~itemStates) & ITEMIS_ADDED))
815 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYMENU, 0, idCmdFirst, ShellMenuDropCopy, uFlags);
817 // Git copy and rename here, source and target from same repository
818 // available if source is a single, versioned but not added item, target is versioned or target folder is added
819 if ((bSourceAndTargetFromSameRepository||(itemStatesFolder & ITEMIS_ADDED))&&(itemStatesFolder & ITEMIS_FOLDERINGIT)&&(itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_ONLYONE)&&((~itemStates) & ITEMIS_ADDED))
820 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYRENAMEMENU, 0, idCmdFirst, ShellMenuDropCopyRename, uFlags);
822 // Git add here
823 // available if target is versioned and source is either unversioned or from another repository
824 if ((itemStatesFolder & ITEMIS_FOLDERINGIT)&&(((~itemStates) & ITEMIS_INGIT)||!bSourceAndTargetFromSameRepository))
825 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPCOPYADDMENU, 0, idCmdFirst, ShellMenuDropCopyAdd, uFlags);
827 // Git export here
828 // available if source is versioned and a folder
829 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
830 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTMENU, 0, idCmdFirst, ShellMenuDropExport, uFlags);
832 // Git export all here
833 // available if source is versioned and a folder
834 //if ((itemStates & ITEMIS_INGIT)&&(itemStates & ITEMIS_FOLDER))
835 // InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_DROPEXPORTEXTENDEDMENU, 0, idCmdFirst, ShellMenuDropExportExtended, uFlags);
837 // apply patch
838 // available if source is a patchfile
839 if (itemStates & ITEMIS_PATCHFILE)
840 InsertGitMenu(FALSE, hMenu, indexMenu++, idCmd++, IDS_MENUAPPLYPATCH, 0, idCmdFirst, ShellMenuApplyPatch, uFlags);
842 // separator
843 if (idCmd != idCmdFirst)
844 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
846 TweakMenu(hMenu);
848 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
851 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
852 UINT indexMenu,
853 UINT idCmdFirst,
854 UINT idCmdLast,
855 UINT uFlags)
857 __try
859 return QueryContextMenu_Wrap(hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags);
861 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
864 return E_FAIL;
867 STDMETHODIMP CShellExt::QueryContextMenu_Wrap(HMENU hMenu,
868 UINT indexMenu,
869 UINT idCmdFirst,
870 UINT /*idCmdLast*/,
871 UINT uFlags)
873 ATLTRACE("Shell :: QueryContextMenu\n");
874 PreserveChdir preserveChdir;
876 //first check if our drop handler is called
877 //and then (if true) provide the context menu for the
878 //drop handler
879 if (m_State == FileStateDropHandler)
881 return QueryDropContext(uFlags, idCmdFirst, hMenu, indexMenu);
884 if ((uFlags & CMF_DEFAULTONLY)!=0)
885 return S_OK; //we don't change the default action
887 if (files_.empty() && folder_.empty())
888 return S_OK;
890 if (((uFlags & 0x000f)!=CMF_NORMAL)&&(!(uFlags & CMF_EXPLORE))&&(!(uFlags & CMF_VERBSONLY)))
891 return S_OK;
893 int csidlarray[] =
895 CSIDL_BITBUCKET,
896 CSIDL_CDBURN_AREA,
897 CSIDL_COMMON_FAVORITES,
898 CSIDL_COMMON_STARTMENU,
899 CSIDL_COMPUTERSNEARME,
900 CSIDL_CONNECTIONS,
901 CSIDL_CONTROLS,
902 CSIDL_COOKIES,
903 CSIDL_FAVORITES,
904 CSIDL_FONTS,
905 CSIDL_HISTORY,
906 CSIDL_INTERNET,
907 CSIDL_INTERNET_CACHE,
908 CSIDL_NETHOOD,
909 CSIDL_NETWORK,
910 CSIDL_PRINTERS,
911 CSIDL_PRINTHOOD,
912 CSIDL_RECENT,
913 CSIDL_SENDTO,
914 CSIDL_STARTMENU,
917 if (IsIllegalFolder(folder_, csidlarray))
918 return S_OK;
920 if (folder_.empty())
922 // folder is empty, but maybe files are selected
923 if (files_.empty())
924 return S_OK; // nothing selected - we don't have a menu to show
925 // check whether a selected entry is an UID - those are namespace extensions
926 // which we can't handle
927 for (std::vector<stdstring>::const_iterator it = files_.begin(); it != files_.end(); ++it)
929 if (_tcsncmp(it->c_str(), _T("::{"), 3)==0)
930 return S_OK;
933 else
935 if (_tcsncmp(folder_.c_str(), _T("::{"), 3) == 0)
936 return S_OK;
939 if (((uFlags & CMF_EXTENDEDVERBS) == 0) && g_ShellCache.HideMenusForUnversionedItems())
941 if ((itemStates & (ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER|ITEMIS_FOLDERINGIT|ITEMIS_BAREREPO|ITEMIS_TWO))==0)
942 return S_OK;
945 //check if our menu is requested for a subversion admin directory
946 if (g_GitAdminDir.IsAdminDirPath(folder_.c_str()))
947 return S_OK;
949 if (uFlags & CMF_EXTENDEDVERBS)
950 itemStates |= ITEMIS_EXTENDED;
952 const BOOL bShortcut = !!(uFlags & CMF_VERBSONLY);
953 if ( bShortcut && (files_.size()==1))
955 // Don't show the context menu for a link if the
956 // destination is not part of a working copy.
957 // It would only show the standard menu items
958 // which are already shown for the lnk-file.
959 CString path = files_.front().c_str();
960 if ( !g_GitAdminDir.HasAdminDir(path) )
962 return S_OK;
966 //check if we already added our menu entry for a folder.
967 //we check that by iterating through all menu entries and check if
968 //the dwItemData member points to our global ID string. That string is set
969 //by our shell extension when the folder menu is inserted.
970 TCHAR menubuf[MAX_PATH];
971 int count = GetMenuItemCount(hMenu);
972 for (int i=0; i<count; ++i)
974 MENUITEMINFO miif;
975 SecureZeroMemory(&miif, sizeof(MENUITEMINFO));
976 miif.cbSize = sizeof(MENUITEMINFO);
977 miif.fMask = MIIM_DATA;
978 miif.dwTypeData = menubuf;
979 miif.cch = _countof(menubuf);
980 GetMenuItemInfo(hMenu, i, TRUE, &miif);
981 if (miif.dwItemData == (ULONG_PTR)g_MenuIDString)
982 return S_OK;
985 LoadLangDll();
986 UINT idCmd = idCmdFirst;
988 //create the sub menu
989 HMENU subMenu = CreateMenu();
990 int indexSubMenu = 0;
992 unsigned __int64 topmenu = g_ShellCache.GetMenuLayout();
993 unsigned __int64 menumask = g_ShellCache.GetMenuMask();
994 unsigned __int64 menuex = g_ShellCache.GetMenuExt();
996 int menuIndex = 0;
997 bool bAddSeparator = false;
998 bool bMenuEntryAdded = false;
999 bool bMenuEmpty = true;
1000 // insert separator at start
1001 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1002 bool bShowIcons = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\ShowContextMenuIcons"), TRUE));
1004 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1006 if (menuInfo[menuIndex].command == ShellSeparator)
1008 // we don't add a separator immediately. Because there might not be
1009 // another 'normal' menu entry after we insert a separator.
1010 // we simply set a flag here, indicating that before the next
1011 // 'normal' menu entry, a separator should be added.
1012 if (!bMenuEmpty)
1013 bAddSeparator = true;
1015 else
1017 // check the conditions whether to show the menu entry or not
1018 bool bInsertMenu = ShouldInsertItem(menuInfo[menuIndex]);
1019 if (menuInfo[menuIndex].menuID & menuex)
1021 if( !(itemStates & ITEMIS_EXTENDED) )
1023 bInsertMenu = false;
1027 if (menuInfo[menuIndex].menuID & (~menumask))
1029 if (bInsertMenu)
1031 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1032 // insert a separator
1033 if ((bMenuEntryAdded)&&(bAddSeparator)&&(!bIsTop))
1035 bAddSeparator = false;
1036 bMenuEntryAdded = false;
1037 InsertMenu(subMenu, indexSubMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
1038 idCmd++;
1041 // handle special cases (sub menus)
1042 if ((menuInfo[menuIndex].command == ShellMenuIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuUnIgnoreSub)||(menuInfo[menuIndex].command == ShellMenuDeleteIgnoreSub))
1044 if(InsertIgnoreSubmenus(idCmd, idCmdFirst, hMenu, subMenu, indexMenu, indexSubMenu, topmenu, bShowIcons, uFlags))
1046 bMenuEntryAdded = true;
1047 bMenuEmpty = false;
1050 else
1052 bool bIsTop = ((topmenu & menuInfo[menuIndex].menuID) != 0);
1054 // insert the menu entry
1055 InsertGitMenu( bIsTop,
1056 bIsTop ? hMenu : subMenu,
1057 bIsTop ? indexMenu++ : indexSubMenu++,
1058 idCmd++,
1059 menuInfo[menuIndex].menuTextID,
1060 bShowIcons ? menuInfo[menuIndex].iconID : 0,
1061 idCmdFirst,
1062 menuInfo[menuIndex].command,
1063 uFlags);
1064 if (!bIsTop)
1066 bMenuEntryAdded = true;
1067 bMenuEmpty = false;
1068 bAddSeparator = false;
1074 menuIndex++;
1077 //add sub menu to main context menu
1078 //don't use InsertMenu because this will lead to multiple menu entries in the explorer file menu.
1079 //see http://support.microsoft.com/default.aspx?scid=kb;en-us;214477 for details of that.
1080 MAKESTRING(IDS_MENUSUBMENU);
1081 MENUITEMINFO menuiteminfo;
1082 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
1083 menuiteminfo.cbSize = sizeof(menuiteminfo);
1084 menuiteminfo.fType = MFT_STRING;
1085 menuiteminfo.dwTypeData = stringtablebuffer;
1087 UINT uIcon = bShowIcons ? IDI_APP : 0;
1088 if (!folder_.empty())
1090 uIcon = bShowIcons ? IDI_MENUFOLDER : 0;
1091 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFolder;
1092 myIDMap[idCmd] = ShellSubMenuFolder;
1093 menuiteminfo.dwItemData = (ULONG_PTR)g_MenuIDString;
1095 else if (!bShortcut && (files_.size()==1))
1097 uIcon = bShowIcons ? IDI_MENUFILE : 0;
1098 myIDMap[idCmd - idCmdFirst] = ShellSubMenuFile;
1099 myIDMap[idCmd] = ShellSubMenuFile;
1101 else if (bShortcut && (files_.size()==1))
1103 uIcon = bShowIcons ? IDI_MENULINK : 0;
1104 myIDMap[idCmd - idCmdFirst] = ShellSubMenuLink;
1105 myIDMap[idCmd] = ShellSubMenuLink;
1107 else if (!files_.empty())
1109 uIcon = bShowIcons ? IDI_MENUMULTIPLE : 0;
1110 myIDMap[idCmd - idCmdFirst] = ShellSubMenuMultiple;
1111 myIDMap[idCmd] = ShellSubMenuMultiple;
1113 else
1115 myIDMap[idCmd - idCmdFirst] = ShellSubMenu;
1116 myIDMap[idCmd] = ShellSubMenu;
1118 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
1119 if (uIcon)
1121 menuiteminfo.fMask |= MIIM_BITMAP;
1122 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(uIcon) : HBMMENU_CALLBACK;
1124 menuiteminfo.hSubMenu = subMenu;
1125 menuiteminfo.wID = idCmd++;
1126 InsertMenuItem(hMenu, indexMenu++, TRUE, &menuiteminfo);
1128 //separator after
1129 InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL); idCmd++;
1131 TweakMenu(hMenu);
1133 //return number of menu items added
1134 return ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(idCmd - idCmdFirst)));
1137 void CShellExt::TweakMenu(HMENU hMenu)
1139 MENUINFO MenuInfo = {};
1140 MenuInfo.cbSize = sizeof(MenuInfo);
1141 MenuInfo.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS;
1142 MenuInfo.dwStyle = MNS_CHECKORBMP;
1143 SetMenuInfo(hMenu, &MenuInfo);
1146 void CShellExt::AddPathCommand(tstring& gitCmd, LPCTSTR command, bool bFilesAllowed)
1148 gitCmd += command;
1149 gitCmd += _T(" /path:\"");
1150 if ((bFilesAllowed) && !files_.empty())
1151 gitCmd += files_.front();
1152 else
1153 gitCmd += folder_;
1154 gitCmd += _T("\"");
1157 void CShellExt::AddPathFileCommand(tstring& gitCmd, LPCTSTR command)
1159 tstring tempfile = WriteFileListToTempFile();
1160 gitCmd += command;
1161 gitCmd += _T(" /pathfile:\"");
1162 gitCmd += tempfile;
1163 gitCmd += _T("\"");
1164 gitCmd += _T(" /deletepathfile");
1167 void CShellExt::AddPathFileDropCommand(tstring& gitCmd, LPCTSTR command)
1169 tstring tempfile = WriteFileListToTempFile();
1170 gitCmd += command;
1171 gitCmd += _T(" /pathfile:\"");
1172 gitCmd += tempfile;
1173 gitCmd += _T("\"");
1174 gitCmd += _T(" /deletepathfile");
1175 gitCmd += _T(" /droptarget:\"");
1176 gitCmd += folder_;
1177 gitCmd += _T("\"");
1180 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
1182 __try
1184 return InvokeCommand_Wrap(lpcmi);
1186 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1189 return E_FAIL;
1192 // This is called when you invoke a command on the menu:
1193 STDMETHODIMP CShellExt::InvokeCommand_Wrap(LPCMINVOKECOMMANDINFO lpcmi)
1195 PreserveChdir preserveChdir;
1196 HRESULT hr = E_INVALIDARG;
1197 if (lpcmi == NULL)
1198 return hr;
1200 if (!files_.empty() || !folder_.empty())
1202 UINT_PTR idCmd = LOWORD(lpcmi->lpVerb);
1204 if (HIWORD(lpcmi->lpVerb))
1206 stdstring verb = stdstring(MultibyteToWide(lpcmi->lpVerb));
1207 std::map<stdstring, UINT_PTR>::const_iterator verb_it = myVerbsMap.lower_bound(verb);
1208 if (verb_it != myVerbsMap.end() && verb_it->first == verb)
1209 idCmd = verb_it->second;
1210 else
1211 return hr;
1214 // See if we have a handler interface for this id
1215 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1216 if (id_it != myIDMap.end() && id_it->first == idCmd)
1218 tstring tortoiseProcPath = CPathUtils::GetAppDirectory(g_hmodThisDll) + _T("TortoiseGitProc.exe");
1219 tstring tortoiseMergePath = CPathUtils::GetAppDirectory(g_hmodThisDll) + _T("TortoiseGitMerge.exe");
1221 //TortoiseProc expects a command line of the form:
1222 //"/command:<commandname> /pathfile:<path> /startrev:<startrevision> /endrev:<endrevision> /deletepathfile
1223 // or
1224 //"/command:<commandname> /path:<path> /startrev:<startrevision> /endrev:<endrevision>
1226 //* path is a path to a single file/directory for commands which only act on single items (log, checkout, ...)
1227 //* pathfile is a path to a temporary file which contains a list of file paths
1228 stdstring gitCmd = _T(" /command:");
1229 stdstring tempfile;
1230 switch (id_it->second)
1232 //#region case
1233 case ShellMenuSync:
1234 AddPathCommand(gitCmd, L"sync", false);
1235 break;
1236 case ShellMenuSubSync:
1237 AddPathFileCommand(gitCmd, L"subsync");
1238 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1240 gitCmd += _T(" /bkpath:\"");
1241 gitCmd += folder_;
1242 gitCmd += _T("\"");
1244 break;
1245 case ShellMenuUpdateExt:
1246 AddPathFileCommand(gitCmd, L"subupdate");
1247 if (itemStatesFolder & ITEMIS_SUBMODULECONTAINER || (itemStates & ITEMIS_SUBMODULECONTAINER && itemStates & ITEMIS_WCROOT && itemStates & ITEMIS_ONLYONE))
1249 gitCmd += _T(" /bkpath:\"");
1250 gitCmd += folder_;
1251 gitCmd += _T("\"");
1253 break;
1254 case ShellMenuCommit:
1255 AddPathFileCommand(gitCmd, L"commit");
1256 break;
1257 case ShellMenuAdd:
1258 AddPathFileCommand(gitCmd, L"add");
1259 break;
1260 case ShellMenuIgnore:
1261 AddPathFileCommand(gitCmd, L"ignore");
1262 break;
1263 case ShellMenuIgnoreCaseSensitive:
1264 AddPathFileCommand(gitCmd, L"ignore");
1265 gitCmd += _T(" /onlymask");
1266 break;
1267 case ShellMenuDeleteIgnore:
1268 AddPathFileCommand(gitCmd, L"ignore");
1269 gitCmd += _T(" /delete");
1270 break;
1271 case ShellMenuDeleteIgnoreCaseSensitive:
1272 AddPathFileCommand(gitCmd, L"ignore");
1273 gitCmd += _T(" /delete /onlymask");
1274 break;
1275 case ShellMenuUnIgnore:
1276 AddPathFileCommand(gitCmd, L"unignore");
1277 break;
1278 case ShellMenuUnIgnoreCaseSensitive:
1279 AddPathFileCommand(gitCmd, L"unignore");
1280 gitCmd += _T(" /onlymask");
1281 break;
1282 case ShellMenuRevert:
1283 AddPathFileCommand(gitCmd, L"revert");
1284 break;
1285 case ShellMenuCleanup:
1286 AddPathFileCommand(gitCmd, L"cleanup");
1287 break;
1288 case ShellMenuSendMail:
1289 AddPathFileCommand(gitCmd, L"sendmail");
1290 break;
1291 case ShellMenuResolve:
1292 AddPathFileCommand(gitCmd, L"resolve");
1293 break;
1294 case ShellMenuSwitch:
1295 AddPathCommand(gitCmd, L"switch", false);
1296 break;
1297 case ShellMenuExport:
1298 AddPathCommand(gitCmd, L"export", false);
1299 break;
1300 case ShellMenuAbout:
1301 gitCmd += _T("about");
1302 break;
1303 case ShellMenuCreateRepos:
1304 AddPathCommand(gitCmd, L"repocreate", false);
1305 break;
1306 case ShellMenuMerge:
1307 AddPathCommand(gitCmd, L"merge", false);
1308 break;
1309 case ShellMenuCopy:
1310 AddPathCommand(gitCmd, L"copy", true);
1311 break;
1312 case ShellMenuSettings:
1313 AddPathCommand(gitCmd, L"settings", true);
1314 break;
1315 case ShellMenuHelp:
1316 gitCmd += _T("help");
1317 break;
1318 case ShellMenuRename:
1319 AddPathCommand(gitCmd, L"rename", true);
1320 break;
1321 case ShellMenuRemove:
1322 AddPathFileCommand(gitCmd, L"remove");
1323 break;
1324 case ShellMenuRemoveKeep:
1325 AddPathFileCommand(gitCmd, L"remove");
1326 gitCmd += _T(" /keep");
1327 break;
1328 case ShellMenuDiff:
1329 gitCmd += _T("diff /path:\"");
1330 if (files_.size() == 1)
1331 gitCmd += files_.front();
1332 else if (files_.size() == 2)
1334 std::vector<stdstring>::iterator I = files_.begin();
1335 gitCmd += *I;
1336 I++;
1337 gitCmd += _T("\" /path2:\"");
1338 gitCmd += *I;
1340 else
1341 gitCmd += folder_;
1342 gitCmd += _T("\"");
1343 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1344 gitCmd += _T(" /alternative");
1345 break;
1346 case ShellMenuPrevDiff:
1347 AddPathCommand(gitCmd, L"prevdiff", true);
1348 if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
1349 gitCmd += _T(" /alternative");
1350 break;
1351 case ShellMenuDiffTwo:
1352 AddPathCommand(gitCmd, L"diffcommits", true);
1353 break;
1354 case ShellMenuDropCopyAdd:
1355 AddPathFileDropCommand(gitCmd, L"dropcopyadd");
1356 break;
1357 case ShellMenuDropCopy:
1358 AddPathFileDropCommand(gitCmd, L"dropcopy");
1359 break;
1360 case ShellMenuDropCopyRename:
1361 AddPathFileDropCommand(gitCmd, L"dropcopy");
1362 gitCmd += _T("\" /rename";)
1363 break;
1364 case ShellMenuDropMove:
1365 AddPathFileDropCommand(gitCmd, L"dropmove");
1366 break;
1367 case ShellMenuDropMoveRename:
1368 AddPathFileDropCommand(gitCmd, L"dropmove");
1369 gitCmd += _T("\" /rename";)
1370 break;
1371 case ShellMenuDropExport:
1372 AddPathFileDropCommand(gitCmd, L"dropexport");
1373 break;
1374 case ShellMenuDropExportExtended:
1375 AddPathFileDropCommand(gitCmd, L"dropexport");
1376 gitCmd += _T(" /extended");
1377 break;
1378 case ShellMenuLog:
1379 case ShellMenuLogSubmoduleFolder:
1380 AddPathCommand(gitCmd, L"log", true);
1381 if (id_it->second == ShellMenuLogSubmoduleFolder)
1382 gitCmd += _T(" /submodule");
1383 break;
1384 case ShellMenuRevisionGraph:
1385 AddPathCommand(gitCmd, L"revisiongraph", true);
1386 break;
1387 case ShellMenuConflictEditor:
1388 AddPathCommand(gitCmd, L"conflicteditor", true);
1389 break;
1390 case ShellMenuGitSVNRebase:
1391 AddPathCommand(gitCmd, L"svnrebase", false);
1392 break;
1393 case ShellMenuGitSVNDCommit:
1394 AddPathCommand(gitCmd, L"svndcommit", true);
1395 break;
1396 case ShellMenuGitSVNDFetch:
1397 AddPathCommand(gitCmd, L"svnfetch", false);
1398 break;
1399 case ShellMenuGitSVNIgnore:
1400 AddPathCommand(gitCmd, L"svnignore", false);
1401 break;
1402 case ShellMenuRebase:
1403 AddPathCommand(gitCmd, L"rebase", false);
1404 break;
1405 case ShellMenuShowChanged:
1406 if (files_.size() > 1)
1408 AddPathFileCommand(gitCmd, L"repostatus");
1410 else
1412 AddPathCommand(gitCmd, L"repostatus", true);
1414 break;
1415 case ShellMenuRepoBrowse:
1416 AddPathCommand(gitCmd, L"repobrowser", false);
1417 break;
1418 case ShellMenuRefBrowse:
1419 AddPathCommand(gitCmd, L"refbrowse", false);
1420 break;
1421 case ShellMenuRefLog:
1422 AddPathCommand(gitCmd, L"reflog", false);
1423 break;
1424 case ShellMenuStashSave:
1425 AddPathCommand(gitCmd, L"stashsave", true);
1426 break;
1427 case ShellMenuStashApply:
1428 AddPathCommand(gitCmd, L"stashapply", false);
1429 break;
1430 case ShellMenuStashPop:
1431 AddPathCommand(gitCmd, L"stashpop", false);
1432 break;
1433 case ShellMenuStashList:
1434 AddPathCommand(gitCmd, L"reflog", false);
1435 gitCmd += _T(" /ref:refs/stash");
1436 break;
1437 case ShellMenuBisectStart:
1438 AddPathCommand(gitCmd, L"bisect", false);
1439 gitCmd += _T("\" /start");
1440 break;
1441 case ShellMenuBisectGood:
1442 AddPathCommand(gitCmd, L"bisect", false);
1443 gitCmd += _T("\" /good");
1444 break;
1445 case ShellMenuBisectBad:
1446 AddPathCommand(gitCmd, L"bisect", false);
1447 gitCmd += _T("\" /bad");
1448 break;
1449 case ShellMenuBisectReset:
1450 AddPathCommand(gitCmd, L"bisect", false);
1451 gitCmd += _T("\" /reset");
1452 break;
1453 case ShellMenuSubAdd:
1454 AddPathCommand(gitCmd, L"subadd", false);
1455 break;
1456 case ShellMenuBlame:
1457 AddPathCommand(gitCmd, L"blame", true);
1458 break;
1459 case ShellMenuApplyPatch:
1460 if ((itemStates & ITEMIS_PATCHINCLIPBOARD) && ((~itemStates) & ITEMIS_PATCHFILE))
1462 // if there's a patch file in the clipboard, we save it
1463 // to a temporary file and tell TortoiseGitMerge to use that one
1464 UINT cFormat = RegisterClipboardFormat(_T("TGIT_UNIFIEDDIFF"));
1465 if ((cFormat)&&(OpenClipboard(NULL)))
1467 HGLOBAL hglb = GetClipboardData(cFormat);
1468 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1470 DWORD len = GetTortoiseGitTempPath(0, NULL);
1471 std::unique_ptr<TCHAR[]> path(new TCHAR[len + 1]);
1472 std::unique_ptr<TCHAR[]> tempF(new TCHAR[len + 100]);
1473 GetTortoiseGitTempPath(len + 1, path.get());
1474 GetTempFileName(path.get(), TEXT("git"), 0, tempF.get());
1475 std::wstring sTempFile = std::wstring(tempF.get());
1477 FILE * outFile;
1478 size_t patchlen = strlen(lpstr);
1479 _tfopen_s(&outFile, sTempFile.c_str(), _T("wb"));
1480 if(outFile)
1482 size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
1483 if (size == patchlen)
1485 itemStates |= ITEMIS_PATCHFILE;
1486 files_.clear();
1487 files_.push_back(sTempFile);
1489 fclose(outFile);
1491 GlobalUnlock(hglb);
1492 CloseClipboard();
1495 if (itemStates & ITEMIS_PATCHFILE)
1497 gitCmd = _T(" /diff:\"");
1498 if (!files_.empty())
1500 gitCmd += files_.front();
1501 if (itemStatesFolder & ITEMIS_FOLDERINGIT)
1503 gitCmd += _T("\" /patchpath:\"");
1504 gitCmd += folder_;
1507 else
1508 gitCmd += folder_;
1509 if (itemStates & ITEMIS_INVERSIONEDFOLDER)
1510 gitCmd += _T("\" /wc");
1511 else
1512 gitCmd += _T("\"");
1514 else
1516 gitCmd = _T(" /patchpath:\"");
1517 if (!files_.empty())
1518 gitCmd += files_.front();
1519 else
1520 gitCmd += folder_;
1521 gitCmd += _T("\"");
1523 myIDMap.clear();
1524 myVerbsIDMap.clear();
1525 myVerbsMap.clear();
1526 RunCommand(tortoiseMergePath, gitCmd, _T("TortoiseGitMerge launch failed"));
1527 return S_OK;
1528 break;
1529 case ShellMenuClipPaste:
1530 if (WriteClipboardPathsToTempFile(tempfile))
1532 bool bCopy = true;
1533 UINT cPrefDropFormat = RegisterClipboardFormat(_T("Preferred DropEffect"));
1534 if (cPrefDropFormat)
1536 if (OpenClipboard(lpcmi->hwnd))
1538 HGLOBAL hglb = GetClipboardData(cPrefDropFormat);
1539 if (hglb)
1541 DWORD* effect = (DWORD*) GlobalLock(hglb);
1542 if (*effect == DROPEFFECT_MOVE)
1543 bCopy = false;
1544 GlobalUnlock(hglb);
1546 CloseClipboard();
1550 if (bCopy)
1551 gitCmd += _T("pastecopy /pathfile:\"");
1552 else
1553 gitCmd += _T("pastemove /pathfile:\"");
1554 gitCmd += tempfile;
1555 gitCmd += _T("\"");
1556 gitCmd += _T(" /deletepathfile");
1557 gitCmd += _T(" /droptarget:\"");
1558 gitCmd += folder_;
1559 gitCmd += _T("\"");
1561 else return S_OK;
1562 break;
1563 case ShellMenuClone:
1564 AddPathCommand(gitCmd, L"clone", false);
1565 break;
1566 case ShellMenuPull:
1567 AddPathCommand(gitCmd, L"pull", false);
1568 break;
1569 case ShellMenuPush:
1570 AddPathCommand(gitCmd, L"push", false);
1571 break;
1572 case ShellMenuBranch:
1573 AddPathCommand(gitCmd, L"branch", false);
1574 break;
1575 case ShellMenuTag:
1576 AddPathCommand(gitCmd, L"tag", false);
1577 break;
1578 case ShellMenuFormatPatch:
1579 AddPathCommand(gitCmd, L"formatpatch", false);
1580 break;
1581 case ShellMenuImportPatch:
1582 AddPathFileCommand(gitCmd, L"importpatch");
1583 break;
1584 case ShellMenuFetch:
1585 AddPathCommand(gitCmd, L"fetch", false);
1586 break;
1588 default:
1589 break;
1590 //#endregion
1591 } // switch (id_it->second)
1592 gitCmd += _T(" /hwnd:");
1593 TCHAR buf[30];
1594 _stprintf_s(buf, _T("%ld"), (LONG_PTR)lpcmi->hwnd);
1595 gitCmd += buf;
1596 myIDMap.clear();
1597 myVerbsIDMap.clear();
1598 myVerbsMap.clear();
1599 RunCommand(tortoiseProcPath, gitCmd, _T("TortoiseProc launch failed"));
1600 hr = S_OK;
1601 } // if (id_it != myIDMap.end() && id_it->first == idCmd)
1602 } // if (files_.empty() || folder_.empty())
1603 return hr;
1607 // This is for the status bar and things like that:
1608 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR idCmd,
1609 UINT uFlags,
1610 UINT FAR * reserved,
1611 LPSTR pszName,
1612 UINT cchMax)
1614 __try
1616 return GetCommandString_Wrap(idCmd, uFlags, reserved, pszName, cchMax);
1618 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1621 return E_FAIL;
1624 // This is for the status bar and things like that:
1625 STDMETHODIMP CShellExt::GetCommandString_Wrap(UINT_PTR idCmd,
1626 UINT uFlags,
1627 UINT FAR * /*reserved*/,
1628 LPSTR pszName,
1629 UINT cchMax)
1631 PreserveChdir preserveChdir;
1632 //do we know the id?
1633 std::map<UINT_PTR, UINT_PTR>::const_iterator id_it = myIDMap.lower_bound(idCmd);
1634 if (id_it == myIDMap.end() || id_it->first != idCmd)
1636 return E_INVALIDARG; //no, we don't
1639 LoadLangDll();
1640 HRESULT hr = E_INVALIDARG;
1642 MAKESTRING(IDS_MENUDESCDEFAULT);
1643 int menuIndex = 0;
1644 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1646 if (menuInfo[menuIndex].command == (GitCommands)id_it->second)
1648 MAKESTRING(menuInfo[menuIndex].menuDescID);
1649 break;
1651 menuIndex++;
1654 const TCHAR * desc = stringtablebuffer;
1655 switch(uFlags)
1657 case GCS_HELPTEXTA:
1659 std::string help = WideToMultibyte(desc);
1660 lstrcpynA(pszName, help.c_str(), cchMax);
1661 hr = S_OK;
1662 break;
1664 case GCS_HELPTEXTW:
1666 wide_string help = desc;
1667 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
1668 hr = S_OK;
1669 break;
1671 case GCS_VERBA:
1673 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
1674 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
1676 std::string help = WideToMultibyte(verb_id_it->second);
1677 lstrcpynA(pszName, help.c_str(), cchMax);
1678 hr = S_OK;
1681 break;
1682 case GCS_VERBW:
1684 std::map<UINT_PTR, stdstring>::const_iterator verb_id_it = myVerbsIDMap.lower_bound(idCmd);
1685 if (verb_id_it != myVerbsIDMap.end() && verb_id_it->first == idCmd)
1687 wide_string help = verb_id_it->second;
1688 ATLTRACE("verb : %ws\n", help.c_str());
1689 lstrcpynW((LPWSTR)pszName, help.c_str(), cchMax);
1690 hr = S_OK;
1693 break;
1695 return hr;
1698 STDMETHODIMP CShellExt::HandleMenuMsg(UINT uMsg, WPARAM wParam, LPARAM lParam)
1700 __try
1702 return HandleMenuMsg_Wrap(uMsg, wParam, lParam);
1704 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1707 return E_FAIL;
1710 STDMETHODIMP CShellExt::HandleMenuMsg_Wrap(UINT uMsg, WPARAM wParam, LPARAM lParam)
1712 LRESULT res;
1713 return HandleMenuMsg2(uMsg, wParam, lParam, &res);
1716 STDMETHODIMP CShellExt::HandleMenuMsg2(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
1718 __try
1720 return HandleMenuMsg2_Wrap(uMsg, wParam, lParam, pResult);
1722 __except(CCrashReport::Instance().SendReport(GetExceptionInformation()))
1725 return E_FAIL;
1728 STDMETHODIMP CShellExt::HandleMenuMsg2_Wrap(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
1730 PreserveChdir preserveChdir;
1732 LRESULT res;
1733 if (pResult == NULL)
1734 pResult = &res;
1735 *pResult = FALSE;
1737 LoadLangDll();
1738 switch (uMsg)
1740 case WM_MEASUREITEM:
1742 MEASUREITEMSTRUCT* lpmis = (MEASUREITEMSTRUCT*)lParam;
1743 if (lpmis==NULL)
1744 break;
1745 lpmis->itemWidth = 16;
1746 lpmis->itemHeight = 16;
1747 *pResult = TRUE;
1749 break;
1750 case WM_DRAWITEM:
1752 LPCTSTR resource;
1753 DRAWITEMSTRUCT* lpdis = (DRAWITEMSTRUCT*)lParam;
1754 if ((lpdis==NULL)||(lpdis->CtlType != ODT_MENU))
1755 return S_OK; //not for a menu
1756 resource = GetMenuTextFromResource((int)myIDMap[lpdis->itemID]);
1757 if (resource == NULL)
1758 return S_OK;
1759 HICON hIcon = (HICON)LoadImage(g_hResInst, resource, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
1760 if (hIcon == NULL)
1761 return S_OK;
1762 DrawIconEx(lpdis->hDC,
1763 lpdis->rcItem.left,
1764 lpdis->rcItem.top + (lpdis->rcItem.bottom - lpdis->rcItem.top - 16) / 2,
1765 hIcon, 16, 16,
1766 0, NULL, DI_NORMAL);
1767 DestroyIcon(hIcon);
1768 *pResult = TRUE;
1770 break;
1771 case WM_MENUCHAR:
1773 LPCTSTR resource;
1774 TCHAR *szItem;
1775 if (HIWORD(wParam) != MF_POPUP)
1776 return S_OK;
1777 int nChar = LOWORD(wParam);
1778 if (_istascii((wint_t)nChar) && _istupper((wint_t)nChar))
1779 nChar = tolower(nChar);
1780 // we have the char the user pressed, now search that char in all our
1781 // menu items
1782 std::vector<UINT_PTR> accmenus;
1783 for (std::map<UINT_PTR, UINT_PTR>::iterator It = mySubMenuMap.begin(); It != mySubMenuMap.end(); ++It)
1785 resource = GetMenuTextFromResource((int)mySubMenuMap[It->first]);
1786 if (resource == NULL)
1787 continue;
1788 szItem = stringtablebuffer;
1789 TCHAR * amp = _tcschr(szItem, '&');
1790 if (amp == NULL)
1791 continue;
1792 amp++;
1793 int ampChar = LOWORD(*amp);
1794 if (_istascii((wint_t)ampChar) && _istupper((wint_t)ampChar))
1795 ampChar = tolower(ampChar);
1796 if (ampChar == nChar)
1798 // yep, we found a menu which has the pressed key
1799 // as an accelerator. Add that menu to the list to
1800 // process later.
1801 accmenus.push_back(It->first);
1804 if (accmenus.empty())
1806 // no menu with that accelerator key.
1807 *pResult = MAKELONG(0, MNC_IGNORE);
1808 return S_OK;
1810 if (accmenus.size() == 1)
1812 // Only one menu with that accelerator key. We're lucky!
1813 // So just execute that menu entry.
1814 *pResult = MAKELONG(accmenus[0], MNC_EXECUTE);
1815 return S_OK;
1817 if (accmenus.size() > 1)
1819 // we have more than one menu item with this accelerator key!
1820 MENUITEMINFO mif;
1821 mif.cbSize = sizeof(MENUITEMINFO);
1822 mif.fMask = MIIM_STATE;
1823 for (std::vector<UINT_PTR>::iterator it = accmenus.begin(); it != accmenus.end(); ++it)
1825 GetMenuItemInfo((HMENU)lParam, (UINT)*it, TRUE, &mif);
1826 if (mif.fState == MFS_HILITE)
1828 // this is the selected item, so select the next one
1829 ++it;
1830 if (it == accmenus.end())
1831 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
1832 else
1833 *pResult = MAKELONG(*it, MNC_SELECT);
1834 return S_OK;
1837 *pResult = MAKELONG(accmenus[0], MNC_SELECT);
1840 break;
1841 default:
1842 return S_OK;
1845 return S_OK;
1848 LPCTSTR CShellExt::GetMenuTextFromResource(int id)
1850 TCHAR textbuf[255];
1851 LPCTSTR resource = NULL;
1852 unsigned __int64 layout = g_ShellCache.GetMenuLayout();
1853 space = 6;
1855 int menuIndex = 0;
1856 while (menuInfo[menuIndex].command != ShellMenuLastEntry)
1858 if (menuInfo[menuIndex].command == id)
1860 MAKESTRING(menuInfo[menuIndex].menuTextID);
1861 resource = MAKEINTRESOURCE(menuInfo[menuIndex].iconID);
1862 switch (id)
1864 case ShellSubMenuMultiple:
1865 case ShellSubMenuLink:
1866 case ShellSubMenuFolder:
1867 case ShellSubMenuFile:
1868 case ShellSubMenu:
1869 space = 0;
1870 break;
1871 default:
1872 space = layout & menuInfo[menuIndex].menuID ? 0 : 6;
1873 if (layout & (menuInfo[menuIndex].menuID))
1875 _tcscpy_s(textbuf, 255, _T("Git "));
1876 _tcscat_s(textbuf, 255, stringtablebuffer);
1877 _tcscpy_s(stringtablebuffer, 255, textbuf);
1879 break;
1881 return resource;
1883 menuIndex++;
1885 return NULL;
1888 bool CShellExt::IsIllegalFolder(std::wstring folder, int * cslidarray)
1890 int i=0;
1891 TCHAR buf[MAX_PATH]; //MAX_PATH ok, since SHGetSpecialFolderPath doesn't return the required buffer length!
1892 LPITEMIDLIST pidl = NULL;
1893 while (cslidarray[i])
1895 ++i;
1896 pidl = NULL;
1897 if (SHGetFolderLocation(NULL, cslidarray[i-1], NULL, 0, &pidl)!=S_OK)
1898 continue;
1899 if (!SHGetPathFromIDList(pidl, buf))
1901 // not a file system path, definitely illegal for our use
1902 CoTaskMemFree(pidl);
1903 continue;
1905 CoTaskMemFree(pidl);
1906 if (_tcslen(buf)==0)
1907 continue;
1908 if (_tcscmp(buf, folder.c_str())==0)
1909 return true;
1911 return false;
1914 bool CShellExt::InsertIgnoreSubmenus(UINT &idCmd, UINT idCmdFirst, HMENU hMenu, HMENU subMenu, UINT &indexMenu, int &indexSubMenu, unsigned __int64 topmenu, bool bShowIcons, UINT /*uFlags*/)
1916 HMENU ignoresubmenu = NULL;
1917 int indexignoresub = 0;
1918 bool bShowIgnoreMenu = false;
1919 TCHAR maskbuf[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
1920 TCHAR ignorepath[MAX_PATH]; // MAX_PATH is ok, since this only holds a filename
1921 if (files_.empty())
1922 return false;
1923 UINT icon = bShowIcons ? IDI_IGNORE : 0;
1925 std::vector<stdstring>::iterator I = files_.begin();
1926 if (_tcsrchr(I->c_str(), '\\'))
1927 _tcscpy_s(ignorepath, MAX_PATH, _tcsrchr(I->c_str(), '\\')+1);
1928 else
1929 _tcscpy_s(ignorepath, MAX_PATH, I->c_str());
1930 if ((itemStates & ITEMIS_IGNORED) && (!ignoredprops.empty()))
1932 // check if the item name is ignored or the mask
1933 size_t p = 0;
1934 while ( (p=ignoredprops.find( ignorepath,p )) != -1 )
1936 if ( (p==0 || ignoredprops[p-1]==TCHAR('\n'))
1937 && (p+_tcslen(ignorepath)==ignoredprops.length() || ignoredprops[p+_tcslen(ignorepath)+1]==TCHAR('\n')) )
1939 break;
1941 p++;
1943 if (p!=-1)
1945 ignoresubmenu = CreateMenu();
1946 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
1947 stdstring verb = stdstring(ignorepath);
1948 myVerbsMap[verb] = idCmd - idCmdFirst;
1949 myVerbsMap[verb] = idCmd;
1950 myVerbsIDMap[idCmd - idCmdFirst] = verb;
1951 myVerbsIDMap[idCmd] = verb;
1952 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnore;
1953 myIDMap[idCmd++] = ShellMenuUnIgnore;
1954 bShowIgnoreMenu = true;
1956 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
1957 if (_tcsrchr(ignorepath, '.'))
1959 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
1960 p = ignoredprops.find(maskbuf);
1961 if ((p!=-1) &&
1962 ((ignoredprops.compare(maskbuf)==0) || (ignoredprops.find('\n', p)==p+_tcslen(maskbuf)+1) || (ignoredprops.rfind('\n', p)==p-1)))
1964 if (ignoresubmenu==NULL)
1965 ignoresubmenu = CreateMenu();
1967 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
1968 stdstring verb = stdstring(maskbuf);
1969 myVerbsMap[verb] = idCmd - idCmdFirst;
1970 myVerbsMap[verb] = idCmd;
1971 myVerbsIDMap[idCmd - idCmdFirst] = verb;
1972 myVerbsIDMap[idCmd] = verb;
1973 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreCaseSensitive;
1974 myIDMap[idCmd++] = ShellMenuUnIgnoreCaseSensitive;
1975 bShowIgnoreMenu = true;
1979 else if ((itemStates & ITEMIS_IGNORED) == 0)
1981 bShowIgnoreMenu = true;
1982 ignoresubmenu = CreateMenu();
1983 if (itemStates & ITEMIS_ONLYONE)
1985 if (itemStates & ITEMIS_INGIT)
1987 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
1988 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
1989 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
1991 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
1992 if (!(itemStates & ITEMIS_FOLDER) && _tcsrchr(ignorepath, '.'))
1994 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
1995 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
1996 stdstring verb = stdstring(maskbuf);
1997 myVerbsMap[verb] = idCmd - idCmdFirst;
1998 myVerbsMap[verb] = idCmd;
1999 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2000 myVerbsIDMap[idCmd] = verb;
2001 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2002 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2005 else
2007 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2008 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2009 myIDMap[idCmd++] = ShellMenuIgnore;
2011 _tcscpy_s(maskbuf, MAX_PATH, _T("*"));
2012 if (!(itemStates & ITEMIS_FOLDER) && _tcsrchr(ignorepath, '.'))
2014 _tcscat_s(maskbuf, MAX_PATH, _tcsrchr(ignorepath, '.'));
2015 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, maskbuf);
2016 stdstring verb = stdstring(maskbuf);
2017 myVerbsMap[verb] = idCmd - idCmdFirst;
2018 myVerbsMap[verb] = idCmd;
2019 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2020 myVerbsIDMap[idCmd] = verb;
2021 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2022 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2026 else
2028 if (itemStates & ITEMIS_INGIT)
2030 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLE);
2031 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2032 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2033 stdstring verb = stdstring(ignorepath);
2034 myVerbsMap[verb] = idCmd - idCmdFirst;
2035 myVerbsMap[verb] = idCmd;
2036 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2037 myVerbsIDMap[idCmd] = verb;
2038 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnore;
2039 myIDMap[idCmd++] = ShellMenuDeleteIgnore;
2041 MAKESTRING(IDS_MENUDELETEIGNOREMULTIPLEMASK);
2042 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2043 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2044 verb = stdstring(ignorepath);
2045 myVerbsMap[verb] = idCmd - idCmdFirst;
2046 myVerbsMap[verb] = idCmd;
2047 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2048 myVerbsIDMap[idCmd] = verb;
2049 myIDMap[idCmd - idCmdFirst] = ShellMenuDeleteIgnoreCaseSensitive;
2050 myIDMap[idCmd++] = ShellMenuDeleteIgnoreCaseSensitive;
2052 else
2054 MAKESTRING(IDS_MENUIGNOREMULTIPLE);
2055 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2056 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2057 stdstring verb = stdstring(ignorepath);
2058 myVerbsMap[verb] = idCmd - idCmdFirst;
2059 myVerbsMap[verb] = idCmd;
2060 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2061 myVerbsIDMap[idCmd] = verb;
2062 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnore;
2063 myIDMap[idCmd++] = ShellMenuIgnore;
2065 MAKESTRING(IDS_MENUIGNOREMULTIPLEMASK);
2066 _stprintf_s(ignorepath, MAX_PATH, stringtablebuffer, files_.size());
2067 InsertMenu(ignoresubmenu, indexignoresub++, MF_BYPOSITION | MF_STRING , idCmd, ignorepath);
2068 verb = stdstring(ignorepath);
2069 myVerbsMap[verb] = idCmd - idCmdFirst;
2070 myVerbsMap[verb] = idCmd;
2071 myVerbsIDMap[idCmd - idCmdFirst] = verb;
2072 myVerbsIDMap[idCmd] = verb;
2073 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreCaseSensitive;
2074 myIDMap[idCmd++] = ShellMenuIgnoreCaseSensitive;
2079 if (bShowIgnoreMenu)
2081 MENUITEMINFO menuiteminfo;
2082 SecureZeroMemory(&menuiteminfo, sizeof(menuiteminfo));
2083 menuiteminfo.cbSize = sizeof(menuiteminfo);
2084 menuiteminfo.fMask = MIIM_FTYPE | MIIM_ID | MIIM_SUBMENU | MIIM_DATA | MIIM_STRING;
2085 if (icon)
2087 menuiteminfo.fMask |= MIIM_BITMAP;
2088 menuiteminfo.hbmpItem = (SysInfo::Instance().IsVistaOrLater()) ? IconToBitmapPARGB32(icon) : HBMMENU_CALLBACK;
2090 menuiteminfo.fType = MFT_STRING;
2091 menuiteminfo.hSubMenu = ignoresubmenu;
2092 menuiteminfo.wID = idCmd;
2093 SecureZeroMemory(stringtablebuffer, sizeof(stringtablebuffer));
2094 if (itemStates & ITEMIS_IGNORED)
2095 GetMenuTextFromResource(ShellMenuUnIgnoreSub);
2096 else if (itemStates & ITEMIS_INGIT)
2097 GetMenuTextFromResource(ShellMenuDeleteIgnoreSub);
2098 else
2099 GetMenuTextFromResource(ShellMenuIgnoreSub);
2100 menuiteminfo.dwTypeData = stringtablebuffer;
2101 menuiteminfo.cch = (UINT)min(_tcslen(menuiteminfo.dwTypeData), UINT_MAX);
2103 InsertMenuItem((topmenu & MENUIGNORE) ? hMenu : subMenu, (topmenu & MENUIGNORE) ? indexMenu++ : indexSubMenu++, TRUE, &menuiteminfo);
2104 if (itemStates & ITEMIS_IGNORED)
2106 myIDMap[idCmd - idCmdFirst] = ShellMenuUnIgnoreSub;
2107 myIDMap[idCmd++] = ShellMenuUnIgnoreSub;
2109 else
2111 myIDMap[idCmd - idCmdFirst] = ShellMenuIgnoreSub;
2112 myIDMap[idCmd++] = ShellMenuIgnoreSub;
2115 return bShowIgnoreMenu;
2118 HBITMAP CShellExt::IconToBitmapPARGB32(UINT uIcon)
2120 std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon);
2121 if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon)
2122 return bitmap_it->second;
2124 HICON hIcon = (HICON)LoadImage(g_hResInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
2125 if (!hIcon)
2126 return NULL;
2128 if (pfnBeginBufferedPaint == NULL || pfnEndBufferedPaint == NULL || pfnGetBufferedPaintBits == NULL)
2129 return NULL;
2131 SIZE sizIcon;
2132 sizIcon.cx = GetSystemMetrics(SM_CXSMICON);
2133 sizIcon.cy = GetSystemMetrics(SM_CYSMICON);
2135 RECT rcIcon;
2136 SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy);
2137 HBITMAP hBmp = NULL;
2139 HDC hdcDest = CreateCompatibleDC(NULL);
2140 if (hdcDest)
2142 if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp)))
2144 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp);
2145 if (hbmpOld)
2147 BLENDFUNCTION bfAlpha = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2148 BP_PAINTPARAMS paintParams = {0};
2149 paintParams.cbSize = sizeof(paintParams);
2150 paintParams.dwFlags = BPPF_ERASE;
2151 paintParams.pBlendFunction = &bfAlpha;
2153 HDC hdcBuffer;
2154 HPAINTBUFFER hPaintBuffer = pfnBeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer);
2155 if (hPaintBuffer)
2157 if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL))
2159 // If icon did not have an alpha channel we need to convert buffer to PARGB
2160 ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon);
2163 // This will write the buffer contents to the destination bitmap
2164 pfnEndBufferedPaint(hPaintBuffer, TRUE);
2167 SelectObject(hdcDest, hbmpOld);
2171 DeleteDC(hdcDest);
2174 DestroyIcon(hIcon);
2176 if(hBmp)
2177 bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp));
2178 return hBmp;
2181 HRESULT CShellExt::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP* phBmp)
2183 *phBmp = NULL;
2185 BITMAPINFO bmi;
2186 SecureZeroMemory(&bmi, sizeof(bmi));
2187 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2188 bmi.bmiHeader.biPlanes = 1;
2189 bmi.bmiHeader.biCompression = BI_RGB;
2191 bmi.bmiHeader.biWidth = psize->cx;
2192 bmi.bmiHeader.biHeight = psize->cy;
2193 bmi.bmiHeader.biBitCount = 32;
2195 HDC hdcUsed = hdc ? hdc : GetDC(NULL);
2196 if (hdcUsed)
2198 *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0);
2199 if (hdc != hdcUsed)
2201 ReleaseDC(NULL, hdcUsed);
2204 return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK;
2207 HRESULT CShellExt::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon)
2209 RGBQUAD *prgbQuad;
2210 int cxRow;
2211 HRESULT hr = pfnGetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow);
2212 if (SUCCEEDED(hr))
2214 ARGB *pargb = reinterpret_cast<ARGB *>(prgbQuad);
2215 if (!HasAlpha(pargb, sizIcon, cxRow))
2217 ICONINFO info;
2218 if (GetIconInfo(hicon, &info))
2220 if (info.hbmMask)
2222 hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow);
2225 DeleteObject(info.hbmColor);
2226 DeleteObject(info.hbmMask);
2231 return hr;
2234 bool CShellExt::HasAlpha(__in ARGB *pargb, SIZE& sizImage, int cxRow)
2236 ULONG cxDelta = cxRow - sizImage.cx;
2237 for (ULONG y = sizImage.cy; y; --y)
2239 for (ULONG x = sizImage.cx; x; --x)
2241 if (*pargb++ & 0xFF000000)
2243 return true;
2247 pargb += cxDelta;
2250 return false;
2253 HRESULT CShellExt::ConvertToPARGB32(HDC hdc, __inout ARGB *pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow)
2255 BITMAPINFO bmi;
2256 SecureZeroMemory(&bmi, sizeof(bmi));
2257 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2258 bmi.bmiHeader.biPlanes = 1;
2259 bmi.bmiHeader.biCompression = BI_RGB;
2261 bmi.bmiHeader.biWidth = sizImage.cx;
2262 bmi.bmiHeader.biHeight = sizImage.cy;
2263 bmi.bmiHeader.biBitCount = 32;
2265 HRESULT hr = E_OUTOFMEMORY;
2266 HANDLE hHeap = GetProcessHeap();
2267 void *pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight);
2268 if (pvBits)
2270 hr = E_UNEXPECTED;
2271 if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight)
2273 ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth;
2274 ARGB *pargbMask = static_cast<ARGB *>(pvBits);
2276 for (ULONG y = bmi.bmiHeader.biHeight; y; --y)
2278 for (ULONG x = bmi.bmiHeader.biWidth; x; --x)
2280 if (*pargbMask++)
2282 // transparent pixel
2283 *pargb++ = 0;
2285 else
2287 // opaque pixel
2288 *pargb++ |= 0xFF000000;
2292 pargb += cxDelta;
2295 hr = S_OK;
2298 HeapFree(hHeap, 0, pvBits);
2301 return hr;
2304 void CShellExt::RunCommand(const tstring& path, const tstring& command, LPCTSTR errorMessage)
2306 if (CCreateProcessHelper::CreateProcessDetached(path.c_str(), const_cast<TCHAR*>(command.c_str())))
2308 // process started - exit
2309 return;
2312 MessageBox(NULL, CFormatMessageWrapper(), errorMessage, MB_OK | MB_ICONINFORMATION);
2315 bool CShellExt::ShouldInsertItem(const MenuInfo& item) const
2317 return ShouldEnableMenu(item.first) || ShouldEnableMenu(item.second) ||
2318 ShouldEnableMenu(item.third) || ShouldEnableMenu(item.fourth);
2321 bool CShellExt::ShouldEnableMenu(const YesNoPair& pair) const
2323 if (pair.yes && pair.no)
2325 if (((pair.yes & itemStates) == pair.yes) && ((pair.no & (~itemStates)) == pair.no))
2326 return true;
2328 else if ((pair.yes) && ((pair.yes & itemStates) == pair.yes))
2329 return true;
2330 else if ((pair.no) && ((pair.no & (~itemStates)) == pair.no))
2331 return true;
2332 return false;