Skip to content

Test #3508 #3512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Flow.Launcher.Core/Plugin/PluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.DependencyInjection;
using Droplex;
using Flow.Launcher.Core.ExternalPlugins;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.UserSettings;
Expand Down Expand Up @@ -276,31 +277,49 @@ public static ICollection<PluginPair> ValidPluginsForQuery(Query query)

public static async Task<List<Result>> QueryForPluginAsync(PluginPair pair, Query query, CancellationToken token)
{
API.LogDebug(ClassName, $"a");

var results = new List<Result>();
var metadata = pair.Metadata;

try
{
API.LogDebug(ClassName, $"b");

var milliseconds = await API.StopwatchLogDebugAsync(ClassName, $"Cost for {metadata.Name}",
async () => results = await pair.Plugin.QueryAsync(query, token).ConfigureAwait(false));

API.LogDebug(ClassName, $"c");

token.ThrowIfCancellationRequested();

API.LogDebug(ClassName, $"d");

if (results == null)
return null;

API.LogDebug(ClassName, $"e");

UpdatePluginMetadata(results, metadata, query);

API.LogDebug(ClassName, $"f");

metadata.QueryCount += 1;
metadata.AvgQueryTime =
metadata.QueryCount == 1 ? milliseconds : (metadata.AvgQueryTime + milliseconds) / 2;
token.ThrowIfCancellationRequested();

API.LogDebug(ClassName, $"g");
}
catch (OperationCanceledException)
{
// null will be fine since the results will only be added into queue if the token hasn't been cancelled
API.LogDebug(ClassName, $"h");
return null;
}
catch (Exception e)
{
API.LogDebug(ClassName, $"i");
Result r = new()
{
Title = $"{metadata.Name}: Failed to respond!",
Expand All @@ -315,6 +334,7 @@ public static async Task<List<Result>> QueryForPluginAsync(PluginPair pair, Quer
};
results.Add(r);
}
API.LogDebug(ClassName, $"j");
return results;
}

Expand Down
41 changes: 29 additions & 12 deletions Flow.Launcher/ViewModel/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public partial class MainViewModel : BaseModel, ISavable, IDisposable
private bool _isQueryRunning;
private Query _lastQuery;
private string _queryTextBeforeLeaveResults;
private string _ignoredQueryText = null;
private string _ignoredQueryText; // Used to ignore query text change when switching between context menu and query results

private readonly FlowLauncherJsonStorage<History> _historyItemsStorage;
private readonly FlowLauncherJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
Expand All @@ -45,6 +45,7 @@ public partial class MainViewModel : BaseModel, ISavable, IDisposable
private readonly TopMostRecord _topMostRecord;

private CancellationTokenSource _updateSource; // Used to cancel old query flows
private CancellationToken _updateToken; // Used to avoid ObjectDisposedException of _updateSource.Token

private ChannelWriter<ResultsForUpdate> _resultsUpdateChannelWriter;
private Task _resultsViewUpdateTask;
Expand All @@ -60,6 +61,9 @@ public MainViewModel()
_queryTextBeforeLeaveResults = "";
_queryText = "";
_lastQuery = new Query();
_ignoredQueryText = null;
_updateSource = new CancellationTokenSource();
_updateToken = _updateSource.Token;

Settings = Ioc.Default.GetRequiredService<Settings>();
Settings.PropertyChanged += (_, args) =>
Expand Down Expand Up @@ -241,7 +245,7 @@ public void RegisterResultsUpdatedEvent()
return;
}

var token = e.Token == default ? _updateSource.Token : e.Token;
var token = e.Token == default ? _updateToken : e.Token;

// make a clone to avoid possible issue that plugin will also change the list and items when updating view model
var resultsCopy = DeepCloneResults(e.Results, token);
Expand Down Expand Up @@ -1213,7 +1217,7 @@ private void QueryHistory()

private async Task QueryResultsAsync(bool searchDelay, bool isReQuery = false, bool reSelect = true)
{
_updateSource?.Cancel();
_updateSource.Cancel();

App.API.LogDebug(ClassName, $"Start query with text: <{QueryText}>");

Expand All @@ -1239,15 +1243,17 @@ private async Task QueryResultsAsync(bool searchDelay, bool isReQuery = false, b

App.API.LogDebug(ClassName, $"Start query with ActionKeyword <{query.ActionKeyword}> and RawQuery <{query.RawQuery}>");

_updateSource.Dispose();
_updateSource = new CancellationTokenSource();
_updateToken = _updateSource.Token;

ProgressBarVisibility = Visibility.Hidden;
_isQueryRunning = true;

// Switch to ThreadPool thread
await TaskScheduler.Default;

if (_updateSource.Token.IsCancellationRequested) return;
if (_updateToken.IsCancellationRequested) return;

// Update the query's IsReQuery property to true if this is a re-query
query.IsReQuery = isReQuery;
Expand Down Expand Up @@ -1280,28 +1286,27 @@ private async Task QueryResultsAsync(bool searchDelay, bool isReQuery = false, b
{
// Wait 15 millisecond for query change in global query
// if query changes, return so that it won't be calculated
await Task.Delay(15, _updateSource.Token);
if (_updateSource.Token.IsCancellationRequested)
return;
await Task.Delay(15, _updateToken);
if (_updateToken.IsCancellationRequested) return;
}*/

_ = Task.Delay(200, _updateSource.Token).ContinueWith(_ =>
_ = Task.Delay(200, _updateToken).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 (_isQueryRunning)
{
ProgressBarVisibility = Visibility.Visible;
}
},
_updateSource.Token,
_updateToken,
TaskContinuationOptions.NotOnCanceled,
TaskScheduler.Default);

// plugins are ICollection, meaning LINQ will get the Count and preallocate Array

var tasks = plugins.Select(plugin => plugin.Metadata.Disabled switch
{
false => QueryTaskAsync(plugin, _updateSource.Token),
false => QueryTaskAsync(plugin, _updateToken),
true => Task.CompletedTask
}).ToArray();

Expand All @@ -1315,13 +1320,13 @@ private async Task QueryResultsAsync(bool searchDelay, bool isReQuery = false, b
// nothing to do here
}

if (_updateSource.Token.IsCancellationRequested) return;
if (_updateToken.IsCancellationRequested) return;

// this should happen once after all queries are done so progress bar should continue
// until the end of all querying
_isQueryRunning = false;

if (!_updateSource.Token.IsCancellationRequested)
if (!_updateToken.IsCancellationRequested)
{
// update to hidden if this is still the current query
ProgressBarVisibility = Visibility.Hidden;
Expand All @@ -1341,14 +1346,22 @@ async Task QueryTaskAsync(PluginPair plugin, CancellationToken token)
if (token.IsCancellationRequested) return;
}

App.API.LogDebug(ClassName, $"1");

// Since it is wrapped within a ThreadPool Thread, the synchronous context is null
// Task.Yield will force it to run in ThreadPool
await Task.Yield();

App.API.LogDebug(ClassName, $"2");

var results = await PluginManager.QueryForPluginAsync(plugin, query, token);

App.API.LogDebug(ClassName, $"3");

if (token.IsCancellationRequested) return;

App.API.LogDebug(ClassName, $"4");

IReadOnlyList<Result> resultsCopy;
if (results == null)
{
Expand All @@ -1360,6 +1373,8 @@ async Task QueryTaskAsync(PluginPair plugin, CancellationToken token)
resultsCopy = DeepCloneResults(results, token);
}

App.API.LogDebug(ClassName, $"5");

foreach (var result in resultsCopy)
{
if (string.IsNullOrEmpty(result.BadgeIcoPath))
Expand All @@ -1368,6 +1383,8 @@ async Task QueryTaskAsync(PluginPair plugin, CancellationToken token)
}
}

App.API.LogDebug(ClassName, $"6");

if (token.IsCancellationRequested) return;

App.API.LogDebug(ClassName, $"Update results for plugin <{plugin.Metadata.Name}>");
Expand Down
Loading