Search by regex, modal Enter fixes

This commit is contained in:
2023-07-31 14:07:52 +02:00
parent a537277546
commit bc31b71130
38 changed files with 301 additions and 53 deletions

View File

@@ -1,4 +1,5 @@
using FileTime.App.Core.ViewModels;
using Avalonia.Input;
using FileTime.App.Core.ViewModels;
using FileTime.App.FuzzyPanel;
namespace FileTime.App.CommandPalette.ViewModels;
@@ -7,4 +8,5 @@ public interface ICommandPaletteViewModel : IFuzzyPanelViewModel<ICommandPalette
{
IObservable<bool> ShowWindow { get; }
void Close();
Task<bool> HandleKeyUp(KeyEventArgs keyEventArgs);
}

View File

@@ -25,6 +25,7 @@ public class CommandPaletteViewModel : FuzzyPanelViewModel<ICommandPaletteEntryV
IUserCommandHandlerService userCommandHandlerService,
IKeyboardConfigurationService keyboardConfigurationService,
ILogger<CommandPaletteViewModel> logger)
: base((a, b) => a.Identifier == b.Identifier)
{
_commandPaletteService = commandPaletteService;
_identifiableUserCommandService = identifiableUserCommandService;
@@ -105,6 +106,13 @@ public class CommandPaletteViewModel : FuzzyPanelViewModel<ICommandPaletteEntryV
return true;
}
return false;
}
public async Task<bool> HandleKeyUp(KeyEventArgs keyEventArgs)
{
if (keyEventArgs.Handled) return false;
if (keyEventArgs.Key == Key.Enter)
{
if (SelectedItem is null) return false;

View File

@@ -0,0 +1,32 @@
using FileTime.Core.Models;
namespace FileTime.App.Core.Exceptions;
public enum ItemNotFoundExceptionType
{
Raw,
FullName,
NativePath
}
public class ItemNotFoundException : Exception
{
public string Path { get; }
public ItemNotFoundExceptionType Type { get; } = ItemNotFoundExceptionType.Raw;
public ItemNotFoundException(string path)
{
Path = path;
}
public ItemNotFoundException(FullName path)
{
Path = path.Path;
Type = ItemNotFoundExceptionType.FullName;
}
public ItemNotFoundException(NativePath path)
{
Path = path.Path;
Type = ItemNotFoundExceptionType.NativePath;
}
}

View File

@@ -1,6 +1,7 @@
using System.Reactive.Subjects;
using FileTime.App.Core.Models;
using FileTime.Core.Interactions;
using FileTime.Core.Models;
namespace FileTime.App.Core.Interactions;

View File

@@ -1,3 +0,0 @@
namespace FileTime.App.Core.Models;
public record ItemNamePart(string Text, bool IsSpecial = false);

View File

@@ -1,4 +1,5 @@
using FileTime.App.Core.Models;
using FileTime.Core.Models;
namespace FileTime.App.Core.Services;

View File

@@ -21,10 +21,14 @@ public class SearchCommand : IUserCommand
public sealed class IdentifiableSearchCommand : SearchCommand, IIdentifiableUserCommand
{
public const string SearchByNameContainsCommandName = "search_name_contains";
public const string SearchByRegexCommandName = "search_name_regex";
public static readonly IdentifiableSearchCommand SearchByNameContains =
new(null, SearchType.NameContains, SearchByNameContainsCommandName, "Search by name");
public static readonly IdentifiableSearchCommand SearchByRegex =
new(null, SearchType.NameRegex, SearchByRegexCommandName, "Search by name (Regex)");
private IdentifiableSearchCommand(
string? searchText,
SearchType searchType,

View File

@@ -10,7 +10,7 @@ public interface IAppState
ReadOnlyObservableCollection<ITabViewModel> Tabs { get; }
IObservable<ITabViewModel?> SelectedTab { get; }
IObservable<string?> SearchText { get; }
IObservable<ViewMode> ViewMode { get; }
IDeclarativeProperty<ViewMode> ViewMode { get; }
DeclarativeProperty<string?> RapidTravelText { get; }
ITabViewModel? CurrentSelectedTab { get; }
ITimelineViewModel TimelineViewModel { get; }
@@ -18,6 +18,6 @@ public interface IAppState
void AddTab(ITabViewModel tabViewModel);
void RemoveTab(ITabViewModel tabViewModel);
void SetSearchText(string? searchText);
void SwitchViewMode(ViewMode newViewMode);
Task SwitchViewModeAsync(ViewMode newViewMode);
void SetSelectedTab(ITabViewModel tabToSelect);
}

View File

@@ -1,5 +1,4 @@
using DeclarativeProperty;
using FileTime.App.Core.Models;
using FileTime.App.Core.Models.Enums;
using FileTime.Core.Models;
using InitableService;

View File

@@ -1,4 +1,5 @@
using FileTime.App.Core.Models;
using FileTime.Core.Models;
namespace FileTime.App.Core.Services;
@@ -13,7 +14,7 @@ public class ItemNameConverterService : IItemNameConverterService
{
var nameLeft = name;
while (nameLeft.ToLower().IndexOf(searchText, StringComparison.Ordinal) is int rapidTextStart && rapidTextStart != -1)
while (nameLeft.ToLower().IndexOf(searchText, StringComparison.Ordinal) is var rapidTextStart && rapidTextStart != -1)
{
var before = rapidTextStart > 0 ? nameLeft.Substring(0, rapidTextStart) : null;
var rapidTravel = nameLeft.Substring(rapidTextStart, searchText.Length);

View File

@@ -310,13 +310,13 @@ public class NavigationUserCommandHandlerService : UserCommandHandlerServiceBase
private Task EnterRapidTravel()
{
_appState.SwitchViewMode(ViewMode.RapidTravel);
_appState.SwitchViewModeAsync(ViewMode.RapidTravel);
return Task.CompletedTask;
}
private Task ExitRapidTravel()
{
_appState.SwitchViewMode(ViewMode.Default);
_appState.SwitchViewModeAsync(ViewMode.Default);
return Task.CompletedTask;
}

View File

@@ -106,10 +106,10 @@ public class ToolUserCommandHandlerService : UserCommandHandlerServiceBase
//TODO proper error message
if (string.IsNullOrWhiteSpace(searchQuery)) return;
var searchMatcher = searchCommand.SearchType switch
ISearchMatcher searchMatcher = searchCommand.SearchType switch
{
SearchType.NameContains => new NameContainsMatcher(_itemNameConverterService, searchQuery),
//SearchType.NameRegex => new NameRegexMatcher(searchQuery),
SearchType.NameRegex => new RegexMatcher(searchQuery),
_ => throw new ArgumentOutOfRangeException()
};

View File

@@ -54,6 +54,7 @@ public class DefaultIdentifiableCommandHandlerRegister : IStartupHandler
AddUserCommand(SortItemsCommand.OrderByDateCommand);
AddUserCommand(SortItemsCommand.OrderByDateDescCommand);
AddUserCommand(IdentifiableSearchCommand.SearchByNameContains);
AddUserCommand(IdentifiableSearchCommand.SearchByRegex);
AddUserCommand(SwitchToTabCommand.SwitchToLastTab);
AddUserCommand(SwitchToTabCommand.SwitchToTab1);
AddUserCommand(SwitchToTabCommand.SwitchToTab2);

View File

@@ -16,10 +16,10 @@ public abstract partial class AppStateBase : IAppState
{
private readonly BehaviorSubject<string?> _searchText = new(null);
private readonly BehaviorSubject<ITabViewModel?> _selectedTab = new(null);
private readonly BehaviorSubject<ViewMode> _viewMode = new(Models.Enums.ViewMode.Default);
private readonly DeclarativeProperty<ViewMode> _viewMode = new(Models.Enums.ViewMode.Default);
private readonly SourceList<ITabViewModel> _tabs = new();
public IObservable<ViewMode> ViewMode { get; private set; }
public IDeclarativeProperty<ViewMode> ViewMode { get; private set; }
public ReadOnlyObservableCollection<ITabViewModel> Tabs { get; private set; }
public IObservable<string?> SearchText { get; private set; }
@@ -31,7 +31,7 @@ public abstract partial class AppStateBase : IAppState
partial void OnInitialize()
{
RapidTravelText = new("");
ViewMode = _viewMode.AsObservable();
ViewMode = _viewMode;
var tabsObservable = _tabs.Connect();
@@ -70,10 +70,7 @@ public abstract partial class AppStateBase : IAppState
public void SetSearchText(string? searchText) => _searchText.OnNext(searchText);
public void SwitchViewMode(ViewMode newViewMode)
{
_viewMode.OnNext(newViewMode);
}
public async Task SwitchViewModeAsync(ViewMode newViewMode) => await _viewMode.SetValue(newViewMode);
public void SetSelectedTab(ITabViewModel tabToSelect) => _selectedTab.OnNext(tabToSelect);

View File

@@ -15,8 +15,6 @@ public partial class ContainerSizeContainerViewModel : ItemViewModel, IContainer
{
}
public void Init(IContainer item, ITabViewModel parentTab, ItemViewModelType itemViewModelType)
{
Init((IItem)item, parentTab, itemViewModelType);
}
public void Init(IContainer item, ITabViewModel parentTab, ItemViewModelType itemViewModelType)
=> Init((IItem)item, parentTab, itemViewModelType);
}

View File

@@ -17,8 +17,6 @@ public partial class ElementViewModel : ItemViewModel, IElementViewModel
{
}
public void Init(IElement item, ITabViewModel parentTab, ItemViewModelType itemViewModelType)
{
Init((IItem)item, parentTab, itemViewModelType);
}
public void Init(IElement item, ITabViewModel parentTab, ItemViewModelType itemViewModelType)
=> Init((IItem)item, parentTab, itemViewModelType);
}

View File

@@ -96,6 +96,7 @@ public partial class ElementPreviewViewModel : IItemPreviewViewModel, IAsyncInit
var encodingsWithPartialResult = binaryCharacter.Where(e => !string.IsNullOrWhiteSpace(e.Value.PartialResult)).ToList();
if (encodingsWithPartialResult.Count > 0)
{
stringBuilder.AppendLine();
stringBuilder.AppendLine("The following partial texts could be read by encodings:");
foreach (var binaryByEncoding in encodingsWithPartialResult)
{

View File

@@ -2,9 +2,9 @@ using System.ComponentModel;
using System.Reactive.Linq;
using DeclarativeProperty;
using DynamicData;
using FileTime.App.Core.Models;
using FileTime.App.Core.Models.Enums;
using FileTime.App.Core.Services;
using FileTime.Core.Behaviors;
using FileTime.Core.Helper;
using FileTime.Core.Models;
using MoreLinq;
@@ -37,7 +37,10 @@ public abstract partial class ItemViewModel : IItemViewModel
public IDeclarativeProperty<IReadOnlyList<ItemNamePart>>? DisplayName { get; private set; }
public void Init(IItem item, ITabViewModel parentTab, ItemViewModelType itemViewModelType)
public void Init(
IItem item,
ITabViewModel parentTab,
ItemViewModelType itemViewModelType)
{
_parentTab = parentTab;
@@ -51,7 +54,12 @@ public abstract partial class ItemViewModel : IItemViewModel
var displayName = itemViewModelType switch
{
ItemViewModelType.Main => _appState.RapidTravelText.Map(s => (IReadOnlyList<ItemNamePart>) _itemNameConverterService.GetDisplayName(item.DisplayName, s)),
ItemViewModelType.Main => _appState.RapidTravelText.Map(async (s, _) =>
_appState.ViewMode.Value != Models.Enums.ViewMode.RapidTravel
&& _appState.CurrentSelectedTab?.CurrentLocation.Value?.Provider is IItemNameConverterProvider nameConverterProvider
? (IReadOnlyList<ItemNamePart>) await nameConverterProvider.GetItemNamePartsAsync(item)
: _itemNameConverterService.GetDisplayName(item.DisplayName, s)
),
_ => new DeclarativeProperty<IReadOnlyList<ItemNamePart>>(new List<ItemNamePart> {new(item.DisplayName)}),
};

View File

@@ -1,3 +1,4 @@
using Avalonia.Input;
using FileTime.App.Core.ViewModels;
using FileTime.App.FuzzyPanel;
@@ -7,4 +8,5 @@ public interface IFrequencyNavigationViewModel : IFuzzyPanelViewModel<string>, I
{
IObservable<bool> ShowWindow { get; }
void Close();
Task<bool> HandleKeyUp(KeyEventArgs keyEventArgs);
}

View File

@@ -30,11 +30,9 @@ public class FrequencyNavigationViewModel : FuzzyPanelViewModel<string>, IFreque
public void Close()
=> _frequencyNavigationService.CloseNavigationWindow();
public override async Task<bool> HandleKeyDown(KeyEventArgs keyEventArgs)
public async Task<bool> HandleKeyUp(KeyEventArgs keyEventArgs)
{
var handled = await base.HandleKeyDown(keyEventArgs);
if (handled) return true;
if (keyEventArgs.Handled) return false;
if (keyEventArgs.Key == Key.Enter)
{
@@ -49,6 +47,23 @@ public class FrequencyNavigationViewModel : FuzzyPanelViewModel<string>, IFreque
return false;
}
public override async Task<bool> HandleKeyDown(KeyEventArgs keyEventArgs)
{
if (keyEventArgs.Handled) return false;
var handled = await base.HandleKeyDown(keyEventArgs);
if (handled) return true;
if (keyEventArgs.Key == Key.Escape)
{
keyEventArgs.Handled = true;
Close();
return true;
}
return false;
}
public override void UpdateFilteredMatches() =>
FilteredMatches = new List<string>(_frequencyNavigationService.GetMatchingContainers(SearchText));

View File

@@ -6,12 +6,18 @@ namespace FileTime.App.FuzzyPanel;
public abstract partial class FuzzyPanelViewModel<TItem> : IFuzzyPanelViewModel<TItem> where TItem : class
{
private readonly Func<TItem, TItem, bool> _itemEquality;
private string _searchText = String.Empty;
[Notify(set: Setter.Protected)] private IObservable<bool> _showWindow;
[Notify(set: Setter.Protected)] private List<TItem> _filteredMatches;
[Notify(set: Setter.Protected)] private TItem? _selectedItem;
protected FuzzyPanelViewModel(Func<TItem, TItem, bool>? itemEquality = null)
{
_itemEquality = itemEquality ?? ((a, b) => a == b);
}
public string SearchText
{
get => _searchText;
@@ -42,7 +48,9 @@ public abstract partial class FuzzyPanelViewModel<TItem> : IFuzzyPanelViewModel<
{
if (keyEventArgs.Key == Key.Down)
{
var nextItem = FilteredMatches.SkipWhile(i => i != SelectedItem).Skip(1).FirstOrDefault();
var nextItem = SelectedItem is null
? FilteredMatches.FirstOrDefault()
: FilteredMatches.SkipWhile(i => !_itemEquality(i, SelectedItem)).Skip(1).FirstOrDefault();
if (nextItem is not null)
{
@@ -54,7 +62,9 @@ public abstract partial class FuzzyPanelViewModel<TItem> : IFuzzyPanelViewModel<
}
else if (keyEventArgs.Key == Key.Up)
{
var previousItem = FilteredMatches.TakeWhile(i => i != SelectedItem).LastOrDefault();
var previousItem = SelectedItem is null
? FilteredMatches.LastOrDefault()
: FilteredMatches.TakeWhile(i => !_itemEquality(i, SelectedItem)).LastOrDefault();
if (previousItem is not null)
{

View File

@@ -5,5 +5,6 @@ namespace FileTime.App.Search;
public interface ISearchTask
{
IContainer SearchContainer { get; }
IReadOnlyDictionary<FullName, FullName> RealFullNames { get; }
Task StartAsync();
}

View File

@@ -0,0 +1,61 @@
using System.Text.RegularExpressions;
using FileTime.App.Core.Models;
using FileTime.Core.Models;
namespace FileTime.App.Search;
public class RegexMatcher : ISearchMatcher
{
private readonly Regex _regex;
public RegexMatcher(string pattern)
{
_regex = new Regex(pattern);
}
public Task<bool> IsItemMatchAsync(IItem item)
=> Task.FromResult(_regex.IsMatch(item.DisplayName));
public List<ItemNamePart> GetDisplayName(IItem item)
{
var displayName = item.DisplayName;
var match = _regex.Match(item.DisplayName);
var splitPoints = new List<int>(match.Groups.Count * 2);
if (match.Groups.Count == 0)
{
return new List<ItemNamePart>
{
new(displayName)
};
}
var areEvensSpecial = match.Groups[0].Index == 0;
var isSpecialMatchNumber = areEvensSpecial ? 0 : 1;
foreach (Group group in match.Groups)
{
splitPoints.Add(group.Index);
splitPoints.Add(group.Index + group.Value.Length);
}
if (splitPoints[0] != 0)
splitPoints.Insert(0, 0);
var itemNameParts = new List<ItemNamePart>();
for (var i = 0; i < splitPoints.Count; i++)
{
var index = splitPoints[i];
var nextIndex = i == splitPoints.Count - 1
? displayName.Length
: splitPoints[i + 1];
if (nextIndex == index) continue;
var text = displayName.Substring(index, nextIndex - index);
itemNameParts.Add(new ItemNamePart(text, i % 2 == isSpecialMatchNumber));
}
return itemNameParts;
}
}

View File

@@ -1,3 +1,5 @@
using FileTime.App.Core.Exceptions;
using FileTime.Core.Behaviors;
using FileTime.Core.ContentAccess;
using FileTime.Core.Enums;
using FileTime.Core.Models;
@@ -5,7 +7,7 @@ using FileTime.Core.Timeline;
namespace FileTime.App.Search;
public class SearchContentProvider : ContentProviderBase, ISearchContentProvider
public class SearchContentProvider : ContentProviderBase, ISearchContentProvider, IItemNameConverterProvider
{
private readonly ITimelessContentProvider _timelessContentProvider;
private readonly List<SearchTask> _searchTasks = new();
@@ -17,6 +19,40 @@ public class SearchContentProvider : ContentProviderBase, ISearchContentProvider
_timelessContentProvider = timelessContentProvider;
}
public override async Task<IItem> GetItemByFullNameAsync(
FullName fullName,
PointInTime pointInTime,
bool forceResolve = false,
AbsolutePathType forceResolvePathType = AbsolutePathType.Unknown,
ItemInitializationSettings itemInitializationSettings = null
)
{
if (fullName.Path == ContentProviderName)
return this;
if (_searchTasks
.FirstOrDefault(t => t.SearchContainer.FullName == fullName) is { } searchTask)
{
return searchTask.SearchContainer;
}
if (_searchTasks.FirstOrDefault(t => t.RealFullNames.ContainsKey(fullName)) is { } searchTask2)
{
var realFullName = searchTask2.RealFullNames[fullName];
var item = await _timelessContentProvider.GetItemByFullNameAsync(
realFullName,
pointInTime,
forceResolve,
forceResolvePathType,
itemInitializationSettings
);
item = item.WithParent(new AbsolutePath(_timelessContentProvider, searchTask2.SearchContainer));
return item;
}
throw new ItemNotFoundException(fullName);
}
public override Task<IItem> GetItemByNativePathAsync(
NativePath nativePath,
PointInTime pointInTime,
@@ -63,7 +99,7 @@ public class SearchContentProvider : ContentProviderBase, ISearchContentProvider
{
var searchTask = _searchTasks.FirstOrDefault(t => t.SearchContainer.FullName == searchFullName);
if (searchTask is null) return;
_searchTasks.Remove(searchTask);
var searchItem = Items.FirstOrDefault(c => c.Path == searchTask.SearchContainer.FullName);
if (searchItem is not null)
@@ -71,4 +107,23 @@ public class SearchContentProvider : ContentProviderBase, ISearchContentProvider
Items.Remove(searchItem);
}
}
public async Task<IEnumerable<ItemNamePart>> GetItemNamePartsAsync(IItem item)
{
var currentItem = item;
SearchTask? searchTask = null;
while (searchTask is null && currentItem is not null)
{
searchTask = currentItem.GetExtension<SearchExtension>()?.SearchTask;
currentItem = currentItem.Parent is null
? null
: await currentItem.Parent.ResolveAsync(itemInitializationSettings: new ItemInitializationSettings {SkipChildInitialization = true});
}
if (searchTask is null) return new List<ItemNamePart> {new(item.DisplayName)};
return searchTask.Matcher.GetDisplayName(item);
}
}

View File

@@ -0,0 +1,3 @@
namespace FileTime.App.Search;
public record SearchExtension(SearchTask SearchTask);

View File

@@ -1,6 +1,4 @@
using System.Collections.ObjectModel;
using DynamicData;
using FileTime.Core.ContentAccess;
using FileTime.Core.Enums;
using FileTime.Core.Models;
using FileTime.Core.Timeline;
@@ -18,8 +16,11 @@ public class SearchTask : ISearchTask
private readonly SemaphoreSlim _searchingLock = new(1, 1);
private bool _isSearching;
private static int _searchId = 1;
private readonly Dictionary<FullName, FullName> _realFullNames = new();
public IReadOnlyDictionary<FullName, FullName> RealFullNames { get; }
public IContainer SearchContainer => _container;
public ISearchMatcher Matcher => _matcher;
public SearchTask(
IContainer baseContainer,
@@ -33,6 +34,12 @@ public class SearchTask : ISearchTask
_baseContainer = baseContainer;
_timelessContentProvider = timelessContentProvider;
_matcher = matcher;
RealFullNames = _realFullNames.AsReadOnly();
var extensions = new ExtensionCollection
{
new SearchExtension(this)
};
_container = new Container(
baseContainer.Name,
baseContainer.DisplayName,
@@ -49,7 +56,7 @@ public class SearchTask : ISearchTask
false,
PointInTime.Present,
_exceptions,
new ReadOnlyExtensionCollection(new ExtensionCollection()),
new ReadOnlyExtensionCollection(extensions),
_items
);
}
@@ -89,14 +96,17 @@ public class SearchTask : ISearchTask
foreach (var itemPath in items)
{
var item = await itemPath.ResolveAsync(
itemInitializationSettings: new ItemInitializationSettings
{
Parent = new AbsolutePath(_timelessContentProvider, _container)
});
var item = await itemPath.ResolveAsync();
if (await _matcher.IsItemMatchAsync(item))
{
_items.Add(itemPath);
var childName = _container.FullName.GetChild(itemPath.Path.GetName());
_realFullNames.Add(childName, itemPath.Path);
_items.Add(new AbsolutePath(
_timelessContentProvider,
PointInTime.Present,
childName,
AbsolutePathType.Container
));
}
if (item is IContainer childContainer)