Merge remote-tracking branch 'origin/dev' into add_quickaccess_actionkeyword

This commit is contained in:
Jeremy 2021-09-15 21:15:33 +10:00
commit dd6b8f8c47
13 changed files with 100 additions and 164 deletions

View file

@ -40,15 +40,7 @@ namespace Flow.Launcher.Core.Plugin
public List<Result> LoadContextMenus(Result selectedResult)
{
var output = ExecuteContextMenu(selectedResult);
try
{
return DeserializedResult(output);
}
catch (Exception e)
{
Log.Exception($"|JsonRPCPlugin.LoadContextMenus|Exception on result <{selectedResult}>", e);
return null;
}
return DeserializedResult(output);
}
private static readonly JsonSerializerOptions options = new()
@ -65,23 +57,10 @@ namespace Flow.Launcher.Core.Plugin
{
if (output == Stream.Null) return null;
try
{
var queryResponseModel =
await JsonSerializer.DeserializeAsync<JsonRPCQueryResponseModel>(output, options);
var queryResponseModel =
await JsonSerializer.DeserializeAsync<JsonRPCQueryResponseModel>(output, options);
return ParseResults(queryResponseModel);
}
catch (JsonException e)
{
Log.Exception(GetType().FullName, "Unexpected Json Input", e);
}
finally
{
await output.DisposeAsync();
}
return null;
return ParseResults(queryResponseModel);
}
private List<Result> DeserializedResult(string output)
@ -249,7 +228,7 @@ namespace Flow.Launcher.Core.Plugin
await using var source = process.StandardOutput.BaseStream;
var buffer = BufferManager.GetStream();
token.Register(() =>
{
// ReSharper disable once AccessToModifiedClosure
@ -274,6 +253,14 @@ namespace Flow.Launcher.Core.Plugin
token.ThrowIfCancellationRequested();
if (buffer.Length == 0)
{
var errorMessage = process.StandardError.EndOfStream ?
"Empty JSONRPC Response" :
await process.StandardError.ReadToEndAsync();
throw new InvalidDataException($"{context.CurrentPluginMetadata.Name}|{errorMessage}");
}
if (!process.StandardError.EndOfStream)
{
using var standardError = process.StandardError;
@ -281,23 +268,12 @@ namespace Flow.Launcher.Core.Plugin
if (!string.IsNullOrEmpty(error))
{
Log.Error($"|JsonRPCPlugin.ExecuteAsync|{error}");
return Stream.Null;
Log.Error($"|{context.CurrentPluginMetadata.Name}.{nameof(ExecuteAsync)}|{error}");
}
Log.Error("|JsonRPCPlugin.ExecuteAsync|Empty standard output and standard error.");
return Stream.Null;
}
return buffer;
}
catch (Exception e)
{
Log.Exception(
$"|JsonRPCPlugin.ExecuteAsync|Exception for filename <{startInfo.FileName}> with argument <{startInfo.Arguments}>",
e);
return Stream.Null;
}
finally
{
process?.Dispose();
@ -307,20 +283,8 @@ namespace Flow.Launcher.Core.Plugin
public async Task<List<Result>> QueryAsync(Query query, CancellationToken token)
{
try
{
var output = await ExecuteQueryAsync(query, token);
return await DeserializedResultAsync(output);
}
catch (OperationCanceledException)
{
return null;
}
catch (Exception e)
{
Log.Exception($"|JsonRPCPlugin.Query|Exception when query <{query}>", e);
return null;
}
var output = await ExecuteQueryAsync(query, token);
return await DeserializedResultAsync(output);
}
public virtual Task InitAsync(PluginInitContext context)
@ -329,4 +293,4 @@ namespace Flow.Launcher.Core.Plugin
return Task.CompletedTask;
}
}
}
}

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
@ -26,7 +27,8 @@ namespace Flow.Launcher.Infrastructure.Image
private const int MaxCached = 50;
public ConcurrentDictionary<string, ImageUsage> Data { get; private set; } = new ConcurrentDictionary<string, ImageUsage>();
private const int permissibleFactor = 2;
private SemaphoreSlim semaphore = new(1, 1);
public void Initialization(Dictionary<string, int> usage)
{
foreach (var key in usage.Keys)
@ -60,20 +62,29 @@ namespace Flow.Launcher.Infrastructure.Image
}
);
// To prevent the dictionary from drastically increasing in size by caching images, the dictionary size is not allowed to grow more than the permissibleFactor * maxCached size
// This is done so that we don't constantly perform this resizing operation and also maintain the image cache size at the same time
if (Data.Count > permissibleFactor * MaxCached)
SliceExtra();
async void SliceExtra()
{
// To delete the images from the data dictionary based on the resizing of the Usage Dictionary.
foreach (var key in Data.OrderBy(x => x.Value.usage).Take(Data.Count - MaxCached).Select(x => x.Key))
Data.TryRemove(key, out _);
// To prevent the dictionary from drastically increasing in size by caching images, the dictionary size is not allowed to grow more than the permissibleFactor * maxCached size
// This is done so that we don't constantly perform this resizing operation and also maintain the image cache size at the same time
if (Data.Count > permissibleFactor * MaxCached)
{
await semaphore.WaitAsync().ConfigureAwait(false);
// To delete the images from the data dictionary based on the resizing of the Usage Dictionary
// Double Check to avoid concurrent remove
if (Data.Count > permissibleFactor * MaxCached)
foreach (var key in Data.OrderBy(x => x.Value.usage).Take(Data.Count - MaxCached).Select(x => x.Key).ToArray())
Data.TryRemove(key, out _);
semaphore.Release();
}
}
}
}
public bool ContainsKey(string key)
{
return Data.ContainsKey(key) && Data[key].imageSource != null;
return key is not null && Data.ContainsKey(key) && Data[key].imageSource != null;
}
public int CacheSize()

View file

@ -42,7 +42,7 @@
<ColumnDefinition Width="0" />
</Grid.ColumnDefinitions>
<Image x:Name="ImageIcon" Width="32" Height="32" HorizontalAlignment="Left"
Source="{Binding Image.Value}" />
Source="{Binding Image}" />
<Grid Margin="5 0 5 0" Grid.Column="1" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition />

View file

@ -11,62 +11,12 @@ namespace Flow.Launcher.ViewModel
{
public class ResultViewModel : BaseModel
{
public class LazyAsync<T> : Lazy<ValueTask<T>>
{
private readonly T defaultValue;
private readonly Action _updateCallback;
public new T Value
{
get
{
if (!IsValueCreated)
{
_ = Exercute(); // manually use callback strategy
return defaultValue;
}
if (!base.Value.IsCompletedSuccessfully)
return defaultValue;
return base.Value.Result;
// If none of the variables captured by the local function are captured by other lambdas,
// the compiler can avoid heap allocations.
async ValueTask Exercute()
{
await base.Value.ConfigureAwait(false);
_updateCallback();
}
}
}
public LazyAsync(Func<ValueTask<T>> factory, T defaultValue, Action updateCallback) : base(factory)
{
if (defaultValue != null)
{
this.defaultValue = defaultValue;
}
_updateCallback = updateCallback;
}
}
public ResultViewModel(Result result, Settings settings)
{
if (result != null)
{
Result = result;
Image = new LazyAsync<ImageSource>(
SetImage,
ImageLoader.DefaultImage,
() =>
{
OnPropertyChanged(nameof(Image));
});
}
}
Settings = settings;
}
@ -85,44 +35,55 @@ namespace Flow.Launcher.ViewModel
? Result.SubTitle
: Result.SubTitleToolTip;
public LazyAsync<ImageSource> Image { get; set; }
private volatile bool ImageLoaded;
private async ValueTask<ImageSource> SetImage()
private ImageSource image = ImageLoader.DefaultImage;
public ImageSource Image
{
get
{
if (!ImageLoaded)
{
ImageLoaded = true;
_ = LoadImageAsync();
}
return image;
}
private set => image = value;
}
private async ValueTask LoadImageAsync()
{
var imagePath = Result.IcoPath;
if (string.IsNullOrEmpty(imagePath) && Result.Icon != null)
{
try
{
return Result.Icon();
image = Result.Icon();
return;
}
catch (Exception e)
{
Log.Exception($"|ResultViewModel.Image|IcoPath is empty and exception when calling Icon() for result <{Result.Title}> of plugin <{Result.PluginDirectory}>", e);
return ImageLoader.DefaultImage;
}
}
if (ImageLoader.CacheContainImage(imagePath))
{
// will get here either when icoPath has value\icon delegate is null\when had exception in delegate
return ImageLoader.Load(imagePath);
image = ImageLoader.Load(imagePath);
return;
}
return await Task.Run(() => ImageLoader.Load(imagePath));
// We need to modify the property not field here to trigger the OnPropertyChanged event
Image = await Task.Run(() => ImageLoader.Load(imagePath)).ConfigureAwait(false);
}
public Result Result { get; }
public override bool Equals(object obj)
{
var r = obj as ResultViewModel;
if (r != null)
{
return Result.Equals(r.Result);
}
else
{
return false;
}
return obj is ResultViewModel r && Result.Equals(r.Result);
}
public override int GetHashCode()

View file

@ -52,7 +52,7 @@ namespace Flow.Launcher.Plugin.Explorer.Search
},
Score = score,
TitleToolTip = Constants.ToolTipOpenDirectory,
SubTitleToolTip = Constants.ToolTipOpenDirectory,
SubTitleToolTip = path,
ContextData = new SearchResult
{
Type = ResultType.Folder,
@ -144,7 +144,7 @@ namespace Flow.Launcher.Plugin.Explorer.Search
return true;
},
TitleToolTip = Constants.ToolTipOpenContainingFolder,
SubTitleToolTip = Constants.ToolTipOpenContainingFolder,
SubTitleToolTip = filePath,
ContextData = new SearchResult
{
Type = ResultType.File,

View file

@ -88,9 +88,10 @@ namespace Flow.Launcher.Plugin.Explorer.Search
keyword == Settings.SearchActionKeyword,
Settings.ActionKeyword.PathSearchActionKeyword => Settings.PathSearchKeywordEnabled &&
keyword == Settings.PathSearchActionKeyword,
Settings.ActionKeyword.FileContentSearchActionKeyword => keyword == Settings.FileContentSearchActionKeyword,
Settings.ActionKeyword.IndexSearchActionKeyword => Settings.IndexOnlySearchKeywordEnabled &&
keyword == Settings.IndexSearchActionKeyword,
Settings.ActionKeyword.FileContentSearchActionKeyword => Settings.FileContentSearchKeywordEnabled &&
keyword == Settings.FileContentSearchActionKeyword,
Settings.ActionKeyword.IndexSearchActionKeyword => Settings.IndexSearchKeywordEnabled &&
keyword == Settings.IndexSearchActionKeyword,
Settings.ActionKeyword.QuickAccessActionKeyword => Settings.QuickAccessKeywordEnabled &&
keyword == Settings.QuickAccessActionKeyword
};

View file

@ -1,9 +1,7 @@
using Flow.Launcher.Plugin.Explorer.Search;
using Flow.Launcher.Plugin.Explorer.Search.QuickAccessLinks;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using System;
using System.Collections.Generic;
using System.IO;
namespace Flow.Launcher.Plugin.Explorer
{
@ -26,13 +24,15 @@ namespace Flow.Launcher.Plugin.Explorer
public string FileContentSearchActionKeyword { get; set; } = Constants.DefaultContentSearchActionKeyword;
public bool FileContentSearchKeywordEnabled { get; set; } = true;
public string PathSearchActionKeyword { get; set; } = Query.GlobalPluginWildcardSign;
public bool PathSearchKeywordEnabled { get; set; }
public string IndexSearchActionKeyword { get; set; } = Query.GlobalPluginWildcardSign;
public bool IndexOnlySearchKeywordEnabled { get; set; }
public bool IndexSearchKeywordEnabled { get; set; }
public string QuickAccessActionKeyword { get; set; } = Query.GlobalPluginWildcardSign;
@ -55,7 +55,8 @@ namespace Flow.Launcher.Plugin.Explorer
ActionKeyword.PathSearchActionKeyword => PathSearchActionKeyword,
ActionKeyword.FileContentSearchActionKeyword => FileContentSearchActionKeyword,
ActionKeyword.IndexSearchActionKeyword => IndexSearchActionKeyword,
ActionKeyword.QuickAccessActionKeyword => QuickAccessActionKeyword
ActionKeyword.QuickAccessActionKeyword => QuickAccessActionKeyword,
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "ActionKeyWord property not found")
};
internal void SetActionKeyword(ActionKeyword actionKeyword, string keyword) => _ = actionKeyword switch
@ -65,25 +66,27 @@ namespace Flow.Launcher.Plugin.Explorer
ActionKeyword.FileContentSearchActionKeyword => FileContentSearchActionKeyword = keyword,
ActionKeyword.IndexSearchActionKeyword => IndexSearchActionKeyword = keyword,
ActionKeyword.QuickAccessActionKeyword => QuickAccessActionKeyword = keyword,
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "Unexpected property")
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "ActionKeyWord property not found")
};
internal bool? GetActionKeywordEnabled(ActionKeyword actionKeyword) => actionKeyword switch
internal bool GetActionKeywordEnabled(ActionKeyword actionKeyword) => actionKeyword switch
{
ActionKeyword.SearchActionKeyword => SearchActionKeywordEnabled,
ActionKeyword.PathSearchActionKeyword => PathSearchKeywordEnabled,
ActionKeyword.IndexSearchActionKeyword => IndexOnlySearchKeywordEnabled,
ActionKeyword.IndexSearchActionKeyword => IndexSearchKeywordEnabled,
ActionKeyword.FileContentSearchActionKeyword => FileContentSearchKeywordEnabled,
ActionKeyword.QuickAccessActionKeyword => QuickAccessKeywordEnabled,
_ => null
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "ActionKeyword enabled status not defined")
};
internal void SetActionKeywordEnabled(ActionKeyword actionKeyword, bool enable) => _ = actionKeyword switch
{
ActionKeyword.SearchActionKeyword => SearchActionKeywordEnabled = enable,
ActionKeyword.PathSearchActionKeyword => PathSearchKeywordEnabled = enable,
ActionKeyword.IndexSearchActionKeyword => IndexOnlySearchKeywordEnabled = enable,
ActionKeyword.IndexSearchActionKeyword => IndexSearchKeywordEnabled = enable,
ActionKeyword.FileContentSearchActionKeyword => FileContentSearchKeywordEnabled = enable,
ActionKeyword.QuickAccessActionKeyword => QuickAccessKeywordEnabled = enable,
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "Unexpected property")
_ => throw new ArgumentOutOfRangeException(nameof(actionKeyword), actionKeyword, "ActionKeyword enabled status not defined")
};
}
}

View file

@ -30,8 +30,7 @@
<CheckBox Name="ChkActionKeywordEnabled" ToolTip="{DynamicResource plugin_explorer_actionkeyword_enabled_tooltip}"
Margin="10" Grid.Row="0" Grid.Column="2" Content="{DynamicResource plugin_explorer_actionkeyword_enabled}"
Width="auto"
VerticalAlignment="Center" IsChecked="{Binding Enabled}"
Visibility="{Binding Visible}"/>
VerticalAlignment="Center" IsChecked="{Binding Enabled}" />
<Button Name="DownButton"
Click="OnDoneButtonClick" Grid.Row="1" Grid.Column="2"
Margin="10 0 10 0" Width="80" Height="35"

View file

@ -19,22 +19,18 @@ namespace Flow.Launcher.Plugin.Explorer.Views
public string ActionKeyword
{
get => _actionKeyword;
get => actionKeyword;
set
{
// Set Enable to be true if user change ActionKeyword
if (Enabled is not null)
Enabled = true;
_actionKeyword = value;
Enabled = true;
actionKeyword = value;
}
}
public bool? Enabled { get; set; }
public bool Enabled { get; set; }
private string _actionKeyword;
public Visibility Visible =>
CurrentActionKeyword.Enabled is not null ? Visibility.Visible : Visibility.Collapsed;
private string actionKeyword;
public ActionKeywordSetting(SettingsViewModel settingsViewModel,
ActionKeywordView selectedActionKeyword)
@ -76,8 +72,7 @@ namespace Flow.Launcher.Plugin.Explorer.Views
var oldActionKeyword = CurrentActionKeyword.Keyword;
// == because of nullable
if (Enabled == false || !settingsViewModel.IsActionKeywordAlreadyAssigned(ActionKeyword))
if (!Enabled || !settingsViewModel.IsActionKeywordAlreadyAssigned(ActionKeyword))
{
// Update View Data
CurrentActionKeyword.Keyword = Enabled == true ? ActionKeyword : Query.GlobalPluginWildcardSign;

View file

@ -327,7 +327,7 @@ namespace Flow.Launcher.Plugin.Explorer.Views
}
public string Description { get; private init; }
public string Color => Enabled ?? true ? "Black" : "Gray";
public string Color => Enabled ? "Black" : "Gray";
internal Settings.ActionKeyword KeywordProperty { get; }
@ -337,11 +337,10 @@ namespace Flow.Launcher.Plugin.Explorer.Views
set => _settings.SetActionKeyword(KeywordProperty, value);
}
public bool? Enabled
public bool Enabled
{
get => _settings.GetActionKeywordEnabled(KeywordProperty);
set => _settings.SetActionKeywordEnabled(KeywordProperty,
value ?? throw new ArgumentException("Unexpected null value"));
set => _settings.SetActionKeywordEnabled(KeywordProperty, value);
}
}
}

View file

@ -120,7 +120,10 @@ namespace Flow.Launcher.Plugin.PluginsManager
.ChangeQuery(
$"{Context.CurrentPluginMetadata.ActionKeywords.FirstOrDefault()} {Settings.HotkeyUpdate} {plugin.Name}");
Application.Current.MainWindow.Show();
var mainWindow = Application.Current.MainWindow;
mainWindow.Visibility = Visibility.Visible;
mainWindow.Focus();
shouldHideWindow = false;
return;

View file

@ -6,7 +6,7 @@
"Name": "Plugins Manager",
"Description": "Management of installing, uninstalling or updating Flow Launcher plugins",
"Author": "Jeremy Wu",
"Version": "1.8.4",
"Version": "1.8.5",
"Language": "csharp",
"Website": "https://github.com/Flow-Launcher/Flow.Launcher",
"ExecuteFileName": "Flow.Launcher.Plugin.PluginsManager.dll",

View file

@ -1,4 +1,4 @@
version: '1.8.1.{build}'
version: '1.8.3.{build}'
init:
- ps: |
@ -79,5 +79,5 @@ on_success:
if ($env:APPVEYOR_REPO_BRANCH -eq "master" -and $env:APPVEYOR_REPO_TAG -eq "true")
{
iwr https://aka.ms/wingetcreate/latest -OutFile wingetcreate.exe
.\wingetcreate.exe update Flow-Launcher.Flow-Launcher -s true -u https://github.com/Flow-Launcher/Flow.Launcher/releases/download/v$env:flowVersion/Flow-Launcher-v$env:flowVersion.exe -v $env:flowVersion -t $env:winget_token
.\wingetcreate.exe update Flow-Launcher.Flow-Launcher -s true -u https://github.com/Flow-Launcher/Flow.Launcher/releases/download/v$env:flowVersion/Flow-Launcher-Setup.exe -v $env:flowVersion -t $env:winget_token
}