Flow.Launcher/Flow.Launcher/ViewModel/MainViewModel.cs

732 lines
25 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2016-06-22 23:22:41 +00:00
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using System.Windows;
using System.Windows.Input;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Core.Plugin;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Helper;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Hotkey;
using Flow.Launcher.Infrastructure.Storage;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
2020-04-23 10:10:20 +00:00
using Flow.Launcher.Plugin.SharedCommands;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Storage;
2020-11-16 00:32:11 +00:00
using Flow.Launcher.Infrastructure.Logger;
2021-06-11 04:40:07 +00:00
using Microsoft.VisualStudio.Threading;
2021-02-15 09:58:15 +00:00
using System.Threading.Channels;
2021-06-21 11:56:20 +00:00
using ISavable = Flow.Launcher.Plugin.ISavable;
2021-06-11 04:40:07 +00:00
using System.Windows.Threading;
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.ViewModel
{
2021-06-21 11:56:20 +00:00
public class MainViewModel : BaseModel, ISavable
{
#region Private Fields
2020-05-03 17:17:16 +00:00
private const string DefaultOpenResultModifiers = "Alt";
2019-12-13 22:17:05 +00:00
private bool _isQueryRunning;
private Query _lastQuery;
private string _queryTextBeforeLeaveResults;
2020-04-21 12:16:10 +00:00
private readonly FlowLauncherJsonStorage<History> _historyItemsStorage;
private readonly FlowLauncherJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly FlowLauncherJsonStorage<TopMostRecord> _topMostRecordStorage;
internal readonly Settings _settings;
private readonly History _history;
private readonly UserSelectedRecord _userSelectedRecord;
private readonly TopMostRecord _topMostRecord;
private CancellationTokenSource _updateSource;
private CancellationToken _updateToken;
2019-12-13 22:17:05 +00:00
private readonly Internationalization _translator = InternationalizationManager.Instance;
2021-02-15 18:12:28 +00:00
private ChannelWriter<ResultsForUpdate> _resultsUpdateChannelWriter;
private Task _resultsViewUpdateTask;
#endregion
#region Constructor
2016-05-21 21:44:27 +00:00
public MainViewModel(Settings settings)
{
_queryTextBeforeLeaveResults = "";
_queryText = "";
_lastQuery = new Query();
_settings = settings;
2020-04-21 12:16:10 +00:00
_historyItemsStorage = new FlowLauncherJsonStorage<History>();
_userSelectedRecordStorage = new FlowLauncherJsonStorage<UserSelectedRecord>();
_topMostRecordStorage = new FlowLauncherJsonStorage<TopMostRecord>();
_history = _historyItemsStorage.Load();
_userSelectedRecord = _userSelectedRecordStorage.Load();
_topMostRecord = _topMostRecordStorage.Load();
ContextMenu = new ResultsViewModel(_settings);
Results = new ResultsViewModel(_settings);
History = new ResultsViewModel(_settings);
_selectedResults = Results;
InitializeKeyCommands();
RegisterViewUpdate();
2021-01-26 08:29:06 +00:00
RegisterResultsUpdatedEvent();
2020-05-03 17:17:16 +00:00
SetOpenResultModifiers();
}
private void RegisterViewUpdate()
{
2021-02-15 18:12:28 +00:00
var resultUpdateChannel = Channel.CreateUnbounded<ResultsForUpdate>();
_resultsUpdateChannelWriter = resultUpdateChannel.Writer;
_resultsViewUpdateTask =
Task.Run(updateAction).ContinueWith(continueAction, TaskContinuationOptions.OnlyOnFaulted);
async Task updateAction()
{
var queue = new Dictionary<string, ResultsForUpdate>();
2021-02-15 18:12:28 +00:00
var channelReader = resultUpdateChannel.Reader;
2021-02-15 09:58:15 +00:00
// it is not supposed to be false because it won't be complete
2021-02-15 18:12:28 +00:00
while (await channelReader.WaitToReadAsync())
{
2020-11-21 04:01:57 +00:00
await Task.Delay(20);
2021-02-15 18:12:28 +00:00
while (channelReader.TryRead(out var item))
{
if (!item.Token.IsCancellationRequested)
queue[item.ID] = item;
}
UpdateResultView(queue.Values);
2021-02-15 10:19:30 +00:00
queue.Clear();
}
2021-02-15 09:58:15 +00:00
Log.Error("MainViewModel", "Unexpected ResultViewUpdate ends");
2021-06-11 04:40:07 +00:00
}
;
void continueAction(Task t)
{
#if DEBUG
throw t.Exception;
#else
Log.Error($"Error happen in task dealing with viewupdate for results. {t.Exception}");
2021-06-11 04:40:07 +00:00
_resultsViewUpdateTask =
2021-02-12 03:45:31 +00:00
Task.Run(updateAction).ContinueWith(continueAction, TaskContinuationOptions.OnlyOnFaulted);
#endif
}
}
private void RegisterResultsUpdatedEvent()
{
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
{
2021-01-12 23:35:48 +00:00
var plugin = (IResultUpdated)pair.Plugin;
plugin.ResultsUpdated += (s, e) =>
{
if (e.Query.RawQuery != QueryText || e.Token.IsCancellationRequested)
{
return;
}
var token = e.Token == default ? _updateToken : e.Token;
PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query);
if (!_resultsUpdateChannelWriter.TryWrite(new ResultsForUpdate(e.Results, pair.Metadata, e.Query, token)))
{
Log.Error("MainViewModel", "Unable to add item to Result Update Queue");
2021-01-12 23:35:48 +00:00
}
};
}
}
private void InitializeKeyCommands()
{
2016-02-22 21:43:37 +00:00
EscCommand = new RelayCommand(_ =>
2016-02-12 09:20:46 +00:00
{
if (!SelectedIsFromQueryResults())
{
SelectedResults = Results;
}
else
{
2016-02-26 12:05:32 +00:00
MainWindowVisibility = Visibility.Collapsed;
}
});
2016-02-12 06:21:12 +00:00
SelectNextItemCommand = new RelayCommand(_ => { SelectedResults.SelectNextResult(); });
2016-02-12 06:21:12 +00:00
SelectPrevItemCommand = new RelayCommand(_ => { SelectedResults.SelectPrevResult(); });
2016-02-12 06:21:12 +00:00
SelectNextPageCommand = new RelayCommand(_ => { SelectedResults.SelectNextPage(); });
2016-02-12 06:21:12 +00:00
SelectPrevPageCommand = new RelayCommand(_ => { SelectedResults.SelectPrevPage(); });
2016-02-12 06:21:12 +00:00
SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult());
2016-02-22 21:43:37 +00:00
StartHelpCommand = new RelayCommand(_ =>
2016-02-12 09:20:46 +00:00
{
2020-11-20 14:26:29 +00:00
SearchWeb.NewTabInBrowser("https://github.com/Flow-Launcher/Flow.Launcher/wiki/Flow-Launcher/");
2016-02-12 06:21:12 +00:00
});
2016-05-06 02:24:14 +00:00
OpenResultCommand = new RelayCommand(index =>
2016-02-12 09:20:46 +00:00
{
var results = SelectedResults;
2016-05-06 02:24:14 +00:00
if (index != null)
{
2016-05-06 02:24:14 +00:00
results.SelectedIndex = int.Parse(index.ToString());
}
2016-06-22 23:22:41 +00:00
var result = results.SelectedItem?.Result;
2016-05-06 02:24:14 +00:00
if (result != null) // SelectedItem returns null if selection is empty.
2016-02-12 06:21:12 +00:00
{
bool hideWindow = result.Action != null && result.Action(new ActionContext
2016-05-06 02:24:14 +00:00
{
SpecialKeyState = GlobalHotkey.Instance.CheckModifiers()
});
2016-05-06 02:24:14 +00:00
if (hideWindow)
{
MainWindowVisibility = Visibility.Collapsed;
}
if (SelectedIsFromQueryResults())
2016-05-06 02:24:14 +00:00
{
_userSelectedRecord.Add(result);
_history.Add(result.OriginQuery.RawQuery);
2016-05-06 02:24:14 +00:00
}
else
{
SelectedResults = Results;
}
}
2016-02-12 06:21:12 +00:00
});
LoadContextMenuCommand = new RelayCommand(_ =>
2016-02-12 09:20:46 +00:00
{
if (SelectedIsFromQueryResults())
2016-02-12 06:21:12 +00:00
{
// When switch to ContextMenu from QueryResults, but no item being chosen, should do nothing
// i.e. Shift+Enter/Ctrl+O right after Alt + Space should do nothing
if (SelectedResults.SelectedItem != null)
SelectedResults = ContextMenu;
}
else
{
SelectedResults = Results;
2016-02-12 06:21:12 +00:00
}
});
2016-02-12 09:20:46 +00:00
LoadHistoryCommand = new RelayCommand(_ =>
{
if (SelectedIsFromQueryResults())
{
SelectedResults = History;
History.SelectedIndex = _history.Items.Count - 1;
}
else
{
SelectedResults = Results;
}
});
2021-02-12 03:45:31 +00:00
ReloadPluginDataCommand = new RelayCommand(_ =>
{
2021-06-11 04:40:07 +00:00
var msg = new Msg
{
Owner = Application.Current.MainWindow
};
2021-02-12 03:45:31 +00:00
MainWindowVisibility = Visibility.Collapsed;
PluginManager
2021-06-11 04:40:07 +00:00
.ReloadData()
.ContinueWith(_ =>
Application.Current.Dispatcher.Invoke(() =>
{
msg.Show(
InternationalizationManager.Instance.GetTranslation("success"),
InternationalizationManager.Instance.GetTranslation("completedSuccessfully"),
"");
}))
.ConfigureAwait(false);
2021-02-12 03:45:31 +00:00
});
}
#endregion
#region ViewModel Properties
public ResultsViewModel Results { get; private set; }
public ResultsViewModel ContextMenu { get; private set; }
public ResultsViewModel History { get; private set; }
private string _queryText;
public string QueryText
{
get => _queryText;
set
{
_queryText = value;
Query();
}
}
2020-05-04 22:41:24 +00:00
2016-07-20 22:37:06 +00:00
/// <summary>
/// we need move cursor to end when we manually changed query
/// but we don't want to move cursor to end when query is updated from TextBox
/// </summary>
/// <param name="queryText"></param>
public void ChangeQueryText(string queryText)
{
QueryTextCursorMovedToEnd = true;
QueryText = queryText;
}
public bool LastQuerySelected { get; set; }
2016-07-20 22:37:06 +00:00
public bool QueryTextCursorMovedToEnd { get; set; }
private ResultsViewModel _selectedResults;
private ResultsViewModel SelectedResults
{
get { return _selectedResults; }
set
{
_selectedResults = value;
if (SelectedIsFromQueryResults())
{
ContextMenu.Visbility = Visibility.Collapsed;
History.Visbility = Visibility.Collapsed;
2016-07-20 22:37:06 +00:00
ChangeQueryText(_queryTextBeforeLeaveResults);
}
else
{
Results.Visbility = Visibility.Collapsed;
_queryTextBeforeLeaveResults = QueryText;
// Because of Fody's optimization
// setter won't be called when property value is not changed.
// so we need manually call Query()
// http://stackoverflow.com/posts/25895769/revisions
if (string.IsNullOrEmpty(QueryText))
{
Query();
}
else
{
QueryText = string.Empty;
}
}
_selectedResults.Visbility = Visibility.Visible;
}
}
2016-05-23 21:17:38 +00:00
public Visibility ProgressBarVisibility { get; set; }
2016-05-23 21:17:38 +00:00
public Visibility MainWindowVisibility { get; set; }
public ICommand EscCommand { get; set; }
public ICommand SelectNextItemCommand { get; set; }
public ICommand SelectPrevItemCommand { get; set; }
public ICommand SelectNextPageCommand { get; set; }
public ICommand SelectPrevPageCommand { get; set; }
public ICommand SelectFirstResultCommand { get; set; }
public ICommand StartHelpCommand { get; set; }
public ICommand LoadContextMenuCommand { get; set; }
public ICommand LoadHistoryCommand { get; set; }
public ICommand OpenResultCommand { get; set; }
2021-02-12 03:45:31 +00:00
public ICommand ReloadPluginDataCommand { get; set; }
2020-05-03 17:17:16 +00:00
public string OpenResultCommandModifiers { get; private set; }
2021-01-06 02:34:08 +00:00
public string Image => Constant.QueryTextBoxIconImagePath;
2020-05-04 22:41:24 +00:00
#endregion
public void Query()
{
if (SelectedIsFromQueryResults())
{
QueryResults();
}
else if (ContextMenuSelected())
{
QueryContextMenu();
}
else if (HistorySelected())
{
QueryHistory();
}
}
private void QueryContextMenu()
{
const string id = "Context Menu ID";
var query = QueryText.ToLower().Trim();
ContextMenu.Clear();
var selected = Results.SelectedItem?.Result;
if (selected != null) // SelectedItem returns null if selection is empty.
{
var results = PluginManager.GetContextMenusForPlugin(selected);
results.Add(ContextMenuTopMost(selected));
results.Add(ContextMenuPluginInfo(selected.PluginID));
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
2021-01-17 10:10:36 +00:00
r =>
{
var match = StringMatcher.FuzzySearch(query, r.Title);
if (!match.IsSearchPrecisionScoreMet())
{
match = StringMatcher.FuzzySearch(query, r.SubTitle);
}
if (!match.IsSearchPrecisionScoreMet()) return false;
2021-01-17 10:10:36 +00:00
r.Score = match.Score;
return true;
}).ToList();
ContextMenu.AddResults(filtered, id);
}
else
{
ContextMenu.AddResults(results, id);
}
}
}
private void QueryHistory()
{
const string id = "Query History ID";
var query = QueryText.ToLower().Trim();
History.Clear();
var results = new List<Result>();
foreach (var h in _history.Items)
{
var title = _translator.GetTranslation("executeQuery");
var time = _translator.GetTranslation("lastExecuteTime");
var result = new Result
{
Title = string.Format(title, h.Query),
SubTitle = string.Format(time, h.ExecutedDateTime),
IcoPath = "Images\\history.png",
2021-06-11 04:40:07 +00:00
OriginQuery = new Query
{
RawQuery = h.Query
},
Action = _ =>
{
SelectedResults = Results;
2016-07-20 22:37:06 +00:00
ChangeQueryText(h.Query);
return false;
}
};
results.Add(result);
}
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
2019-09-29 05:17:40 +00:00
r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet() ||
StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
).ToList();
History.AddResults(filtered, id);
}
else
{
History.AddResults(results, id);
}
}
2021-06-11 04:40:07 +00:00
private readonly IReadOnlyList<Result> _emptyResult = new List<Result>();
2021-06-11 04:40:07 +00:00
private async void QueryResults()
{
_updateSource?.Cancel();
if (string.IsNullOrWhiteSpace(QueryText))
{
Results.Clear();
Results.Visbility = Visibility.Collapsed;
return;
}
_updateSource?.Dispose();
var currentUpdateSource = new CancellationTokenSource();
_updateSource = currentUpdateSource;
var currentCancellationToken = _updateSource.Token;
_updateToken = currentCancellationToken;
ProgressBarVisibility = Visibility.Hidden;
_isQueryRunning = true;
// Switch to ThreadPool thread
await TaskScheduler.Default;
if (currentCancellationToken.IsCancellationRequested)
return;
var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
// handle the exclusiveness of plugin using action keyword
RemoveOldQueryResults(query);
_lastQuery = query;
var plugins = PluginManager.ValidPluginsForQuery(query);
2021-06-11 04:40:07 +00:00
if (query.ActionKeyword == Plugin.Query.GlobalPluginWildcardSign)
{
// Wait 45 millisecond for query change in global query
// if query changes, return so that it won't be calculated
await Task.Delay(45, currentCancellationToken);
if (currentCancellationToken.IsCancellationRequested)
return;
}
_ = Task.Delay(200, currentCancellationToken).ContinueWith(_ =>
{
// start the progress bar if query takes more than 200 ms and this is the current running query and it didn't finish yet
if (!currentCancellationToken.IsCancellationRequested && _isQueryRunning)
{
2021-06-11 04:40:07 +00:00
ProgressBarVisibility = Visibility.Visible;
}
}, currentCancellationToken, TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default);
2019-12-03 22:15:46 +00:00
2021-06-11 04:40:07 +00:00
// plugins is ICollection, meaning LINQ will get the Count and preallocate Array
2021-06-11 04:40:07 +00:00
var tasks = plugins.Select(plugin => plugin.Metadata.Disabled switch
{
false => QueryTask(plugin),
true => Task.CompletedTask
}).ToArray();
2019-12-03 22:15:46 +00:00
2021-06-11 04:40:07 +00:00
try
{
// Check the code, WhenAll will translate all type of IEnumerable or Collection to Array, so make an array at first
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
{
// nothing to do here
}
2021-01-10 03:13:46 +00:00
2021-06-11 04:40:07 +00:00
if (currentCancellationToken.IsCancellationRequested)
return;
2021-06-11 04:40:07 +00:00
// this should happen once after all queries are done so progress bar should continue
// until the end of all querying
_isQueryRunning = false;
if (!currentCancellationToken.IsCancellationRequested)
{
// update to hidden if this is still the current query
ProgressBarVisibility = Visibility.Hidden;
}
2021-06-11 04:40:07 +00:00
// Local function
async Task QueryTask(PluginPair plugin)
{
// Since it is wrapped within a ThreadPool Thread, the synchronous context is null
2021-06-11 04:40:07 +00:00
// Task.Yield will force it to run in ThreadPool
await Task.Yield();
2021-06-11 04:40:07 +00:00
IReadOnlyList<Result> results = await PluginManager.QueryForPluginAsync(plugin, query, currentCancellationToken);
2021-06-11 04:40:07 +00:00
currentCancellationToken.ThrowIfCancellationRequested();
2021-06-11 04:40:07 +00:00
results ??= _emptyResult;
if (!_resultsUpdateChannelWriter.TryWrite(new ResultsForUpdate(results, plugin.Metadata, query, currentCancellationToken)))
{
Log.Error("MainViewModel", "Unable to add item to Result Update Queue");
}
}
2016-02-12 06:21:12 +00:00
}
2019-12-13 22:17:05 +00:00
private void RemoveOldQueryResults(Query query)
{
2021-06-06 06:31:47 +00:00
if (_lastQuery.ActionKeyword != query.ActionKeyword)
2019-12-13 22:17:05 +00:00
{
Results.Clear();
2019-12-13 22:17:05 +00:00
}
}
private Result ContextMenuTopMost(Result result)
{
Result menu;
if (_topMostRecord.IsTopMost(result))
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"),
IcoPath = "Images\\down.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.Remove(result);
2019-08-21 10:18:20 +00:00
App.API.ShowMsg("Success");
return false;
}
};
}
else
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("setAsTopMostInThisQuery"),
IcoPath = "Images\\up.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.AddOrUpdate(result);
2019-08-21 10:18:20 +00:00
App.API.ShowMsg("Success");
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;
}
private bool SelectedIsFromQueryResults()
{
var selected = SelectedResults == Results;
return selected;
}
private bool ContextMenuSelected()
{
var selected = SelectedResults == ContextMenu;
return selected;
}
private bool HistorySelected()
{
var selected = SelectedResults == History;
return selected;
}
#region Hotkey
2020-05-03 17:17:16 +00:00
private void SetOpenResultModifiers()
{
OpenResultCommandModifiers = _settings.OpenResultModifiers ?? DefaultOpenResultModifiers;
}
internal void ToggleFlowLauncher()
{
if (MainWindowVisibility != Visibility.Visible)
{
MainWindowVisibility = Visibility.Visible;
}
else
{
MainWindowVisibility = Visibility.Collapsed;
}
}
#endregion
#region Public Methods
public void Save()
{
_historyItemsStorage.Save();
_userSelectedRecordStorage.Save();
_topMostRecordStorage.Save();
}
/// <summary>
/// To avoid deadlock, this method should not called from main thread
/// </summary>
public void UpdateResultView(IEnumerable<ResultsForUpdate> resultsForUpdates)
{
2020-11-16 00:32:11 +00:00
if (!resultsForUpdates.Any())
return;
CancellationToken token;
try
{
// Don't know why sometimes even resultsForUpdates is empty, the method won't return;
token = resultsForUpdates.Select(r => r.Token).Distinct().SingleOrDefault();
}
#if DEBUG
catch
{
throw new ArgumentException("Unacceptable token");
}
#else
catch
{
token = default;
}
#endif
2020-11-16 00:32:11 +00:00
2021-01-13 01:43:15 +00:00
foreach (var metaResults in resultsForUpdates)
{
2021-01-13 01:43:15 +00:00
foreach (var result in metaResults.Results)
{
2021-01-13 01:43:15 +00:00
if (_topMostRecord.IsTopMost(result))
{
result.Score = int.MaxValue;
}
else
{
var priorityScore = metaResults.Metadata.Priority * 150;
result.Score += _userSelectedRecord.GetSelectedCount(result) + priorityScore;
2021-01-13 01:43:15 +00:00
}
}
}
2020-11-16 11:20:52 +00:00
Results.AddResults(resultsForUpdates, token);
}
#endregion
2016-02-12 09:20:46 +00:00
}
2019-12-13 22:17:05 +00:00
}