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)
{
this.context = context;
this.context.API.BackKeyDownEvent += ApiBackKeyDownEvent;
InitialDriverList();
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)
{
string input = query.Search.ToLower();

View File

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

View File

@@ -63,12 +63,10 @@ namespace Wox.Core.Plugin
/// <summary>
/// Load and init all Wox plugins
/// </summary>
public static void Init(IPublicAPI api)
///
public static void Initialize()
{
if (api == null) throw new WoxFatalException("api is null");
SetupPluginDirectories();
API = api;
var metadatas = PluginConfig.Parse(PluginDirectories);
AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)).
@@ -76,7 +74,11 @@ namespace Wox.Core.Plugin
//load plugin i18n languages
ResourceMerger.UpdatePluginLanguages();
}
public static void InitializePlugins(IPublicAPI api)
{
API = api;
foreach (PluginPair pluginPair in AllPlugins)
{
PluginPair pair = pluginPair;
@@ -98,7 +100,6 @@ namespace Wox.Core.Plugin
ThreadPool.QueueUserWorkItem(o =>
{
InstantQueryPlugins = GetPluginsForInterface<IInstantQuery>();
_contextMenuPlugins = GetPluginsForInterface<IContextMenu>();
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) ?
new List<PluginPair> { NonGlobalPlugins[query.ActionKeyword] } : GlobalPlugins;
foreach (var plugin in pluginPairs)
if (NonGlobalPlugins.ContainsKey(query.ActionKeyword))
{
var customizedPluginConfig = UserSettingStorage.Instance.
CustomizedPluginConfigs[plugin.Metadata.ID];
if (customizedPluginConfig.Disabled) continue;
if (IsInstantQueryPlugin(plugin))
{
Stopwatch.Normal($"Instant QueryForPlugin for {plugin.Metadata.Name}", () =>
{
QueryForPlugin(plugin, query);
});
}
else
{
ThreadPool.QueueUserWorkItem(state =>
{
Stopwatch.Normal($"Normal QueryForPlugin for {plugin.Metadata.Name}", () =>
{
QueryForPlugin(plugin, query);
});
});
}
var plugin = NonGlobalPlugins[query.ActionKeyword];
return new List<PluginPair> { plugin };
}
else
{
return GlobalPlugins;
}
}
private static void QueryForPlugin(PluginPair pair, Query query)
public static List<Result> QueryForPlugin(PluginPair pair, Query query)
{
var results = new List<Result>();
try
{
List<Result> results = new List<Result>();
var milliseconds = Stopwatch.Normal($"Plugin.Query cost for {pair.Metadata.Name}", () =>
{
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.AvgQueryTime = pair.QueryCount == 1 ? milliseconds : (pair.AvgQueryTime + milliseconds) / 2;
API.PushResults(query, pair.Metadata, results);
}
catch (Exception e)
{
throw new WoxPluginException(pair.Metadata.Name, $"QueryForPlugin failed", e);
}
return results;
}
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
{
@@ -13,6 +14,7 @@ namespace Wox.Plugin
/// <param name="query"></param>
/// <param name="plugin"></param>
/// <param name="results"></param>
[Obsolete("This method will be removed in Wox 1.3")]
void PushResults(Query query, PluginMetadata plugin, List<Result> results);
/// <summary>
@@ -99,11 +101,6 @@ namespace Wox.Plugin
/// <returns></returns>
List<PluginPair> GetAllPlugins();
/// <summary>
/// Fired after Back key down in the Wox query box
/// </summary>
event WoxKeyDownEventHandler BackKeyDownEvent;
/// <summary>
/// Fired after global keyboard events
/// 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]
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.QueueUserWorkItem(_ => { ImageLoader.ImageLoader.PreloadImages(); });
MainViewModel mainVM = new MainViewModel();
PluginManager.Initialize();
UserSettingStorage settings = UserSettingStorage.Instance;
MainViewModel mainVM = new MainViewModel(settings);
API = new PublicAPIInstance(mainVM);
PluginManager.InitializePlugins(API);
Window = new MainWindow {DataContext = mainVM};
NotifyIconManager notifyIconManager = new NotifyIconManager(API);
PluginManager.Init(API);
CommandArgsFactory.Execute(e.Args.ToList());
// 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="pluginDirectory">Plugin Directory</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>
<!--Setting Theme-->

View File

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

View File

@@ -126,7 +126,7 @@
<TextBlock Margin="5 0 0 0" ToolTip="Change Action Keywords" Cursor="Hand"
MouseUp="PluginActionKeywords_OnMouseUp" Foreground="Blue" Text="keys"
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 HorizontalAlignment="Right" Cursor="Hand"
MouseUp="tbOpenPluginDirecoty_MouseUp" Foreground="Blue"

View File

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