Rearrange query execution order

1. remove usage of PushResult
2. rearrange query execution order
3. decouple UserSetting dependency
4. remove instant query
5. remove backkeydown event
6. part of #389
This commit is contained in:
bao-qian 2016-03-28 01:09:40 +01:00
parent 7eea6ebe57
commit c596039453
10 changed files with 77 additions and 97 deletions

View file

@ -21,7 +21,6 @@ namespace Wox.Plugin.Folder
public void Init(PluginInitContext context) public void Init(PluginInitContext context)
{ {
this.context = context; this.context = context;
this.context.API.BackKeyDownEvent += ApiBackKeyDownEvent;
InitialDriverList(); InitialDriverList();
if (FolderStorage.Instance.FolderLinks == null) if (FolderStorage.Instance.FolderLinks == null)
{ {
@ -30,26 +29,6 @@ namespace Wox.Plugin.Folder
} }
} }
private void ApiBackKeyDownEvent(WoxKeyDownEventArgs e)
{
string query = e.Query;
if (Directory.Exists(query))
{
if (query.EndsWith("\\"))
{
query = query.Remove(query.Length - 1);
}
if (query.Contains("\\"))
{
int index = query.LastIndexOf("\\");
query = query.Remove(index) + "\\";
}
context.API.ChangeQuery(query);
}
}
public List<Result> Query(Query query) public List<Result> Query(Query query)
{ {
string input = query.Search.ToLower(); string input = query.Search.ToLower();

View file

@ -80,7 +80,7 @@ namespace Wox.Core.Plugin
//current solution is to restart wox. Ugly. //current solution is to restart wox. Ugly.
//if (MainWindow.Initialized) //if (MainWindow.Initialized)
//{ //{
// Plugins.Init(); // Plugins.Initialize();
//} //}
if (MessageBox.Show($"You have installed plugin {plugin.Name} successfully.{Environment.NewLine}" + if (MessageBox.Show($"You have installed plugin {plugin.Name} successfully.{Environment.NewLine}" +
" Restart Wox to take effect?", " Restart Wox to take effect?",

View file

@ -63,12 +63,10 @@ namespace Wox.Core.Plugin
/// <summary> /// <summary>
/// Load and init all Wox plugins /// Load and init all Wox plugins
/// </summary> /// </summary>
public static void Init(IPublicAPI api) ///
public static void Initialize()
{ {
if (api == null) throw new WoxFatalException("api is null");
SetupPluginDirectories(); SetupPluginDirectories();
API = api;
var metadatas = PluginConfig.Parse(PluginDirectories); var metadatas = PluginConfig.Parse(PluginDirectories);
AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)). AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)).
@ -76,7 +74,11 @@ namespace Wox.Core.Plugin
//load plugin i18n languages //load plugin i18n languages
ResourceMerger.UpdatePluginLanguages(); ResourceMerger.UpdatePluginLanguages();
}
public static void InitializePlugins(IPublicAPI api)
{
API = api;
foreach (PluginPair pluginPair in AllPlugins) foreach (PluginPair pluginPair in AllPlugins)
{ {
PluginPair pair = pluginPair; PluginPair pair = pluginPair;
@ -98,7 +100,6 @@ namespace Wox.Core.Plugin
ThreadPool.QueueUserWorkItem(o => ThreadPool.QueueUserWorkItem(o =>
{ {
InstantQueryPlugins = GetPluginsForInterface<IInstantQuery>();
_contextMenuPlugins = GetPluginsForInterface<IContextMenu>(); _contextMenuPlugins = GetPluginsForInterface<IContextMenu>();
foreach (var plugin in AllPlugins) foreach (var plugin in AllPlugins)
{ {
@ -149,53 +150,41 @@ namespace Wox.Core.Plugin
}; };
} }
public static void QueryForAllPlugins(Query query) public static List<PluginPair> ValidPluginsForQuery(Query query)
{ {
var pluginPairs = NonGlobalPlugins.ContainsKey(query.ActionKeyword) ? if (NonGlobalPlugins.ContainsKey(query.ActionKeyword))
new List<PluginPair> { NonGlobalPlugins[query.ActionKeyword] } : GlobalPlugins;
foreach (var plugin in pluginPairs)
{ {
var customizedPluginConfig = UserSettingStorage.Instance. var plugin = NonGlobalPlugins[query.ActionKeyword];
CustomizedPluginConfigs[plugin.Metadata.ID]; return new List<PluginPair> { plugin };
if (customizedPluginConfig.Disabled) continue; }
if (IsInstantQueryPlugin(plugin)) else
{ {
Stopwatch.Normal($"Instant QueryForPlugin for {plugin.Metadata.Name}", () => return GlobalPlugins;
{
QueryForPlugin(plugin, query);
});
}
else
{
ThreadPool.QueueUserWorkItem(state =>
{
Stopwatch.Normal($"Normal QueryForPlugin for {plugin.Metadata.Name}", () =>
{
QueryForPlugin(plugin, query);
});
});
}
} }
} }
public static List<Result> QueryForPlugin(PluginPair pair, Query query)
private static void QueryForPlugin(PluginPair pair, Query query)
{ {
var results = new List<Result>();
try try
{ {
List<Result> results = new List<Result>();
var milliseconds = Stopwatch.Normal($"Plugin.Query cost for {pair.Metadata.Name}", () => var milliseconds = Stopwatch.Normal($"Plugin.Query cost for {pair.Metadata.Name}", () =>
{ {
results = pair.Plugin.Query(query) ?? results; results = pair.Plugin.Query(query) ?? results;
results.ForEach(o => { o.PluginID = pair.Metadata.ID; }); results.ForEach(o =>
{
o.PluginDirectory = pair.Metadata.PluginDirectory;
o.PluginID = pair.Metadata.ID;
o.OriginQuery = query;
});
}); });
pair.QueryCount += 1; pair.QueryCount += 1;
pair.AvgQueryTime = pair.QueryCount == 1 ? milliseconds : (pair.AvgQueryTime + milliseconds) / 2; pair.AvgQueryTime = pair.QueryCount == 1 ? milliseconds : (pair.AvgQueryTime + milliseconds) / 2;
API.PushResults(query, pair.Metadata, results);
} }
catch (Exception e) catch (Exception e)
{ {
throw new WoxPluginException(pair.Metadata.Name, $"QueryForPlugin failed", e); throw new WoxPluginException(pair.Metadata.Name, $"QueryForPlugin failed", e);
} }
return results;
} }
private static bool IsGlobalPlugin(PluginMetadata metadata) private static bool IsGlobalPlugin(PluginMetadata metadata)

View file

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
namespace Wox.Plugin namespace Wox.Plugin
{ {
@ -13,6 +14,7 @@ namespace Wox.Plugin
/// <param name="query"></param> /// <param name="query"></param>
/// <param name="plugin"></param> /// <param name="plugin"></param>
/// <param name="results"></param> /// <param name="results"></param>
[Obsolete("This method will be removed in Wox 1.3")]
void PushResults(Query query, PluginMetadata plugin, List<Result> results); void PushResults(Query query, PluginMetadata plugin, List<Result> results);
/// <summary> /// <summary>
@ -99,11 +101,6 @@ namespace Wox.Plugin
/// <returns></returns> /// <returns></returns>
List<PluginPair> GetAllPlugins(); List<PluginPair> GetAllPlugins();
/// <summary>
/// Fired after Back key down in the Wox query box
/// </summary>
event WoxKeyDownEventHandler BackKeyDownEvent;
/// <summary> /// <summary>
/// Fired after global keyboard events /// Fired after global keyboard events
/// if you want to hook something like Ctrl+R, you should use this event /// if you want to hook something like Ctrl+R, you should use this event

View file

@ -11,7 +11,7 @@ namespace Wox.Test.Plugins
[Test] [Test]
public void PublicAPIIsNullTest() public void PublicAPIIsNullTest()
{ {
Assert.Throws(typeof(WoxFatalException), () => PluginManager.Init(null)); //Assert.Throws(typeof(WoxFatalException), () => PluginManager.Initialize(null));
} }
} }
} }

View file

@ -47,11 +47,14 @@ namespace Wox
ThreadPool.SetMinThreads(10, 5); ThreadPool.SetMinThreads(10, 5);
ThreadPool.QueueUserWorkItem(_ => { ImageLoader.ImageLoader.PreloadImages(); }); ThreadPool.QueueUserWorkItem(_ => { ImageLoader.ImageLoader.PreloadImages(); });
MainViewModel mainVM = new MainViewModel(); PluginManager.Initialize();
UserSettingStorage settings = UserSettingStorage.Instance;
MainViewModel mainVM = new MainViewModel(settings);
API = new PublicAPIInstance(mainVM); API = new PublicAPIInstance(mainVM);
PluginManager.InitializePlugins(API);
Window = new MainWindow {DataContext = mainVM}; Window = new MainWindow {DataContext = mainVM};
NotifyIconManager notifyIconManager = new NotifyIconManager(API); NotifyIconManager notifyIconManager = new NotifyIconManager(API);
PluginManager.Init(API);
CommandArgsFactory.Execute(e.Args.ToList()); CommandArgsFactory.Execute(e.Args.ToList());
// happlebao todo: the whole setting releated initialization should be put into seperate class/method // happlebao todo: the whole setting releated initialization should be put into seperate class/method

View file

@ -32,7 +32,7 @@
<system:String x:Key="actionKeywords">Action keywords</system:String> <system:String x:Key="actionKeywords">Action keywords</system:String>
<system:String x:Key="pluginDirectory">Plugin Directory</system:String> <system:String x:Key="pluginDirectory">Plugin Directory</system:String>
<system:String x:Key="author">Author</system:String> <system:String x:Key="author">Author</system:String>
<system:String x:Key="plugin_init_time">Init time: {0}ms</system:String> <system:String x:Key="plugin_init_time">Initialize time: {0}ms</system:String>
<system:String x:Key="plugin_query_time">Query time: {0}ms</system:String> <system:String x:Key="plugin_query_time">Query time: {0}ms</system:String>
<!--Setting Theme--> <!--Setting Theme-->

View file

@ -19,36 +19,21 @@ namespace Wox
{ {
public class PublicAPIInstance : IPublicAPI public class PublicAPIInstance : IPublicAPI
{ {
private UserSettingStorage _settings;
#region Constructor #region Constructor
public PublicAPIInstance(MainViewModel mainVM) public PublicAPIInstance(MainViewModel mainVM)
{ {
MainVM = mainVM; MainVM = mainVM;
GlobalHotkey.Instance.hookedKeyboardCallback += KListener_hookedKeyboardCallback; GlobalHotkey.Instance.hookedKeyboardCallback += KListener_hookedKeyboardCallback;
WebRequest.RegisterPrefix("data", new DataWebRequestFactory()); WebRequest.RegisterPrefix("data", new DataWebRequestFactory());
MainVM.ListeningKeyPressed += (o, e) =>
{
if (e.KeyEventArgs.Key == Key.Back)
{
BackKeyDownEvent?.Invoke(new WoxKeyDownEventArgs
{
Query = MainVM.QueryText,
keyEventArgs = e.KeyEventArgs
});
}
};
} }
#endregion #endregion
#region Properties #region Properties
private MainViewModel MainVM public MainViewModel MainVM
{ {
get; get;
set; set;
@ -131,7 +116,11 @@ namespace Wox
public void ReloadPlugins() public void ReloadPlugins()
{ {
Application.Current.Dispatcher.Invoke(() => PluginManager.Init(this)); Application.Current.Dispatcher.Invoke(() =>
{
PluginManager.Initialize();
PluginManager.InitializePlugins(this);
});
} }
public string GetTranslation(string key) public string GetTranslation(string key)
@ -144,9 +133,9 @@ namespace Wox
return PluginManager.AllPlugins.ToList(); return PluginManager.AllPlugins.ToList();
} }
public event WoxKeyDownEventHandler BackKeyDownEvent;
public event WoxGlobalKeyboardEventHandler GlobalKeyboardEvent; public event WoxGlobalKeyboardEventHandler GlobalKeyboardEvent;
[Obsolete("This will be removed in Wox 1.3")]
public void PushResults(Query query, PluginMetadata plugin, List<Result> results) public void PushResults(Query query, PluginMetadata plugin, List<Result> results)
{ {
results.ForEach(o => results.ForEach(o =>

View file

@ -126,7 +126,7 @@
<TextBlock Margin="5 0 0 0" ToolTip="Change Action Keywords" Cursor="Hand" <TextBlock Margin="5 0 0 0" ToolTip="Change Action Keywords" Cursor="Hand"
MouseUp="PluginActionKeywords_OnMouseUp" Foreground="Blue" Text="keys" MouseUp="PluginActionKeywords_OnMouseUp" Foreground="Blue" Text="keys"
x:Name="pluginActionKeywords" /> x:Name="pluginActionKeywords" />
<TextBlock Margin="10 0 0 0" Text="Init time: 0ms" x:Name="pluginInitTime" /> <TextBlock Margin="10 0 0 0" Text="Initialize time: 0ms" x:Name="pluginInitTime" />
<TextBlock Margin="10 0 0 0" Text="Query time: 0ms" x:Name="pluginQueryTime" /> <TextBlock Margin="10 0 0 0" Text="Query time: 0ms" x:Name="pluginQueryTime" />
<TextBlock HorizontalAlignment="Right" Cursor="Hand" <TextBlock HorizontalAlignment="Right" Cursor="Hand"
MouseUp="tbOpenPluginDirecoty_MouseUp" Foreground="Blue" MouseUp="tbOpenPluginDirecoty_MouseUp" Foreground="Blue"

View file

@ -1,11 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Input; using System.Windows.Input;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.Resource; using Wox.Core.Resource;
using Wox.Core.UserSettings;
using Wox.Helper; using Wox.Helper;
using Wox.Infrastructure; using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Hotkey;
@ -34,19 +36,28 @@ namespace Wox.ViewModel
private string _queryTextBeforeLoadContextMenu; private string _queryTextBeforeLoadContextMenu;
private string _queryText; private string _queryText;
private UserSettingStorage _settings;
private QueryHistoryStorage _queryHistory;
private UserSelectedRecordStorage _userSelectedRecord;
private TopMostRecordStorage _topMostRecord;
#endregion #endregion
#region Constructor #region Constructor
public MainViewModel() public MainViewModel(UserSettingStorage settings)
{ {
_queryTextBeforeLoadContextMenu = ""; _queryTextBeforeLoadContextMenu = "";
_queryText = ""; _queryText = "";
_lastQuery = new Query(); _lastQuery = new Query();
_settings = settings;
InitializeResultListBox(); InitializeResultListBox();
InitializeContextMenu(); InitializeContextMenu();
InitializeKeyCommands(); InitializeKeyCommands();
_queryHistory = QueryHistoryStorage.Instance;
_userSelectedRecord = UserSelectedRecordStorage.Instance;
_topMostRecord = TopMostRecordStorage.Instance;
} }
#endregion #endregion
@ -243,13 +254,13 @@ namespace Wox.ViewModel
DisplayNextQueryCommand = new RelayCommand(_ => DisplayNextQueryCommand = new RelayCommand(_ =>
{ {
var nextQuery = QueryHistoryStorage.Instance.Next(); var nextQuery = _queryHistory.Next();
DisplayQueryHistory(nextQuery); DisplayQueryHistory(nextQuery);
}); });
DisplayPrevQueryCommand = new RelayCommand(_ => DisplayPrevQueryCommand = new RelayCommand(_ =>
{ {
var prev = QueryHistoryStorage.Instance.Previous(); var prev = _queryHistory.Previous();
DisplayQueryHistory(prev); DisplayQueryHistory(prev);
}); });
@ -288,8 +299,8 @@ namespace Wox.ViewModel
MainWindowVisibility = Visibility.Collapsed; MainWindowVisibility = Visibility.Collapsed;
} }
UserSelectedRecordStorage.Instance.Add(result); _userSelectedRecord.Add(result);
QueryHistoryStorage.Instance.Add(result.OriginQuery.RawQuery); _queryHistory.Add(result.OriginQuery.RawQuery);
}); });
LoadContextMenuCommand = new RelayCommand(_ => LoadContextMenuCommand = new RelayCommand(_ =>
@ -413,7 +424,19 @@ namespace Wox.ViewModel
} }
}; };
action.Invoke(); action.Invoke();
PluginManager.QueryForAllPlugins(query); var plugins = PluginManager.ValidPluginsForQuery(query);
foreach (var plugin in plugins)
{
var config = _settings.CustomizedPluginConfigs[plugin.Metadata.ID];
if (!config.Disabled)
{
ThreadPool.QueueUserWorkItem(o =>
{
var results = PluginManager.QueryForPlugin(plugin, query);
UpdateResultView(results, plugin.Metadata, query);
});
}
}
} }
IsProgressBarTooltipVisible = false; IsProgressBarTooltipVisible = false;
@ -422,7 +445,7 @@ namespace Wox.ViewModel
private void ResetQueryHistoryIndex() private void ResetQueryHistoryIndex()
{ {
Results.RemoveResultsFor(QueryHistoryStorage.MetaData); Results.RemoveResultsFor(QueryHistoryStorage.MetaData);
QueryHistoryStorage.Instance.Reset(); _queryHistory.Reset();
} }
private void UpdateResultViewInternal(List<Result> list, PluginMetadata metadata) private void UpdateResultViewInternal(List<Result> list, PluginMetadata metadata)
@ -462,14 +485,14 @@ namespace Wox.ViewModel
} }
private Result GetTopMostContextMenu(Result result) private Result GetTopMostContextMenu(Result result)
{ {
if (TopMostRecordStorage.Instance.IsTopMost(result)) if (_topMostRecord.IsTopMost(result))
{ {
return new Result(InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"), "Images\\down.png") return new Result(InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"), "Images\\down.png")
{ {
PluginDirectory = WoxDirectroy.Executable, PluginDirectory = WoxDirectroy.Executable,
Action = _ => Action = _ =>
{ {
TopMostRecordStorage.Instance.Remove(result); _topMostRecord.Remove(result);
App.API.ShowMsg("Succeed"); App.API.ShowMsg("Succeed");
return false; return false;
} }
@ -482,7 +505,7 @@ namespace Wox.ViewModel
PluginDirectory = WoxDirectroy.Executable, PluginDirectory = WoxDirectroy.Executable,
Action = _ => Action = _ =>
{ {
TopMostRecordStorage.Instance.AddOrUpdate(result); _topMostRecord.AddOrUpdate(result);
App.API.ShowMsg("Succeed"); App.API.ShowMsg("Succeed");
return false; return false;
} }
@ -500,7 +523,7 @@ namespace Wox.ViewModel
list.ForEach(o => list.ForEach(o =>
{ {
o.Score += UserSelectedRecordStorage.Instance.GetSelectedCount(o) * 5; o.Score += _userSelectedRecord.GetSelectedCount(o) * 5;
}); });
if (originQuery.RawQuery == _lastQuery.RawQuery) if (originQuery.RawQuery == _lastQuery.RawQuery)
{ {