PowerToys/Wox/ViewModel/MainViewModel.cs

624 lines
20 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2016-02-12 14:21:12 +08:00
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.Updater;
using Wox.Core.UserSettings;
2016-02-26 20:05:32 +08:00
using Wox.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Storage;
using Wox.Plugin;
using Wox.Storage;
namespace Wox.ViewModel
{
public class MainViewModel : BaseViewModel
{
#region Private Fields
private bool _isProgressBarTooltipVisible;
private double _left;
private double _top;
private Visibility _contextMenuVisibility;
private Visibility _progressBarVisibility;
private Visibility _resultListBoxVisibility;
2016-02-26 20:05:32 +08:00
private Visibility _mainWindowVisibility;
private bool _queryHasReturn;
private Query _lastQuery;
private bool _ignoreTextChange;
private string _queryTextBeforeLoadContextMenu;
private string _queryText;
private readonly JsonStrorage<Settings> _settingsStorage;
private readonly JsonStrorage<QueryHistory> _queryHistoryStorage;
private readonly JsonStrorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly JsonStrorage<TopMostRecord> _topMostRecordStorage;
// todo happlebao this field should be private in the future
public readonly Settings _settings;
private readonly QueryHistory _queryHistory;
private readonly UserSelectedRecord _userSelectedRecord;
private readonly TopMostRecord _topMostRecord;
private CancellationTokenSource _updateSource;
private CancellationToken _updateToken;
#endregion
#region Constructor
public MainViewModel()
{
_queryTextBeforeLoadContextMenu = "";
_queryText = "";
_lastQuery = new Query();
_settingsStorage = new JsonStrorage<Settings>();
_settings = _settingsStorage.Load();
// happlebao todo temp fix for instance code logic
HttpProxy.Instance.Settings = _settings;
UpdaterManager.Instance.Settings = _settings;
InternationalizationManager.Instance.Settings = _settings;
ThemeManager.Instance.Settings = _settings;
_queryHistoryStorage = new JsonStrorage<QueryHistory>();
_userSelectedRecordStorage = new JsonStrorage<UserSelectedRecord>();
_topMostRecordStorage = new JsonStrorage<TopMostRecord>();
_queryHistory = _queryHistoryStorage.Load();
_userSelectedRecord = _userSelectedRecordStorage.Load();
_topMostRecord = _topMostRecordStorage.Load();
InitializeResultListBox();
InitializeContextMenu();
InitializeKeyCommands();
}
~MainViewModel()
{
_settingsStorage.Save();
_queryHistoryStorage.Save();
_userSelectedRecordStorage.Save();
_topMostRecordStorage.Save();
}
#endregion
#region ViewModel Properties
public ResultsViewModel Results { get; private set; }
public ResultsViewModel ContextMenu { get; private set; }
public string QueryText
{
get
{
return _queryText;
}
set
{
_queryText = value;
OnPropertyChanged();
if (_ignoreTextChange)
{
_ignoreTextChange = false;
}
else
{
HandleQueryTextUpdated();
}
}
}
public double Left
{
get
{
2016-02-24 10:07:35 +08:00
return _left;
}
set
{
2016-02-24 10:07:35 +08:00
_left = value;
OnPropertyChanged();
}
}
public double Top
{
get
{
2016-02-24 10:07:35 +08:00
return _top;
}
set
{
2016-02-24 10:07:35 +08:00
_top = value;
OnPropertyChanged();
}
}
public Visibility ContextMenuVisibility
{
get
{
2016-02-24 10:07:35 +08:00
return _contextMenuVisibility;
}
set
{
2016-02-24 10:07:35 +08:00
_contextMenuVisibility = value;
OnPropertyChanged();
2016-03-26 11:15:28 +08:00
_ignoreTextChange = true;
if (!value.IsVisible())
{
QueryText = _queryTextBeforeLoadContextMenu;
ResultListBoxVisibility = Visibility.Visible;
OnCursorMovedToEnd();
}
else
{
_queryTextBeforeLoadContextMenu = QueryText;
QueryText = "";
ResultListBoxVisibility = Visibility.Collapsed;
}
}
}
public Visibility ProgressBarVisibility
{
get
{
2016-02-24 10:07:35 +08:00
return _progressBarVisibility;
}
set
{
2016-02-24 10:07:35 +08:00
_progressBarVisibility = value;
OnPropertyChanged();
}
}
public Visibility ResultListBoxVisibility
{
get
{
2016-02-24 10:07:35 +08:00
return _resultListBoxVisibility;
}
set
{
2016-02-24 10:07:35 +08:00
_resultListBoxVisibility = value;
OnPropertyChanged();
}
}
2016-02-26 20:05:32 +08:00
public Visibility MainWindowVisibility
{
get
{
2016-02-26 20:05:32 +08:00
return _mainWindowVisibility;
}
set
{
2016-02-26 20:05:32 +08:00
_mainWindowVisibility = value;
OnPropertyChanged();
2016-02-27 07:43:57 +08:00
MainWindowVisibilityChanged?.Invoke(this, new EventArgs());
}
}
public ICommand EscCommand { get; set; }
public ICommand SelectNextItemCommand { get; set; }
public ICommand SelectPrevItemCommand { get; set; }
public ICommand DisplayNextQueryCommand { get; set; }
public ICommand DisplayPrevQueryCommand { get; set; }
public ICommand SelectNextPageCommand { get; set; }
public ICommand SelectPrevPageCommand { get; set; }
public ICommand StartHelpCommand { get; set; }
public ICommand LoadContextMenuCommand { get; set; }
public ICommand OpenResultCommand { get; set; }
public ICommand BackCommand { get; set; }
#endregion
#region Private Methods
private void InitializeKeyCommands()
{
2016-02-23 05:43:37 +08:00
EscCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
2016-02-24 10:07:35 +08:00
if (ContextMenuVisibility.IsVisible())
{
ContextMenuVisibility = Visibility.Collapsed;
}
else
{
2016-02-26 20:05:32 +08:00
MainWindowVisibility = Visibility.Collapsed;
}
});
2016-02-12 14:21:12 +08:00
2016-02-27 07:43:57 +08:00
SelectNextItemCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
2016-02-24 10:07:35 +08:00
if (ContextMenuVisibility.IsVisible())
2016-02-12 14:21:12 +08:00
{
ContextMenu.SelectNextResult();
2016-02-12 14:21:12 +08:00
}
else
{
Results.SelectNextResult();
2016-02-12 14:21:12 +08:00
}
});
2016-02-23 05:43:37 +08:00
SelectPrevItemCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
2016-02-24 10:07:35 +08:00
if (ContextMenuVisibility.IsVisible())
2016-02-12 14:21:12 +08:00
{
ContextMenu.SelectPrevResult();
2016-02-12 14:21:12 +08:00
}
else
{
Results.SelectPrevResult();
2016-02-12 14:21:12 +08:00
}
});
2016-02-12 14:21:12 +08:00
2016-02-23 05:43:37 +08:00
DisplayNextQueryCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
var nextQuery = _queryHistory.Next();
2016-02-12 14:21:12 +08:00
DisplayQueryHistory(nextQuery);
});
2016-02-23 05:43:37 +08:00
DisplayPrevQueryCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
var prev = _queryHistory.Previous();
2016-02-12 14:21:12 +08:00
DisplayQueryHistory(prev);
});
2016-02-23 05:43:37 +08:00
SelectNextPageCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
Results.SelectNextPage();
2016-02-12 14:21:12 +08:00
});
2016-02-23 05:43:37 +08:00
SelectPrevPageCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
Results.SelectPrevPage();
2016-02-12 14:21:12 +08:00
});
2016-02-23 05:43:37 +08:00
StartHelpCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
2016-02-12 14:21:12 +08:00
Process.Start("http://doc.getwox.com");
});
OpenResultCommand = new RelayCommand(o =>
2016-02-12 17:20:46 +08:00
{
var results = ContextMenuVisibility.IsVisible() ? ContextMenu : Results;
if (o != null)
{
var index = int.Parse(o.ToString());
results.SelectResult(index);
}
var result = results.SelectedResult.RawResult;
bool hideWindow = result.Action(new ActionContext
2016-02-12 14:21:12 +08:00
{
SpecialKeyState = GlobalHotkey.Instance.CheckModifiers()
});
if (hideWindow)
{
MainWindowVisibility = Visibility.Collapsed;
2016-02-12 14:21:12 +08:00
}
if (!ContextMenuVisibility.IsVisible())
{
_userSelectedRecord.Add(result);
_queryHistory.Add(result.OriginQuery.RawQuery);
}
2016-02-12 14:21:12 +08:00
});
LoadContextMenuCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
if (!ContextMenuVisibility.IsVisible())
2016-02-12 14:21:12 +08:00
{
var result = Results.SelectedResult.RawResult;
var id = result.PluginID;
var menus = PluginManager.GetContextMenusForPlugin(result);
menus.Add(ContextMenuTopMost(result));
menus.Add(ContextMenuPluginInfo(id));
ContextMenu.Clear();
ContextMenu.AddResults(menus, id);
ContextMenuVisibility = Visibility.Visible;
}
else
{
ContextMenuVisibility = Visibility.Collapsed;
2016-02-12 14:21:12 +08:00
}
});
2016-02-12 17:20:46 +08:00
2016-02-23 05:43:37 +08:00
BackCommand = new RelayCommand(_ =>
2016-02-12 17:20:46 +08:00
{
2016-02-23 05:43:37 +08:00
ListeningKeyPressed?.Invoke(this, new ListeningKeyPressedEventArgs(_ as KeyEventArgs));
2016-02-12 17:20:46 +08:00
});
}
private void InitializeResultListBox()
{
Results = new ResultsViewModel(_settings, _topMostRecord);
2016-02-24 10:07:35 +08:00
ResultListBoxVisibility = Visibility.Collapsed;
}
private void InitializeContextMenu()
{
ContextMenu = new ResultsViewModel(_settings, _topMostRecord);
2016-02-24 10:07:35 +08:00
ContextMenuVisibility = Visibility.Collapsed;
}
private void HandleQueryTextUpdated()
{
2016-04-25 10:00:55 +08:00
ProgressBarVisibility = Visibility.Hidden;
_updateSource?.Cancel();
_updateSource = new CancellationTokenSource();
_updateToken = _updateSource.Token;
2016-02-24 10:07:35 +08:00
if (ContextMenuVisibility.IsVisible())
{
QueryContextMenu();
}
else
{
string query = QueryText.Trim();
if (!string.IsNullOrEmpty(query))
{
Query(query);
//reset query history index after user start new query
ResetQueryHistoryIndex();
}
else
{
Results.Clear();
ResultListBoxVisibility = Visibility.Collapsed;
}
}
}
private void QueryContextMenu()
{
var contextMenuId = "Context Menu Id";
var query = QueryText.ToLower();
if (!string.IsNullOrEmpty(query))
{
List<Result> filterResults = new List<Result>();
foreach (var contextMenu in ContextMenu.Results)
{
if (StringMatcher.IsMatch(contextMenu.Title, query)
|| StringMatcher.IsMatch(contextMenu.SubTitle, query))
{
filterResults.Add(contextMenu.RawResult);
}
}
ContextMenu.Clear();
ContextMenu.AddResults(filterResults, contextMenuId);
}
}
private void Query(string text)
{
_queryHasReturn = false;
var query = PluginManager.QueryInit(text);
if (query != null)
{
// handle the exclusiveness of plugin using action keyword
string lastKeyword = _lastQuery.ActionKeyword;
string keyword = query.ActionKeyword;
if (string.IsNullOrEmpty(lastKeyword))
{
if (!string.IsNullOrEmpty(keyword))
{
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
}
}
else
{
if (string.IsNullOrEmpty(keyword))
{
Results.RemoveResultsFor(PluginManager.NonGlobalPlugins[lastKeyword].Metadata);
}
else if (lastKeyword != keyword)
{
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
}
}
_lastQuery = query;
Task.Delay(200, _updateToken).ContinueWith(_ =>
{
if (query.RawQuery == _lastQuery.RawQuery && !_queryHasReturn)
{
ProgressBarVisibility = Visibility.Visible;
}
}, _updateToken);
var plugins = PluginManager.ValidPluginsForQuery(query);
foreach (var plugin in plugins)
{
var config = _settings.PluginSettings[plugin.Metadata.ID];
if (!config.Disabled)
{
Task.Factory.StartNew(() =>
{
var results = PluginManager.QueryForPlugin(plugin, query);
UpdateResultView(results, plugin.Metadata, query);
}, _updateToken);
}
}
}
}
private void ResetQueryHistoryIndex()
{
Results.RemoveResultsFor(QueryHistory.MetaData);
_queryHistory.Reset();
}
private void UpdateResultViewInternal(List<Result> list, PluginMetadata metadata)
{
Results.AddResults(list, metadata.ID);
}
2016-02-12 14:21:12 +08:00
private void DisplayQueryHistory(HistoryItem history)
{
if (history != null)
{
var historyMetadata = QueryHistory.MetaData;
2016-02-12 14:21:12 +08:00
QueryText = history.Query;
2016-02-27 07:43:57 +08:00
OnTextBoxSelected();
2016-02-12 14:21:12 +08:00
var executeQueryHistoryTitle = InternationalizationManager.Instance.GetTranslation("executeQuery");
var lastExecuteTime = InternationalizationManager.Instance.GetTranslation("lastExecuteTime");
Results.RemoveResultsExcept(historyMetadata);
2016-02-12 14:21:12 +08:00
UpdateResultViewInternal(new List<Result>
{
new Result
{
Title = string.Format(executeQueryHistoryTitle,history.Query),
SubTitle = string.Format(lastExecuteTime,history.ExecutedDateTime),
IcoPath = "Images\\history.png",
PluginDirectory = Infrastructure.Wox.ProgramPath,
2016-02-12 14:21:12 +08:00
Action = _ =>{
QueryText = history.Query;
2016-02-27 07:43:57 +08:00
OnTextBoxSelected();
2016-02-12 14:21:12 +08:00
return false;
}
}
}, historyMetadata);
}
}
private Result ContextMenuTopMost(Result result)
{
Result menu;
if (_topMostRecord.IsTopMost(result))
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"),
IcoPath = "Images\\down.png",
PluginDirectory = Infrastructure.Wox.ProgramPath,
Action = _ =>
{
_topMostRecord.Remove(result);
App.API.ShowMsg("Succeed");
return false;
}
};
}
else
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("setAsTopMostInThisQuery"),
IcoPath = "Images\\up.png",
PluginDirectory = Infrastructure.Wox.ProgramPath,
Action = _ =>
{
_topMostRecord.AddOrUpdate(result);
App.API.ShowMsg("Succeed");
return false;
}
};
}
return menu;
}
private Result ContextMenuPluginInfo(string id)
{
var metadata = PluginManager.GetPluginForId(id).Metadata;
var translator = InternationalizationManager.Instance;
var author = translator.GetTranslation("author");
var website = translator.GetTranslation("website");
var version = translator.GetTranslation("version");
var plugin = translator.GetTranslation("plugin");
var title = $"{plugin}: {metadata.Name}";
var icon = metadata.IcoPath;
var subtitle = $"{author}: {metadata.Author}, {website}: {metadata.Website} {version}: {metadata.Version}";
var menu = new Result
{
Title = title,
IcoPath = icon,
SubTitle = subtitle,
PluginDirectory = metadata.PluginDirectory,
Action = _ => false
};
return menu;
}
#endregion
#region Public Methods
public void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery)
{
_queryHasReturn = true;
2016-04-25 10:00:55 +08:00
ProgressBarVisibility = Visibility.Hidden;
list.ForEach(o =>
{
o.Score += _userSelectedRecord.GetSelectedCount(o) * 5;
});
if (originQuery.RawQuery == _lastQuery.RawQuery)
{
2016-02-23 05:43:37 +08:00
Application.Current.Dispatcher.Invoke(() =>
2016-02-12 17:20:46 +08:00
{
UpdateResultViewInternal(list, metadata);
});
}
2016-04-25 10:00:55 +08:00
if (list.Count > 0 && !ResultListBoxVisibility.IsVisible())
{
2016-02-24 10:07:35 +08:00
ResultListBoxVisibility = Visibility.Visible;
}
}
#endregion
2016-02-12 17:20:46 +08:00
public event EventHandler<ListeningKeyPressedEventArgs> ListeningKeyPressed;
2016-02-27 07:43:57 +08:00
public event EventHandler MainWindowVisibilityChanged;
public event EventHandler CursorMovedToEnd;
public void OnCursorMovedToEnd()
{
CursorMovedToEnd?.Invoke(this, new EventArgs());
}
public event EventHandler TextBoxSelected;
public void OnTextBoxSelected()
{
TextBoxSelected?.Invoke(this, new EventArgs());
}
2016-02-12 17:20:46 +08:00
}
public class ListeningKeyPressedEventArgs : EventArgs
{
2016-03-24 04:31:59 +08:00
public KeyEventArgs KeyEventArgs { get; private set; }
2016-02-12 17:20:46 +08:00
2016-02-23 05:43:37 +08:00
public ListeningKeyPressedEventArgs(KeyEventArgs keyEventArgs)
2016-02-12 17:20:46 +08:00
{
KeyEventArgs = keyEventArgs;
2016-02-12 17:20:46 +08:00
}
}
}