Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Donut groups: an editor to build them in Settings → Toolbar
SeoJCalive06de66f74791
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex f9c07147..ba8cef21 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -255,6 +255,19 @@"toolbar.hole": "Hole","toolbar.opacity": "Opacity","toolbar.new_preset": "New preset",+ "toolbar.new_group": "New group",+ "group.editor_title": "Group",+ "group.hint": "A group is one donut slice for several presets: rest on it or move outward and they fan out around it.",+ "group.members": "Presets ({0} / {1})",+ "group.empty": "No presets yet. Add some below.",+ "group.add": "Add",+ "group.add_placeholder": "Choose a preset",+ "group.full": "A group holds up to 6 presets.",+ "group.move_up": "Move up",+ "group.move_down": "Move down",+ "group.remove": "Remove from the group",+ "group.delete": "Delete group",+ "group.delete_confirm": "Delete the group \"{0}\"? Its presets stay.","toolbar.ext_none": "No extensions yet. This profile is only used once you add some.","toolbar.ext_invalid": "“{0}” isn't a file extension (e.g. jpg or tar.gz).","toolbar.ext_duplicate": "{0} is already in the list.",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex aafa46d6..e333712c 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -255,6 +255,19 @@"toolbar.hole": "구멍","toolbar.opacity": "불투명도","toolbar.new_preset": "새 프리셋",+ "toolbar.new_group": "새 묶음",+ "group.editor_title": "묶음",+ "group.hint": "묶음은 여러 프리셋을 도넛 한 칸에 담아요. 칸 위에 머물거나 바깥으로 움직이면 주변으로 펼쳐져요.",+ "group.members": "프리셋 ({0} / {1})",+ "group.empty": "아직 프리셋이 없어요. 아래에서 추가하세요.",+ "group.add": "추가",+ "group.add_placeholder": "프리셋 선택",+ "group.full": "묶음에는 프리셋을 6개까지 넣을 수 있어요.",+ "group.move_up": "위로",+ "group.move_down": "아래로",+ "group.remove": "묶음에서 빼기",+ "group.delete": "묶음 삭제",+ "group.delete_confirm": "\"{0}\" 묶음을 삭제할까요? 안의 프리셋은 그대로 남아요.","toolbar.ext_none": "아직 확장자가 없어요. 확장자를 추가해야 이 프로필이 쓰여요.","toolbar.ext_invalid": "“{0}”은(는) 파일 확장자가 아니에요. (예: jpg, tar.gz)","toolbar.ext_duplicate": "{0}은(는) 이미 목록에 있어요.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex b9d36234..cc4203fe 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -255,6 +255,19 @@"toolbar.hole": "内圈","toolbar.opacity": "不透明度","toolbar.new_preset": "新预设",+ "toolbar.new_group": "新建组",+ "group.editor_title": "组",+ "group.hint": "组把多个预设放进圆环的一格:停留在上面或向外移动,它们就会在周围展开。",+ "group.members": "预设({0} / {1})",+ "group.empty": "还没有预设。请在下方添加。",+ "group.add": "添加",+ "group.add_placeholder": "选择预设",+ "group.full": "一个组最多可放 6 个预设。",+ "group.move_up": "上移",+ "group.move_down": "下移",+ "group.remove": "从组中移除",+ "group.delete": "删除组",+ "group.delete_confirm": "删除组“{0}”?其中的预设会保留。","toolbar.ext_none": "还没有扩展名:添加后才会使用此配置。","toolbar.ext_invalid": "“{0}”不是文件扩展名(例如 jpg 或 tar.gz)。","toolbar.ext_duplicate": "{0} 已在列表中。",diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.csindex 948ef71f..e2c3666a 100644--- a/src/Filee.App/Services/WindowService.cs+++ b/src/Filee.App/Services/WindowService.cs@@ -9,6 +9,7 @@ using Filee.App.ViewModels;using Filee.App.Views;using Filee.Core.Localization;using Filee.Core.Presets;+using Filee.Core.Settings;using Microsoft.Extensions.DependencyInjection;namespace Filee.App.Services;@@ -132,9 +133,9 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)/// <summary>Opens the preset popup. Returns true when the user saved (the preset object was updated).</summary>public async Task<bool> EditPresetAsync(Preset preset, Window? owner){- // The conversion editor has nothing to edit on a group (it converts nothing).+ // A group converts nothing: it gets its own editor (name and the presets it fans out).if (preset.IsGroup)- return false;+ return await EditGroupAsync(preset, owner);var dialog = new PresetEditorWindow{DataContext = new PresetEditorViewModel(preset, loc),@@ -154,6 +155,32 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)return await dialog.ShowDialog<bool>(owner);}+ /// <summary>+ /// Opens the group editor. Returns true when the user saved (the group was updated) or deleted it (it was removed+ /// from the presets and every donut). <paramref name="isNew"/>: not in the store yet, so it can't be deleted.+ /// </summary>+ public async Task<bool> EditGroupAsync(Preset group, Window? owner, bool isNew = false)+ {+ owner ??= _main ?? MainWindowOrNull();+ var visibleOwner = owner is { IsVisible: true } ? owner : null;+ var dialog = new GroupEditorWindow+ {+ DataContext = new GroupEditorViewModel(group, services.GetRequiredService<UserDataStore>(), loc, isNew),+ Topmost = owner?.Topmost ?? false,+ Confirm = message => visibleOwner is null ? Task.FromResult(true) : ConfirmAsync(visibleOwner, message, destructive: true),+ };+ if (visibleOwner is null)+ {+ var closed = new TaskCompletionSource();+ dialog.Closed += (_, _) => closed.TrySetResult();+ dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;+ dialog.Show();+ await closed.Task;+ return dialog.Changed;+ }+ return await dialog.ShowDialog<bool>(visibleOwner);+ }+/// <summary>Simple yes/no confirmation.</summary>public Task<bool> ConfirmAsync(Window owner, string message, bool destructive = false) =>ShowMessageAsync(owner, message, destructive, withCancel: true);diff --git a/src/Filee.App/ViewModels/GroupEditorViewModel.cs b/src/Filee.App/ViewModels/GroupEditorViewModel.csnew file mode 100644index 00000000..d7767ab2--- /dev/null+++ b/src/Filee.App/ViewModels/GroupEditorViewModel.cs@@ -0,0 +1,143 @@+// Editor for a donut group (Settings → Toolbar → New group, or right-click on a group): its name and the presets+// its slice fans out. Works on copies; Apply() writes them back into the group (Cancel = just drop the VM).++using System.Collections.ObjectModel;+using CommunityToolkit.Mvvm.ComponentModel;+using CommunityToolkit.Mvvm.Input;+using Filee.App.Services;+using Filee.Core.Localization;+using Filee.Core.Presets;+using Filee.Core.Settings;++namespace Filee.App.ViewModels;++/// <summary>One preset in a group, in fan-out order.</summary>+public sealed record GroupMember(string PresetId, string Label, string? Caption);++public sealed partial class GroupEditorViewModel : ObservableObject+{+ private readonly Preset _group;+ private readonly UserDataStore _store;+ private readonly ILocalizer _loc;++ /// <param name="isNew">A group not yet in the store: it can't be deleted, only not saved.</param>+ public GroupEditorViewModel(Preset group, UserDataStore store, ILocalizer loc, bool isNew = false)+ {+ _group = group;+ _store = store;+ _loc = loc;+ IsNew = isNew;+ _name = loc.DisplayName(group);+ foreach (var id in group.SubPresetIds)+ {+ if (store.FindPreset(id) is { IsGroup: false } preset)+ Members.Add(MemberOf(preset));+ }+ Members.CollectionChanged += (_, _) => Refresh();+ Refresh();+ }++ public bool IsNew { get; }++ public bool CanDelete => !IsNew;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(IsValid), nameof(NameError))]+ private string _name;++ /// <summary>The presets the group fans out, in order.</summary>+ public ObservableCollection<GroupMember> Members { get; } = [];++ /// <summary>Conversions that can still be added (not groups, not already in it).</summary>+ public ObservableCollection<Choice<string>> Available { get; } = [];++ [ObservableProperty]+ [NotifyCanExecuteChangedFor(nameof(AddCommand))]+ private Choice<string>? _toAdd;++ public bool IsFull => Members.Count >= Preset.MaxSubPresets;++ public bool IsEmpty => Members.Count == 0;++ /// <summary>"Presets (2 / 6)".</summary>+ public string MembersTitle => _loc.Format("group.members", Members.Count, Preset.MaxSubPresets);++ public string? NameError => string.IsNullOrWhiteSpace(Name) ? _loc["presets.name_required"] : null;++ /// <summary>A name and at least one preset: a group without presets would fan out nothing.</summary>+ public bool IsValid => NameError is null && Members.Count > 0;++ /// <summary>Set by <see cref="Delete"/>: the group was removed from the store and its donuts.</summary>+ public bool Deleted { get; private set; }++ [RelayCommand(CanExecute = nameof(CanAdd))]+ private void Add()+ {+ if (ToAdd is null || _store.FindPreset(ToAdd.Value) is not { } preset)+ return;+ Members.Add(MemberOf(preset));+ ToAdd = null;+ }++ private bool CanAdd() => ToAdd is not null && !IsFull;++ [RelayCommand]+ private void Remove(GroupMember member) => Members.Remove(member);++ [RelayCommand]+ private void MoveUp(GroupMember member) => Move(member, -1);++ [RelayCommand]+ private void MoveDown(GroupMember member) => Move(member, 1);++ private void Move(GroupMember member, int by)+ {+ var from = Members.IndexOf(member);+ var to = from + by;+ if (from >= 0 && to >= 0 && to < Members.Count)+ Members.Move(from, to);+ }++ /// <summary>Copies the edits into the group. Returns false (and changes nothing) when they aren't valid.</summary>+ public bool Apply()+ {+ if (!IsValid)+ return false;+ // Keep a built-in group's translatable name unless the user actually renamed it.+ if (_group.NameKey is null || Name.Trim() != _loc.DisplayName(_group))+ _group.Name = Name.Trim();+ _group.Kind = PresetKind.Group;+ _group.TargetFormat = BuiltInData.SameAsSource;+ _group.SubPresetIds = Members.Select(m => m.PresetId).ToList();+ return true;+ }++ /// <summary>Removes the group from the store and from every donut (its presets stay).</summary>+ public void Delete()+ {+ _store.Presets.Remove(_group);+ foreach (var profile in _store.Profiles)+ profile.PresetIds.Remove(_group.Id);+ Deleted = true;+ }++ public string DeleteConfirmation => _loc.Format("group.delete_confirm", Name.Trim());++ private void Refresh()+ {+ var taken = Members.Select(m => m.PresetId).ToHashSet();+ Available.Clear();+ foreach (var preset in _store.Presets.Where(p => !p.IsGroup && !taken.Contains(p.Id)))+ Available.Add(new Choice<string>(preset.Id, _loc.DisplayName(preset), CaptionOf(preset)));+ OnPropertyChanged(nameof(IsFull));+ OnPropertyChanged(nameof(IsEmpty));+ OnPropertyChanged(nameof(MembersTitle));+ OnPropertyChanged(nameof(IsValid));+ AddCommand.NotifyCanExecuteChanged();+ }++ private GroupMember MemberOf(Preset preset) => new(preset.Id, _loc.DisplayName(preset), CaptionOf(preset));++ private string CaptionOf(Preset preset) =>+ preset.TargetFormat == BuiltInData.SameAsSource ? _loc["donut.same_format"] : FormatLabels.NameOf(_loc, preset.TargetFormat);+}diff --git a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.csindex 20e62a85..8c014fad 100644--- a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs@@ -250,6 +250,19 @@ public sealed partial class ToolbarPageViewModel : ObservableObjectCommit();}+ /// <summary>A new group (a slice that fans out presets), added to the selected donut when there's room.</summary>+ [RelayCommand]+ private async Task NewGroup()+ {+ var group = new Preset { Name = _loc["toolbar.new_group"], Kind = PresetKind.Group, TargetFormat = BuiltInData.SameAsSource };+ if (!await _windows.EditGroupAsync(group, _windows.Main, isNew: true))+ return;+ _store.Presets.Add(group);+ if (Profile is not null && Profile.PresetIds.Count < ToolbarProfile.MaxSlices)+ Profile.PresetIds.Add(group.Id);+ Commit();+ }+[RelayCommand]private async Task NewPreset(){diff --git a/src/Filee.App/Views/GroupEditorWindow.axaml b/src/Filee.App/Views/GroupEditorWindow.axamlnew file mode 100644index 00000000..bb400070--- /dev/null+++ b/src/Filee.App/Views/GroupEditorWindow.axaml@@ -0,0 +1,104 @@+<!-- Group editor: the name of a donut group and the presets its slice fans out (Settings → Toolbar → New group,+ or right-click / ✎ on a group). -->+<Window xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:vm="using:Filee.App.ViewModels"+ x:Class="Filee.App.Views.GroupEditorWindow"+ x:DataType="vm:GroupEditorViewModel"+ Title="{DynamicResource group.editor_title}"+ Icon="avares://Filee/Assets/Icons/filee.ico"+ Width="480" Height="560" MinWidth="400" MinHeight="420"+ WindowStartupLocation="CenterOwner"+ ShowInTaskbar="False">+ <DockPanel>+ <Border DockPanel.Dock="Bottom" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{DynamicResource SubtleBorderBrush}"+ Background="{DynamicResource SurfaceBrush}">+ <DockPanel>+ <Button DockPanel.Dock="Left" Classes="ghost" Content="{DynamicResource group.delete}" Click="OnDelete"+ IsVisible="{Binding CanDelete}" />+ <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">+ <Button Content="{DynamicResource common.cancel}" Click="OnCancel" IsCancel="True" />+ <Button Classes="accent" Content="{DynamicResource common.save}" Click="OnSave" IsDefault="True" IsEnabled="{Binding IsValid}" />+ </StackPanel>+ </DockPanel>+ </Border>+ <ScrollViewer Padding="20,16">+ <StackPanel Spacing="14">+ <StackPanel Orientation="Horizontal" Spacing="10">+ <Border Width="34" Height="34" CornerRadius="999" Background="{DynamicResource AccentSoftBrush}">+ <PathIcon Width="16" Height="16" Data="{StaticResource Icon.Donut}" Foreground="{DynamicResource AccentStrongBrush}" />+ </Border>+ <TextBlock Classes="h2" VerticalAlignment="Center" Text="{DynamicResource group.editor_title}" />+ </StackPanel>+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource group.hint}" />++ <StackPanel>+ <TextBlock Classes="label" Text="{DynamicResource presets.name}" />+ <TextBox x:Name="NameBox" Text="{Binding Name}" />+ <TextBlock Classes="caption danger" Text="{Binding NameError}" Margin="2,4,0,0"+ IsVisible="{Binding NameError, Converter={x:Static ObjectConverters.IsNotNull}}" />+ </StackPanel>++ <Border Classes="card" Padding="14">+ <StackPanel Spacing="10">+ <TextBlock Classes="h2" Text="{Binding MembersTitle}" />+ <TextBlock Classes="caption" Text="{DynamicResource group.empty}" IsVisible="{Binding IsEmpty}" />+ <ItemsControl ItemsSource="{Binding Members}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Spacing="4" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:GroupMember">+ <Border Classes="chip" HorizontalAlignment="Stretch">+ <DockPanel>+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="2">+ <Button Classes="icon" ToolTip.Tip="{DynamicResource group.move_up}"+ Command="{Binding $parent[ItemsControl].((vm:GroupEditorViewModel)DataContext).MoveUpCommand}" CommandParameter="{Binding}">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.ArrowUp}" />+ </Button>+ <Button Classes="icon" ToolTip.Tip="{DynamicResource group.move_down}"+ Command="{Binding $parent[ItemsControl].((vm:GroupEditorViewModel)DataContext).MoveDownCommand}" CommandParameter="{Binding}">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.ArrowDown}" />+ </Button>+ <Button Classes="icon" ToolTip.Tip="{DynamicResource group.remove}"+ Command="{Binding $parent[ItemsControl].((vm:GroupEditorViewModel)DataContext).RemoveCommand}" CommandParameter="{Binding}">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" />+ </Button>+ </StackPanel>+ <StackPanel Orientation="Horizontal" Spacing="6" VerticalAlignment="Center">+ <TextBlock Text="{Binding Label}" FontWeight="SemiBold" />+ <TextBlock Classes="caption" Text="{Binding Caption}" VerticalAlignment="Center" />+ </StackPanel>+ </DockPanel>+ </Border>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ <Grid ColumnDefinitions="*,8,Auto" IsVisible="{Binding !IsFull}">+ <ComboBox ItemsSource="{Binding Available}" SelectedItem="{Binding ToAdd}" HorizontalAlignment="Stretch"+ PlaceholderText="{DynamicResource group.add_placeholder}" MaxDropDownHeight="360">+ <ComboBox.ItemTemplate>+ <DataTemplate x:DataType="vm:IChoice">+ <DockPanel>+ <TextBlock DockPanel.Dock="Right" Classes="caption" Text="{Binding Detail}" Margin="12,0,0,0" VerticalAlignment="Center" />+ <TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />+ </DockPanel>+ </DataTemplate>+ </ComboBox.ItemTemplate>+ </ComboBox>+ <Button Grid.Column="2" Command="{Binding AddCommand}">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />+ <TextBlock Text="{DynamicResource group.add}" />+ </StackPanel>+ </Button>+ </Grid>+ <TextBlock Classes="caption" Text="{DynamicResource group.full}" IsVisible="{Binding IsFull}" />+ </StackPanel>+ </Border>+ </StackPanel>+ </ScrollViewer>+ </DockPanel>+</Window>diff --git a/src/Filee.App/Views/GroupEditorWindow.axaml.cs b/src/Filee.App/Views/GroupEditorWindow.axaml.csnew file mode 100644index 00000000..995d9524--- /dev/null+++ b/src/Filee.App/Views/GroupEditorWindow.axaml.cs@@ -0,0 +1,44 @@+using Avalonia.Controls;+using Avalonia.Interactivity;+using Filee.App.Services;+using Filee.App.ViewModels;++namespace Filee.App.Views;++/// <summary>Modal group editor. Returns true from ShowDialog when the user saved or deleted the group.</summary>+public partial class GroupEditorWindow : Window+{+ public GroupEditorWindow()+ {+ InitializeComponent();+ Motion.Track(this);+ Opened += (_, _) => NameBox.Focus();+ }++ /// <summary>Asks before deleting (set by WindowService; without it the group is deleted at once).</summary>+ public Func<string, Task<bool>>? Confirm { get; init; }++ /// <summary>True after the user saved or deleted (also available when the window was not shown as a dialog).</summary>+ public bool Changed { get; private set; }++ private void OnSave(object? sender, RoutedEventArgs e)+ {+ if (DataContext is not GroupEditorViewModel vm || !vm.Apply())+ return;+ Changed = true;+ Close(true);+ }++ private async void OnDelete(object? sender, RoutedEventArgs e)+ {+ if (DataContext is not GroupEditorViewModel vm)+ return;+ if (Confirm is not null && !await Confirm(vm.DeleteConfirmation))+ return;+ vm.Delete();+ Changed = true;+ Close(true);+ }++ private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);+}diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml b/src/Filee.App/Views/Pages/ToolbarPage.axamlindex bb5c0013..3cfc5c59 100644--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml@@ -295,12 +295,21 @@</ItemsControl.ItemTemplate></ItemsControl></Border>- <Button HorizontalAlignment="Stretch" Command="{Binding NewPresetCommand}">- <StackPanel Orientation="Horizontal" Spacing="6">- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />- <TextBlock Text="{DynamicResource toolbar.new_preset}" />- </StackPanel>- </Button>+ <Grid ColumnDefinitions="*,8,*">+ <Button HorizontalAlignment="Stretch" Command="{Binding NewPresetCommand}">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />+ <TextBlock Text="{DynamicResource toolbar.new_preset}" />+ </StackPanel>+ </Button>+ <Button Grid.Column="2" HorizontalAlignment="Stretch" Command="{Binding NewGroupCommand}"+ ToolTip.Tip="{DynamicResource group.hint}">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Donut}" />+ <TextBlock Text="{DynamicResource toolbar.new_group}" />+ </StackPanel>+ </Button>+ </Grid><StackPanel Spacing="4" Margin="2,6,0,0"><TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_add}" /><TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_remove}" />diff --git a/tests/Filee.App.Tests/GroupEditorTests.cs b/tests/Filee.App.Tests/GroupEditorTests.csnew file mode 100644index 00000000..870a1ce9--- /dev/null+++ b/tests/Filee.App.Tests/GroupEditorTests.cs@@ -0,0 +1,116 @@+// The group editor (Settings → Toolbar → New group): picking the presets a group fans out, their order, the limit of+// six, saving and deleting.++using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Threading;+using Filee.App.Services;+using Filee.App.ViewModels;+using Filee.App.Views;+using Filee.Core.Localization;+using Filee.Core.Presets;+using Filee.Core.Settings;++namespace Filee.App.Tests;++public class GroupEditorTests+{+ private static GroupEditorViewModel Edit(Preset group, bool isNew = false)+ {+ TestServices.EnsureInitialized("en");+ return new GroupEditorViewModel(group, AppHost.Get<UserDataStore>(), AppHost.Get<ILocalizer>(), isNew);+ }++ private static void Add(GroupEditorViewModel vm, string presetId)+ {+ vm.ToAdd = vm.Available.Single(c => c.Value == presetId);+ vm.AddCommand.Execute(null);+ }++ [AvaloniaFact]+ public void Presets_are_added_in_order_moved_and_removed_then_saved_into_the_group()+ {+ var group = new Preset { Name = "Web", Kind = PresetKind.Group, TargetFormat = BuiltInData.SameAsSource };+ var vm = Edit(group, isNew: true);+ Assert.False(vm.IsValid); // nothing to fan out yet+ Assert.False(vm.CanDelete);+ Assert.DoesNotContain(vm.Available, c => AppHost.Get<UserDataStore>().FindPreset(c.Value)!.IsGroup);++ Add(vm, "to-png");+ Add(vm, "to-jpg");+ Add(vm, "to-webp");+ Assert.DoesNotContain(vm.Available, c => c.Value == "to-jpg"); // each preset once+ vm.MoveUpCommand.Execute(vm.Members[2]);+ vm.RemoveCommand.Execute(vm.Members[0]);+ Assert.Equal("Presets (2 / 6)", vm.MembersTitle);++ Assert.True(vm.Apply());+ Assert.Equal(["to-webp", "to-jpg"], group.SubPresetIds);+ Assert.True(group.IsGroup);+ }++ [AvaloniaFact]+ public void A_group_takes_six_presets_at_most_and_needs_a_name()+ {+ var vm = Edit(new Preset { Name = "Many", Kind = PresetKind.Group });+ foreach (var id in new[] { "to-png", "to-jpg", "to-webp", "to-tiff", "to-bmp", "to-ico" })+ Add(vm, id);+ Assert.True(vm.IsFull);+ vm.ToAdd = vm.Available.First();+ Assert.False(vm.AddCommand.CanExecute(null));++ vm.Name = " ";+ Assert.False(vm.IsValid);+ Assert.NotNull(vm.NameError);+ }++ [AvaloniaFact]+ public void Deleting_a_group_removes_it_from_the_presets_and_every_donut_but_keeps_its_presets()+ {+ TestServices.EnsureInitialized("en");+ var store = AppHost.Get<UserDataStore>();+ var group = new Preset { Id = "test-delete-group", Name = "Gone", Kind = PresetKind.Group, SubPresetIds = ["to-png"] };+ var images = store.Profiles.Single(p => p.Id == "images");+ store.Presets.Add(group);+ images.PresetIds.Add(group.Id);+ try+ {+ var vm = Edit(group);+ Assert.True(vm.CanDelete);+ vm.Delete();++ Assert.True(vm.Deleted);+ Assert.Null(store.FindPreset(group.Id));+ Assert.DoesNotContain(group.Id, images.PresetIds);+ Assert.NotNull(store.FindPreset("to-png"));+ }+ finally+ {+ store.Presets.Remove(group);+ images.PresetIds.Remove(group.Id);+ }+ }++ [AvaloniaTheory]+ [InlineData("ko")]+ [InlineData("en")]+ public void The_group_editor_renders(string language)+ {+ TestServices.EnsureInitialized(language);+ var vm = new GroupEditorViewModel(+ new Preset { Name = language == "ko" ? "이미지 도구" : "Image tools", Kind = PresetKind.Group, SubPresetIds = ["half-size", "grayscale", "remove-background"] },+ AppHost.Get<UserDataStore>(), AppHost.Get<ILocalizer>());+ var window = new GroupEditorWindow { DataContext = vm };+ window.Show();+ for (var i = 0; i < 20; i++)+ {+ Dispatcher.UIThread.RunJobs();+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();+ }+ var frame = window.CaptureRenderedFrame();+ Assert.NotNull(frame);+ using (var stream = File.Create(Path.Combine(TestServices.ScreenshotDirectory, $"group-editor-{language}.png")))+ frame.Save(stream, new Avalonia.Media.Imaging.PngBitmapEncoderOptions());+ window.Close();+ }+}