mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-05 02:36:19 +02:00
Merge pull request #7820 from davidegiacometti/issue-7336
[PT Run] Wox.Core merged into PowerLauncher
This commit is contained in:
@@ -10,9 +10,9 @@ using ManagedCommon;
|
||||
using Microsoft.PowerLauncher.Telemetry;
|
||||
using Microsoft.PowerToys.Telemetry;
|
||||
using PowerLauncher.Helper;
|
||||
using PowerLauncher.Plugin;
|
||||
using PowerLauncher.ViewModel;
|
||||
using Wox;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Http;
|
||||
using Wox.Infrastructure.Image;
|
||||
|
||||
105
src/modules/launcher/PowerLauncher/Helper/FontHelper.cs
Normal file
105
src/modules/launcher/PowerLauncher/Helper/FontHelper.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
public static class FontHelper
|
||||
{
|
||||
private static readonly FontWeightConverter _fontWeightConverter = new FontWeightConverter();
|
||||
|
||||
public static FontWeight GetFontWeightFromInvariantStringOrNormal(string value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return FontWeights.Normal;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return (FontWeight)_fontWeightConverter.ConvertFromInvariantString(value);
|
||||
}
|
||||
catch (NotSupportedException e)
|
||||
{
|
||||
Log.Exception($"Can't convert {value} to FontWeight", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return FontWeights.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly FontStyleConverter _fontStyleConverter = new FontStyleConverter();
|
||||
|
||||
public static FontStyle GetFontStyleFromInvariantStringOrNormal(string value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return FontStyles.Normal;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return (FontStyle)_fontStyleConverter.ConvertFromInvariantString(value);
|
||||
}
|
||||
catch (NotSupportedException e)
|
||||
{
|
||||
Log.Exception($"Can't convert {value} to FontStyle", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return FontStyles.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly FontStretchConverter _fontStretchConverter = new FontStretchConverter();
|
||||
|
||||
public static FontStretch GetFontStretchFromInvariantStringOrNormal(string value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return FontStretches.Normal;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return (FontStretch)_fontStretchConverter.ConvertFromInvariantString(value);
|
||||
}
|
||||
catch (NotSupportedException e)
|
||||
{
|
||||
Log.Exception($"Can't convert {value} to FontStretch", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return FontStretches.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
public static FamilyTypeface ChooseRegularFamilyTypeface(this FontFamily family)
|
||||
{
|
||||
if (family == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(family));
|
||||
}
|
||||
|
||||
return family.FamilyTypefaces.OrderBy(o =>
|
||||
{
|
||||
return (Math.Abs(o.Stretch.ToOpenTypeStretch() - FontStretches.Normal.ToOpenTypeStretch()) * 100) +
|
||||
Math.Abs(o.Weight.ToOpenTypeWeight() - FontWeights.Normal.ToOpenTypeWeight()) +
|
||||
((o.Style == FontStyles.Normal ? 0 : o.Style == FontStyles.Oblique ? 1 : 2) * 1000);
|
||||
}).FirstOrDefault() ?? family.FamilyTypefaces.FirstOrDefault();
|
||||
}
|
||||
|
||||
public static FamilyTypeface ConvertFromInvariantStringsOrNormal(this FontFamily family, string style, string weight, string stretch)
|
||||
{
|
||||
if (family == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(family));
|
||||
}
|
||||
|
||||
var styleObj = GetFontStyleFromInvariantStringOrNormal(style);
|
||||
var weightObj = GetFontWeightFromInvariantStringOrNormal(weight);
|
||||
var stretchObj = GetFontStretchFromInvariantStringOrNormal(stretch);
|
||||
return family.FamilyTypefaces.FirstOrDefault(o => o.Style == styleObj && o.Weight == weightObj && o.Stretch == stretchObj)
|
||||
?? family.ChooseRegularFamilyTypeface();
|
||||
}
|
||||
}
|
||||
}
|
||||
112
src/modules/launcher/PowerLauncher/Plugin/PluginConfig.cs
Normal file
112
src/modules/launcher/PowerLauncher/Plugin/PluginConfig.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Newtonsoft.Json;
|
||||
using Wox.Plugin;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
namespace PowerLauncher.Plugin
|
||||
{
|
||||
internal abstract class PluginConfig
|
||||
{
|
||||
private static readonly IFileSystem FileSystem = new FileSystem();
|
||||
private static readonly IPath Path = FileSystem.Path;
|
||||
private static readonly IFile File = FileSystem.File;
|
||||
private static readonly IDirectory Directory = FileSystem.Directory;
|
||||
|
||||
private const string PluginConfigName = "plugin.json";
|
||||
private static readonly List<PluginMetadata> PluginMetadatas = new List<PluginMetadata>();
|
||||
|
||||
/// <summary>
|
||||
/// Parse plugin metadata in giving directories
|
||||
/// </summary>
|
||||
/// <param name="pluginDirectories">directories with plugins</param>
|
||||
/// <returns>List with plugin meta data</returns>
|
||||
public static List<PluginMetadata> Parse(string[] pluginDirectories)
|
||||
{
|
||||
PluginMetadatas.Clear();
|
||||
var directories = pluginDirectories.SelectMany(Directory.GetDirectories);
|
||||
ParsePluginConfigs(directories);
|
||||
|
||||
return PluginMetadatas;
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
private static void ParsePluginConfigs(IEnumerable<string> directories)
|
||||
{
|
||||
// todo use linq when diable plugin is implemented since parallel.foreach + list is not thread saft
|
||||
foreach (var directory in directories)
|
||||
{
|
||||
if (File.Exists(Path.Combine(directory, "NeedDelete.txt")))
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Can't delete <{directory}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
PluginMetadata metadata = GetPluginMetadata(directory);
|
||||
if (metadata != null)
|
||||
{
|
||||
PluginMetadatas.Add(metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
private static PluginMetadata GetPluginMetadata(string pluginDirectory)
|
||||
{
|
||||
string configPath = Path.Combine(pluginDirectory, PluginConfigName);
|
||||
if (!File.Exists(configPath))
|
||||
{
|
||||
Log.Error($"Didn't find config file <{configPath}>", MethodBase.GetCurrentMethod().DeclaringType);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
PluginMetadata metadata;
|
||||
try
|
||||
{
|
||||
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
|
||||
metadata.PluginDirectory = pluginDirectory;
|
||||
|
||||
// for plugins which doesn't has ActionKeywords key
|
||||
metadata.SetActionKeywords(metadata.GetActionKeywords() ?? new List<string> { metadata.ActionKeyword });
|
||||
|
||||
// for plugin still use old ActionKeyword
|
||||
metadata.ActionKeyword = metadata.GetActionKeywords()?[0];
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"|PluginConfig.GetPluginMetadata|invalid json for config <{configPath}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!AllowedLanguage.IsAllowed(metadata.Language))
|
||||
{
|
||||
Log.Error($"|PluginConfig.GetPluginMetadata|Invalid language <{metadata.Language}> for config <{configPath}>", MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!File.Exists(metadata.ExecuteFilePath))
|
||||
{
|
||||
Log.Error($"|PluginConfig.GetPluginMetadata|execute file path didn't exist <{metadata.ExecuteFilePath}> for config <{configPath}", MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return null;
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
}
|
||||
232
src/modules/launcher/PowerLauncher/Plugin/PluginInstaller.cs
Normal file
232
src/modules/launcher/PowerLauncher/Plugin/PluginInstaller.cs
Normal file
@@ -0,0 +1,232 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using ICSharpCode.SharpZipLib.Zip;
|
||||
using Newtonsoft.Json;
|
||||
using Wox.Plugin;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
namespace PowerLauncher.Plugin
|
||||
{
|
||||
internal class PluginInstaller
|
||||
{
|
||||
private static readonly IFileSystem FileSystem = new FileSystem();
|
||||
private static readonly IPath Path = FileSystem.Path;
|
||||
private static readonly IFile File = FileSystem.File;
|
||||
private static readonly IDirectory Directory = FileSystem.Directory;
|
||||
|
||||
internal static void Install(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
string tempFolder = Path.Combine(Path.GetTempPath(), "wox\\plugins");
|
||||
if (Directory.Exists(tempFolder))
|
||||
{
|
||||
Directory.Delete(tempFolder, true);
|
||||
}
|
||||
|
||||
UnZip(path, tempFolder, true);
|
||||
|
||||
string iniPath = Path.Combine(tempFolder, "plugin.json");
|
||||
if (!File.Exists(iniPath))
|
||||
{
|
||||
MessageBox.Show("Install failed: plugin config is missing");
|
||||
return;
|
||||
}
|
||||
|
||||
PluginMetadata plugin = GetMetadataFromJson(tempFolder);
|
||||
if (plugin?.Name == null)
|
||||
{
|
||||
MessageBox.Show("Install failed: plugin config is invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
string pluginFolderPath = Constant.PluginsDirectory;
|
||||
|
||||
// Using Ordinal since this is part of a path
|
||||
string newPluginName = plugin.Name
|
||||
.Replace("/", "_", StringComparison.Ordinal)
|
||||
.Replace("\\", "_", StringComparison.Ordinal)
|
||||
.Replace(":", "_", StringComparison.Ordinal)
|
||||
.Replace("<", "_", StringComparison.Ordinal)
|
||||
.Replace(">", "_", StringComparison.Ordinal)
|
||||
.Replace("?", "_", StringComparison.Ordinal)
|
||||
.Replace("*", "_", StringComparison.Ordinal)
|
||||
.Replace("|", "_", StringComparison.Ordinal)
|
||||
+ "-" + Guid.NewGuid();
|
||||
string newPluginPath = Path.Combine(pluginFolderPath, newPluginName);
|
||||
string content = $"Do you want to install following plugin?{Environment.NewLine}{Environment.NewLine}" +
|
||||
$"Name: {plugin.Name}{Environment.NewLine}" +
|
||||
$"Version: {plugin.Version}{Environment.NewLine}" +
|
||||
$"Author: {plugin.Author}";
|
||||
PluginPair existingPlugin = PluginManager.GetPluginForId(plugin.ID);
|
||||
|
||||
if (existingPlugin != null)
|
||||
{
|
||||
content = $"Do you want to update following plugin?{Environment.NewLine}{Environment.NewLine}" +
|
||||
$"Name: {plugin.Name}{Environment.NewLine}" +
|
||||
$"Old Version: {existingPlugin.Metadata.Version}" +
|
||||
$"{Environment.NewLine}New Version: {plugin.Version}" +
|
||||
$"{Environment.NewLine}Author: {plugin.Author}";
|
||||
}
|
||||
|
||||
var result = MessageBox.Show(content, "Install plugin", MessageBoxButton.YesNo, MessageBoxImage.Question);
|
||||
if (result == MessageBoxResult.Yes)
|
||||
{
|
||||
if (existingPlugin != null && Directory.Exists(existingPlugin.Metadata.PluginDirectory))
|
||||
{
|
||||
// when plugin is in use, we can't delete them. That's why we need to make plugin folder a random name
|
||||
File.Create(Path.Combine(existingPlugin.Metadata.PluginDirectory, "NeedDelete.txt")).Close();
|
||||
}
|
||||
|
||||
UnZip(path, newPluginPath, true);
|
||||
Directory.Delete(tempFolder, true);
|
||||
|
||||
// existing plugins could be loaded by the application,
|
||||
// if we try to delete those kind of plugins, we will get a error that indicate the
|
||||
// file is been used now.
|
||||
// current solution is to restart wox. Ugly.
|
||||
// if (MainWindow.Initialized)
|
||||
// {
|
||||
// Plugins.Initialize();
|
||||
// }
|
||||
if (MessageBox.Show($"You have installed plugin {plugin.Name} successfully.{Environment.NewLine} Restart Wox to take effect?", "Install plugin", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
|
||||
{
|
||||
PluginManager.API.RestartApp();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
private static PluginMetadata GetMetadataFromJson(string pluginDirectory)
|
||||
{
|
||||
string configPath = Path.Combine(pluginDirectory, "plugin.json");
|
||||
PluginMetadata metadata;
|
||||
|
||||
if (!File.Exists(configPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
|
||||
metadata.PluginDirectory = pluginDirectory;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string error = $"Parse plugin config {configPath} failed: json format is not valid";
|
||||
Log.Exception(error, e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
#if DEBUG
|
||||
{
|
||||
throw new Exception(error);
|
||||
}
|
||||
#else
|
||||
return null;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (!AllowedLanguage.IsAllowed(metadata.Language))
|
||||
{
|
||||
string error = $"Parse plugin config {configPath} failed: invalid language {metadata.Language}";
|
||||
#if DEBUG
|
||||
{
|
||||
throw new Exception(error);
|
||||
}
|
||||
#else
|
||||
return null;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (!File.Exists(metadata.ExecuteFilePath))
|
||||
{
|
||||
string error = $"Parse plugin config {configPath} failed: ExecuteFile {metadata.ExecuteFilePath} didn't exist";
|
||||
#if DEBUG
|
||||
{
|
||||
throw new Exception(error);
|
||||
}
|
||||
#else
|
||||
return null;
|
||||
#endif
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// unzip
|
||||
/// </summary>
|
||||
/// <param name="zippedFile">The zipped file.</param>
|
||||
/// <param name="strDirectory">The STR directory.</param>
|
||||
/// <param name="overWrite">overwrite</param>
|
||||
private static void UnZip(string zippedFile, string strDirectory, bool overWrite)
|
||||
{
|
||||
if (string.IsNullOrEmpty(strDirectory))
|
||||
{
|
||||
strDirectory = Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
// Using Ordinal since this is a path
|
||||
if (!strDirectory.EndsWith("\\", StringComparison.Ordinal))
|
||||
{
|
||||
strDirectory += "\\";
|
||||
}
|
||||
|
||||
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zippedFile)))
|
||||
{
|
||||
ZipEntry theEntry;
|
||||
|
||||
while ((theEntry = s.GetNextEntry()) != null)
|
||||
{
|
||||
string directoryName = string.Empty;
|
||||
string pathToZip = string.Empty;
|
||||
pathToZip = theEntry.Name;
|
||||
|
||||
if (!string.IsNullOrEmpty(pathToZip))
|
||||
{
|
||||
directoryName = Path.GetDirectoryName(pathToZip) + "\\";
|
||||
}
|
||||
|
||||
string fileName = Path.GetFileName(pathToZip);
|
||||
|
||||
Directory.CreateDirectory(strDirectory + directoryName);
|
||||
|
||||
if (!string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
|
||||
{
|
||||
using (Stream streamWriter = File.Create(strDirectory + directoryName + fileName))
|
||||
{
|
||||
byte[] data = new byte[2048];
|
||||
while (true)
|
||||
{
|
||||
int size = s.Read(data, 0, data.Length);
|
||||
|
||||
if (size > 0)
|
||||
{
|
||||
streamWriter.Write(data, 0, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
streamWriter.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
371
src/modules/launcher/PowerLauncher/Plugin/PluginManager.cs
Normal file
371
src/modules/launcher/PowerLauncher/Plugin/PluginManager.cs
Normal file
@@ -0,0 +1,371 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Storage;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
namespace PowerLauncher.Plugin
|
||||
{
|
||||
/// <summary>
|
||||
/// The entry for managing Wox plugins
|
||||
/// </summary>
|
||||
public static class PluginManager
|
||||
{
|
||||
private static readonly IFileSystem FileSystem = new FileSystem();
|
||||
private static readonly IDirectory Directory = FileSystem.Directory;
|
||||
|
||||
private static IEnumerable<PluginPair> _contextMenuPlugins = new List<PluginPair>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets directories that will hold Wox plugin directory
|
||||
/// </summary>
|
||||
public static List<PluginPair> AllPlugins { get; private set; } = new List<PluginPair>();
|
||||
|
||||
public static IPublicAPI API { get; private set; }
|
||||
|
||||
public static readonly List<PluginPair> GlobalPlugins = new List<PluginPair>();
|
||||
public static readonly Dictionary<string, PluginPair> NonGlobalPlugins = new Dictionary<string, PluginPair>();
|
||||
private static readonly string[] Directories = { Constant.PreinstalledDirectory, Constant.PluginsDirectory };
|
||||
|
||||
// todo happlebao, this should not be public, the indicator function should be embedded
|
||||
public static PluginSettings Settings { get; set; }
|
||||
|
||||
private static List<PluginMetadata> _metadatas;
|
||||
|
||||
private static void ValidateUserDirectory()
|
||||
{
|
||||
if (!Directory.Exists(Constant.PluginsDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(Constant.PluginsDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Save()
|
||||
{
|
||||
foreach (var plugin in AllPlugins)
|
||||
{
|
||||
var savable = plugin.Plugin as ISavable;
|
||||
savable?.Save();
|
||||
}
|
||||
}
|
||||
|
||||
public static void ReloadData()
|
||||
{
|
||||
foreach (var plugin in AllPlugins)
|
||||
{
|
||||
var reloadablePlugin = plugin.Plugin as IReloadable;
|
||||
reloadablePlugin?.ReloadData();
|
||||
}
|
||||
}
|
||||
|
||||
static PluginManager()
|
||||
{
|
||||
ValidateUserDirectory();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// because InitializePlugins needs API, so LoadPlugins needs to be called first
|
||||
/// todo happlebao The API should be removed
|
||||
/// </summary>
|
||||
/// <param name="settings">Plugin settings</param>
|
||||
public static void LoadPlugins(PluginSettings settings)
|
||||
{
|
||||
_metadatas = PluginConfig.Parse(Directories);
|
||||
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
Settings.UpdatePluginSettings(_metadatas);
|
||||
AllPlugins = PluginsLoader.Plugins(_metadatas);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call initialize for all plugins
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
public static void InitializePlugins(IPublicAPI api)
|
||||
{
|
||||
API = api ?? throw new ArgumentNullException(nameof(api));
|
||||
var failedPlugins = new ConcurrentQueue<PluginPair>();
|
||||
Parallel.ForEach(AllPlugins, pair =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var milliseconds = Stopwatch.Debug($"|PluginManager.InitializePlugins|Init method time cost for <{pair.Metadata.Name}>", () =>
|
||||
{
|
||||
pair.Plugin.Init(new PluginInitContext
|
||||
{
|
||||
CurrentPluginMetadata = pair.Metadata,
|
||||
API = API,
|
||||
});
|
||||
});
|
||||
pair.Metadata.InitTime += milliseconds;
|
||||
Log.Info($"Total init cost for <{pair.Metadata.Name}> is <{pair.Metadata.InitTime}ms>", MethodBase.GetCurrentMethod().DeclaringType);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Fail to Init plugin: {pair.Metadata.Name}", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
pair.Metadata.Disabled = true;
|
||||
failedPlugins.Enqueue(pair);
|
||||
}
|
||||
});
|
||||
|
||||
_contextMenuPlugins = GetPluginsForInterface<IContextMenu>();
|
||||
foreach (var plugin in AllPlugins)
|
||||
{
|
||||
if (IsGlobalPlugin(plugin.Metadata))
|
||||
{
|
||||
GlobalPlugins.Add(plugin);
|
||||
}
|
||||
|
||||
// Plugins may have multiple ActionKeywords, eg. WebSearch
|
||||
plugin.Metadata.GetActionKeywords().Where(x => x != Query.GlobalPluginWildcardSign)
|
||||
.ToList()
|
||||
.ForEach(x => NonGlobalPlugins[x] = plugin);
|
||||
}
|
||||
|
||||
if (failedPlugins.Any())
|
||||
{
|
||||
var failed = string.Join(",", failedPlugins.Select(x => x.Metadata.Name));
|
||||
API.ShowMsg($"Fail to Init Plugins", $"Plugins: {failed} - fail to load and would be disabled, please contact plugin creator for help", string.Empty, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void InstallPlugin(string path)
|
||||
{
|
||||
PluginInstaller.Install(path);
|
||||
}
|
||||
|
||||
public static List<PluginPair> ValidPluginsForQuery(Query query)
|
||||
{
|
||||
if (query == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(query));
|
||||
}
|
||||
|
||||
if (NonGlobalPlugins.ContainsKey(query.ActionKeyword))
|
||||
{
|
||||
var plugin = NonGlobalPlugins[query.ActionKeyword];
|
||||
return new List<PluginPair> { plugin };
|
||||
}
|
||||
else
|
||||
{
|
||||
return GlobalPlugins;
|
||||
}
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
public static List<Result> QueryForPlugin(PluginPair pair, Query query, bool delayedExecution = false)
|
||||
{
|
||||
if (pair == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(pair));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
List<Result> results = null;
|
||||
var metadata = pair.Metadata;
|
||||
var milliseconds = Stopwatch.Debug($"|PluginManager.QueryForPlugin|Cost for {metadata.Name}", () =>
|
||||
{
|
||||
if (delayedExecution && (pair.Plugin is IDelayedExecutionPlugin))
|
||||
{
|
||||
results = ((IDelayedExecutionPlugin)pair.Plugin).Query(query, delayedExecution) ?? new List<Result>();
|
||||
}
|
||||
else if (!delayedExecution)
|
||||
{
|
||||
results = pair.Plugin.Query(query) ?? new List<Result>();
|
||||
}
|
||||
|
||||
if (results != null)
|
||||
{
|
||||
UpdatePluginMetadata(results, metadata, query);
|
||||
UpdateResultWithActionKeyword(results, query);
|
||||
}
|
||||
});
|
||||
|
||||
metadata.QueryCount += 1;
|
||||
metadata.AvgQueryTime = metadata.QueryCount == 1 ? milliseconds : (metadata.AvgQueryTime + milliseconds) / 2;
|
||||
|
||||
return results;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Exception for plugin <{pair.Metadata.Name}> when query <{query}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
|
||||
return new List<Result>();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Result> UpdateResultWithActionKeyword(List<Result> results, Query query)
|
||||
{
|
||||
foreach (Result result in results)
|
||||
{
|
||||
if (string.IsNullOrEmpty(result.QueryTextDisplay))
|
||||
{
|
||||
result.QueryTextDisplay = result.Title;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(query.ActionKeyword))
|
||||
{
|
||||
// Using CurrentCulture since this is user facing
|
||||
result.QueryTextDisplay = string.Format(CultureInfo.CurrentCulture, "{0} {1}", query.ActionKeyword, result.QueryTextDisplay);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public static void UpdatePluginMetadata(List<Result> results, PluginMetadata metadata, Query query)
|
||||
{
|
||||
if (results == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(results));
|
||||
}
|
||||
|
||||
if (metadata == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(metadata));
|
||||
}
|
||||
|
||||
foreach (var r in results)
|
||||
{
|
||||
r.PluginDirectory = metadata.PluginDirectory;
|
||||
r.PluginID = metadata.ID;
|
||||
r.OriginQuery = query;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsGlobalPlugin(PluginMetadata metadata)
|
||||
{
|
||||
return metadata.GetActionKeywords().Contains(Query.GlobalPluginWildcardSign);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// get specified plugin, return null if not found
|
||||
/// </summary>
|
||||
/// <param name="id">id of plugin</param>
|
||||
/// <returns>plugin</returns>
|
||||
public static PluginPair GetPluginForId(string id)
|
||||
{
|
||||
return AllPlugins.FirstOrDefault(o => o.Metadata.ID == id);
|
||||
}
|
||||
|
||||
public static IEnumerable<PluginPair> GetPluginsForInterface<T>()
|
||||
{
|
||||
return AllPlugins.Where(p => p.Plugin is T);
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
public static List<ContextMenuResult> GetContextMenusForPlugin(Result result)
|
||||
{
|
||||
var pluginPair = _contextMenuPlugins.FirstOrDefault(o => o.Metadata.ID == result.PluginID);
|
||||
if (pluginPair != null)
|
||||
{
|
||||
var metadata = pluginPair.Metadata;
|
||||
var plugin = (IContextMenu)pluginPair.Plugin;
|
||||
|
||||
try
|
||||
{
|
||||
var results = plugin.LoadContextMenus(result);
|
||||
|
||||
return results;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Can't load context menus for plugin <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
|
||||
return new List<ContextMenuResult>();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return new List<ContextMenuResult>();
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ActionKeywordRegistered(string actionKeyword)
|
||||
{
|
||||
if (actionKeyword != Query.GlobalPluginWildcardSign &&
|
||||
NonGlobalPlugins.ContainsKey(actionKeyword))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// used to add action keyword for multiple action keyword plugin
|
||||
/// e.g. web search
|
||||
/// </summary>
|
||||
public static void AddActionKeyword(string id, string newActionKeyword)
|
||||
{
|
||||
var plugin = GetPluginForId(id);
|
||||
if (newActionKeyword == Query.GlobalPluginWildcardSign)
|
||||
{
|
||||
GlobalPlugins.Add(plugin);
|
||||
}
|
||||
else
|
||||
{
|
||||
NonGlobalPlugins[newActionKeyword] = plugin;
|
||||
}
|
||||
|
||||
plugin.Metadata.GetActionKeywords().Add(newActionKeyword);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// used to add action keyword for multiple action keyword plugin
|
||||
/// e.g. web search
|
||||
/// </summary>
|
||||
public static void RemoveActionKeyword(string id, string oldActionkeyword)
|
||||
{
|
||||
var plugin = GetPluginForId(id);
|
||||
if (oldActionkeyword == Query.GlobalPluginWildcardSign
|
||||
&& // Plugins may have multiple ActionKeywords that are global, eg. WebSearch
|
||||
plugin.Metadata.GetActionKeywords()
|
||||
.Where(x => x == Query.GlobalPluginWildcardSign)
|
||||
.ToList()
|
||||
.Count == 1)
|
||||
{
|
||||
GlobalPlugins.Remove(plugin);
|
||||
}
|
||||
|
||||
if (oldActionkeyword != Query.GlobalPluginWildcardSign)
|
||||
{
|
||||
NonGlobalPlugins.Remove(oldActionkeyword);
|
||||
}
|
||||
|
||||
plugin.Metadata.GetActionKeywords().Remove(oldActionkeyword);
|
||||
}
|
||||
|
||||
public static void ReplaceActionKeyword(string id, string oldActionKeyword, string newActionKeyword)
|
||||
{
|
||||
if (oldActionKeyword != newActionKeyword)
|
||||
{
|
||||
AddActionKeyword(id, newActionKeyword);
|
||||
RemoveActionKeyword(id, oldActionKeyword);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Dispose()
|
||||
{
|
||||
foreach (var plugin in AllPlugins)
|
||||
{
|
||||
var disposablePlugin = plugin.Plugin as IDisposable;
|
||||
disposablePlugin?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
89
src/modules/launcher/PowerLauncher/Plugin/PluginsLoader.cs
Normal file
89
src/modules/launcher/PowerLauncher/Plugin/PluginsLoader.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Plugin;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
namespace PowerLauncher.Plugin
|
||||
{
|
||||
public static class PluginsLoader
|
||||
{
|
||||
public const string PATH = "PATH";
|
||||
|
||||
public static List<PluginPair> Plugins(List<PluginMetadata> metadatas)
|
||||
{
|
||||
var csharpPlugins = CSharpPlugins(metadatas).ToList();
|
||||
return csharpPlugins;
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
|
||||
public static IEnumerable<PluginPair> CSharpPlugins(List<PluginMetadata> source)
|
||||
{
|
||||
var plugins = new List<PluginPair>();
|
||||
var metadatas = source.Where(o => o.Language.ToUpperInvariant() == AllowedLanguage.CSharp);
|
||||
|
||||
foreach (var metadata in metadatas)
|
||||
{
|
||||
var milliseconds = Stopwatch.Debug($"|PluginsLoader.CSharpPlugins|Constructor init cost for {metadata.Name}", () =>
|
||||
{
|
||||
#if DEBUG
|
||||
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(metadata.ExecuteFilePath);
|
||||
var types = assembly.GetTypes();
|
||||
var type = types.First(o => o.IsClass && !o.IsAbstract && o.GetInterfaces().Contains(typeof(IPlugin)));
|
||||
var plugin = (IPlugin)Activator.CreateInstance(type);
|
||||
#else
|
||||
Assembly assembly;
|
||||
try
|
||||
{
|
||||
assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(metadata.ExecuteFilePath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Couldn't load assembly for {metadata.Name}", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return;
|
||||
}
|
||||
|
||||
var types = assembly.GetTypes();
|
||||
Type type;
|
||||
try
|
||||
{
|
||||
type = types.First(o => o.IsClass && !o.IsAbstract && o.GetInterfaces().Contains(typeof(IPlugin)));
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
Log.Exception($"Can't find class implement IPlugin for <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return;
|
||||
}
|
||||
|
||||
IPlugin plugin;
|
||||
try
|
||||
{
|
||||
plugin = (IPlugin)Activator.CreateInstance(type);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Exception($"Can't create instance for <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
PluginPair pair = new PluginPair
|
||||
{
|
||||
Plugin = plugin,
|
||||
Metadata = metadata,
|
||||
};
|
||||
plugins.Add(pair);
|
||||
});
|
||||
metadata.InitTime += milliseconds;
|
||||
}
|
||||
|
||||
return plugins;
|
||||
}
|
||||
}
|
||||
}
|
||||
93
src/modules/launcher/PowerLauncher/Plugin/QueryBuilder.cs
Normal file
93
src/modules/launcher/PowerLauncher/Plugin/QueryBuilder.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Mono.Collections.Generic;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.Plugin
|
||||
{
|
||||
public static class QueryBuilder
|
||||
{
|
||||
public static Dictionary<PluginPair, Query> Build(ref string text, Dictionary<string, PluginPair> nonGlobalPlugins)
|
||||
{
|
||||
if (text == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(text));
|
||||
}
|
||||
|
||||
if (nonGlobalPlugins == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(nonGlobalPlugins));
|
||||
}
|
||||
|
||||
// replace multiple white spaces with one white space
|
||||
var terms = text.Split(new[] { Query.TermSeparator }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (terms.Length == 0)
|
||||
{ // nothing was typed
|
||||
return null;
|
||||
}
|
||||
|
||||
// This Dictionary contains the corresponding query for each plugin
|
||||
Dictionary<PluginPair, Query> pluginQueryPair = new Dictionary<PluginPair, Query>();
|
||||
|
||||
var rawQuery = string.Join(Query.TermSeparator, terms);
|
||||
|
||||
// This is the query on removing extra spaces which would be executed by global Plugins
|
||||
text = rawQuery;
|
||||
|
||||
string possibleActionKeyword = terms[0];
|
||||
|
||||
foreach (string pluginActionKeyword in nonGlobalPlugins.Keys)
|
||||
{
|
||||
// Using Ordinal since this is used internally
|
||||
if (possibleActionKeyword.StartsWith(pluginActionKeyword, StringComparison.Ordinal))
|
||||
{
|
||||
if (nonGlobalPlugins.TryGetValue(pluginActionKeyword, out var pluginPair) && !pluginPair.Metadata.Disabled)
|
||||
{
|
||||
// The search string is the raw query excluding the action keyword
|
||||
string search = rawQuery.Substring(pluginActionKeyword.Length).Trim();
|
||||
|
||||
// To set the terms of the query after removing the action keyword
|
||||
if (possibleActionKeyword.Length > pluginActionKeyword.Length)
|
||||
{
|
||||
// If the first term contains the action keyword, then set the remaining string to be the first term
|
||||
terms[0] = possibleActionKeyword.Substring(pluginActionKeyword.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the first term is the action keyword, then skip it.
|
||||
terms = terms.Skip(1).ToArray();
|
||||
}
|
||||
|
||||
// A new query is constructed for each plugin as they have different action keywords
|
||||
var query = new Query(rawQuery, search, new ReadOnlyCollection<string>(terms), pluginActionKeyword);
|
||||
|
||||
pluginQueryPair.TryAdd(pluginPair, query);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If the user has specified a matching action keyword, then do not
|
||||
// add the global plugins to the list.
|
||||
if (pluginQueryPair.Count == 0)
|
||||
{
|
||||
var globalplugins = PluginManager.GlobalPlugins;
|
||||
|
||||
foreach (PluginPair globalPlugin in PluginManager.GlobalPlugins)
|
||||
{
|
||||
if (!pluginQueryPair.ContainsKey(globalPlugin))
|
||||
{
|
||||
var query = new Query(rawQuery, rawQuery, new ReadOnlyCollection<string>(terms), string.Empty);
|
||||
pluginQueryPair.Add(globalPlugin, query);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return pluginQueryPair;
|
||||
}
|
||||
}
|
||||
}
|
||||
5
src/modules/launcher/PowerLauncher/Plugin/README.md
Normal file
5
src/modules/launcher/PowerLauncher/Plugin/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
There are two kinds of plugins:
|
||||
1. System plugin
|
||||
Those plugins that action keyword is "*", those plugin doesn't need action keyword
|
||||
2. User Plugin
|
||||
Those plugins that contains customized action keyword
|
||||
@@ -109,6 +109,7 @@
|
||||
<PackageReference Include="PropertyChanged.Fody" Version="3.2.10">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="SharpZipLib" Version="1.2.0" />
|
||||
<PackageReference Include="System.Runtime" Version="4.3.1" />
|
||||
<PackageReference Include="Microsoft.VCRTForwarders.140" Version="1.0.6" />
|
||||
<PackageReference Include="System.Data.OleDb" Version="4.7.1" />
|
||||
@@ -122,7 +123,6 @@
|
||||
<ProjectReference Include="..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
|
||||
<ProjectReference Include="..\..\..\core\Microsoft.PowerToys.Settings.UI.Library\Microsoft.PowerToys.Settings.UI.Library.csproj" />
|
||||
<ProjectReference Include="..\PowerLauncher.Telemetry\PowerLauncher.Telemetry.csproj" />
|
||||
<ProjectReference Include="..\Wox.Core\Wox.Core.csproj" />
|
||||
<ProjectReference Include="..\Wox.Infrastructure\Wox.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\Wox.Plugin\Wox.Plugin.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -9,8 +9,8 @@ using System.Net;
|
||||
using System.Windows;
|
||||
using ManagedCommon;
|
||||
using PowerLauncher.Helper;
|
||||
using PowerLauncher.Plugin;
|
||||
using PowerLauncher.ViewModel;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Image;
|
||||
using Wox.Plugin;
|
||||
|
||||
@@ -10,7 +10,7 @@ using System.Windows.Input;
|
||||
using ManagedCommon;
|
||||
using Microsoft.PowerToys.Settings.UI.Library;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Core.Plugin;
|
||||
using PowerLauncher.Plugin;
|
||||
using Wox.Infrastructure.Hotkey;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
|
||||
@@ -16,8 +16,8 @@ using interop;
|
||||
using Microsoft.PowerLauncher.Telemetry;
|
||||
using Microsoft.PowerToys.Telemetry;
|
||||
using PowerLauncher.Helper;
|
||||
using PowerLauncher.Plugin;
|
||||
using PowerLauncher.Storage;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Hotkey;
|
||||
using Wox.Infrastructure.Storage;
|
||||
|
||||
@@ -7,7 +7,7 @@ using System.Collections.ObjectModel;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Core.Plugin;
|
||||
using PowerLauncher.Plugin;
|
||||
using Wox.Infrastructure.Image;
|
||||
using Wox.Plugin;
|
||||
using Wox.Plugin.Logger;
|
||||
|
||||
Reference in New Issue
Block a user