Skip to content

Commit

Permalink
Code Quality: Merged all Win32 helpers into single class (#14947)
Browse files Browse the repository at this point in the history
  • Loading branch information
0x5bfa committed Mar 13, 2024
1 parent 68ef926 commit 7883b19
Show file tree
Hide file tree
Showing 41 changed files with 112 additions and 120 deletions.
2 changes: 1 addition & 1 deletion src/Files.App/Actions/Content/Install/InstallFontAction.cs
Expand Up @@ -34,7 +34,7 @@ public InstallFontAction()
public Task ExecuteAsync()
{
var paths = context.SelectedItems.Select(item => item.ItemPath).ToArray();
return Win32API.InstallFontsAsync(paths, false);
return Win32Helper.InstallFontsAsync(paths, false);
}

public void Context_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
Expand Down
Expand Up @@ -33,7 +33,7 @@ public InstallInfDriverAction()

public async Task ExecuteAsync()
{
await Task.WhenAll(context.SelectedItems.Select(selectedItem => Win32API.InstallInf(selectedItem.ItemPath)));
await Task.WhenAll(context.SelectedItems.Select(selectedItem => Win32Helper.InstallInf(selectedItem.ItemPath)));
}

public void Context_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
Expand Down
Expand Up @@ -31,7 +31,7 @@ public RunWithPowershellAction()

public Task ExecuteAsync()
{
return Win32API.RunPowershellCommandAsync($"{context.ShellPage?.SlimContentPage?.SelectedItem?.ItemPath}", false);
return Win32Helper.RunPowershellCommandAsync($"{context.ShellPage?.SlimContentPage?.SelectedItem?.ItemPath}", false);
}

private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e)
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Actions/FileSystem/FormatDriveAction.cs
Expand Up @@ -33,7 +33,7 @@ public FormatDriveAction()

public Task ExecuteAsync()
{
return Win32API.OpenFormatDriveDialog(context.Folder?.ItemPath ?? string.Empty);
return Win32Helper.OpenFormatDriveDialog(context.Folder?.ItemPath ?? string.Empty);
}

public void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e)
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Actions/Open/OpenInVSCodeAction.cs
Expand Up @@ -32,7 +32,7 @@ public OpenInVSCodeAction()

public Task ExecuteAsync()
{
return Win32API.RunPowershellCommandAsync($"code \'{_context.ShellPage?.FilesystemViewModel.WorkingDirectory}\'", false);
return Win32Helper.RunPowershellCommandAsync($"code \'{_context.ShellPage?.FilesystemViewModel.WorkingDirectory}\'", false);
}

private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e)
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Actions/Open/OpenRepoInVSCodeAction.cs
Expand Up @@ -33,7 +33,7 @@ public OpenRepoInVSCodeAction()

public Task ExecuteAsync()
{
return Win32API.RunPowershellCommandAsync($"code \'{_context.ShellPage!.InstanceViewModel.GitRepositoryPath}\'", false);
return Win32Helper.RunPowershellCommandAsync($"code \'{_context.ShellPage!.InstanceViewModel.GitRepositoryPath}\'", false);
}

private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e)
Expand Down
20 changes: 10 additions & 10 deletions src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs
Expand Up @@ -40,11 +40,11 @@ public static async Task<List<ContextMenuFlyoutItemViewModel>> GetShellContextme
"Windows.ModernShare", "Windows.Share", "setdesktopwallpaper",
"eject", "rename", "explore", "openinfiles", "extract",
"copyaspath", "undelete", "empty", "format", "rotate90", "rotate270",
Win32API.ExtractStringFromDLL("shell32.dll", 34593), // Add to collection
Win32API.ExtractStringFromDLL("shell32.dll", 5384), // Pin to Start
Win32API.ExtractStringFromDLL("shell32.dll", 5385), // Unpin from Start
Win32API.ExtractStringFromDLL("shell32.dll", 5386), // Pin to taskbar
Win32API.ExtractStringFromDLL("shell32.dll", 5387), // Unpin from taskbar
Win32Helper.ExtractStringFromDLL("shell32.dll", 34593), // Add to collection
Win32Helper.ExtractStringFromDLL("shell32.dll", 5384), // Pin to Start
Win32Helper.ExtractStringFromDLL("shell32.dll", 5385), // Unpin from Start
Win32Helper.ExtractStringFromDLL("shell32.dll", 5386), // Pin to taskbar
Win32Helper.ExtractStringFromDLL("shell32.dll", 5387), // Unpin from taskbar
};

bool filterMenuItemsImpl(string menuItem) => !string.IsNullOrEmpty(menuItem)
Expand Down Expand Up @@ -130,7 +130,7 @@ bool filterMenuItemsImpl(string menuItem) => !string.IsNullOrEmpty(menuItem)
}
else if (!string.IsNullOrEmpty(menuFlyoutItem.Label) && menuFlyoutItem.SubItems is not null)
{
if (string.Equals(menuFlyoutItem.Label, Win32API.ExtractStringFromDLL("shell32.dll", 30312)))
if (string.Equals(menuFlyoutItem.Label, Win32Helper.ExtractStringFromDLL("shell32.dll", 30312)))
menuFlyoutItem.CommandString = "sendto";

var menuLayoutSubItem = new ContextMenuFlyoutItemViewModel()
Expand Down Expand Up @@ -181,21 +181,21 @@ async Task InvokeShellMenuItemAsync(ContextMenu contextMenu, object? tag)
switch (verb)
{
case "install" when isFont:
await Win32API.InstallFontsAsync(contextMenu.ItemsPath.ToArray(), false);
await Win32Helper.InstallFontsAsync(contextMenu.ItemsPath.ToArray(), false);
break;

case "installAllUsers" when isFont:
await Win32API.InstallFontsAsync(contextMenu.ItemsPath.ToArray(), true);
await Win32Helper.InstallFontsAsync(contextMenu.ItemsPath.ToArray(), true);
break;

case "mount":
var vhdPath = contextMenu.ItemsPath[0];
await Win32API.MountVhdDisk(vhdPath);
await Win32Helper.MountVhdDisk(vhdPath);
break;

case "format":
var drivePath = contextMenu.ItemsPath[0];
await Win32API.OpenFormatDriveDialog(drivePath);
await Win32Helper.OpenFormatDriveDialog(drivePath);
break;

default:
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Helpers/Interop/NativeWinApiHelper.cs
Expand Up @@ -257,6 +257,6 @@ public static bool IsHasThreadAccessPropertyPresent
}

public static Task<string> GetFileAssociationAsync(string filePath)
=> Win32API.GetFileAssociationAsync(filePath, true);
=> Win32Helper.GetFileAssociationAsync(filePath, true);
}
}
16 changes: 8 additions & 8 deletions src/Files.App/Helpers/Navigation/NavigationHelpers.cs
Expand Up @@ -292,7 +292,7 @@ public static async Task OpenSelectedItemsAsync(IShellPage associatedInstance, b
selectedItems.Count > 1 &&
selectedItems.All(x => x.PrimaryItemAttribute == StorageItemTypes.File && !x.IsExecutable && !x.IsShortcut))
{
opened = await Win32Helpers.InvokeWin32ComponentAsync(string.Join('|', selectedItems.Select(x => x.ItemPath)), associatedInstance);
opened = await Win32Helper.InvokeWin32ComponentAsync(string.Join('|', selectedItems.Select(x => x.ItemPath)), associatedInstance);
}

if (opened)
Expand All @@ -319,7 +319,7 @@ public static async Task OpenItemsWithExecutableAsync(IShellPage associatedInsta
return;

var arguments = string.Join(" ", items.Select(item => $"\"{item.Path}\""));
await Win32Helpers.InvokeWin32ComponentAsync(executablePath, associatedInstance, arguments);
await Win32Helper.InvokeWin32ComponentAsync(executablePath, associatedInstance, arguments);
}

/// <summary>
Expand Down Expand Up @@ -469,7 +469,7 @@ private static async Task<FilesystemResult> OpenDirectory(string path, IShellPag
{
if (string.IsNullOrEmpty(shortcutInfo.TargetPath))
{
await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance);
opened = (FilesystemResult)true;
}
else
Expand Down Expand Up @@ -498,7 +498,7 @@ private static async Task<FilesystemResult> OpenDirectory(string path, IShellPag
if (opened)
await OpenPath(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, path, associatedInstance, selectItems);
else
await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance);
}
return opened;
}
Expand All @@ -513,7 +513,7 @@ private static async Task<FilesystemResult> OpenFile(string path, IShellPage ass
{
if (string.IsNullOrEmpty(shortcutInfo.TargetPath))
{
await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args);
}
else
{
Expand All @@ -524,13 +524,13 @@ private static async Task<FilesystemResult> OpenFile(string path, IShellPage ass
if (childFile?.Item is SystemStorageFile)
App.RecentItemsManager.AddToRecentItems(childFile.Path);
}
await Win32Helpers.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory);
await Win32Helper.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory);
}
opened = (FilesystemResult)true;
}
else if (isHiddenItem)
{
await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args);
}
else
{
Expand Down Expand Up @@ -630,7 +630,7 @@ private static async Task<FilesystemResult> OpenFile(string path, IShellPage ass
}
if (!launchSuccess)
await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args);
}
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/Files.App/Helpers/UI/UIHelpers.cs
Expand Up @@ -163,7 +163,7 @@ public static IconFileInfo GetSidebarIconResourceInfo(int index)
private static IEnumerable<IconFileInfo> LoadSidebarIconResources()
{
string imageres = Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll");
var imageResList = Win32API.ExtractSelectedIconsFromDLL(imageres, new List<int>() {
var imageResList = Win32Helper.ExtractSelectedIconsFromDLL(imageres, new List<int>() {
Constants.ImageRes.RecycleBin,
Constants.ImageRes.NetworkDrives,
Constants.ImageRes.Libraries,
Expand All @@ -179,7 +179,7 @@ private static IEnumerable<IconFileInfo> LoadSidebarIconResources()
private static IconFileInfo LoadShieldIconResource()
{
string imageres = Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll");
var imageResList = Win32API.ExtractSelectedIconsFromDLL(imageres, new List<int>() {
var imageResList = Win32Helper.ExtractSelectedIconsFromDLL(imageres, new List<int>() {
Constants.ImageRes.ShieldIcon
}, 16);

Expand Down
@@ -1,16 +1,12 @@
// Copyright (c) 2024 Files Community
// Licensed under the MIT License. See the LICENSE.

using Files.App.Utils.Shell;
using Files.Shared.Extensions;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Files.App.Helpers
{
public static class Win32Helpers
/// <summary>
/// Provides static helper for Win32.
/// </summary>
public static partial class Win32Helper
{
public static async Task<bool> InvokeWin32ComponentAsync(string applicationPath, IShellPage associatedInstance, string arguments = null, bool runAsAdmin = false, string workingDirectory = null)
{
Expand Down Expand Up @@ -42,4 +38,4 @@ public static async Task<bool> InvokeWin32ComponentsAsync(IEnumerable<string> ap
}
}
}
}
}
Expand Up @@ -6,23 +6,16 @@
using Vanara.PInvoke;
using Vanara.Windows.Shell;

namespace Files.App.Utils.Shell
namespace Files.App.Helpers
{
/// <summary>
/// Provides a utility to manage shell folders.
/// Provides static helper for Win32.
/// </summary>
public class Win32Shell
public static partial class Win32Helper
{
private readonly static ShellFolder _controlPanel;
private readonly static ShellFolder _controlPanel = new(Shell32.KNOWNFOLDERID.FOLDERID_ControlPanelFolder);

private readonly static ShellFolder _controlPanelCategoryView;

static Win32Shell()
{
_controlPanel = new ShellFolder(Shell32.KNOWNFOLDERID.FOLDERID_ControlPanelFolder);

_controlPanelCategoryView = new ShellFolder("::{26EE0668-A00A-44D7-9371-BEB064C98683}");
}
private readonly static ShellFolder _controlPanelCategoryView = new("::{26EE0668-A00A-44D7-9371-BEB064C98683}");

public static async Task<(ShellFileItem Folder, List<ShellFileItem> Enumerate)> GetShellFolderAsync(string path, string action, int from, int count, params string[] properties)
{
Expand All @@ -31,7 +24,7 @@ public static async Task<(ShellFileItem Folder, List<ShellFileItem> Enumerate)>
path = $"shell:{path}";
}

return await Win32API.StartSTATask(() =>
return await Win32Helper.StartSTATask(() =>
{
var flc = new List<ShellFileItem>();
var folder = (ShellFileItem)null;
Expand Down Expand Up @@ -88,10 +81,10 @@ public static async Task<(ShellFileItem Folder, List<ShellFileItem> Enumerate)>

public static (bool HasRecycleBin, long NumItems, long BinSize) QueryRecycleBin(string drive = "")
{
Win32API.SHQUERYRBINFO queryBinInfo = new Win32API.SHQUERYRBINFO();
Win32Helper.SHQUERYRBINFO queryBinInfo = new Win32Helper.SHQUERYRBINFO();
queryBinInfo.cbSize = Marshal.SizeOf(queryBinInfo);

var res = Win32API.SHQueryRecycleBin(drive, ref queryBinInfo);
var res = Win32Helper.SHQueryRecycleBin(drive, ref queryBinInfo);
if (res == HRESULT.S_OK)
{
var numItems = queryBinInfo.i64NumItems;
Expand Down
Expand Up @@ -12,12 +12,12 @@
using Vanara.PInvoke;
using Windows.System;

namespace Files.App.Utils.Shell
namespace Files.App.Helpers
{
/// <summary>
/// Provides static helper for general Win32API.
/// Provides static helper for Win32.
/// </summary>
internal class Win32API
public static partial class Win32Helper
{
public static Task StartSTATask(Func<Task> func)
{
Expand Down
3 changes: 3 additions & 0 deletions src/Files.App/Helpers/Win32/Win32Helper.WindowManagement.cs
Expand Up @@ -6,6 +6,9 @@

namespace Files.App.Helpers
{
/// <summary>
/// Provides static helper for Win32.
/// </summary>
public static partial class Win32Helper
{
/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Program.cs
Expand Up @@ -209,7 +209,7 @@ public static void RedirectActivationTo(AppInstance keyInstance, AppActivationAr

public static void OpenShellCommandInExplorer(string shellCommand, int pid)
{
Win32API.OpenFolderInExistingShellWindow(shellCommand);
Win32Helper.OpenFolderInExistingShellWindow(shellCommand);
}

public static void OpenFileFromTile(string filePath)
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Services/NetworkDrivesService.cs
Expand Up @@ -17,7 +17,7 @@ public bool DisconnectNetworkDrive(ILocatableFolder drive)

public async IAsyncEnumerable<ILocatableFolder> GetDrivesAsync()
{
var networkLocations = await Win32API.StartSTATask(() =>
var networkLocations = await Win32Helper.StartSTATask(() =>
{
var locations = new List<ShellLinkItem>();
using (var nethood = new ShellFolder(Shell32.KNOWNFOLDERID.FOLDERID_NetHood))
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Services/QuickAccessService.cs
Expand Up @@ -12,7 +12,7 @@ internal class QuickAccessService : IQuickAccessService

public async Task<IEnumerable<ShellFileItem>> GetPinnedFoldersAsync()
{
var result = (await Win32Shell.GetShellFolderAsync(guid, "Enumerate", 0, int.MaxValue, "System.Home.IsPinned")).Enumerate
var result = (await Win32Helper.GetShellFolderAsync(guid, "Enumerate", 0, int.MaxValue, "System.Home.IsPinned")).Enumerate
.Where(link => link.IsFolder);
return result;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Files.App/Services/WindowsCompatibilityService.cs
Expand Up @@ -39,13 +39,13 @@ public bool SetCompatibilityOptionsForPath(string filePath, WindowsCompatibility
// Remove old one if new one is valid
if (string.IsNullOrEmpty(stringOptions) || stringOptions == "~")
{
return Win32API.RunPowershellCommand(
return Win32Helper.RunPowershellCommand(
@$"Remove-ItemProperty -Path 'HKCU:\{_registrySubPath}' -Name '{filePath}' | Out-Null",
true);
}

// Set the new one
return Win32API.RunPowershellCommand(
return Win32Helper.RunPowershellCommand(
@$"New-ItemProperty -Path 'HKCU:\{_registrySubPath}' -Name '{filePath}' -Value '{options}' -PropertyType String -Force | Out-Null",
true);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/UserControls/Widgets/DrivesWidget.xaml.cs
Expand Up @@ -238,7 +238,7 @@ private async Task EjectDeviceAsync(WidgetDriveCardItem item)

private void FormatDrive(WidgetDriveCardItem? item)
{
Win32API.OpenFormatDriveDialog(item?.Path ?? string.Empty);
Win32Helper.OpenFormatDriveDialog(item?.Path ?? string.Empty);
}

private void OpenProperties(WidgetDriveCardItem item)
Expand Down

0 comments on commit 7883b19

Please sign in to comment.