Flow.Launcher/Flow.Launcher.Core/Plugin/PluginManager.cs

326 lines
12 KiB
C#
Raw Normal View History

using System;
using System.Collections.Concurrent;
2015-11-03 05:09:54 +00:00
using System.Collections.Generic;
2014-12-26 11:36:43 +00:00
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.Storage;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
2014-12-26 11:36:43 +00:00
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Core.Plugin
2014-12-26 11:36:43 +00:00
{
/// <summary>
2020-04-22 10:26:09 +00:00
/// The entry for managing Flow Launcher plugins
2014-12-26 11:36:43 +00:00
/// </summary>
public static class PluginManager
{
2016-01-08 01:13:36 +00:00
private static IEnumerable<PluginPair> _contextMenuPlugins;
2014-12-26 14:51:04 +00:00
public static List<PluginPair> AllPlugins { get; private set; }
2016-01-08 01:13:36 +00:00
public static readonly List<PluginPair> GlobalPlugins = new List<PluginPair>();
public static readonly Dictionary<string, PluginPair> NonGlobalPlugins = new Dictionary<string, PluginPair>();
public static IPublicAPI API { private set; get; }
2016-05-12 01:45:35 +00:00
// todo happlebao, this should not be public, the indicator function should be embeded
public static PluginsSettings Settings;
private static List<PluginMetadata> _metadatas;
2020-06-25 00:40:29 +00:00
/// <summary>
/// Directories that will hold Flow Launcher plugin directory
/// </summary>
2021-01-02 14:30:56 +00:00
private static readonly string[] Directories = { Constant.PreinstalledDirectory, DataLocation.PluginsDirectory };
private static void DeletePythonBinding()
{
2020-04-21 12:54:41 +00:00
const string binding = "flowlauncher.py";
2020-06-25 00:40:29 +00:00
foreach (var subDirectory in Directory.GetDirectories(DataLocation.PluginsDirectory))
{
2020-06-25 00:40:29 +00:00
File.Delete(Path.Combine(subDirectory, binding));
2014-12-26 11:36:43 +00:00
}
}
public static void Save()
{
foreach (var plugin in AllPlugins)
{
var savable = plugin.Plugin as ISavable;
savable?.Save();
}
}
public static async Task ReloadData()
{
await Task.WhenAll(AllPlugins.Select(plugin => plugin.Plugin switch
{
IReloadable p => Task.Run(p.ReloadData),
IAsyncReloadable p => p.ReloadDataAsync(),
_ => Task.CompletedTask,
}).ToArray());
}
static PluginManager()
{
2020-06-25 00:40:29 +00:00
// validate user directory
Directory.CreateDirectory(DataLocation.PluginsDirectory);
// force old plugins use new python binding
DeletePythonBinding();
}
/// <summary>
/// because InitializePlugins needs API, so LoadPlugins needs to be called first
/// todo happlebao The API should be removed
/// </summary>
/// <param name="settings"></param>
public static void LoadPlugins(PluginsSettings settings)
{
_metadatas = PluginConfig.Parse(Directories);
2016-05-12 01:45:35 +00:00
Settings = settings;
Settings.UpdatePluginSettings(_metadatas);
AllPlugins = PluginsLoader.Plugins(_metadatas, Settings);
}
/// <summary>
/// Call initialize for all plugins
/// </summary>
/// <returns>return the list of failed to init plugins or null for none</returns>
public static async Task InitializePlugins(IPublicAPI api)
{
API = api;
var failedPlugins = new ConcurrentQueue<PluginPair>();
var InitTasks = AllPlugins.Select(pair => Task.Run(async delegate
2014-12-26 11:36:43 +00:00
{
try
2014-12-26 11:36:43 +00:00
{
var milliseconds = pair.Plugin switch
2015-01-04 15:08:26 +00:00
{
IAsyncPlugin plugin
=> await Stopwatch.DebugAsync($"|PluginManager.InitializePlugins|Init method time cost for <{pair.Metadata.Name}>",
() => plugin.InitAsync(new PluginInitContext(pair.Metadata, API))),
IPlugin plugin
=> Stopwatch.Debug($"|PluginManager.InitializePlugins|Init method time cost for <{pair.Metadata.Name}>",
() => plugin.Init(new PluginInitContext(pair.Metadata, API))),
_ => throw new ArgumentException(),
};
pair.Metadata.InitTime += milliseconds;
Log.Info(
$"|PluginManager.InitializePlugins|Total init cost for <{pair.Metadata.Name}> is <{pair.Metadata.InitTime}ms>");
}
catch (Exception e)
{
Log.Exception(nameof(PluginManager), $"Fail to Init plugin: {pair.Metadata.Name}", e);
2021-01-02 14:30:56 +00:00
pair.Metadata.Disabled = true;
failedPlugins.Enqueue(pair);
}
}));
await Task.WhenAll(InitTasks);
_contextMenuPlugins = GetPluginsForInterface<IContextMenu>();
foreach (var plugin in AllPlugins)
2015-02-04 15:16:41 +00:00
{
foreach (var actionKeyword in plugin.Metadata.ActionKeywords)
{
switch (actionKeyword)
{
case Query.GlobalPluginWildcardSign:
GlobalPlugins.Add(plugin);
break;
default:
NonGlobalPlugins[actionKeyword] = plugin;
break;
}
}
}
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",
"", false);
}
2014-12-26 11:36:43 +00:00
}
public static List<PluginPair> ValidPluginsForQuery(Query query)
{
if (NonGlobalPlugins.ContainsKey(query.ActionKeyword))
{
var plugin = NonGlobalPlugins[query.ActionKeyword];
2021-01-02 14:30:56 +00:00
return new List<PluginPair> { plugin };
}
else
{
return GlobalPlugins;
}
2014-12-26 14:51:04 +00:00
}
public static async Task<List<Result>> QueryForPlugin(PluginPair pair, Query query, CancellationToken token)
2014-12-26 11:36:43 +00:00
{
2020-06-25 00:40:29 +00:00
var results = new List<Result>();
try
2014-12-26 11:36:43 +00:00
{
var metadata = pair.Metadata;
2021-01-03 02:19:33 +00:00
long milliseconds = -1L;
switch (pair.Plugin)
{
case IAsyncPlugin plugin:
milliseconds = await Stopwatch.DebugAsync($"|PluginManager.QueryForPlugin|Cost for {metadata.Name}",
async () => results = await plugin.QueryAsync(query, token).ConfigureAwait(false));
break;
case IPlugin plugin:
2021-01-06 11:33:55 +00:00
await Task.Run(() => milliseconds = Stopwatch.Debug($"|PluginManager.QueryForPlugin|Cost for {metadata.Name}",
() => results = plugin.Query(query)), token).ConfigureAwait(false);
2021-01-03 02:19:33 +00:00
break;
default:
throw new ArgumentOutOfRangeException();
}
token.ThrowIfCancellationRequested();
if (results == null)
return results;
2021-01-03 02:19:33 +00:00
UpdatePluginMetadata(results, metadata, query);
metadata.QueryCount += 1;
metadata.AvgQueryTime =
metadata.QueryCount == 1 ? milliseconds : (metadata.AvgQueryTime + milliseconds) / 2;
2021-01-03 02:19:33 +00:00
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
2021-01-03 02:19:33 +00:00
{
2021-01-06 11:33:55 +00:00
// null will be fine since the results will only be added into queue if the token hasn't been cancelled
2021-01-03 02:19:33 +00:00
return results = null;
}
catch (Exception e)
{
2021-01-03 02:19:33 +00:00
Log.Exception($"|PluginManager.QueryForPlugin|Exception for plugin <{pair.Metadata.Name}> when query <{query}>", e);
2014-12-26 11:36:43 +00:00
}
2021-01-03 02:19:33 +00:00
return results;
2014-12-26 11:36:43 +00:00
}
public static void UpdatePluginMetadata(List<Result> results, PluginMetadata metadata, Query query)
{
foreach (var r in results)
{
r.PluginDirectory = metadata.PluginDirectory;
r.PluginID = metadata.ID;
r.OriginQuery = query;
// ActionKeywordAssigned is used for constructing MainViewModel's query text auto-complete suggestions
// Plugins may have multi-actionkeywords eg. WebSearches. In this scenario it needs to be overriden on the plugin level
if (metadata.ActionKeywords.Count == 1)
r.ActionKeywordAssigned = query.ActionKeyword;
}
}
2014-12-26 11:36:43 +00:00
/// <summary>
/// get specified plugin, return null if not found
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static PluginPair GetPluginForId(string id)
2014-12-26 11:36:43 +00:00
{
return AllPlugins.FirstOrDefault(o => o.Metadata.ID == id);
2014-12-26 11:36:43 +00:00
}
2015-02-05 10:43:05 +00:00
public static IEnumerable<PluginPair> GetPluginsForInterface<T>() where T : IFeatures
2015-02-05 14:20:42 +00:00
{
return AllPlugins.Where(p => p.Plugin is T);
2015-02-05 14:20:42 +00:00
}
public static List<Result> GetContextMenusForPlugin(Result result)
{
2020-06-25 00:40:29 +00:00
var results = new List<Result>();
2016-01-08 01:13:36 +00:00
var pluginPair = _contextMenuPlugins.FirstOrDefault(o => o.Metadata.ID == result.PluginID);
if (pluginPair != null)
{
2021-01-02 14:30:56 +00:00
var plugin = (IContextMenu)pluginPair.Plugin;
try
{
2020-06-25 00:40:29 +00:00
results = plugin.LoadContextMenus(result);
foreach (var r in results)
{
2020-06-25 00:40:29 +00:00
r.PluginDirectory = pluginPair.Metadata.PluginDirectory;
r.PluginID = pluginPair.Metadata.ID;
r.OriginQuery = result.OriginQuery;
}
}
catch (Exception e)
{
Log.Exception(
$"|PluginManager.GetContextMenusForPlugin|Can't load context menus for plugin <{pluginPair.Metadata.Name}>",
e);
}
}
2020-06-25 00:40:29 +00:00
return results;
}
public static bool ActionKeywordRegistered(string actionKeyword)
{
2020-06-25 00:40:29 +00:00
return actionKeyword != Query.GlobalPluginWildcardSign
&& NonGlobalPlugins.ContainsKey(actionKeyword);
}
2016-06-22 23:03:01 +00:00
/// <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.ActionKeywords.Add(newActionKeyword);
}
2016-06-22 23:03:01 +00:00
/// <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.ActionKeywords
.Where(x => x == Query.GlobalPluginWildcardSign)
.ToList()
.Count == 1)
{
GlobalPlugins.Remove(plugin);
}
2021-01-02 14:30:56 +00:00
2020-06-25 00:40:29 +00:00
if (oldActionkeyword != Query.GlobalPluginWildcardSign)
NonGlobalPlugins.Remove(oldActionkeyword);
2021-01-02 14:30:56 +00:00
plugin.Metadata.ActionKeywords.Remove(oldActionkeyword);
}
public static void ReplaceActionKeyword(string id, string oldActionKeyword, string newActionKeyword)
{
if (oldActionKeyword != newActionKeyword)
{
AddActionKeyword(id, newActionKeyword);
RemoveActionKeyword(id, oldActionKeyword);
}
}
2014-12-26 11:36:43 +00:00
}
2021-01-17 07:47:19 +00:00
}