Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate native Windows context menu directly into the Explorer plugin #2742

Merged
merged 33 commits into from
Jun 18, 2024

Conversation

Yusyuriv
Copy link
Member

@Yusyuriv Yusyuriv commented May 30, 2024

Native context menu has Send to > Email recipient option, so fixes #1192?

What's the PR

  • This PR integrates the native Windows context menu directly into the Explorer plugin.
  • This feature is enabled through the Explorer plugin and can be turned on or off as needed.
  • You can filter out specific context menu items that you don't want to display.
  • The menu is set at a slightly different height.
  • Features that are unavailable or overlap with the plugin are excluded.
  • The existing open context menu and unavailable menu will be maintained.

Why do we need a feature

  • It allows users to access features not currently offered by Flow Launcher through the native context menu.
  • While there is already an option to open the context menu, this new integration improves search functionality and accessibility.

TODO

  • Correctly free all memory in case of exceptions
  • Test on different versions of Windows
    • Windows 11
    • Windows 10
    • Windos 7?
  • Add settings option to disable the native context menu
  • Show a message to user if the selected context menu action failed?
  • Display some icon when a context menu item doesn't have an icon?
  • Combine this with the existing Helper/ShellContextMenu.cs?

Known issues

  • Icons look bad because it's 16x16 icons stretched to 32x32
  • If you launch something via this context menu and then close Flow Launcher, the thing you launched from the context menu also closes. I feel like that shouldn't happen.
  • Pin to Start returns error code 80070005.
  • Share returns error code 80070578.
  • Off-by-one error in Send to submenu
  • There is a very small delay when retrieving the context menu. It's minor and can be addressed later with caching.

There might be other commands that don't work.

Test Cases

  • You must be able to exclude specific menu items using a word filter.
  • There should be no errors with the features provided.

Summary by CodeRabbit

  • New Features

    • Added support for native context menu in the Explorer plugin.
  • Improvements

    • Updated UI margins for better alignment and consistency.
    • Enhanced context menu logic to respect user settings for included and excluded items.
  • Settings

    • Introduced new settings for managing Windows context menu items in the Explorer plugin.

@Yusyuriv Yusyuriv added the enhancement New feature or request label May 30, 2024
@Yusyuriv Yusyuriv self-assigned this May 30, 2024
@taooceros
Copy link
Member

Do you use the win11 context menu or the old one?

@Yusyuriv
Copy link
Member Author

I believe it's the old menu.

@Yusyuriv Yusyuriv marked this pull request as ready for review June 7, 2024 19:24
@Yusyuriv
Copy link
Member Author

Yusyuriv commented Jun 7, 2024

I'll need to take a closer look at the changes to Result tomorrow.

@Yusyuriv Yusyuriv added the Explorer Plugin Issue or Enhancement Link to Explorer Plugin label Jun 8, 2024
@Yusyuriv Yusyuriv marked this pull request as draft June 9, 2024 09:19

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

Copy link

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

❌ Errors Count
❌ ignored-expect-variant 1
⚠️ non-alpha-in-dictionary 13

See ❌ Event descriptions for more information.

If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

@Yusyuriv Yusyuriv marked this pull request as ready for review June 18, 2024 15:26
Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Walkthrough

Walkthrough

In the Flow.Launcher project, updates included margin and padding adjustments in XAML files, incorporation of context menu functionality based on user settings in C# files, and introduction of properties for Windows context menu settings within Explorer plugin settings and view models. Additionally, support for opening a new email with search results as attachments was introduced.

Changes

Files Summary of Changes
Flow.Launcher/ResultListBox.xaml Adjusted margin and padding values; added StretchDirection to Image; modified ListBox.ItemContainerStyle properties.
.../Flow.Launcher.Plugin.Explorer/ContextMenu.cs Introduced usage of Helper for contextual menu logic; adjusted logic based on inclusion/exclusion settings.
.../Helper/ShellContextMenuDisplayHelper.cs Added static class for shell context menu interactions, including execution and retrieval methods.
.../Languages/en.xaml Added support for native context menu options within the Explorer plugin.
.../Settings.cs Added new properties for context menu settings; updated existing property for context menu display.
.../ViewModels/SettingsViewModel.cs Added properties for context menu settings interacting with the settings model.
.../Views/ExplorerSettings.xaml Modified margin values from comma-separated to space-separated within various elements.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FlowLauncher
    participant ContextMenuHelper

    User->>+FlowLauncher: Select Search Result
    alt Show Context Menu
        FlowLauncher->>+ContextMenuHelper: Get Context Menu Items
        ContextMenuHelper-->>-FlowLauncher: Context Menu Items
        FlowLauncher-->>User: Display Context Menu
    end
    opt Add Email Attachment Action
        FlowLauncher->>User: Open Email Application with Attachment
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Introduce new properties for context menu settings (#1192)
Adjust margin values in XAML files (#1192)
Add action to open email with search result as attachment (#1192) The change summary did not explicitly mention this feature

Poem

In code's vast sea, we tweaked and pruned,
With margins aligned, our layout tuned.
Context menus sparked delight,
With settings to tailor the sight.
Launcher's paths now converge so neat,
A joyful hop, a coder's feat. 🌟


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2dd51c8 and f743288.

Files selected for processing (7)
  • Flow.Launcher/ResultListBox.xaml (8 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/ContextMenu.cs (2 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/Helper/ShellContextMenuDisplayHelper.cs (1 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/Languages/en.xaml (1 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/Settings.cs (2 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/ViewModels/SettingsViewModel.cs (1 hunks)
  • Plugins/Flow.Launcher.Plugin.Explorer/Views/ExplorerSettings.xaml (22 hunks)
Additional comments not posted (4)
Plugins/Flow.Launcher.Plugin.Explorer/Settings.cs (1)

31-35: Ensure proper default values for new properties related to the native Windows context menu.

The default values of false and string.Empty for the new properties are sensible, ensuring that the native context menu is disabled by default and there are no pre-included or excluded items, which is a safe and conservative approach.

Flow.Launcher/ResultListBox.xaml (1)

65-65: Review the consistency and necessity of the margin and padding adjustments.

The changes to margins and paddings are consistent with a style that uses space-separated values instead of comma-separated, which aligns with standard XAML practices. The introduction of StretchDirection="DownOnly" for the ImageIcon ensures that icons only scale down to fit the space, preserving their aspect ratio and quality.

Also applies to: 70-70, 100-100, 105-111, 134-134, 150-150, 176-176, 196-196, 225-226

Plugins/Flow.Launcher.Plugin.Explorer/Languages/en.xaml (1)

156-159: Ensure clarity and accuracy in the descriptions for the native context menu settings.

The descriptions provided for the native context menu settings are clear and informative. They guide the user on how to include or exclude items from the context menu, which enhances usability and configuration flexibility.

Plugins/Flow.Launcher.Plugin.Explorer/ContextMenu.cs (1)

257-294: Validate the inclusion and exclusion logic for context menu items.

The logic for including and excluding items from the native Windows context menu is complex and should be thoroughly tested to ensure it behaves as expected. Consider adding unit tests or manually verifying through different scenarios to ensure both inclusion and exclusion conditions are met correctly.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

gitstream-cm bot commented Jun 18, 2024

🥷 Code experts: onesounds

Yusyuriv, onesounds have most 👩‍💻 activity in the files.
onesounds, jjw24 have most 🧠 knowledge in the files.

See details

Flow.Launcher/ResultListBox.xaml

Activity based on git-commit:

Yusyuriv onesounds
JUN
MAY 3 additions & 4 deletions 9 additions & 4 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
onesounds: 66%

Plugins/Flow.Launcher.Plugin.Explorer/ContextMenu.cs

Activity based on git-commit:

Yusyuriv onesounds
JUN 1 additions & 28 deletions
MAY 6 additions & 3 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
jjw24: 62%
onesounds: 4%

Plugins/Flow.Launcher.Plugin.Explorer/Languages/en.xaml

Activity based on git-commit:

Yusyuriv onesounds
JUN
MAY 6 additions & 1 deletions 8 additions & 6 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
jjw24: 29%
onesounds: 14%

Plugins/Flow.Launcher.Plugin.Explorer/Settings.cs

Activity based on git-commit:

Yusyuriv onesounds
JUN
MAY 11 additions & 1 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
jjw24: 9%

Plugins/Flow.Launcher.Plugin.Explorer/ViewModels/SettingsViewModel.cs

Activity based on git-commit:

Yusyuriv onesounds
JUN
MAY 101 additions & 0 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
jjw24: 6%

Plugins/Flow.Launcher.Plugin.Explorer/Views/ExplorerSettings.xaml

Activity based on git-commit:

Yusyuriv onesounds
JUN
MAY 51 additions & 0 deletions 10 additions & 10 deletions
APR
MAR
FEB
JAN

Knowledge based on git-blame:
onesounds: 77%
jjw24: 1%

To learn more about /:\ gitStream - Visit our Docs

Copy link

gitstream-cm bot commented Jun 18, 2024

This PR is 92.90322580645162% new code.

Copy link

gitstream-cm bot commented Jun 18, 2024

Be a legend 🏆 by adding a before and after screenshot of the changes you made, especially if they are around UI/UX.

@prlabeler prlabeler bot added the bug Something isn't working label Jun 18, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range and nitpick comments (1)
Plugins/Flow.Launcher.Plugin.Explorer/Views/ExplorerSettings.xaml (1)

355-405: Ensure consistent UI design and usability for native context menu settings.

The UI elements for managing the native Windows context menu (include and exclude patterns) are well-integrated. However, consider adding tooltips or help icons next to these settings to provide users with more information on how to use these settings effectively.

Comment on lines +107 to +135
public bool ShowWindowsContextMenu
{
get => Settings.ShowInlinedWindowsContextMenu;
set
{
Settings.ShowInlinedWindowsContextMenu = value;
OnPropertyChanged();
}
}

public string WindowsContextMenuIncludedItems
{
get => Settings.WindowsContextMenuIncludedItems;
set
{
Settings.WindowsContextMenuIncludedItems = value;
OnPropertyChanged();
}
}

public string WindowsContextMenuExcludedItems
{
get => Settings.WindowsContextMenuExcludedItems;
set
{
Settings.WindowsContextMenuExcludedItems = value;
OnPropertyChanged();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper naming for properties reflecting their actual functionality.

The properties ShowWindowsContextMenu, WindowsContextMenuIncludedItems, and WindowsContextMenuExcludedItems are misleading. The getter for ShowWindowsContextMenu returns Settings.ShowInlinedWindowsContextMenu, which suggests the property should be named ShowInlinedWindowsContextMenu to avoid confusion and improve code readability.

- public bool ShowWindowsContextMenu
+ public bool ShowInlinedWindowsContextMenu
- public string WindowsContextMenuIncludedItems
+ public string IncludedWindowsContextMenuItems
- public string WindowsContextMenuExcludedItems
+ public string ExcludedWindowsContextMenuItems
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public bool ShowWindowsContextMenu
{
get => Settings.ShowInlinedWindowsContextMenu;
set
{
Settings.ShowInlinedWindowsContextMenu = value;
OnPropertyChanged();
}
}
public string WindowsContextMenuIncludedItems
{
get => Settings.WindowsContextMenuIncludedItems;
set
{
Settings.WindowsContextMenuIncludedItems = value;
OnPropertyChanged();
}
}
public string WindowsContextMenuExcludedItems
{
get => Settings.WindowsContextMenuExcludedItems;
set
{
Settings.WindowsContextMenuExcludedItems = value;
OnPropertyChanged();
}
}
public bool ShowInlinedWindowsContextMenu
{
get => Settings.ShowInlinedWindowsContextMenu;
set
{
Settings.ShowInlinedWindowsContextMenu = value;
OnPropertyChanged();
}
}
public string IncludedWindowsContextMenuItems
{
get => Settings.WindowsContextMenuIncludedItems;
set
{
Settings.WindowsContextMenuIncludedItems = value;
OnPropertyChanged();
}
}
public string ExcludedWindowsContextMenuItems
{
get => Settings.WindowsContextMenuExcludedItems;
set
{
Settings.WindowsContextMenuExcludedItems = value;
OnPropertyChanged();
}
}

Comment on lines +15 to +402
Marshal.ReleaseComObject(shellFolder);

if (pShellFolder != IntPtr.Zero)
Marshal.Release(pShellFolder);

if (originalPidl != IntPtr.Zero)
malloc?.Free(originalPidl);

if (malloc != null)
Marshal.ReleaseComObject(malloc);
}
}


private static void ProcessMenuWithIcons(IntPtr hMenu, IContextMenu contextMenu, List<ContextMenuItem> menuItems, string prefix = "")
{
uint menuCount = GetMenuItemCount(hMenu);

for (uint i = 0; i < menuCount; i++)
{
var mii = new MENUITEMINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(MENUITEMINFO)),
fMask = (uint)(MenuItemInformationMask.Bitmap | MenuItemInformationMask.Ftype |
MenuItemInformationMask.Submenu | MenuItemInformationMask.Id)
};

GetMenuItemInfo(hMenu, i, true, ref mii);
var menuText = new StringBuilder(256);
uint result = GetMenuString(hMenu, mii.wID, menuText, menuText.Capacity, 0);

if (result == 0 || string.IsNullOrWhiteSpace(menuText.ToString()))
{
continue;
}

menuText.Replace("&", "");

IntPtr hSubMenu = GetSubMenu(hMenu, (int)i);
if (hSubMenu != IntPtr.Zero)
{
ProcessMenuWithIcons(hSubMenu, contextMenu, menuItems, prefix + menuText + " > ");
}
else if (!string.IsNullOrWhiteSpace(menuText.ToString()))
{
var commandBuilder = new StringBuilder(256);
contextMenu.GetCommandString(
mii.wID - ContextMenuStartId,
(uint)GetCommandStringFlags.Verb,
IntPtr.Zero,
commandBuilder,
commandBuilder.Capacity
);
if (IgnoredContextMenuCommands.Contains(commandBuilder.ToString(), StringComparer.OrdinalIgnoreCase))
{
continue;
}

ImageSource icon = null;
if (mii.hbmpItem != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpItem);
}
else if (mii.hbmpChecked != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpChecked);
}

menuItems.Add(new ContextMenuItem(prefix + menuText, icon, mii.wID));
}
}
}

private static BitmapSource GetBitmapSourceFromHBitmap(IntPtr hBitmap)
{
try
{
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(16, 16)
);

if (!DeleteObject(hBitmap))
{
throw new Exception("Failed to delete HBitmap.");
}

return bitmapSource;
}
catch (COMException)
{
// ignore
}

return null;
}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper error handling and resource management in native Windows API interactions.

The implementation of native Windows API interactions in ExecuteContextMenuItem and GetContextMenuWithIcons methods is thorough, but consider enhancing error handling by logging errors or providing more detailed user feedback on failures. Additionally, ensure all resources (like handles and pointers) are correctly managed to avoid memory leaks.

- if (hr != 0) throw new Exception("SHParseDisplayName failed");
+ if (hr != 0) 
+ {
+     Logger.LogError($"SHParseDisplayName failed with HRESULT: {hr}");
+     throw new Exception($"SHParseDisplayName failed with HRESULT: {hr}");
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static class ShellContextMenuDisplayHelper
{
#region DllImport
[DllImport("shell32.dll")]
private static extern Int32 SHGetMalloc(out IntPtr hObject);
[DllImport("shell32.dll")]
private static extern Int32 SHParseDisplayName(
[MarshalAs(UnmanagedType.LPWStr)] string pszName,
IntPtr pbc,
out IntPtr ppidl,
UInt32 sfgaoIn,
out UInt32 psfgaoOut
);
[DllImport("shell32.dll")]
private static extern Int32 SHBindToParent(
IntPtr pidl,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid,
out IntPtr ppv,
ref IntPtr ppidlLast
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreatePopupMenu();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool DestroyMenu(IntPtr hMenu);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint GetMenuItemCount(IntPtr hMenu);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint GetMenuString(
IntPtr hMenu, uint uIDItem, StringBuilder lpString, int nMaxCount, uint uFlag
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetSubMenu(IntPtr hMenu, int nPos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMenuItemInfo(IntPtr hMenu, uint uItem, bool fByPosition, ref MENUITEMINFO lpmii);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
#endregion
#region Constants
private const uint ContextMenuStartId = 0x0001;
private const uint ContextMenuEndId = 0x7FFF;
private static readonly string[] IgnoredContextMenuCommands =
{
// We haven't managed to make these work, so we don't display them in the context menu.
"Share",
"Windows.ModernShare",
"PinToStartScreen",
"CopyAsPath",
// Hide functionality provided by the Explorer plugin itself
"Copy",
"Delete"
};
#endregion
#region Enums
[Flags]
enum ContextMenuFlags : uint
{
Normal = 0x00000000,
DefaultOnly = 0x00000001,
VerbsOnly = 0x00000002,
Explore = 0x00000004,
NoVerbs = 0x00000008,
CanRename = 0x00000010,
NoDefault = 0x00000020,
IncludeStatic = 0x00000040,
ItemMenu = 0x00000080,
ExtendedVerbs = 0x00000100,
DisabledVerbs = 0x00000200,
AsyncVerbState = 0x00000400,
OptimizeForInvoke = 0x00000800,
SyncCascadeMenu = 0x00001000,
DoNotPickDefault = 0x00002000,
Reserved = 0xffff0000
}
[Flags]
enum ContextMenuInvokeCommandFlags : uint
{
Icon = 0x00000010,
Hotkey = 0x00000020,
FlagNoUi = 0x00000400,
Unicode = 0x00004000,
NoConsole = 0x00008000,
AsyncOk = 0x00100000,
NoZoneChecks = 0x00800000,
ShiftDown = 0x10000000,
ControlDown = 0x40000000,
FlagLogUsage = 0x04000000,
PointInvoke = 0x20000000
}
[Flags]
enum MenuItemInformationMask : uint
{
Bitmap = 0x00000080,
Checkmarks = 0x00000008,
Data = 0x00000020,
Ftype = 0x00000100,
Id = 0x00000002,
State = 0x00000001,
String = 0x00000040,
Submenu = 0x00000004,
Type = 0x00000010
}
enum MenuItemFtype : uint
{
Bitmap = 0x00000004,
MenuBarBreak = 0x00000020,
MenuBreak = 0x00000040,
OwnerDraw = 0x00000100,
RadioCheck = 0x00000200,
RightJustify = 0x00004000,
RightOrder = 0x00002000,
Separator = 0x00000800,
String = 0x00000000,
}
enum GetCommandStringFlags : uint
{
VerbA = 0x00000000,
HelpTextA = 0x00000001,
ValidateA = 0x00000002,
Unicode = VerbW,
Verb = VerbW,
VerbW = 0x00000004,
HelpText = HelpTextW,
HelpTextW = 0x00000005,
Validate = ValidateW,
ValidateW = 0x00000006,
VerbIconW = 0x00000014
}
#endregion
private static IMalloc GetMalloc()
{
SHGetMalloc(out var pMalloc);
return (IMalloc)Marshal.GetTypedObjectForIUnknown(pMalloc, typeof(IMalloc));
}
public static void ExecuteContextMenuItem(string fileName, uint menuItemId)
{
IMalloc malloc = null;
IntPtr originalPidl = IntPtr.Zero;
IntPtr pShellFolder = IntPtr.Zero;
IntPtr pContextMenu = IntPtr.Zero;
IntPtr hMenu = IntPtr.Zero;
IContextMenu contextMenu = null;
IShellFolder shellFolder = null;
try
{
malloc = GetMalloc();
var hr = SHParseDisplayName(fileName, IntPtr.Zero, out var pidl, 0, out _);
if (hr != 0) throw new Exception("SHParseDisplayName failed");
originalPidl = pidl;
var guid = typeof(IShellFolder).GUID;
hr = SHBindToParent(pidl, guid, out pShellFolder, ref pidl);
if (hr != 0) throw new Exception("SHBindToParent failed");
shellFolder = (IShellFolder)Marshal.GetTypedObjectForIUnknown(pShellFolder, typeof(IShellFolder));
hr = shellFolder.GetUIObjectOf(
IntPtr.Zero, 1, new[] { pidl }, typeof(IContextMenu).GUID, IntPtr.Zero, out pContextMenu
);
if (hr != 0) throw new Exception("GetUIObjectOf failed");
contextMenu = (IContextMenu)Marshal.GetTypedObjectForIUnknown(pContextMenu, typeof(IContextMenu));
hMenu = CreatePopupMenu();
contextMenu.QueryContextMenu(hMenu, 0, ContextMenuStartId, ContextMenuEndId, (uint)ContextMenuFlags.Explore);
var directory = Path.GetDirectoryName(fileName);
var invokeCommandInfo = new CMINVOKECOMMANDINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(CMINVOKECOMMANDINFO)),
fMask = (uint)ContextMenuInvokeCommandFlags.Unicode,
hwnd = IntPtr.Zero,
lpVerb = (IntPtr)(menuItemId - ContextMenuStartId),
lpParameters = null,
lpDirectory = null,
nShow = 1,
hIcon = IntPtr.Zero,
};
hr = contextMenu.InvokeCommand(ref invokeCommandInfo);
if (hr != 0)
{
throw new Exception($"InvokeCommand failed with code {hr:X}");
}
}
finally
{
if (hMenu != IntPtr.Zero)
DestroyMenu(hMenu);
if (contextMenu != null)
Marshal.ReleaseComObject(contextMenu);
if (pContextMenu != IntPtr.Zero)
Marshal.Release(pContextMenu);
if (shellFolder != null)
Marshal.ReleaseComObject(shellFolder);
if (pShellFolder != IntPtr.Zero)
Marshal.Release(pShellFolder);
if (originalPidl != IntPtr.Zero)
malloc?.Free(originalPidl);
if (malloc != null)
Marshal.ReleaseComObject(malloc);
}
}
public static List<ContextMenuItem> GetContextMenuWithIcons(string filePath)
{
IMalloc malloc = null;
IntPtr originalPidl = IntPtr.Zero;
IntPtr pShellFolder = IntPtr.Zero;
IntPtr pContextMenu = IntPtr.Zero;
IntPtr hMenu = IntPtr.Zero;
IShellFolder shellFolder = null;
IContextMenu contextMenu = null;
try
{
malloc = GetMalloc();
var hr = SHParseDisplayName(filePath, IntPtr.Zero, out var pidl, 0, out _);
if (hr != 0) throw new Exception("SHParseDisplayName failed");
originalPidl = pidl;
var guid = typeof(IShellFolder).GUID;
hr = SHBindToParent(pidl, guid, out pShellFolder, ref pidl);
if (hr != 0) throw new Exception("SHBindToParent failed");
shellFolder = (IShellFolder)Marshal.GetTypedObjectForIUnknown(pShellFolder, typeof(IShellFolder));
hr = shellFolder.GetUIObjectOf(
IntPtr.Zero, 1, new[] { pidl }, typeof(IContextMenu).GUID, IntPtr.Zero, out pContextMenu
);
if (hr != 0) throw new Exception("GetUIObjectOf failed");
contextMenu = (IContextMenu)Marshal.GetTypedObjectForIUnknown(pContextMenu, typeof(IContextMenu));
// Without waiting, some items, such as "Send to > Documents", don't always appear, which shifts item ids
// even though it shouldn't. Please replace this if you find a better way to fix this bug.
Thread.Sleep(200);
hMenu = CreatePopupMenu();
contextMenu.QueryContextMenu(hMenu, 0, ContextMenuStartId, ContextMenuEndId, (uint)ContextMenuFlags.Explore);
var menuItems = new List<ContextMenuItem>();
ProcessMenuWithIcons(hMenu, contextMenu, menuItems);
return menuItems;
}
finally
{
if (hMenu != IntPtr.Zero)
DestroyMenu(hMenu);
if (contextMenu != null)
Marshal.ReleaseComObject(contextMenu);
if (pContextMenu != IntPtr.Zero)
Marshal.Release(pContextMenu);
if (shellFolder != null)
Marshal.ReleaseComObject(shellFolder);
if (pShellFolder != IntPtr.Zero)
Marshal.Release(pShellFolder);
if (originalPidl != IntPtr.Zero)
malloc?.Free(originalPidl);
if (malloc != null)
Marshal.ReleaseComObject(malloc);
}
}
private static void ProcessMenuWithIcons(IntPtr hMenu, IContextMenu contextMenu, List<ContextMenuItem> menuItems, string prefix = "")
{
uint menuCount = GetMenuItemCount(hMenu);
for (uint i = 0; i < menuCount; i++)
{
var mii = new MENUITEMINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(MENUITEMINFO)),
fMask = (uint)(MenuItemInformationMask.Bitmap | MenuItemInformationMask.Ftype |
MenuItemInformationMask.Submenu | MenuItemInformationMask.Id)
};
GetMenuItemInfo(hMenu, i, true, ref mii);
var menuText = new StringBuilder(256);
uint result = GetMenuString(hMenu, mii.wID, menuText, menuText.Capacity, 0);
if (result == 0 || string.IsNullOrWhiteSpace(menuText.ToString()))
{
continue;
}
menuText.Replace("&", "");
IntPtr hSubMenu = GetSubMenu(hMenu, (int)i);
if (hSubMenu != IntPtr.Zero)
{
ProcessMenuWithIcons(hSubMenu, contextMenu, menuItems, prefix + menuText + " > ");
}
else if (!string.IsNullOrWhiteSpace(menuText.ToString()))
{
var commandBuilder = new StringBuilder(256);
contextMenu.GetCommandString(
mii.wID - ContextMenuStartId,
(uint)GetCommandStringFlags.Verb,
IntPtr.Zero,
commandBuilder,
commandBuilder.Capacity
);
if (IgnoredContextMenuCommands.Contains(commandBuilder.ToString(), StringComparer.OrdinalIgnoreCase))
{
continue;
}
ImageSource icon = null;
if (mii.hbmpItem != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpItem);
}
else if (mii.hbmpChecked != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpChecked);
}
menuItems.Add(new ContextMenuItem(prefix + menuText, icon, mii.wID));
}
}
}
private static BitmapSource GetBitmapSourceFromHBitmap(IntPtr hBitmap)
{
try
{
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(16, 16)
);
if (!DeleteObject(hBitmap))
{
throw new Exception("Failed to delete HBitmap.");
}
return bitmapSource;
}
catch (COMException)
{
// ignore
}
return null;
}
}
public static class ShellContextMenuDisplayHelper
{
#region DllImport
[DllImport("shell32.dll")]
private static extern Int32 SHGetMalloc(out IntPtr hObject);
[DllImport("shell32.dll")]
private static extern Int32 SHParseDisplayName(
[MarshalAs(UnmanagedType.LPWStr)] string pszName,
IntPtr pbc,
out IntPtr ppidl,
UInt32 sfgaoIn,
out UInt32 psfgaoOut
);
[DllImport("shell32.dll")]
private static extern Int32 SHBindToParent(
IntPtr pidl,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid,
out IntPtr ppv,
ref IntPtr ppidlLast
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreatePopupMenu();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool DestroyMenu(IntPtr hMenu);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint GetMenuItemCount(IntPtr hMenu);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint GetMenuString(
IntPtr hMenu, uint uIDItem, StringBuilder lpString, int nMaxCount, uint uFlag
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetSubMenu(IntPtr hMenu, int nPos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMenuItemInfo(IntPtr hMenu, uint uItem, bool fByPosition, ref MENUITEMINFO lpmii);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
#endregion
#region Constants
private const uint ContextMenuStartId = 0x0001;
private const uint ContextMenuEndId = 0x7FFF;
private static readonly string[] IgnoredContextMenuCommands =
{
// We haven't managed to make these work, so we don't display them in the context menu.
"Share",
"Windows.ModernShare",
"PinToStartScreen",
"CopyAsPath",
// Hide functionality provided by the Explorer plugin itself
"Copy",
"Delete"
};
#endregion
#region Enums
[Flags]
enum ContextMenuFlags : uint
{
Normal = 0x00000000,
DefaultOnly = 0x00000001,
VerbsOnly = 0x00000002,
Explore = 0x00000004,
NoVerbs = 0x00000008,
CanRename = 0x00000010,
NoDefault = 0x00000020,
IncludeStatic = 0x00000040,
ItemMenu = 0x00000080,
ExtendedVerbs = 0x00000100,
DisabledVerbs = 0x00000200,
AsyncVerbState = 0x00000400,
OptimizeForInvoke = 0x00000800,
SyncCascadeMenu = 0x00001000,
DoNotPickDefault = 0x00002000,
Reserved = 0xffff0000
}
[Flags]
enum ContextMenuInvokeCommandFlags : uint
{
Icon = 0x00000010,
Hotkey = 0x00000020,
FlagNoUi = 0x00000400,
Unicode = 0x00004000,
NoConsole = 0x00008000,
AsyncOk = 0x00100000,
NoZoneChecks = 0x00800000,
ShiftDown = 0x10000000,
ControlDown = 0x40000000,
FlagLogUsage = 0x04000000,
PointInvoke = 0x20000000
}
[Flags]
enum MenuItemInformationMask : uint
{
Bitmap = 0x00000080,
Checkmarks = 0x00000008,
Data = 0x00000020,
Ftype = 0x00000100,
Id = 0x00000002,
State = 0x00000001,
String = 0x00000040,
Submenu = 0x00000004,
Type = 0x00000010
}
enum MenuItemFtype : uint
{
Bitmap = 0x00000004,
MenuBarBreak = 0x00000020,
MenuBreak = 0x00000040,
OwnerDraw = 0x00000100,
RadioCheck = 0x00000200,
RightJustify = 0x00004000,
RightOrder = 0x00002000,
Separator = 0x00000800,
String = 0x00000000,
}
enum GetCommandStringFlags : uint
{
VerbA = 0x00000000,
HelpTextA = 0x00000001,
ValidateA = 0x00000002,
Unicode = VerbW,
Verb = VerbW,
VerbW = 0x00000004,
HelpText = HelpTextW,
HelpTextW = 0x00000005,
Validate = ValidateW,
ValidateW = 0x00000006,
VerbIconW = 0x00000014
}
#endregion
private static IMalloc GetMalloc()
{
SHGetMalloc(out var pMalloc);
return (IMalloc)Marshal.GetTypedObjectForIUnknown(pMalloc, typeof(IMalloc));
}
public static void ExecuteContextMenuItem(string fileName, uint menuItemId)
{
IMalloc malloc = null;
IntPtr originalPidl = IntPtr.Zero;
IntPtr pShellFolder = IntPtr.Zero;
IntPtr pContextMenu = IntPtr.Zero;
IntPtr hMenu = IntPtr.Zero;
IContextMenu contextMenu = null;
IShellFolder shellFolder = null;
try
{
malloc = GetMalloc();
var hr = SHParseDisplayName(fileName, IntPtr.Zero, out var pidl, 0, out _);
if (hr != 0)
{
Logger.LogError($"SHParseDisplayName failed with HRESULT: {hr}");
throw new Exception($"SHParseDisplayName failed with HRESULT: {hr}");
}
originalPidl = pidl;
var guid = typeof(IShellFolder).GUID;
hr = SHBindToParent(pidl, guid, out pShellFolder, ref pidl);
if (hr != 0) throw new Exception("SHBindToParent failed");
shellFolder = (IShellFolder)Marshal.GetTypedObjectForIUnknown(pShellFolder, typeof(IShellFolder));
hr = shellFolder.GetUIObjectOf(
IntPtr.Zero, 1, new[] { pidl }, typeof(IContextMenu).GUID, IntPtr.Zero, out pContextMenu
);
if (hr != 0) throw new Exception("GetUIObjectOf failed");
contextMenu = (IContextMenu)Marshal.GetTypedObjectForIUnknown(pContextMenu, typeof(IContextMenu));
hMenu = CreatePopupMenu();
contextMenu.QueryContextMenu(hMenu, 0, ContextMenuStartId, ContextMenuEndId, (uint)ContextMenuFlags.Explore);
var directory = Path.GetDirectoryName(fileName);
var invokeCommandInfo = new CMINVOKECOMMANDINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(CMINVOKECOMMANDINFO)),
fMask = (uint)ContextMenuInvokeCommandFlags.Unicode,
hwnd = IntPtr.Zero,
lpVerb = (IntPtr)(menuItemId - ContextMenuStartId),
lpParameters = null,
lpDirectory = null,
nShow = 1,
hIcon = IntPtr.Zero,
};
hr = contextMenu.InvokeCommand(ref invokeCommandInfo);
if (hr != 0)
{
throw new Exception($"InvokeCommand failed with code {hr:X}");
}
}
finally
{
if (hMenu != IntPtr.Zero)
DestroyMenu(hMenu);
if (contextMenu != null)
Marshal.ReleaseComObject(contextMenu);
if (pContextMenu != IntPtr.Zero)
Marshal.Release(pContextMenu);
if (shellFolder != null)
Marshal.ReleaseComObject(shellFolder);
if (pShellFolder != IntPtr.Zero)
Marshal.Release(pShellFolder);
if (originalPidl != IntPtr.Zero)
malloc?.Free(originalPidl);
if (malloc != null)
Marshal.ReleaseComObject(malloc);
}
}
public static List<ContextMenuItem> GetContextMenuWithIcons(string filePath)
{
IMalloc malloc = null;
IntPtr originalPidl = IntPtr.Zero;
IntPtr pShellFolder = IntPtr.Zero;
IntPtr pContextMenu = IntPtr.Zero;
IntPtr hMenu = IntPtr.Zero;
IShellFolder shellFolder = null;
IContextMenu contextMenu = null;
try
{
malloc = GetMalloc();
var hr = SHParseDisplayName(filePath, IntPtr.Zero, out var pidl, 0, out _);
if (hr != 0) throw new Exception("SHParseDisplayName failed");
originalPidl = pidl;
var guid = typeof(IShellFolder).GUID;
hr = SHBindToParent(pidl, guid, out pShellFolder, ref pidl);
if (hr != 0) throw new Exception("SHBindToParent failed");
shellFolder = (IShellFolder)Marshal.GetTypedObjectForIUnknown(pShellFolder, typeof(IShellFolder));
hr = shellFolder.GetUIObjectOf(
IntPtr.Zero, 1, new[] { pidl }, typeof(IContextMenu).GUID, IntPtr.Zero, out pContextMenu
);
if (hr != 0) throw new Exception("GetUIObjectOf failed");
contextMenu = (IContextMenu)Marshal.GetTypedObjectForIUnknown(pContextMenu, typeof(IContextMenu));
// Without waiting, some items, such as "Send to > Documents", don't always appear, which shifts item ids
// even though it shouldn't. Please replace this if you find a better way to fix this bug.
Thread.Sleep(200);
hMenu = CreatePopupMenu();
contextMenu.QueryContextMenu(hMenu, 0, ContextMenuStartId, ContextMenuEndId, (uint)ContextMenuFlags.Explore);
var menuItems = new List<ContextMenuItem>();
ProcessMenuWithIcons(hMenu, contextMenu, menuItems);
return menuItems;
}
finally
{
if (hMenu != IntPtr.Zero)
DestroyMenu(hMenu);
if (contextMenu != null)
Marshal.ReleaseComObject(contextMenu);
if (pContextMenu != IntPtr.Zero)
Marshal.Release(pContextMenu);
if (shellFolder != null)
Marshal.ReleaseComObject(shellFolder);
if (pShellFolder != IntPtr.Zero)
Marshal.Release(pShellFolder);
if (originalPidl != IntPtr.Zero)
malloc?.Free(originalPidl);
if (malloc != null)
Marshal.ReleaseComObject(malloc);
}
}
private static void ProcessMenuWithIcons(IntPtr hMenu, IContextMenu contextMenu, List<ContextMenuItem> menuItems, string prefix = "")
{
uint menuCount = GetMenuItemCount(hMenu);
for (uint i = 0; i < menuCount; i++)
{
var mii = new MENUITEMINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(MENUITEMINFO)),
fMask = (uint)(MenuItemInformationMask.Bitmap | MenuItemInformationMask.Ftype |
MenuItemInformationMask.Submenu | MenuItemInformationMask.Id)
};
GetMenuItemInfo(hMenu, i, true, ref mii);
var menuText = new StringBuilder(256);
uint result = GetMenuString(hMenu, mii.wID, menuText, menuText.Capacity, 0);
if (result == 0 || string.IsNullOrWhiteSpace(menuText.ToString()))
{
continue;
}
menuText.Replace("&", "");
IntPtr hSubMenu = GetSubMenu(hMenu, (int)i);
if (hSubMenu != IntPtr.Zero)
{
ProcessMenuWithIcons(hSubMenu, contextMenu, menuItems, prefix + menuText + " > ");
}
else if (!string.IsNullOrWhiteSpace(menuText.ToString()))
{
var commandBuilder = new StringBuilder(256);
contextMenu.GetCommandString(
mii.wID - ContextMenuStartId,
(uint)GetCommandStringFlags.Verb,
IntPtr.Zero,
commandBuilder,
commandBuilder.Capacity
);
if (IgnoredContextMenuCommands.Contains(commandBuilder.ToString(), StringComparer.OrdinalIgnoreCase))
{
continue;
}
ImageSource icon = null;
if (mii.hbmpItem != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpItem);
}
else if (mii.hbmpChecked != IntPtr.Zero)
{
icon = GetBitmapSourceFromHBitmap(mii.hbmpChecked);
}
menuItems.Add(new ContextMenuItem(prefix + menuText, icon, mii.wID));
}
}
}
private static BitmapSource GetBitmapSourceFromHBitmap(IntPtr hBitmap)
{
try
{
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(16, 16)
);
if (!DeleteObject(hBitmap))
{
throw new Exception("Failed to delete HBitmap.");
}
return bitmapSource;
}
catch (COMException)
{
// ignore
}
return null;
}
}

@onesounds onesounds merged commit 42939ea into dev Jun 18, 2024
13 checks passed
@onesounds onesounds deleted the explorer-plugin-integrated-context-menu branch June 18, 2024 22:55
@jjw24 jjw24 removed bug Something isn't working 30 min review labels Jun 18, 2024
@jjw24 jjw24 added this to the 1.19.0 milestone Jun 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request Explorer Plugin Issue or Enhancement Link to Explorer Plugin
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

[Add action : open a new e-mail with flow search-bar result as attachment]
4 participants