common helper for execute shell process from run plugins (#9538)

This commit is contained in:
Davide Giacometti
2021-02-23 09:53:08 +01:00
committed by GitHub
parent 20a922ce21
commit 571bceb386
17 changed files with 77 additions and 128 deletions

View File

@@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Reflection; using System.Reflection;
using System.Windows; using System.Windows;
@@ -112,16 +111,10 @@ namespace Microsoft.Plugin.Folder
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift, AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ => Action = _ =>
{ {
try if (!Helper.OpenInShell("explorer.exe", $"/select,\"{record.FullPath}\""))
{
Process.Start("explorer.exe", $" /select,\"{record.FullPath}\"");
}
catch (Exception e)
{ {
var message = $"{Properties.Resources.Microsoft_plugin_folder_file_open_failed} {record.FullPath}"; var message = $"{Properties.Resources.Microsoft_plugin_folder_file_open_failed} {record.FullPath}";
Log.Exception(message, e, GetType());
_context.API.ShowMsg(message); _context.API.ShowMsg(message);
return false; return false;
} }

View File

@@ -7,6 +7,7 @@ using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Reflection; using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Wox.Infrastructure;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.Logger; using Wox.Plugin.Logger;
@@ -48,23 +49,12 @@ namespace Microsoft.Plugin.Folder.Sources
return sanitizedPath.Insert(0, "\\"); return sanitizedPath.Insert(0, "\\");
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "We want to keep the process alive and instead inform the user of the error")]
private static bool OpenFileOrFolder(string path, IPublicAPI contextApi) private static bool OpenFileOrFolder(string path, IPublicAPI contextApi)
{ {
try if (!Helper.OpenInShell(path))
{ {
using (var process = new Process()) var message = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", Properties.Resources.wox_plugin_folder_select_folder_OpenFileOrFolder_error_message, path);
{ contextApi.ShowMsg(message);
process.StartInfo.FileName = path;
process.StartInfo.UseShellExecute = true;
process.Start();
}
}
catch (Exception e)
{
string messageBoxTitle = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.wox_plugin_folder_select_folder_OpenFileOrFolder_error_message, path);
Log.Exception($"Failed to open {path}, {e.Message}", e, MethodBase.GetCurrentMethod().DeclaringType);
contextApi.ShowMsg(messageBoxTitle, e.Message);
} }
return true; return true;

View File

@@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -175,15 +174,9 @@ namespace Microsoft.Plugin.Indexer
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift, AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ => Action = _ =>
{ {
try if (!Helper.OpenInShell("explorer.exe", $"/select,\"{record.Path}\""))
{
Process.Start("explorer.exe", $" /select,\"{record.Path}\"");
}
catch (Exception e)
{ {
var message = $"{Properties.Resources.Microsoft_plugin_indexer_folder_open_failed} {record.Path}"; var message = $"{Properties.Resources.Microsoft_plugin_indexer_folder_open_failed} {record.Path}";
Log.Exception(message, e, GetType());
_context.API.ShowMsg(message); _context.API.ShowMsg(message);
return false; return false;
} }

View File

@@ -4,8 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Linq; using System.Linq;
@@ -16,6 +14,7 @@ using Microsoft.Plugin.Indexer.DriveDetection;
using Microsoft.Plugin.Indexer.SearchHelper; using Microsoft.Plugin.Indexer.SearchHelper;
using Microsoft.PowerToys.Settings.UI.Library; using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.Search.Interop; using Microsoft.Search.Interop;
using Wox.Infrastructure;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.Logger; using Wox.Plugin.Logger;
@@ -85,15 +84,7 @@ namespace Microsoft.Plugin.Indexer
IcoPath = WarningIconPath, IcoPath = WarningIconPath,
Action = e => Action = e =>
{ {
try Helper.OpenInShell("ms-settings:cortana-windowssearch");
{
Process.Start(GetWindowsSearchSettingsProcessInfo());
}
catch (Exception ex)
{
Log.Exception($"Unable to launch Windows Search Settings: {ex.Message}", ex, GetType());
}
return true; return true;
}, },
}); });
@@ -129,23 +120,13 @@ namespace Microsoft.Plugin.Indexer
r.ToolTipData = new ToolTipData(toolTipTitle, toolTipText); r.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
r.Action = c => r.Action = c =>
{ {
bool hide; bool hide = true;
try if (!Helper.OpenInShell(path, null, workingDir))
{
Process.Start(new ProcessStartInfo
{
FileName = path,
UseShellExecute = true,
WorkingDirectory = workingDir,
});
hide = true;
}
catch (Win32Exception)
{ {
hide = false;
var name = $"Plugin: {_context.CurrentPluginMetadata.Name}"; var name = $"Plugin: {_context.CurrentPluginMetadata.Name}";
var msg = Properties.Resources.Microsoft_plugin_indexer_file_open_failed; var msg = Properties.Resources.Microsoft_plugin_indexer_file_open_failed;
_context.API.ShowMsg(name, msg, string.Empty); _context.API.ShowMsg(name, msg, string.Empty);
hide = false;
} }
return hide; return hide;
@@ -239,18 +220,6 @@ namespace Microsoft.Plugin.Indexer
throw new NotImplementedException(); throw new NotImplementedException();
} }
// Returns the Process Start Information for the new Windows Search Settings
public static ProcessStartInfo GetWindowsSearchSettingsProcessInfo()
{
var ps = new ProcessStartInfo("ms-settings:cortana-windowssearch")
{
UseShellExecute = true,
Verb = "open",
};
return ps;
}
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (!disposedValue) if (!disposedValue)

View File

@@ -240,7 +240,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
// ShellLinkHelper must be mocked for lnk applications // ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>(); var mockShellLink = new Mock<IShellLinkHelper>();
mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty); mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty);
Win32Program.Helper = mockShellLink.Object; Win32Program.ShellLinkHelper = mockShellLink.Object;
// Act // Act
_fileSystemMocks[0].Raise(m => m.Changed += null, e); _fileSystemMocks[0].Raise(m => m.Changed += null, e);
@@ -310,7 +310,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
// ShellLinkHelper must be mocked for lnk applications // ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>(); var mockShellLink = new Mock<IShellLinkHelper>();
mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty); mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty);
Win32Program.Helper = mockShellLink.Object; Win32Program.ShellLinkHelper = mockShellLink.Object;
string fullPath = directory + "\\" + path; string fullPath = directory + "\\" + path;
Win32Program item = new Win32Program Win32Program item = new Win32Program
@@ -343,7 +343,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
// ShellLinkHelper must be mocked for lnk applications // ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>(); var mockShellLink = new Mock<IShellLinkHelper>();
mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty); mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty);
Win32Program.Helper = mockShellLink.Object; Win32Program.ShellLinkHelper = mockShellLink.Object;
// old item and new item are the actual items when they are in existence // old item and new item are the actual items when they are in existence
Win32Program olditem = new Win32Program Win32Program olditem = new Win32Program

View File

@@ -170,7 +170,7 @@ namespace Microsoft.Plugin.Program.Programs
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift, AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ => Action = _ =>
{ {
Main.StartProcess(Process.Start, new ProcessStartInfo("explorer", Package.Location)); Helper.OpenInShell(Package.Location);
return true; return true;
}, },

View File

@@ -66,7 +66,7 @@ namespace Microsoft.Plugin.Program.Programs
public static IFile FileWrapper { get; set; } = new FileSystem().File; public static IFile FileWrapper { get; set; } = new FileSystem().File;
public static IShellLinkHelper Helper { get; set; } = new ShellLinkHelper(); public static IShellLinkHelper ShellLinkHelper { get; set; } = new ShellLinkHelper();
public static IDirectoryWrapper DirectoryWrapper { get; set; } = new DirectoryWrapper(); public static IDirectoryWrapper DirectoryWrapper { get; set; } = new DirectoryWrapper();
@@ -294,7 +294,7 @@ namespace Microsoft.Plugin.Program.Programs
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift, AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ => Action = _ =>
{ {
Main.StartProcess(Process.Start, new ProcessStartInfo("explorer", ParentDirectory)); Helper.OpenInShell(ParentDirectory);
return true; return true;
}, },
}); });
@@ -473,7 +473,7 @@ namespace Microsoft.Plugin.Program.Programs
const int MAX_PATH = 260; const int MAX_PATH = 260;
StringBuilder buffer = new StringBuilder(MAX_PATH); StringBuilder buffer = new StringBuilder(MAX_PATH);
string target = Helper.RetrieveTargetPath(path); string target = ShellLinkHelper.RetrieveTargetPath(path);
if (!string.IsNullOrEmpty(target)) if (!string.IsNullOrEmpty(target))
{ {
@@ -485,7 +485,7 @@ namespace Microsoft.Plugin.Program.Programs
program.FullPath = Path.GetFullPath(target).ToLower(CultureInfo.CurrentCulture); program.FullPath = Path.GetFullPath(target).ToLower(CultureInfo.CurrentCulture);
program.AppType = GetAppTypeFromPath(target); program.AppType = GetAppTypeFromPath(target);
var description = Helper.Description; var description = ShellLinkHelper.Description;
if (!string.IsNullOrEmpty(description)) if (!string.IsNullOrEmpty(description))
{ {
program.Description = description; program.Description = description;

View File

@@ -4,11 +4,11 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Text; using System.Text;
using ManagedCommon; using ManagedCommon;
using Microsoft.Plugin.Uri.UriHelper; using Microsoft.Plugin.Uri.UriHelper;
using Wox.Infrastructure;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.Logger; using Wox.Plugin.Logger;
@@ -67,10 +67,14 @@ namespace Microsoft.Plugin.Uri
: DefaultIconPath, : DefaultIconPath,
Action = action => Action = action =>
{ {
Process.Start(new ProcessStartInfo(uriResultString) if (!Helper.OpenInShell(uriResultString))
{ {
UseShellExecute = true, var title = $"Plugin: {Properties.Resources.Microsoft_plugin_uri_plugin_name}";
}); var message = $"{Properties.Resources.Microsoft_plugin_uri_open_failed}: {uriResultString}";
Context.API.ShowMsg(title, message);
return false;
}
return true; return true;
}, },
}); });

View File

@@ -60,6 +60,15 @@ namespace Microsoft.Plugin.Uri.Properties {
} }
} }
/// <summary>
/// Looks up a localized string similar to Failed to open URL.
/// </summary>
public static string Microsoft_plugin_uri_open_failed {
get {
return ResourceManager.GetString("Microsoft_plugin_uri_open_failed", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Handles urls. /// Looks up a localized string similar to Handles urls.
/// </summary> /// </summary>

View File

@@ -117,6 +117,9 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="Microsoft_plugin_uri_open_failed" xml:space="preserve">
<value>Failed to open URL</value>
</data>
<data name="Microsoft_plugin_uri_plugin_description" xml:space="preserve"> <data name="Microsoft_plugin_uri_plugin_description" xml:space="preserve">
<value>Handles urls</value> <value>Handles urls</value>
</data> </data>

View File

@@ -5,7 +5,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq; using System.Linq;
using Microsoft.PowerToys.Run.Plugin.Registry.Classes; using Microsoft.PowerToys.Run.Plugin.Registry.Classes;
using Microsoft.PowerToys.Run.Plugin.Registry.Constants; using Microsoft.PowerToys.Run.Plugin.Registry.Constants;
@@ -144,21 +143,8 @@ namespace Microsoft.PowerToys.Run.Plugin.Registry.Helper
// it's impossible to directly open a key via command-line option, so we must override the last remember key // it's impossible to directly open a key via command-line option, so we must override the last remember key
Win32.Registry.SetValue(@"HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", fullKey); Win32.Registry.SetValue(@"HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", fullKey);
var processStartInfo = new ProcessStartInfo // -m => allow multi-instance (hidden start option)
{ Wox.Infrastructure.Helper.OpenInShell("regedit.exe", "-m", null, true);
// -m => allow multi-instance (hidden start option)
Arguments = "-m",
FileName = "regedit.exe",
// Start as administrator
Verb = "runas",
// Start as administrator will not work without this
UseShellExecute = true,
};
Process.Start(processStartInfo);
} }
/// <summary> /// <summary>

View File

@@ -10,6 +10,7 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.ServiceProcess; using System.ServiceProcess;
using Microsoft.PowerToys.Run.Plugin.Service.Properties; using Microsoft.PowerToys.Run.Plugin.Service.Properties;
using Wox.Infrastructure;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.Logger; using Wox.Plugin.Logger;
@@ -90,20 +91,7 @@ namespace Microsoft.PowerToys.Run.Plugin.Service.Helpers
public static void OpenServices() public static void OpenServices()
{ {
try Helper.OpenInShell("services.msc");
{
var info = new ProcessStartInfo
{
FileName = "services.msc",
UseShellExecute = true,
};
Process.Start(info);
}
catch (Win32Exception ex)
{
Log.Error(ex.Message, MethodBase.GetCurrentMethod().DeclaringType);
}
} }
private static string GetResultTitle(ServiceController serviceController) private static string GetResultTitle(ServiceController serviceController)

View File

@@ -71,6 +71,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj" /> <ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj" />
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Windows; using System.Windows;
using System.Windows.Interop; using System.Windows.Interop;
using ManagedCommon; using ManagedCommon;
@@ -70,7 +69,7 @@ namespace Microsoft.PowerToys.Run.Plugin.System
IcoPath = $"Images\\shutdown.{IconTheme}.png", IcoPath = $"Images\\shutdown.{IconTheme}.png",
Action = c => Action = c =>
{ {
Process.Start("shutdown", "/s /t 0"); Helper.OpenInShell("shutdown", "/s /t 0");
return true; return true;
}, },
}, },
@@ -81,7 +80,7 @@ namespace Microsoft.PowerToys.Run.Plugin.System
IcoPath = $"Images\\restart.{IconTheme}.png", IcoPath = $"Images\\restart.{IconTheme}.png",
Action = c => Action = c =>
{ {
Process.Start("shutdown", "/r /t 0"); Helper.OpenInShell("shutdown", "/r /t 0");
return true; return true;
}, },
}, },

View File

@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.IO.Abstractions; using System.IO.Abstractions;
@@ -12,9 +11,7 @@ using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Documents; using System.Windows.Documents;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using PowerLauncher.Helper; using PowerLauncher.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Image; using Wox.Infrastructure.Image;
using Wox.Plugin.Logger; using Wox.Plugin.Logger;
@@ -83,12 +80,8 @@ namespace PowerLauncher
private void RepositoryHyperlink_Click(object sender, RoutedEventArgs e) private void RepositoryHyperlink_Click(object sender, RoutedEventArgs e)
{ {
var ps = new ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()) var uri = (sender as Hyperlink).NavigateUri.ToString();
{ Wox.Infrastructure.Helper.OpenInShell(uri);
UseShellExecute = true,
Verb = "open",
};
Process.Start(ps);
} }
} }
} }

View File

@@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@@ -240,11 +239,6 @@ namespace PowerLauncher.ViewModel
SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult()); SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult());
StartHelpCommand = new RelayCommand(_ =>
{
Process.Start("https://aka.ms/PowerToys/");
});
OpenResultWithKeyboardCommand = new RelayCommand(index => OpenResultWithKeyboardCommand = new RelayCommand(index =>
{ {
OpenResultsEvent(index, false); OpenResultsEvent(index, false);
@@ -459,8 +453,6 @@ namespace PowerLauncher.ViewModel
public ICommand SelectFirstResultCommand { get; set; } public ICommand SelectFirstResultCommand { get; set; }
public ICommand StartHelpCommand { get; set; }
public ICommand LoadContextMenuCommand { get; set; } public ICommand LoadContextMenuCommand { get; set; }
public ICommand LoadHistoryCommand { get; set; } public ICommand LoadHistoryCommand { get; set; }

View File

@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Reflection; using System.Reflection;
@@ -117,5 +118,33 @@ namespace Wox.Infrastructure
return Process.Start(processStartInfo); return Process.Start(processStartInfo);
} }
public static bool OpenInShell(string path, string arguments = null, string workingDir = null, bool runAsAdmin = false)
{
using (var process = new Process())
{
process.StartInfo.FileName = path;
process.StartInfo.WorkingDirectory = string.IsNullOrWhiteSpace(workingDir) ? string.Empty : workingDir;
process.StartInfo.Arguments = string.IsNullOrWhiteSpace(arguments) ? string.Empty : arguments;
if (runAsAdmin)
{
process.StartInfo.Verb = "RunAs";
}
process.StartInfo.UseShellExecute = true;
try
{
process.Start();
return true;
}
catch (Win32Exception ex)
{
Log.Exception($"Unable to open {path}: {ex.Message}", ex, MethodBase.GetCurrentMethod().DeclaringType);
return false;
}
}
}
} }
} }