Use DynamicData as resultcollection

This commit is contained in:
Hongtao Zhang 2024-01-21 17:36:16 -06:00
parent ce6321cf8b
commit 3fe58d7ec5
3 changed files with 67 additions and 161 deletions

View file

@ -12,12 +12,12 @@
SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
SelectionMode="AlwaysSelected"
AutoScrollToSelectedItem="False"
AutoScrollToSelectedItem="True"
IsVisible="{Binding Visibility}"
MaxHeight="{Binding MaxHeight}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button HorizontalAlignment="Stretch" Height="40">
<Button HorizontalAlignment="Stretch" Height="40" x:DataType="vm:ResultViewModel">
<Button.Template>
<ControlTemplate>
<ContentPresenter Content="{TemplateBinding Button.Content}" />
@ -78,7 +78,7 @@
Margin="0,0,0,0"
HorizontalAlignment="Center"
IsHitTestVisible="False"
Source="{Binding Image^, FallbackValue={Binding DefaultImage}, TargetNullValue={x:Null}}"
Source="{Binding Image^, FallbackValue={Binding DefaultImage}}"
Stretch="Uniform"
IsVisible="{Binding ShowIcon}">
</Image>

View file

@ -239,10 +239,7 @@ namespace Flow.Launcher.ViewModel
{
get
{
if (Result.ProgressBar == null)
return 0;
return Result.ProgressBar.Value;
return Result.ProgressBar ?? 0;
}
}

View file

@ -1,14 +1,22 @@
using Flow.Launcher.Infrastructure.UserSettings;
using System;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using Avalonia.ReactiveUI;
using DynamicData;
using DynamicData.Binding;
namespace Flow.Launcher.ViewModel
{
@ -16,16 +24,40 @@ namespace Flow.Launcher.ViewModel
{
#region Private Fields
public ResultCollection Results { get; }
private ReadOnlyObservableCollection<ResultViewModel> _results;
public ReadOnlyObservableCollection<ResultViewModel> Results => _results;
private SourceList<Result> _resultsCache = new();
private readonly object _collectionLock = new object();
private readonly Settings _settings;
private int MaxResults => _settings?.MaxResultsToShow ?? 6;
public void MoveIndex(int diff)
{
if (Results.Count == 0)
{
SelectedIndex = -1;
return;
}
SelectedIndex = Mod(SelectedIndex + diff, Results.Count);
return;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int Mod(int x, int m) => (x % m + m) % m;
}
private IDisposable _resultsSubscription;
public ResultsViewModel()
{
Results = new ResultCollection();
BindingOperations.EnableCollectionSynchronization(Results, _collectionLock);
_resultsSubscription = _resultsCache.Connect()
.Sort(SortExpressionComparer<Result>.Descending(r => r.Score))
.Transform(r => new ResultViewModel(r, _settings))
.Bind(out _results)
.Do(_ => MoveIndex(-SelectedIndex))
.Subscribe();
}
public ResultsViewModel(Settings settings) : this()
@ -59,21 +91,6 @@ namespace Flow.Launcher.ViewModel
#region Private Methods
private int InsertIndexOf(int newScore, IList<ResultViewModel> list)
{
int index = 0;
for (; index < list.Count; index++)
{
var result = list[index];
if (newScore > result.Result.Score)
{
break;
}
}
return index;
}
private int NewIndex(int i)
{
var n = Results.Count;
@ -120,20 +137,23 @@ namespace Flow.Launcher.ViewModel
public void Clear()
{
lock (_collectionLock)
Results.RemoveAll();
_resultsCache.Clear();
}
public void KeepResultsFor(PluginMetadata metadata)
{
lock (_collectionLock)
Results.Update(Results.Where(r => r.Result.PluginID == metadata.ID).ToList());
_resultsCache.Edit(list =>
{
list.Remove(list.Where(x => x.PluginID != metadata.ID));
});
}
public void KeepResultsExcept(PluginMetadata metadata)
{
lock (_collectionLock)
Results.Update(Results.Where(r => r.Result.PluginID != metadata.ID).ToList());
_resultsCache.Edit(list =>
{
list.Remove(list.Where(x => x.PluginID == metadata.ID));
});
}
/// <summary>
@ -141,9 +161,7 @@ namespace Flow.Launcher.ViewModel
/// </summary>
public void AddResults(List<Result> newRawResults, string resultId)
{
var newResults = NewResults(newRawResults, resultId);
UpdateResults(newResults);
NewResults(newRawResults, resultId);
}
/// <summary>
@ -151,59 +169,30 @@ namespace Flow.Launcher.ViewModel
/// </summary>
public void AddResults(IEnumerable<ResultsForUpdate> resultsForUpdates, CancellationToken token)
{
var newResults = NewResults(resultsForUpdates);
if (token.IsCancellationRequested)
return;
UpdateResults(newResults, token);
NewResults(resultsForUpdates);
}
private void UpdateResults(List<ResultViewModel> newResults, CancellationToken token = default)
private void NewResults(IReadOnlyCollection<Result> newRawResults, string resultId)
{
lock (_collectionLock)
_resultsCache.Edit(list =>
{
// update UI in one run, so it can avoid UI flickering
Results.Update(newResults, token);
if (Results.Any())
SelectedItem = Results[0];
}
list.Remove(list.Where(x => x.PluginID == resultId).ToList());
list.AddRange(newRawResults);
});
}
switch (Visibility)
private void NewResults(IEnumerable<ResultsForUpdate> resultsForUpdates)
{
_resultsCache.Edit(list =>
{
case false when Results.Count > 0:
SelectedIndex = 0;
Visibility = true;
break;
case true when Results.Count == 0:
Visibility = false;
break;
}
}
list.Remove(list.Where(x => resultsForUpdates.Any(r => r.ID == x.PluginID)).ToList());
private List<ResultViewModel> NewResults(List<Result> newRawResults, string resultId)
{
if (newRawResults.Count == 0)
return Results;
var newResults = newRawResults.Select(r => new ResultViewModel(r, _settings));
return Results.Where(r => r.Result.PluginID != resultId)
.Concat(newResults)
.OrderByDescending(r => r.Result.Score)
.ToList();
}
private List<ResultViewModel> NewResults(IEnumerable<ResultsForUpdate> resultsForUpdates)
{
if (!resultsForUpdates.Any())
return Results;
return Results.Where(r => r != null && !resultsForUpdates.Any(u => u.ID == r.Result.PluginID))
.Concat(resultsForUpdates.SelectMany(u => u.Results, (u, r) => new ResultViewModel(r, _settings)))
.OrderByDescending(rv => rv.Result.Score)
.ToList();
foreach (var resultsForUpdate in resultsForUpdates)
{
list.AddRange(resultsForUpdate.Results);
}
});
}
#endregion
@ -240,85 +229,5 @@ namespace Flow.Launcher.ViewModel
}
#endregion
public class ResultCollection : List<ResultViewModel>, INotifyCollectionChanged
{
private long editTime = 0;
private CancellationToken _token;
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
CollectionChanged?.Invoke(this, e);
}
public void BulkAddAll(List<ResultViewModel> resultViews)
{
AddRange(resultViews);
// can return because the list will be cleared next time updated, which include a reset event
if (_token.IsCancellationRequested)
return;
// manually update event
// wpf use DirectX / double buffered already, so just reset all won't cause ui flickering
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void AddAll(List<ResultViewModel> Items)
{
for (int i = 0; i < Items.Count; i++)
{
var item = Items[i];
if (_token.IsCancellationRequested)
return;
Add(item);
OnCollectionChanged(
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, i));
}
}
public void RemoveAll(int Capacity = 512)
{
Clear();
if (this.Capacity > 8000 && Capacity < this.Capacity)
this.Capacity = Capacity;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
/// <summary>
/// Update the results collection with new results, try to keep identical results
/// </summary>
/// <param name="newItems"></param>
public void Update(List<ResultViewModel> newItems, CancellationToken token = default)
{
_token = token;
if (Count == 0 && newItems.Count == 0 || _token.IsCancellationRequested)
return;
if (editTime < 10 || newItems.Count < 30)
{
if (Count != 0) RemoveAll(newItems.Count);
AddAll(newItems);
editTime++;
return;
}
else
{
Clear();
BulkAddAll(newItems);
if (Capacity > 8000 && newItems.Count < 3000)
{
Capacity = newItems.Count;
}
editTime++;
}
}
}
}
}