forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContextMenu.cs
365 lines (302 loc) · 9.27 KB
/
ContextMenu.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using Files.Shared;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using Vanara.InteropServices;
using Vanara.PInvoke;
using Vanara.Windows.Shell;
namespace Files.App.Shell
{
[SupportedOSPlatform("Windows10.0.10240")]
public class ContextMenu : Win32ContextMenu, IDisposable
{
private Shell32.IContextMenu cMenu;
private User32.SafeHMENU hMenu;
private ThreadWithMessageQueue owningThread;
public List<string> ItemsPath { get; }
private ContextMenu(Shell32.IContextMenu cMenu, User32.SafeHMENU hMenu, IEnumerable<string> itemsPath, ThreadWithMessageQueue owningThread)
{
this.cMenu = cMenu;
this.hMenu = hMenu;
ItemsPath = itemsPath.ToList();
Items = new List<Win32ContextMenuItem>();
this.owningThread = owningThread;
}
public async static Task<bool> InvokeVerb(string verb, params string[] filePaths)
{
using var cMenu = await GetContextMenuForFiles(filePaths, Shell32.CMF.CMF_DEFAULTONLY);
return cMenu is not null && await cMenu.InvokeVerb(verb);
}
public async Task<bool> InvokeVerb(string? verb)
{
if (string.IsNullOrEmpty(verb))
return false;
try
{
var currentWindows = Win32API.GetDesktopWindows();
var pici = new Shell32.CMINVOKECOMMANDINFOEX
{
lpVerb = new SafeResourceId(verb, CharSet.Ansi),
nShow = ShowWindowCommand.SW_SHOWNORMAL,
};
pici.cbSize = (uint)Marshal.SizeOf(pici);
await owningThread.PostMethod(() => cMenu.InvokeCommand(pici));
Win32API.BringToForeground(currentWindows);
return true;
}
catch (Exception ex) when (ex is COMException or UnauthorizedAccessException)
{
Debug.WriteLine(ex);
}
return false;
}
public async Task InvokeItem(int itemID)
{
if (itemID < 0)
return;
try
{
var currentWindows = Win32API.GetDesktopWindows();
var pici = new Shell32.CMINVOKECOMMANDINFOEX
{
lpVerb = Macros.MAKEINTRESOURCE(itemID),
nShow = ShowWindowCommand.SW_SHOWNORMAL,
};
pici.cbSize = (uint)Marshal.SizeOf(pici);
await owningThread.PostMethod(() => cMenu.InvokeCommand(pici));
Win32API.BringToForeground(currentWindows);
}
catch (Exception ex) when (ex is COMException or UnauthorizedAccessException)
{
Debug.WriteLine(ex);
}
}
#region FactoryMethods
public async static Task<ContextMenu?> GetContextMenuForFiles(string[] filePathList, Shell32.CMF flags, Func<string, bool>? itemFilter = null)
{
var owningThread = new ThreadWithMessageQueue();
return await owningThread.PostMethod<ContextMenu>(() =>
{
var shellItems = new List<ShellItem>();
try
{
foreach (var fp in filePathList.Where(x => !string.IsNullOrEmpty(x)))
shellItems.Add(ShellFolderExtensions.GetShellItemFromPathOrPidl(fp));
return GetContextMenuForFiles(shellItems.ToArray(), flags, owningThread, itemFilter);
}
catch (Exception ex) when (ex is ArgumentException or FileNotFoundException)
{
// Return empty context menu
return null;
}
finally
{
foreach (var si in shellItems)
{
si.Dispose();
}
}
});
}
public async static Task<ContextMenu?> GetContextMenuForFiles(ShellItem[] shellItems, Shell32.CMF flags, Func<string, bool>? itemFilter = null)
{
var owningThread = new ThreadWithMessageQueue();
return await owningThread.PostMethod<ContextMenu>(()
=> GetContextMenuForFiles(shellItems, flags, owningThread, itemFilter));
}
private static ContextMenu? GetContextMenuForFiles(ShellItem[] shellItems, Shell32.CMF flags, ThreadWithMessageQueue owningThread, Func<string, bool>? itemFilter = null)
{
if (!shellItems.Any())
return null;
try
{
// HP: The items are all in the same folder
using var sf = shellItems[0].Parent;
Shell32.IContextMenu menu = sf.GetChildrenUIObjects<Shell32.IContextMenu>(default, shellItems);
var hMenu = User32.CreatePopupMenu();
menu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, flags);
var contextMenu = new ContextMenu(menu, hMenu, shellItems.Select(x => x.ParsingName), owningThread);
EnumMenuItems(menu, hMenu, contextMenu.Items, itemFilter);
return contextMenu;
}
catch (COMException)
{
// Return empty context menu
return null;
}
}
#endregion FactoryMethods
private static void EnumMenuItems(
Shell32.IContextMenu cMenu,
HMENU hMenu,
List<Win32ContextMenuItem> menuItemsResult,
Func<string, bool>? itemFilter = null)
{
var itemCount = User32.GetMenuItemCount(hMenu);
var mii = new User32.MENUITEMINFO()
{
fMask = User32.MenuItemInfoMask.MIIM_BITMAP |
User32.MenuItemInfoMask.MIIM_FTYPE |
User32.MenuItemInfoMask.MIIM_STRING |
User32.MenuItemInfoMask.MIIM_ID |
User32.MenuItemInfoMask.MIIM_SUBMENU,
};
mii.cbSize = (uint)Marshal.SizeOf(mii);
for (uint ii = 0; ii < itemCount; ii++)
{
var menuItem = new ContextMenuItem();
var container = new SafeCoTaskMemString(512);
var cMenu2 = cMenu as Shell32.IContextMenu2;
mii.dwTypeData = (IntPtr)container;
// https://devblogs.microsoft.com/oldnewthing/20040928-00/?p=37723
mii.cch = (uint)container.Capacity - 1;
var retval = User32.GetMenuItemInfo(hMenu, ii, true, ref mii);
if (!retval)
{
container.Dispose();
continue;
}
menuItem.Type = (MenuItemType)mii.fType;
// wID - idCmdFirst
menuItem.ID = (int)(mii.wID - 1);
if (menuItem.Type == MenuItemType.MFT_STRING)
{
Debug.WriteLine("Item {0} ({1}): {2}", ii, mii.wID, mii.dwTypeData);
menuItem.Label = mii.dwTypeData;
menuItem.CommandString = GetCommandString(cMenu, mii.wID - 1);
if (itemFilter is not null && (itemFilter(menuItem.CommandString) || itemFilter(menuItem.Label)))
{
// Skip items implemented in UWP
container.Dispose();
continue;
}
if (mii.hbmpItem != HBITMAP.NULL && !Enum.IsDefined(typeof(HBITMAP_HMENU), ((IntPtr)mii.hbmpItem).ToInt64()))
{
using var bitmap = Win32API.GetBitmapFromHBitmap(mii.hbmpItem);
if (bitmap is not null)
{
byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(bitmap, typeof(byte[]));
menuItem.Icon = bitmapData;
}
}
if (mii.hSubMenu != HMENU.NULL)
{
Debug.WriteLine("Item {0}: has submenu", ii);
var subItems = new List<Win32ContextMenuItem>();
try
{
cMenu2?.HandleMenuMsg((uint)User32.WindowMessage.WM_INITMENUPOPUP, (IntPtr)mii.hSubMenu, new IntPtr(ii));
}
catch (Exception ex) when (ex is COMException or NotImplementedException)
{
// Only for dynamic/owner drawn? (open with, etc)
}
EnumMenuItems(cMenu, mii.hSubMenu, subItems, itemFilter);
menuItem.SubItems = subItems;
Debug.WriteLine("Item {0}: done submenu", ii);
}
}
else
{
Debug.WriteLine("Item {0}: {1}", ii, mii.fType.ToString());
}
container.Dispose();
menuItemsResult.Add(menuItem);
}
}
private static string? GetCommandString(Shell32.IContextMenu cMenu, uint offset, Shell32.GCS flags = Shell32.GCS.GCS_VERBW)
{
// Hackish workaround to avoid an AccessViolationException on some items,
// notably the "Run with graphic processor" menu item of NVidia cards
if (offset > 5000)
return null;
SafeCoTaskMemString? commandString = null;
try
{
commandString = new SafeCoTaskMemString(512);
cMenu.GetCommandString(new IntPtr(offset), flags, IntPtr.Zero, commandString, (uint)commandString.Capacity - 1);
Debug.WriteLine("Verb {0}: {1}", offset, commandString);
return commandString.ToString();
}
catch (Exception ex) when (ex is InvalidCastException or ArgumentException)
{
// TODO: Investigate this...
Debug.WriteLine(ex);
return null;
}
catch (Exception ex) when (ex is COMException or NotImplementedException)
{
// Not every item has an associated verb
return null;
}
finally
{
commandString?.Dispose();
}
}
#region IDisposable Support
// To detect redundant calls
private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: Dispose managed state (managed objects)
if (Items is not null)
{
foreach (var si in Items)
{
(si as IDisposable)?.Dispose();
}
Items = null;
}
}
// TODO: Free unmanaged resources (unmanaged objects) and override a finalizer below
if (hMenu is not null)
{
User32.DestroyMenu(hMenu);
hMenu = null;
}
if (cMenu is not null)
{
Marshal.ReleaseComObject(cMenu);
cMenu = null;
}
owningThread.Dispose();
disposedValue = true;
}
}
~ContextMenu()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable Support
public enum HBITMAP_HMENU : long
{
HBMMENU_CALLBACK = -1,
HBMMENU_MBAR_CLOSE = 5,
HBMMENU_MBAR_CLOSE_D = 6,
HBMMENU_MBAR_MINIMIZE = 3,
HBMMENU_MBAR_MINIMIZE_D = 7,
HBMMENU_MBAR_RESTORE = 2,
HBMMENU_POPUP_CLOSE = 8,
HBMMENU_POPUP_MAXIMIZE = 10,
HBMMENU_POPUP_MINIMIZE = 11,
HBMMENU_POPUP_RESTORE = 9,
HBMMENU_SYSTEM = 1
}
}
}