Skip to content

Commit

Permalink
common helper for execute shell process from run plugins (#9538)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidegiacometti committed Feb 23, 2021
1 parent 20a922c commit 571bceb
Show file tree
Hide file tree
Showing 17 changed files with 77 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions;
using System.Reflection;
using System.Windows;
Expand Down Expand Up @@ -112,16 +111,10 @@ private ContextMenuResult CreateOpenContainingFolderResult(SearchResult record)
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ =>
{
try
{
Process.Start("explorer.exe", $" /select,\"{record.FullPath}\"");
}
catch (Exception e)
if (!Helper.OpenInShell("explorer.exe", $"/select,\"{record.FullPath}\""))
{
var message = $"{Properties.Resources.Microsoft_plugin_folder_file_open_failed} {record.FullPath}";
Log.Exception(message, e, GetType());
_context.API.ShowMsg(message);
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using Wox.Infrastructure;
using Wox.Plugin;
using Wox.Plugin.Logger;

Expand Down Expand Up @@ -48,23 +49,12 @@ private static string SanitizedPath(string search)
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)
{
try
if (!Helper.OpenInShell(path))
{
using (var process = new Process())
{
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);
var message = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", Properties.Resources.wox_plugin_folder_select_folder_OpenFileOrFolder_error_message, path);
contextApi.ShowMsg(message);
}

return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions;
using System.Reflection;
using System.Threading.Tasks;
Expand Down Expand Up @@ -175,15 +174,9 @@ private ContextMenuResult CreateOpenContainingFolderResult(SearchResult record)
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ =>
{
try
{
Process.Start("explorer.exe", $" /select,\"{record.Path}\"");
}
catch (Exception e)
if (!Helper.OpenInShell("explorer.exe", $"/select,\"{record.Path}\""))
{
var message = $"{Properties.Resources.Microsoft_plugin_indexer_folder_open_failed} {record.Path}";
Log.Exception(message, e, GetType());
_context.API.ShowMsg(message);
return false;
}
Expand Down
41 changes: 5 additions & 36 deletions src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO.Abstractions;
using System.Linq;
Expand All @@ -16,6 +14,7 @@
using Microsoft.Plugin.Indexer.SearchHelper;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.Search.Interop;
using Wox.Infrastructure;
using Wox.Infrastructure.Storage;
using Wox.Plugin;
using Wox.Plugin.Logger;
Expand Down Expand Up @@ -85,15 +84,7 @@ public List<Result> Query(Query query, bool isFullQuery)
IcoPath = WarningIconPath,
Action = e =>
{
try
{
Process.Start(GetWindowsSearchSettingsProcessInfo());
}
catch (Exception ex)
{
Log.Exception($"Unable to launch Windows Search Settings: {ex.Message}", ex, GetType());
}
Helper.OpenInShell("ms-settings:cortana-windowssearch");
return true;
},
});
Expand Down Expand Up @@ -129,23 +120,13 @@ public List<Result> Query(Query query, bool isFullQuery)
r.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
r.Action = c =>
{
bool hide;
try
{
Process.Start(new ProcessStartInfo
{
FileName = path,
UseShellExecute = true,
WorkingDirectory = workingDir,
});
hide = true;
}
catch (Win32Exception)
bool hide = true;
if (!Helper.OpenInShell(path, null, workingDir))
{
hide = false;
var name = $"Plugin: {_context.CurrentPluginMetadata.Name}";
var msg = Properties.Resources.Microsoft_plugin_indexer_file_open_failed;
_context.API.ShowMsg(name, msg, string.Empty);
hide = false;
}
return hide;
Expand Down Expand Up @@ -239,18 +220,6 @@ public Control CreateSettingPanel()
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)
{
if (!disposedValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ public void Win32ProgramRepositoryMustNotCreateAnyAppOtherThanUrlAppWhenChangedE
// ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>();
mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty);
Win32Program.Helper = mockShellLink.Object;
Win32Program.ShellLinkHelper = mockShellLink.Object;

// Act
_fileSystemMocks[0].Raise(m => m.Changed += null, e);
Expand Down Expand Up @@ -310,7 +310,7 @@ public void Win32ProgramRepositoryMustCallOnAppDeletedForLnkAppsWhenDeletedEvent
// ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>();
mockShellLink.Setup(m => m.RetrieveTargetPath(It.IsAny<string>())).Returns(string.Empty);
Win32Program.Helper = mockShellLink.Object;
Win32Program.ShellLinkHelper = mockShellLink.Object;

string fullPath = directory + "\\" + path;
Win32Program item = new Win32Program
Expand Down Expand Up @@ -343,7 +343,7 @@ public void Win32ProgramRepositoryMustCallOnAppRenamedForLnkAppsWhenRenamedEvent
// ShellLinkHelper must be mocked for lnk applications
var mockShellLink = new Mock<IShellLinkHelper>();
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
Win32Program olditem = new Win32Program
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public List<ContextMenuResult> ContextMenus(string queryArguments, IPublicAPI ap
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ =>
{
Main.StartProcess(Process.Start, new ProcessStartInfo("explorer", Package.Location));
Helper.OpenInShell(Package.Location);
return true;
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class Win32Program : IProgram

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();

Expand Down Expand Up @@ -294,7 +294,7 @@ public List<ContextMenuResult> ContextMenus(string queryArguments, IPublicAPI ap
AcceleratorModifiers = ModifierKeys.Control | ModifierKeys.Shift,
Action = _ =>
{
Main.StartProcess(Process.Start, new ProcessStartInfo("explorer", ParentDirectory));
Helper.OpenInShell(ParentDirectory);
return true;
},
});
Expand Down Expand Up @@ -473,7 +473,7 @@ private static Win32Program LnkProgram(string path)
const int MAX_PATH = 260;
StringBuilder buffer = new StringBuilder(MAX_PATH);

string target = Helper.RetrieveTargetPath(path);
string target = ShellLinkHelper.RetrieveTargetPath(path);

if (!string.IsNullOrEmpty(target))
{
Expand All @@ -485,7 +485,7 @@ private static Win32Program LnkProgram(string path)
program.FullPath = Path.GetFullPath(target).ToLower(CultureInfo.CurrentCulture);
program.AppType = GetAppTypeFromPath(target);

var description = Helper.Description;
var description = ShellLinkHelper.Description;
if (!string.IsNullOrEmpty(description))
{
program.Description = description;
Expand Down
12 changes: 8 additions & 4 deletions src/modules/launcher/Plugins/Microsoft.Plugin.Uri/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Abstractions;
using System.Text;
using ManagedCommon;
using Microsoft.Plugin.Uri.UriHelper;
using Wox.Infrastructure;
using Wox.Infrastructure.Storage;
using Wox.Plugin;
using Wox.Plugin.Logger;
Expand Down Expand Up @@ -67,10 +67,14 @@ public List<Result> Query(Query query)
: DefaultIconPath,
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;
},
});
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</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">
<value>Handles urls</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.PowerToys.Run.Plugin.Registry.Classes;
using Microsoft.PowerToys.Run.Plugin.Registry.Constants;
Expand Down Expand Up @@ -144,21 +143,8 @@ internal static void OpenRegistryKey(in string fullKey)
// 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);

var processStartInfo = new ProcessStartInfo
{
// -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);
// -m => allow multi-instance (hidden start option)
Wox.Infrastructure.Helper.OpenInShell("regedit.exe", "-m", null, true);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Reflection;
using System.ServiceProcess;
using Microsoft.PowerToys.Run.Plugin.Service.Properties;
using Wox.Infrastructure;
using Wox.Plugin;
using Wox.Plugin.Logger;

Expand Down Expand Up @@ -90,20 +91,7 @@ public static void ChangeStatus(ServiceResult serviceResult, Action action, IPub

public static void OpenServices()
{
try
{
var info = new ProcessStartInfo
{
FileName = "services.msc",
UseShellExecute = true,
};

Process.Start(info);
}
catch (Win32Exception ex)
{
Log.Error(ex.Message, MethodBase.GetCurrentMethod().DeclaringType);
}
Helper.OpenInShell("services.msc");
}

private static string GetResultTitle(ServiceController serviceController)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@

<ItemGroup>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj" />
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Interop;
using ManagedCommon;
Expand Down Expand Up @@ -70,7 +69,7 @@ private List<Result> Commands()
IcoPath = $"Images\\shutdown.{IconTheme}.png",
Action = c =>
{
Process.Start("shutdown", "/s /t 0");
Helper.OpenInShell("shutdown", "/s /t 0");
return true;
},
},
Expand All @@ -81,7 +80,7 @@ private List<Result> Commands()
IcoPath = $"Images\\restart.{IconTheme}.png",
Action = c =>
{
Process.Start("shutdown", "/r /t 0");
Helper.OpenInShell("shutdown", "/r /t 0");
return true;
},
},
Expand Down

0 comments on commit 571bceb

Please sign in to comment.