PowerToys/Wox/Commands/PluginCommand.cs

72 lines
2.4 KiB
C#
Raw Normal View History

2014-01-03 18:16:05 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
2014-01-03 23:52:36 +08:00
using System.Threading;
using Python.Runtime;
2014-01-29 18:33:24 +08:00
using Wox.Helper;
using Wox.Plugin;
using Wox.PluginLoader;
2014-01-03 18:16:05 +08:00
2014-01-29 18:33:24 +08:00
namespace Wox.Commands
2014-01-03 18:16:05 +08:00
{
2014-01-03 23:52:36 +08:00
public class PluginCommand : BaseCommand
2014-01-03 18:16:05 +08:00
{
private string currentPythonModulePath = string.Empty;
private IntPtr GIL;
public override void Dispatch(Query q,bool updateView = true)
2014-01-03 23:52:36 +08:00
{
PluginPair thirdPlugin = Plugins.AllPlugins.FirstOrDefault(o => o.Metadata.ActionKeyword == q.ActionName);
if (thirdPlugin != null && !string.IsNullOrEmpty(thirdPlugin.Metadata.ActionKeyword))
2014-01-03 18:16:05 +08:00
{
if (thirdPlugin.Metadata.Language == AllowedLanguage.Python)
2014-01-03 18:16:05 +08:00
{
SwitchPythonEnv(thirdPlugin);
}
ThreadPool.QueueUserWorkItem(t =>
{
try
2014-01-03 18:16:05 +08:00
{
List<Result> r = thirdPlugin.Plugin.Query(q);
r.ForEach(o =>
2014-01-03 18:16:05 +08:00
{
o.PluginDirectory = thirdPlugin.Metadata.PluginDirecotry;
o.OriginQuery = q;
});
2014-01-13 18:43:44 +08:00
if(updateView) UpdateResultView(r);
}
catch (Exception queryException)
{
Log.Error(string.Format("Plugin {0} query failed: {1}", thirdPlugin.Metadata.Name,
queryException.Message));
2014-01-03 23:52:36 +08:00
#if (DEBUG)
{
throw;
2014-01-03 23:52:36 +08:00
}
#endif
}
});
}
}
private void SwitchPythonEnv(PluginPair thirdPlugin)
{
if (currentPythonModulePath != thirdPlugin.Metadata.PluginDirecotry)
{
currentPythonModulePath = thirdPlugin.Metadata.PluginDirecotry;
if (GIL != IntPtr.Zero)
{
Runtime.PyEval_RestoreThread(GIL);
PythonEngine.Shutdown();
2014-01-03 18:16:05 +08:00
}
PythonEngine.Initialize();
IntPtr pyStrPtr = Runtime.PyString_FromString(thirdPlugin.Metadata.PluginDirecotry);
IntPtr sysDotPath = Runtime.PySys_GetObject("path");
Runtime.PyList_Append(sysDotPath, pyStrPtr);
GIL = PythonEngine.BeginAllowThreads();
2014-01-03 18:16:05 +08:00
}
}
}
}