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
Edit profile extensions as chips and mixed profiles as a check list
KnifeLemonbe823a4ecfc4
diff --git a/src/Filee.App/App.axaml b/src/Filee.App/App.axamlindex 5fd35174..f3d5f05f 100644--- a/src/Filee.App/App.axaml+++ b/src/Filee.App/App.axaml@@ -21,5 +21,6 @@<Application.Styles><FluentTheme /><StyleInclude Source="avares://Filee/Styles/Soft.axaml" />+ <StyleInclude Source="avares://Filee/Styles/TagEditor.axaml" /></Application.Styles></Application>diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex ca855ad4..51bd153b 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -79,6 +79,22 @@"preset.extract": "Extract","preset.zip_all": "One ZIP",+ "format.folder": "Folder",+ "format.category.Image": "Image",+ "format.category.Pdf": "PDF",+ "format.category.Document": "Document",+ "format.category.Spreadsheet": "Spreadsheet",+ "format.category.Presentation": "Presentation",+ "format.category.Hwp": "HWP",+ "format.category.Text": "Text",+ "format.category.Video": "Video",+ "format.category.Audio": "Audio",+ "format.category.Ebook": "E-book",+ "format.category.Archive": "Archive",+ "format.category.Vector": "Vector",+ "format.category.Cad": "CAD",+ "format.category.Font": "Font",+"general.title": "General","general.language": "Language","general.language_auto": "System default",@@ -142,8 +158,7 @@"toolbar.delete_profile": "Delete profile","toolbar.name": "Name","toolbar.extensions": "Used for these extensions",- "toolbar.extensions_hint": "jpg, png, webp",- "toolbar.fallback_note": "Used when files match no other profile or several profiles.",+ "toolbar.extensions_hint": "Add an extension, e.g. jpg","toolbar.available": "Available presets","toolbar.hint_add": "Drag a chip onto the donut to add it","toolbar.hint_remove": "Drag a slice back here to remove it",@@ -155,6 +170,27 @@"toolbar.hole": "Hole","toolbar.opacity": "Opacity","toolbar.new_preset": "New preset",+ "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.",+ "toolbar.ext_also_in": "Also in “{0}”",+ "toolbar.ext_in_profile": "in {0}",+ "toolbar.ext_claimed_first": "{0}: also in “{1}”, which comes first in the list, so these files still open “{1}”.",+ "toolbar.ext_claimed_later": "{0}: also in “{1}”. This profile comes first in the list, so these files now open this one instead.",+ "toolbar.ext_unknown": "{0}: Filee doesn't know this file type. You can keep it, but these files can't be converted.",+ "toolbar.ext_unknown_tip": "Unknown file type",+ "toolbar.mixed_toggle": "Use for mixed selections (files of different types)",+ "toolbar.mixed_locked": "Filee needs at least one profile for mixed selections, so this one stays.",+ "toolbar.mixed_badge": "For mixed selections",+ "toolbar.mixed_title": "Show this toolbar when every selected file is one of:",+ "toolbar.mixed_expand": "Show the extensions",+ "toolbar.mixed_other_group": "Other extensions",+ "toolbar.mixed_catch_all": "Nothing checked: used for any mix of files that no other profile takes.",+ "toolbar.mixed_shadowed": "Nothing checked, but “{0}” comes first and already takes every other mix. Check some extensions to use this profile.",+ "toolbar.mixed_covered": "“{0}” comes first and allows every extension checked here, so this profile is never used.",+ "toolbar.mixed_others": "Other mixes of files open “{0}”.",+ "toolbar.mixed_others_self": "No mixed profile is left with nothing checked, so this one is also used for every other mix.",+ "tags.remove": "Remove","presets.title": "Presets","presets.add": "New",@@ -194,6 +230,25 @@"presets.split": "One file per page","presets.group.document": "Documents","presets.pdfa": "PDF/A (archival)",+ "presets.target_folder": "Folder (extract archives)",+ "presets.group.media": "Video & audio",+ "presets.media_quality": "Quality",+ "presets.media_quality.High": "High (larger files)",+ "presets.media_quality.Balanced": "Balanced",+ "presets.media_quality.Small": "Small (for sharing)",+ "presets.max_height": "Maximum height",+ "presets.max_height.original": "Original",+ "presets.audio_bitrate": "Audio bitrate",+ "presets.audio_bitrate.auto": "Automatic",+ "presets.remove_audio": "Remove the sound",+ "presets.group.archive": "Archive",+ "presets.archive_level": "Compression",+ "presets.archive_level.Store": "None (store only)",+ "presets.archive_level.Fast": "Fast",+ "presets.archive_level.Normal": "Normal",+ "presets.archive_level.Maximum": "Maximum (slower)",+ "presets.combine": "Put all files into one archive",+ "presets.extract_note": "Each archive is extracted into a folder of its own. Where it goes is set under Output.","presets.group.output": "Output","presets.location": "Save to","presets.location.SameFolder": "Same folder as the source",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex c45e8822..2a98bfbe 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -79,6 +79,22 @@"preset.extract": "압축 풀기","preset.zip_all": "ZIP 하나로",+ "format.folder": "폴더",+ "format.category.Image": "이미지",+ "format.category.Pdf": "PDF",+ "format.category.Document": "문서",+ "format.category.Spreadsheet": "스프레드시트",+ "format.category.Presentation": "프레젠테이션",+ "format.category.Hwp": "HWP",+ "format.category.Text": "텍스트",+ "format.category.Video": "동영상",+ "format.category.Audio": "오디오",+ "format.category.Ebook": "전자책",+ "format.category.Archive": "압축 파일",+ "format.category.Vector": "벡터",+ "format.category.Cad": "CAD",+ "format.category.Font": "글꼴",+"general.title": "일반","general.language": "언어","general.language_auto": "시스템 기본값",@@ -142,8 +158,7 @@"toolbar.delete_profile": "프로필 삭제","toolbar.name": "이름","toolbar.extensions": "적용할 확장자",- "toolbar.extensions_hint": "jpg, png, webp",- "toolbar.fallback_note": "다른 프로필에 맞지 않거나 여러 프로필에 걸친 파일에 사용돼요.",+ "toolbar.extensions_hint": "확장자 추가 (예: jpg)","toolbar.available": "사용 가능한 프리셋","toolbar.hint_add": "칩을 도넛으로 끌면 추가","toolbar.hint_remove": "세그먼트를 여기로 끌면 빼기",@@ -155,6 +170,27 @@"toolbar.hole": "구멍","toolbar.opacity": "불투명도","toolbar.new_preset": "새 프리셋",+ "toolbar.ext_none": "아직 확장자가 없어요. 확장자를 추가해야 이 프로필이 쓰여요.",+ "toolbar.ext_invalid": "“{0}”은(는) 파일 확장자가 아니에요. (예: jpg, tar.gz)",+ "toolbar.ext_duplicate": "{0}은(는) 이미 목록에 있어요.",+ "toolbar.ext_also_in": "“{0}”에도 있음",+ "toolbar.ext_in_profile": "{0}에 있음",+ "toolbar.ext_claimed_first": "{0}: “{1}”에도 있어요. 목록에서 “{1}”이(가) 먼저라서 이 파일들은 계속 “{1}”로 열려요.",+ "toolbar.ext_claimed_later": "{0}: “{1}”에도 있어요. 목록에서 이 프로필이 먼저라서 이제 이 파일들은 이 프로필로 열려요.",+ "toolbar.ext_unknown": "{0}: Filee가 모르는 파일 형식이에요. 넣어 둘 수는 있지만 이 파일들은 변환할 수 없어요.",+ "toolbar.ext_unknown_tip": "알 수 없는 파일 형식",+ "toolbar.mixed_toggle": "여러 형식이 섞인 선택에 사용",+ "toolbar.mixed_locked": "혼합 선택용 프로필이 하나는 있어야 해서 끌 수 없어요.",+ "toolbar.mixed_badge": "혼합 선택용",+ "toolbar.mixed_title": "선택한 파일이 모두 다음 확장자 중 하나일 때 이 툴바를 보여 줘요:",+ "toolbar.mixed_expand": "확장자 보기",+ "toolbar.mixed_other_group": "기타 확장자",+ "toolbar.mixed_catch_all": "아무것도 체크하지 않으면 다른 프로필이 맡지 않는 모든 혼합 선택에 쓰여요.",+ "toolbar.mixed_shadowed": "아무것도 체크하지 않았지만 목록에서 먼저인 “{0}”이(가) 나머지 혼합 선택을 모두 맡고 있어요. 확장자를 체크해야 이 프로필이 쓰여요.",+ "toolbar.mixed_covered": "목록에서 먼저인 “{0}”이(가) 여기서 체크한 확장자를 모두 허용해서 이 프로필은 쓰이지 않아요.",+ "toolbar.mixed_others": "그 밖의 혼합 선택에는 “{0}”이(가) 열려요.",+ "toolbar.mixed_others_self": "아무것도 체크하지 않은 혼합 프로필이 없어서 그 밖의 혼합 선택에도 이 프로필이 쓰여요.",+ "tags.remove": "빼기","presets.title": "프리셋","presets.add": "새로 만들기",@@ -194,6 +230,25 @@"presets.split": "페이지마다 파일 하나","presets.group.document": "문서","presets.pdfa": "PDF/A (장기 보존용)",+ "presets.target_folder": "폴더 (압축 풀기)",+ "presets.group.media": "동영상·오디오",+ "presets.media_quality": "품질",+ "presets.media_quality.High": "높음 (큰 파일)",+ "presets.media_quality.Balanced": "균형",+ "presets.media_quality.Small": "작게 (공유용)",+ "presets.max_height": "최대 높이",+ "presets.max_height.original": "원본",+ "presets.audio_bitrate": "오디오 비트레이트",+ "presets.audio_bitrate.auto": "자동",+ "presets.remove_audio": "소리 빼기",+ "presets.group.archive": "압축",+ "presets.archive_level": "압축 수준",+ "presets.archive_level.Store": "압축 안 함 (보관만)",+ "presets.archive_level.Fast": "빠르게",+ "presets.archive_level.Normal": "보통",+ "presets.archive_level.Maximum": "최대 (느림)",+ "presets.combine": "모든 파일을 압축 파일 하나로 묶기",+ "presets.extract_note": "압축 파일마다 따로 폴더를 만들어 풀어요. 저장 위치는 아래 출력에서 정해요.","presets.group.output": "출력","presets.location": "저장 위치","presets.location.SameFolder": "원본과 같은 폴더",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex de9260d8..076e3bd8 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -79,6 +79,22 @@"preset.extract": "解压","preset.zip_all": "打包成一个 ZIP",+ "format.folder": "文件夹",+ "format.category.Image": "图片",+ "format.category.Pdf": "PDF",+ "format.category.Document": "文档",+ "format.category.Spreadsheet": "电子表格",+ "format.category.Presentation": "演示文稿",+ "format.category.Hwp": "HWP",+ "format.category.Text": "文本",+ "format.category.Video": "视频",+ "format.category.Audio": "音频",+ "format.category.Ebook": "电子书",+ "format.category.Archive": "压缩文件",+ "format.category.Vector": "矢量图",+ "format.category.Cad": "CAD",+ "format.category.Font": "字体",+"general.title": "常规","general.language": "语言","general.language_auto": "跟随系统",@@ -142,8 +158,7 @@"toolbar.delete_profile": "删除配置","toolbar.name": "名称","toolbar.extensions": "适用的扩展名",- "toolbar.extensions_hint": "jpg, png, webp",- "toolbar.fallback_note": "当文件不匹配其他配置或跨多个配置时使用。",+ "toolbar.extensions_hint": "添加扩展名,例如 jpg","toolbar.available": "可用预设","toolbar.hint_add": "将标签拖到圆环上即可添加","toolbar.hint_remove": "将扇区拖回这里即可移除",@@ -155,6 +170,27 @@"toolbar.hole": "内圈","toolbar.opacity": "不透明度","toolbar.new_preset": "新预设",+ "toolbar.ext_none": "还没有扩展名:添加后才会使用此配置。",+ "toolbar.ext_invalid": "“{0}”不是文件扩展名(例如 jpg 或 tar.gz)。",+ "toolbar.ext_duplicate": "{0} 已在列表中。",+ "toolbar.ext_also_in": "也在“{0}”中",+ "toolbar.ext_in_profile": "在“{0}”中",+ "toolbar.ext_claimed_first": "{0}:也在“{1}”中。“{1}”在列表中靠前,所以这些文件仍会打开“{1}”。",+ "toolbar.ext_claimed_later": "{0}:也在“{1}”中。此配置在列表中靠前,所以这些文件现在会改用此配置。",+ "toolbar.ext_unknown": "{0}:Filee 不认识这种文件类型。可以保留,但这些文件无法转换。",+ "toolbar.ext_unknown_tip": "未知文件类型",+ "toolbar.mixed_toggle": "用于混合选择(不同类型的文件)",+ "toolbar.mixed_locked": "Filee 至少需要一个用于混合选择的配置,因此无法关闭。",+ "toolbar.mixed_badge": "用于混合选择",+ "toolbar.mixed_title": "当选中的文件都属于以下扩展名时显示此工具栏:",+ "toolbar.mixed_expand": "显示扩展名",+ "toolbar.mixed_other_group": "其他扩展名",+ "toolbar.mixed_catch_all": "未勾选任何项:用于其他配置都不处理的所有混合选择。",+ "toolbar.mixed_shadowed": "未勾选任何项,但靠前的“{0}”已处理所有其他混合选择。勾选扩展名后才会使用此配置。",+ "toolbar.mixed_covered": "靠前的“{0}”允许此处勾选的所有扩展名,因此不会使用此配置。",+ "toolbar.mixed_others": "其他混合选择会打开“{0}”。",+ "toolbar.mixed_others_self": "没有未勾选任何项的混合配置,因此其他混合选择也会使用此配置。",+ "tags.remove": "移除","presets.title": "预设","presets.add": "新建",@@ -194,6 +230,25 @@"presets.split": "每页一个文件","presets.group.document": "文档","presets.pdfa": "PDF/A(长期存档)",+ "presets.target_folder": "文件夹(解压缩)",+ "presets.group.media": "视频和音频",+ "presets.media_quality": "质量",+ "presets.media_quality.High": "高(文件较大)",+ "presets.media_quality.Balanced": "均衡",+ "presets.media_quality.Small": "小(便于分享)",+ "presets.max_height": "最大高度",+ "presets.max_height.original": "原始",+ "presets.audio_bitrate": "音频比特率",+ "presets.audio_bitrate.auto": "自动",+ "presets.remove_audio": "去除声音",+ "presets.group.archive": "压缩文件",+ "presets.archive_level": "压缩级别",+ "presets.archive_level.Store": "不压缩(仅存储)",+ "presets.archive_level.Fast": "快速",+ "presets.archive_level.Normal": "标准",+ "presets.archive_level.Maximum": "最大(较慢)",+ "presets.combine": "将所有文件放入一个压缩文件",+ "presets.extract_note": "每个压缩文件解压到各自的文件夹。保存位置在下方“输出”中设置。","presets.group.output": "输出","presets.location": "保存到","presets.location.SameFolder": "与源文件相同的文件夹",diff --git a/src/Filee.App/Controls/TagEditor.cs b/src/Filee.App/Controls/TagEditor.csnew file mode 100644index 00000000..c662edeb--- /dev/null+++ b/src/Filee.App/Controls/TagEditor.cs@@ -0,0 +1,465 @@+// Chip ("tag") input: type a value and press Enter, Tab, comma, semicolon or space to turn it into a chip, paste a+// list to add several at once, Backspace in the empty box removes the last chip, suggestions pop up while typing.+// The control only handles input and keyboard/mouse gestures. Which values are valid, how chips are marked and+// where they are stored is decided by the view model behind AddCommand / RemoveCommand (see ExtensionTagsViewModel).+// Look: Styles/TagEditor.axaml.++using System.Windows.Input;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Metadata;+using Avalonia.Controls.Primitives;+using Avalonia.Data;+using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.Threading;+using Avalonia.VisualTree;++namespace Filee.App.Controls;++/// <summary>How a <see cref="TagChip"/> is highlighted.</summary>+public enum TagChipKind+{+ Normal,+ /// <summary>Allowed but worth a look (e.g. an extension another profile already has).</summary>+ Warning,+ /// <summary>Allowed but probably useless (e.g. an extension no engine can read).</summary>+ Muted,+}++/// <summary>One chip of a <see cref="TagEditor"/>.</summary>+/// <param name="Value">The stored value, passed back to <see cref="TagEditor.RemoveCommand"/>.</param>+/// <param name="Text">What the chip shows (e.g. ".jpg").</param>+public sealed record TagChip(string Value, string Text, TagChipKind Kind = TagChipKind.Normal, string? ToolTip = null)+{+ public bool IsWarning => Kind == TagChipKind.Warning;+ public bool IsMuted => Kind == TagChipKind.Muted;+}++/// <summary>An autocomplete entry of a <see cref="TagEditor"/>.</summary>+/// <param name="Value">Passed to <see cref="TagEditor.AddCommand"/> when the suggestion is picked.</param>+/// <param name="Text">Main label (e.g. ".jpg").</param>+/// <param name="Detail">Secondary label (e.g. "JPG · Image").</param>+/// <param name="Note">Highlighted remark (e.g. the profile that already has this extension).</param>+public sealed record TagSuggestion(string Value, string Text, string? Detail = null, string? Note = null);++/// <summary>+/// Edits a list of short values as chips. Bind <see cref="Tags"/>, <see cref="Text"/> (the unfinished input),+/// <see cref="Suggestions"/>, <see cref="AddCommand"/> (parameter: one raw token) and <see cref="RemoveCommand"/>+/// (parameter: the <see cref="TagChip"/>).+/// </summary>+/// <remarks>+/// Keyboard: Enter / Tab / separators add the typed text (Tab only while there is text, so it still moves focus+/// otherwise); ↓ / ↑ pick a suggestion and Enter or Tab takes it; Esc closes the suggestions, then clears the text;+/// Backspace in the empty box removes the last chip; ← at the start of the box walks into the chips, where ← / → move,+/// Delete / Backspace remove and Esc / Tab return to the box.+/// </remarks>+[TemplatePart("PART_Input", typeof(TextBox))]+[TemplatePart("PART_Chips", typeof(ItemsControl))]+[TemplatePart("PART_Popup", typeof(Popup))]+[TemplatePart("PART_Suggestions", typeof(ListBox))]+public class TagEditor : TemplatedControl+{+ public static readonly StyledProperty<IReadOnlyList<TagChip>?> TagsProperty =+ AvaloniaProperty.Register<TagEditor, IReadOnlyList<TagChip>?>(nameof(Tags));++ public static readonly StyledProperty<IReadOnlyList<TagSuggestion>?> SuggestionsProperty =+ AvaloniaProperty.Register<TagEditor, IReadOnlyList<TagSuggestion>?>(nameof(Suggestions));++ public static readonly StyledProperty<string?> TextProperty =+ AvaloniaProperty.Register<TagEditor, string?>(nameof(Text), "", defaultBindingMode: BindingMode.TwoWay);++ public static readonly StyledProperty<string?> PlaceholderTextProperty =+ AvaloniaProperty.Register<TagEditor, string?>(nameof(PlaceholderText));++ public static readonly StyledProperty<ICommand?> AddCommandProperty =+ AvaloniaProperty.Register<TagEditor, ICommand?>(nameof(AddCommand));++ public static readonly StyledProperty<ICommand?> RemoveCommandProperty =+ AvaloniaProperty.Register<TagEditor, ICommand?>(nameof(RemoveCommand));++ /// <summary>Characters that end a tag while typing or pasting. Line breaks always do.</summary>+ public static readonly StyledProperty<string> SeparatorsProperty =+ AvaloniaProperty.Register<TagEditor, string>(nameof(Separators), ",; ");++ private TextBox? _input;+ private ItemsControl? _chips;+ private Popup? _popup;+ private ListBox? _list;+ private bool _splitting;+ private bool _suggestionsDismissed;++ public IReadOnlyList<TagChip>? Tags+ {+ get => GetValue(TagsProperty);+ set => SetValue(TagsProperty, value);+ }++ public IReadOnlyList<TagSuggestion>? Suggestions+ {+ get => GetValue(SuggestionsProperty);+ set => SetValue(SuggestionsProperty, value);+ }++ /// <summary>The text typed but not yet turned into a chip.</summary>+ public string? Text+ {+ get => GetValue(TextProperty);+ set => SetValue(TextProperty, value);+ }++ public string? PlaceholderText+ {+ get => GetValue(PlaceholderTextProperty);+ set => SetValue(PlaceholderTextProperty, value);+ }++ /// <summary>Executed once per finished token with the raw token text (trimmed, never empty).</summary>+ public ICommand? AddCommand+ {+ get => GetValue(AddCommandProperty);+ set => SetValue(AddCommandProperty, value);+ }++ /// <summary>Executed with the <see cref="TagChip"/> to remove.</summary>+ public ICommand? RemoveCommand+ {+ get => GetValue(RemoveCommandProperty);+ set => SetValue(RemoveCommandProperty, value);+ }++ public string Separators+ {+ get => GetValue(SeparatorsProperty);+ set => SetValue(SeparatorsProperty, value);+ }++ /// <summary>True while the suggestion list is shown.</summary>+ public bool IsSuggestionListOpen => _popup?.IsOpen == true;++ /// <summary>Moves keyboard focus into the text box.</summary>+ public void FocusInput() => _input?.Focus(NavigationMethod.Tab);++ protected override void OnApplyTemplate(TemplateAppliedEventArgs e)+ {+ base.OnApplyTemplate(e);++ if (_input is not null)+ {+ _input.RemoveHandler(KeyDownEvent, OnInputKeyDown);+ _input.TextChanged -= OnInputTextChanged;+ _input.GotFocus -= OnInputFocusChanged;+ _input.LostFocus -= OnInputLostFocus;+ }+ if (_chips is not null)+ {+ _chips.RemoveHandler(Button.ClickEvent, OnChipButtonClick);+ _chips.RemoveHandler(KeyDownEvent, OnChipKeyDown);+ }+ if (_list is not null)+ {+ _list.RemoveHandler(PointerReleasedEvent, OnSuggestionReleased);+ _list.ContainerPrepared -= OnSuggestionContainerPrepared;+ }++ _input = e.NameScope.Find<TextBox>("PART_Input");+ _chips = e.NameScope.Find<ItemsControl>("PART_Chips");+ _popup = e.NameScope.Find<Popup>("PART_Popup");+ _list = e.NameScope.Find<ListBox>("PART_Suggestions");++ if (_input is not null)+ {+ // Tunnel: see Enter / Tab / arrows before the text box acts on them.+ _input.AddHandler(KeyDownEvent, OnInputKeyDown, RoutingStrategies.Tunnel);+ _input.TextChanged += OnInputTextChanged;+ _input.GotFocus += OnInputFocusChanged;+ _input.LostFocus += OnInputLostFocus;+ }+ if (_chips is not null)+ {+ _chips.AddHandler(Button.ClickEvent, OnChipButtonClick);+ _chips.AddHandler(KeyDownEvent, OnChipKeyDown);+ }+ if (_list is not null)+ {+ _list.AddHandler(PointerReleasedEvent, OnSuggestionReleased, RoutingStrategies.Bubble, handledEventsToo: true);+ _list.ContainerPrepared += OnSuggestionContainerPrepared;+ }+ }++ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)+ {+ base.OnPropertyChanged(change);+ if (change.Property == SuggestionsProperty)+ UpdateSuggestionList();+ else if (change.Property == TextProperty)+ {+ _suggestionsDismissed = false;+ UpdateSuggestionList();+ }+ }++ /// <summary>A click on the empty part of the box puts the caret into the text box.</summary>+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (e.Handled || _input is null || ReferenceEquals(e.Source, _input) || _input.IsFocused)+ return;+ if (e.Source is Visual source && source.FindAncestorOfType<TextBox>(includeSelf: true) is not null)+ return;+ _input.Focus(NavigationMethod.Pointer);+ e.Handled = true;+ }++ // ───────── Typing ─────────++ private void OnInputTextChanged(object? sender, TextChangedEventArgs e)+ {+ if (_splitting || _input?.Text is not { } text || text.IndexOfAny(SeparatorChars()) < 0)+ return;++ // A separator was typed or a list was pasted: everything before the last separator becomes chips,+ // the rest stays in the box.+ var last = text.LastIndexOfAny(SeparatorChars());+ var done = text[..last];+ var rest = text[(last + 1)..];+ _splitting = true;+ try+ {+ AddTokens(done);+ _input.Text = rest;+ _input.CaretIndex = rest.Length;+ }+ finally+ {+ _splitting = false;+ }+ }++ private void OnInputKeyDown(object? sender, KeyEventArgs e)+ {+ if (_input is null)+ return;+ var hasText = !string.IsNullOrWhiteSpace(_input.Text);+ switch (e.Key)+ {+ case Key.Enter:+ // Always handled: a bare Enter must not insert a line break or press a dialog's default button.+ if (!AcceptHighlighted())+ CommitInput();+ e.Handled = true;+ break;++ case Key.Tab when e.KeyModifiers == KeyModifiers.None && (hasText || HighlightedIndex >= 0):+ if (!AcceptHighlighted())+ CommitInput();+ e.Handled = true;+ break;++ case Key.Back when string.IsNullOrEmpty(_input.Text):+ if (Tags is { Count: > 0 } tags)+ RemoveCommand?.Execute(tags[^1]);+ e.Handled = true;+ break;++ case Key.Left when _input.CaretIndex == 0 && _input.SelectionStart == _input.SelectionEnd && Tags is { Count: > 0 }:+ FocusChip(Tags.Count - 1);+ e.Handled = true;+ break;++ case Key.Down when Suggestions is { Count: > 0 } && hasText:+ _suggestionsDismissed = false;+ UpdateSuggestionList();+ MoveHighlight(+1);+ e.Handled = true;+ break;++ case Key.Up when IsSuggestionListOpen:+ MoveHighlight(-1);+ e.Handled = true;+ break;++ case Key.Escape when IsSuggestionListOpen:+ _suggestionsDismissed = true;+ UpdateSuggestionList();+ e.Handled = true;+ break;++ case Key.Escape when hasText:+ _input.Text = "";+ e.Handled = true;+ break;+ }+ }++ private void OnInputFocusChanged(object? sender, RoutedEventArgs e) => UpdateSuggestionList();++ /// <summary>Leaving the box keeps what was typed, like pressing Enter.</summary>+ private void OnInputLostFocus(object? sender, RoutedEventArgs e)+ {+ CommitInput();+ UpdateSuggestionList();+ }++ /// <summary>Adds the typed text (possibly several tokens). Returns false when the box was empty.</summary>+ private bool CommitInput()+ {+ if (_input is null || string.IsNullOrWhiteSpace(_input.Text))+ return false;+ var text = _input.Text;+ _splitting = true;+ try+ {+ _input.Text = "";+ }+ finally+ {+ _splitting = false;+ }+ AddTokens(text);+ return true;+ }++ private void AddTokens(string text)+ {+ foreach (var token in text.Split(SeparatorChars(), StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))+ {+ if (AddCommand is { } command && command.CanExecute(token))+ command.Execute(token);+ }+ }++ private char[] SeparatorChars() => [.. Separators, '\r', '\n', '\t'];++ // ───────── Suggestions ─────────++ private int HighlightedIndex => _list?.SelectedIndex ?? -1;++ private void UpdateSuggestionList()+ {+ if (_popup is null)+ return;+ var open = _input?.IsFocused == true+ && !_suggestionsDismissed+ && !string.IsNullOrWhiteSpace(Text)+ && Suggestions is { Count: > 0 };+ if (open && _list is not null && _popup.Child is Control child)+ child.MinWidth = Math.Max(200, Bounds.Width);+ _popup.IsOpen = open;+ if (_list is not null && (!open || _list.SelectedIndex >= (Suggestions?.Count ?? 0)))+ _list.SelectedIndex = -1;+ }++ private void MoveHighlight(int delta)+ {+ if (_list is null || Suggestions is not { Count: > 0 } items || !IsSuggestionListOpen)+ return;+ var index = Math.Clamp(_list.SelectedIndex + delta, -1, items.Count - 1);+ _list.SelectedIndex = index;+ if (index >= 0)+ _list.ScrollIntoView(index);+ }++ /// <summary>Takes the highlighted suggestion, if any.</summary>+ private bool AcceptHighlighted()+ {+ if (!IsSuggestionListOpen || _list?.SelectedItem is not TagSuggestion suggestion)+ return false;+ Accept(suggestion);+ return true;+ }++ private void Accept(TagSuggestion suggestion)+ {+ if (_input is not null)+ {+ _splitting = true;+ try+ {+ _input.Text = "";+ }+ finally+ {+ _splitting = false;+ }+ }+ if (AddCommand is { } command && command.CanExecute(suggestion.Value))+ command.Execute(suggestion.Value);+ _input?.Focus(NavigationMethod.Pointer);+ }++ private void OnSuggestionReleased(object? sender, PointerReleasedEventArgs e)+ {+ if (e.Source is Visual source && source.FindAncestorOfType<ListBoxItem>(includeSelf: true) is { DataContext: TagSuggestion suggestion })+ {+ Accept(suggestion);+ e.Handled = true;+ }+ }++ /// <summary>Suggestions never take focus, so typing continues while the list is used with the mouse.</summary>+ private static void OnSuggestionContainerPrepared(object? sender, ContainerPreparedEventArgs e) => e.Container.Focusable = false;++ // ───────── Chips ─────────++ private void OnChipButtonClick(object? sender, RoutedEventArgs e)+ {+ if (e.Source is Visual source && source.FindAncestorOfType<Button>(includeSelf: true) is { DataContext: TagChip chip })+ {+ RemoveCommand?.Execute(chip);+ _input?.Focus(NavigationMethod.Pointer);+ e.Handled = true;+ }+ }++ private void OnChipKeyDown(object? sender, KeyEventArgs e)+ {+ if (e.Source is not Control { DataContext: TagChip chip } || Tags is not { } tags)+ return;+ var index = IndexOf(tags, chip);+ switch (e.Key)+ {+ case Key.Left:+ FocusChip(Math.Max(0, index - 1));+ break;+ case Key.Right when index < tags.Count - 1:+ FocusChip(index + 1);+ break;+ case Key.Right or Key.Escape or Key.End or Key.Down:+ FocusInput();+ break;+ case Key.Delete or Key.Back:+ RemoveCommand?.Execute(chip);+ // The chip list may be rebuilt by the view model; focus the neighbour once it is.+ Dispatcher.UIThread.Post(() =>+ {+ if (Tags is { Count: > 0 } now)+ FocusChip(Math.Min(index, now.Count - 1));+ else+ FocusInput();+ }, DispatcherPriority.Loaded);+ break;+ default:+ return;+ }+ e.Handled = true;+ }++ private void FocusChip(int index)+ {+ if (_chips?.ContainerFromIndex(index) is not { } container)+ return;+ var chip = container.GetVisualDescendants().OfType<Border>().FirstOrDefault(b => b.Classes.Contains("tagchip"));+ chip?.Focus(NavigationMethod.Directional);+ }++ private static int IndexOf(IReadOnlyList<TagChip> tags, TagChip chip)+ {+ for (var i = 0; i < tags.Count; i++)+ {+ if (Equals(tags[i], chip))+ return i;+ }+ return -1;+ }+}diff --git a/src/Filee.App/Styles/Icons.axaml b/src/Filee.App/Styles/Icons.axamlindex d67ae116..c0ef6b50 100644--- a/src/Filee.App/Styles/Icons.axaml+++ b/src/Filee.App/Styles/Icons.axaml@@ -17,6 +17,8 @@<StreamGeometry x:Key="Icon.Delete">M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z</StreamGeometry><StreamGeometry x:Key="Icon.Copy">M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z</StreamGeometry><StreamGeometry x:Key="Icon.Close">M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z</StreamGeometry>+ <StreamGeometry x:Key="Icon.ChevronRight">M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z</StreamGeometry>+ <StreamGeometry x:Key="Icon.Shapes">M11,13.5V21.5H3V13.5H11M9,15.5H5V19.5H9V15.5M12,2L17.5,11H6.5L12,2M12,5.86L10.08,9H13.92L12,5.86M17.5,13C20,13 22,15 22,17.5C22,20 20,22 17.5,22C15,22 13,20 13,17.5C13,15 15,13 17.5,13M17.5,15A2.5,2.5 0 0,0 15,17.5A2.5,2.5 0 0,0 17.5,20A2.5,2.5 0 0,0 20,17.5A2.5,2.5 0 0,0 17.5,15Z</StreamGeometry><StreamGeometry x:Key="Icon.ArrowUp">M7,15L12,10L17,15H7Z</StreamGeometry><StreamGeometry x:Key="Icon.ArrowDown">M7,10L12,15L17,10H7Z</StreamGeometry><StreamGeometry x:Key="Icon.Upload">M9,16V10H5L12,3L19,10H15V16H9M5,20V18H19V20H5Z</StreamGeometry>diff --git a/src/Filee.App/Styles/TagEditor.axaml b/src/Filee.App/Styles/TagEditor.axamlnew file mode 100644index 00000000..8c919f8f--- /dev/null+++ b/src/Filee.App/Styles/TagEditor.axaml@@ -0,0 +1,172 @@+<!--+ Look of the chip input (Controls/TagEditor.cs): a box drawn like a Fluent TextBox (same brushes for rest, hover and+ focus) holding rounded chips, a borderless text box and an autocomplete list in the window's overlay layer.+-->+<Styles xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:c="using:Filee.App.Controls">++ <Styles.Resources>+ <ControlTheme x:Key="{x:Type c:TagEditor}" TargetType="c:TagEditor">+ <Setter Property="Background" Value="{DynamicResource TextControlBackground}" />+ <Setter Property="BorderBrush" Value="{DynamicResource TextControlBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />+ <!-- Includes the 1px frame (drawn underneath, see PART_Frame). -->+ <Setter Property="Padding" Value="4" />+ <Setter Property="Cursor" Value="IBeam" />+ <Setter Property="Template">+ <ControlTemplate>+ <Panel>+ <!-- Drawn separately from the content so the thicker focus border doesn't shift the chips. -->+ <Border Name="PART_Frame"+ Background="{TemplateBinding Background}"+ BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}"+ CornerRadius="{TemplateBinding CornerRadius}" />+ <WrapPanel Margin="{TemplateBinding Padding}" MinHeight="30">+ <ItemsControl Name="PART_Chips" ItemsSource="{TemplateBinding Tags}"+ KeyboardNavigation.TabNavigation="None" Cursor="Arrow">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <WrapPanel />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="c:TagChip">+ <Border Classes="tagchip" Classes.warning="{Binding IsWarning}" Classes.muted="{Binding IsMuted}"+ Focusable="True" ToolTip.Tip="{Binding ToolTip}"+ AutomationProperties.Name="{Binding Text}" AutomationProperties.HelpText="{Binding ToolTip}">+ <StackPanel Orientation="Horizontal" Spacing="3">+ <PathIcon Classes="tagchip-flag" Data="{StaticResource Icon.Alert}" IsVisible="{Binding IsWarning}" />+ <TextBlock Classes="tagchip-text" Text="{Binding Text}" />+ <Button Classes="tagchip-remove" Focusable="False" ToolTip.Tip="{DynamicResource tags.remove}">+ <PathIcon Width="8" Height="8" Data="{StaticResource Icon.Close}" />+ </Button>+ </StackPanel>+ </Border>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ <TextBox Name="PART_Input" Classes="bare"+ Text="{TemplateBinding Text, Mode=TwoWay}"+ PlaceholderText="{TemplateBinding PlaceholderText}"+ AcceptsReturn="True" TextWrapping="NoWrap" MinWidth="150" />+ </WrapPanel>++ <Popup Name="PART_Popup" PlacementTarget="{Binding #PART_Frame}" Placement="BottomEdgeAlignedLeft"+ VerticalOffset="4" ShouldUseOverlayLayer="True" IsLightDismissEnabled="False">+ <Border Classes="tag-popup">+ <ListBox Name="PART_Suggestions" Classes="soft tag-suggestions" ItemsSource="{TemplateBinding Suggestions}"+ Focusable="False" MaxHeight="260">+ <ListBox.ItemTemplate>+ <DataTemplate x:DataType="c:TagSuggestion">+ <DockPanel>+ <TextBlock DockPanel.Dock="Right" Classes="caption tag-suggestion-note" Text="{Binding Note}"+ Margin="12,0,0,0" VerticalAlignment="Center" />+ <TextBlock DockPanel.Dock="Left" Text="{Binding Text}" FontWeight="SemiBold" MinWidth="64" VerticalAlignment="Center" />+ <TextBlock Classes="caption" Text="{Binding Detail}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />+ </DockPanel>+ </DataTemplate>+ </ListBox.ItemTemplate>+ </ListBox>+ </Border>+ </Popup>+ </Panel>+ </ControlTemplate>+ </Setter>++ <Style Selector="^:pointerover /template/ Border#PART_Frame">+ <Setter Property="BorderBrush" Value="{DynamicResource TextControlBorderBrushPointerOver}" />+ </Style>+ <Style Selector="^:focus-within /template/ Border#PART_Frame">+ <Setter Property="Background" Value="{DynamicResource TextControlBackgroundFocused}" />+ <Setter Property="BorderBrush" Value="{DynamicResource TextControlBorderBrushFocused}" />+ <Setter Property="BorderThickness" Value="{DynamicResource TextControlBorderThemeThicknessFocused}" />+ </Style>+ </ControlTheme>+ </Styles.Resources>++ <!-- The text box inside the chip box: no frame of its own. -->+ <Style Selector="TextBox.bare">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="MinHeight" Value="28" />+ <Setter Property="Padding" Value="7,4,4,4" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="TextBox.bare /template/ Border#PART_BorderElement, TextBox.bare:pointerover /template/ Border#PART_BorderElement, TextBox.bare:focus /template/ Border#PART_BorderElement">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderThickness" Value="0" />+ </Style>++ <!-- Chips -->+ <Style Selector="Border.tagchip">+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ <Setter Property="BorderBrush" Value="Transparent" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Padding" Value="9,1,2,1" />+ <Setter Property="Margin" Value="2" />+ <Setter Property="MinHeight" Value="26" />+ </Style>+ <Style Selector="Border.tagchip:focus">+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />+ </Style>+ <Style Selector="Border.tagchip.warning">+ <Setter Property="Padding" Value="6,1,2,1" />+ <Setter Property="BorderBrush" Value="{DynamicResource WarningBrush}" />+ </Style>+ <Style Selector="Border.tagchip.muted">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderBrush" Value="{DynamicResource TextControlBorderBrush}" />+ </Style>+ <Style Selector="Border.tagchip TextBlock.tagchip-text">+ <Setter Property="FontSize" Value="13" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="Border.tagchip.muted TextBlock.tagchip-text">+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ <Setter Property="FontStyle" Value="Italic" />+ </Style>+ <Style Selector="PathIcon.tagchip-flag">+ <Setter Property="Width" Value="12" />+ <Setter Property="Height" Value="12" />+ <Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="Button.tagchip-remove">+ <Setter Property="Padding" Value="6" />+ <Setter Property="MinWidth" Value="0" />+ <Setter Property="MinHeight" Value="0" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ </Style>+ <Style Selector="Button.tagchip-remove:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>++ <!-- Suggestions -->+ <Style Selector="Border.tag-popup">+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />+ <Setter Property="Padding" Value="4" />+ <Setter Property="BoxShadow" Value="{DynamicResource CardShadow}" />+ <Setter Property="Margin" Value="0,0,12,12" />+ </Style>+ <Style Selector="ListBox.tag-suggestions ListBoxItem">+ <Setter Property="Padding" Value="10,6" />+ <Setter Property="Cursor" Value="Hand" />+ </Style>+ <Style Selector="TextBlock.tag-suggestion-note">+ <Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />+ </Style>+</Styles>diff --git a/src/Filee.App/ViewModels/FormatLabels.cs b/src/Filee.App/ViewModels/FormatLabels.csnew file mode 100644index 00000000..61f3b5c9--- /dev/null+++ b/src/Filee.App/ViewModels/FormatLabels.cs@@ -0,0 +1,24 @@+// User-facing names of formats and format categories ("MP4 · Video", "폴더"), shared by the settings pages.++using Filee.Core.Formats;+using Filee.Core.Localization;++namespace Filee.App.ViewModels;++/// <summary>Localized labels for <see cref="FileFormat"/> and <see cref="FormatCategory"/>.</summary>+public static class FormatLabels+{+ /// <summary>"Image", "동영상", ... (keys <c>format.category.*</c>).</summary>+ public static string Category(ILocalizer loc, FormatCategory category) => loc[$"format.category.{category}"];++ /// <summary>The format's short name; the "folder" pseudo format (Extract) is translated.</summary>+ public static string Name(ILocalizer loc, FileFormat format) =>+ format.Id == FormatRegistry.Folder ? loc["format.folder"] : format.DisplayName;++ /// <summary>Name of the format with id <paramref name="formatId"/>, or null when it is unknown.</summary>+ public static string? NameOf(ILocalizer loc, string formatId) =>+ FormatRegistry.FindById(formatId) is { } format ? Name(loc, format) : null;++ /// <summary>"JPG · Image".</summary>+ public static string NameAndCategory(ILocalizer loc, FileFormat format) => $"{Name(loc, format)} · {Category(loc, format.Category)}";+}diff --git a/src/Filee.App/ViewModels/Pages/ExtensionInput.cs b/src/Filee.App/ViewModels/Pages/ExtensionInput.csnew file mode 100644index 00000000..7732bdc6--- /dev/null+++ b/src/Filee.App/ViewModels/Pages/ExtensionInput.cs@@ -0,0 +1,85 @@+// Rules for the extensions a user types into a donut profile, and the autocomplete list built from FormatRegistry.++using Filee.App.Controls;+using Filee.Core.Formats;+using Filee.Core.Localization;++namespace Filee.App.ViewModels.Pages;++/// <summary>Cleans up and suggests file extensions for toolbar profiles.</summary>+public static class ExtensionInput+{+ private const int MaxLength = 16;++ /// <summary>+ /// Turns user input into a stored extension: trimmed, lower-case, without leading dots or wildcards+ /// (" *.JPG " → "jpg", ".tar.gz" → "tar.gz"). Returns null for text that can't be an extension.+ /// </summary>+ /// <remarks>+ /// Two-part extensions are only accepted when Filee knows them (tar.gz, tar.xz ...): files are matched with+ /// <see cref="FormatRegistry.ExtensionOf"/>, which only sees the last part of any other name ("x.foo.bar" → "bar").+ /// </remarks>+ public static string? Normalize(string? text)+ {+ var value = (text ?? "").Trim().TrimStart('*', '.').TrimEnd('.').ToLowerInvariant();+ if (value.Length is 0 or > MaxLength || value.Contains("..", StringComparison.Ordinal))+ return null;+ if (!value.All(c => char.IsLetterOrDigit(c) || c is '-' or '_' or '+' or '.'))+ return null;+ if (value.Contains('.') && FormatRegistry.FindByExtension(value) is null)+ return null;+ return value;+ }++ /// <summary>+ /// Autocomplete entries for <paramref name="text"/>: extensions starting with it first, then formats whose name+ /// matches, then everything in a matching category ("video", "동영상"). Extensions in <paramref name="existing"/>+ /// are left out; <paramref name="ownerOf"/> names the profile that already has an extension (shown as a note).+ /// </summary>+ public static IReadOnlyList<TagSuggestion> Suggest(+ string? text, IEnumerable<string> existing, Func<string, string?> ownerOf, ILocalizer loc, int max = 8)+ {+ var query = (text ?? "").Trim().TrimStart('*', '.').ToLowerInvariant();+ if (query.Length == 0)+ return [];+ var taken = existing.ToHashSet(StringComparer.OrdinalIgnoreCase);++ var candidates = FormatRegistry.Known+ .Where(f => f.Id != FormatRegistry.Folder)+ .SelectMany((format, formatIndex) => format.Extensions+ .Where(e => e.Length > 0 && !taken.Contains(e))+ .Select((extension, i) => (Extension: extension, Format: format, Order: formatIndex * 100 + i)));++ return candidates+ .Select(c => (c.Extension, c.Format, c.Order, Score: Score(query, c.Extension, c.Format, loc)))+ .Where(c => c.Score >= 0)+ .OrderBy(c => c.Score)+ .ThenBy(c => c.Order)+ .Take(max)+ .Select(c => new TagSuggestion(+ c.Extension,+ "." + c.Extension,+ FormatLabels.NameAndCategory(loc, c.Format),+ ownerOf(c.Extension) is { } owner ? loc.Format("toolbar.ext_in_profile", owner) : null))+ .ToList();+ }++ /// <summary>Lower is better; -1 = no match.</summary>+ private static int Score(string query, string extension, FileFormat format, ILocalizer loc)+ {+ if (extension.Equals(query, StringComparison.OrdinalIgnoreCase))+ return 0;+ if (extension.StartsWith(query, StringComparison.OrdinalIgnoreCase))+ return 1;+ if (format.DisplayName.StartsWith(query, StringComparison.OrdinalIgnoreCase) || format.Id.StartsWith(query, StringComparison.OrdinalIgnoreCase))+ return 2;+ // Substrings of one letter would match almost everything.+ if (query.Length >= 2 && (extension.Contains(query, StringComparison.OrdinalIgnoreCase)+ || format.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase)))+ return 3;+ if (FormatLabels.Category(loc, format.Category).StartsWith(query, StringComparison.CurrentCultureIgnoreCase)+ || format.Category.ToString().StartsWith(query, StringComparison.OrdinalIgnoreCase))+ return 4;+ return -1;+ }+}diff --git a/src/Filee.App/ViewModels/Pages/ExtensionTagsViewModel.cs b/src/Filee.App/ViewModels/Pages/ExtensionTagsViewModel.csnew file mode 100644index 00000000..0436f39e--- /dev/null+++ b/src/Filee.App/ViewModels/Pages/ExtensionTagsViewModel.cs@@ -0,0 +1,141 @@+// The extension chips of a normal donut profile (Toolbar page): adds and removes extensions, saving immediately,+// and explains the ones that won't work as expected (another profile opens those files, or no engine reads them).++using CommunityToolkit.Mvvm.ComponentModel;+using CommunityToolkit.Mvvm.Input;+using Filee.App.Controls;+using Filee.Core.Formats;+using Filee.Core.Localization;+using Filee.Core.Profiles;++namespace Filee.App.ViewModels.Pages;++/// <summary>An inline remark under the extension chips.</summary>+public sealed record ExtensionNote(string Text, bool IsWarning);++/// <summary>Backs the <see cref="TagEditor"/> of one normal (not mixed-selection) profile.</summary>+public sealed partial class ExtensionTagsViewModel : ObservableObject+{+ private readonly ToolbarProfile _profile;+ private readonly IReadOnlyList<ToolbarProfile> _profiles;+ private readonly ILocalizer _loc;+ private readonly Action _save;++ /// <param name="profile">The profile being edited.</param>+ /// <param name="profiles">All profiles in selection order (used to find who else has an extension).</param>+ /// <param name="save">Persists the library after every change.</param>+ public ExtensionTagsViewModel(ToolbarProfile profile, IReadOnlyList<ToolbarProfile> profiles, ILocalizer loc, Action save)+ {+ _profile = profile;+ _profiles = profiles;+ _loc = loc;+ _save = save;+ Refresh();+ }++ [ObservableProperty] private IReadOnlyList<TagChip> _tags = [];+ [ObservableProperty] private IReadOnlyList<ExtensionNote> _notes = [];+ [ObservableProperty] private IReadOnlyList<TagSuggestion> _suggestions = [];+ [ObservableProperty] private string _text = "";+ [ObservableProperty] private string? _inputError;++ partial void OnTextChanged(string value)+ {+ UpdateSuggestions();+ // Typing again dismisses the last complaint (clearing the box after a refused token must not).+ if (value.Length > 0)+ InputError = null;+ }++ /// <summary>Adds one typed token. Invalid and duplicate input is refused with an inline message.</summary>+ [RelayCommand]+ private void Add(string? token)+ {+ InputError = null;+ if (string.IsNullOrWhiteSpace(token))+ return;+ var extension = ExtensionInput.Normalize(token);+ if (extension is null)+ {+ InputError = _loc.Format("toolbar.ext_invalid", token.Trim());+ return;+ }+ if (_profile.Extensions.Contains(extension, StringComparer.OrdinalIgnoreCase))+ {+ InputError = _loc.Format("toolbar.ext_duplicate", "." + extension);+ return;+ }+ _profile.Extensions.Add(extension);+ _save();+ Refresh();+ }++ [RelayCommand]+ private void Remove(TagChip? chip)+ {+ if (chip is null || _profile.Extensions.RemoveAll(e => e.Equals(chip.Value, StringComparison.OrdinalIgnoreCase)) == 0)+ return;+ InputError = null;+ _save();+ Refresh();+ }++ /// <summary>The first other normal profile (selection order) that also has <paramref name="extension"/>.</summary>+ private ToolbarProfile? OwnerOf(string extension) =>+ _profiles.FirstOrDefault(p => !p.IsFallback && !ReferenceEquals(p, _profile) && p.Matches(extension));++ /// <summary>Rebuilds the chips and the remarks from the profile.</summary>+ private void Refresh()+ {+ var myIndex = IndexOf(_profile);+ var chips = new List<TagChip>();+ var claimed = new List<(ToolbarProfile Owner, string Text)>();+ var unknown = new List<string>();++ foreach (var extension in _profile.Extensions)+ {+ var text = "." + extension;+ if (OwnerOf(extension) is { } owner)+ {+ chips.Add(new TagChip(extension, text, TagChipKind.Warning, _loc.Format("toolbar.ext_also_in", _loc.DisplayName(owner))));+ claimed.Add((owner, text));+ }+ else if (FormatRegistry.FindByExtension(extension) is { } format)+ chips.Add(new TagChip(extension, text, TagChipKind.Normal, FormatLabels.NameAndCategory(_loc, format)));+ else+ {+ chips.Add(new TagChip(extension, text, TagChipKind.Muted, _loc["toolbar.ext_unknown_tip"]));+ unknown.Add(text);+ }+ }++ var notes = new List<ExtensionNote>();+ if (_profile.Extensions.Count == 0)+ notes.Add(new ExtensionNote(_loc["toolbar.ext_none"], false));+ // One line per other profile. Which one wins depends on the list order (ProfileSelector takes the first).+ foreach (var group in claimed.GroupBy(c => c.Owner))+ {+ var key = IndexOf(group.Key) < myIndex ? "toolbar.ext_claimed_first" : "toolbar.ext_claimed_later";+ notes.Add(new ExtensionNote(_loc.Format(key, string.Join(", ", group.Select(c => c.Text)), _loc.DisplayName(group.Key)), true));+ }+ if (unknown.Count > 0)+ notes.Add(new ExtensionNote(_loc.Format("toolbar.ext_unknown", string.Join(", ", unknown)), false));++ Tags = chips;+ Notes = notes;+ UpdateSuggestions();+ }++ private void UpdateSuggestions() =>+ Suggestions = ExtensionInput.Suggest(Text, _profile.Extensions, e => OwnerOf(e) is { } owner ? _loc.DisplayName(owner) : null, _loc);++ private int IndexOf(ToolbarProfile profile)+ {+ for (var i = 0; i < _profiles.Count; i++)+ {+ if (ReferenceEquals(_profiles[i], profile))+ return i;+ }+ return -1;+ }+}diff --git a/src/Filee.App/ViewModels/Pages/MixedExtensionsViewModel.cs b/src/Filee.App/ViewModels/Pages/MixedExtensionsViewModel.csnew file mode 100644index 00000000..bb55c8dc--- /dev/null+++ b/src/Filee.App/ViewModels/Pages/MixedExtensionsViewModel.cs@@ -0,0 +1,196 @@+// The editor of a mixed-selection donut ("Mixed files"): which extensions a mix of files may contain for this donut+// to open, as a check list grouped by the normal profiles. Nothing checked = any mix no other donut takes.+// Checks are stored in the profile's Extensions and saved immediately; ProfileSelector explains the rules.++using CommunityToolkit.Mvvm.ComponentModel;+using CommunityToolkit.Mvvm.Input;+using Filee.Core.Formats;+using Filee.Core.Localization;+using Filee.Core.Profiles;++namespace Filee.App.ViewModels.Pages;++/// <summary>Backs the check list shown instead of the extension chips for a mixed-selection profile.</summary>+public sealed partial class MixedExtensionsViewModel : ObservableObject+{+ private readonly ToolbarProfile _profile;+ private readonly IReadOnlyList<ToolbarProfile> _profiles;+ private readonly ILocalizer _loc;+ private readonly Action _save;++ /// <param name="profile">The mixed-selection profile being edited.</param>+ /// <param name="profiles">All profiles in selection order; every normal one becomes a group.</param>+ /// <param name="save">Persists the library after every change.</param>+ public MixedExtensionsViewModel(ToolbarProfile profile, IReadOnlyList<ToolbarProfile> profiles, ILocalizer loc, Action save)+ {+ _profile = profile;+ _profiles = profiles;+ _loc = loc;+ _save = save;++ var groups = profiles+ .Where(p => !p.IsFallback)+ .Select(p => new ExtensionGroupViewModel(this, loc.DisplayName(p), p.Extensions))+ .Where(g => g.Extensions.Count > 0)+ .ToList();+ // Checked extensions no normal profile has (removed from it later, or never there) stay visible so they+ // can be unchecked.+ var grouped = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);+ var others = profile.Extensions.Where(e => !grouped.Contains(e)).ToList();+ if (others.Count > 0)+ groups.Add(new ExtensionGroupViewModel(this, loc["toolbar.mixed_other_group"], others));+ Groups = groups;+ UpdateHint();+ }++ public IReadOnlyList<ExtensionGroupViewModel> Groups { get; }++ /// <summary>What this donut is used for with the current checks, in words.</summary>+ [ObservableProperty] private string _hint = "";++ /// <summary>True when the checks make this donut unreachable.</summary>+ [ObservableProperty] private bool _hintIsWarning;++ internal ILocalizer Localizer => _loc;++ internal bool IsChecked(string extension) => _profile.Matches(extension);++ /// <summary>Checks or unchecks extensions, saves, and updates every group showing them.</summary>+ internal void Set(IEnumerable<string> extensions, bool check)+ {+ var changed = false;+ foreach (var extension in extensions)+ {+ if (check && !_profile.Matches(extension))+ {+ _profile.Extensions.Add(extension.ToLowerInvariant());+ changed = true;+ }+ else if (!check)+ changed |= _profile.Extensions.RemoveAll(e => e.Equals(extension, StringComparison.OrdinalIgnoreCase)) > 0;+ }+ if (!changed)+ return;+ _save();+ // An extension can sit in two groups (two profiles have it): keep both in step.+ foreach (var group in Groups)+ group.Sync();+ UpdateHint();+ }++ private void UpdateHint()+ {+ var catchAll = ProfileSelector.CatchAll(_profiles);+ var catchAllName = catchAll is null ? "" : _loc.DisplayName(catchAll);+ var isCatchAll = ReferenceEquals(catchAll, _profile);+ // A mixed profile listed earlier that allows everything checked here takes all of this one's selections.+ var covering = _profile.Extensions.Count == 0 ? null : _profiles+ .TakeWhile(p => !ReferenceEquals(p, _profile))+ .FirstOrDefault(p => p.IsFallback && p.Extensions.Count > 0 && _profile.Extensions.All(p.Matches));++ (Hint, HintIsWarning) = (_profile.Extensions.Count, isCatchAll, covering) switch+ {+ (0, true, _) => (_loc["toolbar.mixed_catch_all"], false),+ (0, false, _) => (_loc.Format("toolbar.mixed_shadowed", catchAllName), true),+ (_, _, { } earlier) => (_loc.Format("toolbar.mixed_covered", _loc.DisplayName(earlier)), true),+ (_, true, _) => (_loc["toolbar.mixed_others_self"], false),+ _ => (_loc.Format("toolbar.mixed_others", catchAllName), false),+ };+ }+}++/// <summary>The extensions of one normal profile in the mixed-selection check list.</summary>+public sealed partial class ExtensionGroupViewModel : ObservableObject+{+ private readonly MixedExtensionsViewModel _owner;++ internal ExtensionGroupViewModel(MixedExtensionsViewModel owner, string name, IEnumerable<string> extensions)+ {+ _owner = owner;+ Name = name;+ Extensions = extensions+ .Distinct(StringComparer.OrdinalIgnoreCase)+ .Select(e => new ExtensionToggleViewModel(owner, e, owner.IsChecked(e)))+ .ToList();+ }++ public string Name { get; }++ public IReadOnlyList<ExtensionToggleViewModel> Extensions { get; }++ /// <summary>Collapsed by default: the group check box and the count tell the state.</summary>+ [ObservableProperty] private bool _isExpanded;++ /// <summary>True = all checked, false = none, null = some.</summary>+ public bool? State+ {+ get+ {+ var count = CheckedCount;+ return count == 0 ? false : count == Extensions.Count ? true : null;+ }+ }++ /// <summary>"3 / 41".</summary>+ public string Count => $"{CheckedCount} / {Extensions.Count}";++ private int CheckedCount => Extensions.Count(e => e.IsChecked);++ /// <summary>The group check box: all checked → none; otherwise → all.</summary>+ [RelayCommand]+ private void ToggleAll() => _owner.Set(Extensions.Select(e => e.Extension), State != true);++ internal void Sync()+ {+ foreach (var toggle in Extensions)+ toggle.Sync();+ OnPropertyChanged(nameof(State));+ OnPropertyChanged(nameof(Count));+ }+}++/// <summary>One extension chip of the mixed-selection check list.</summary>+public sealed partial class ExtensionToggleViewModel : ObservableObject+{+ private readonly MixedExtensionsViewModel _owner;+ private bool _isChecked;++ internal ExtensionToggleViewModel(MixedExtensionsViewModel owner, string extension, bool isChecked)+ {+ _owner = owner;+ _isChecked = isChecked;+ Extension = extension;+ ToolTip = FormatRegistry.FindByExtension(extension) is { } format+ ? FormatLabels.NameAndCategory(owner.Localizer, format)+ : owner.Localizer["toolbar.ext_unknown_tip"];+ }++ public string Extension { get; }++ public string Text => "." + Extension;++ public string ToolTip { get; }++ public bool IsChecked+ {+ get => _isChecked;+ set+ {+ if (_isChecked == value)+ return;+ _isChecked = value;+ OnPropertyChanged();+ _owner.Set([Extension], value);+ }+ }++ /// <summary>Re-reads the state from the profile without writing it back.</summary>+ internal void Sync()+ {+ var value = _owner.IsChecked(Extension);+ if (_isChecked == value)+ return;+ _isChecked = value;+ OnPropertyChanged(nameof(IsChecked));+ }+}diff --git a/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.csindex 53e668c6..9f0627fe 100644--- a/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs@@ -4,7 +4,6 @@ using System.Collections.ObjectModel;using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;using Filee.App.Services;-using Filee.Core.Formats;using Filee.Core.Localization;using Filee.Core.Presets;using Filee.Core.Settings;@@ -26,7 +25,7 @@ public sealed partial class PresetListItem(Preset preset, ILocalizer loc) : Obseprivate static string TargetLabel(Preset p, ILocalizer l) =>p.TargetFormat == BuiltInData.SameAsSource ? l["presets.same_as_source"]- : "→ " + (FormatRegistry.FindById(p.TargetFormat)?.DisplayName ?? p.TargetFormat);+ : "→ " + (FormatLabels.NameOf(l, p.TargetFormat) ?? p.TargetFormat);}public sealed partial class PresetsPageViewModel : ObservableObjectdiff --git a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.csindex ea47b1f9..d8263e34 100644--- a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs@@ -1,12 +1,14 @@// Donut toolbar editor: 1) choose a profile 2) arrange its presets on a live donut by drag & drop.// The drag gestures themselves live in the view (ToolbarPage.axaml.cs); this class only mutates the model.+// A profile is either normal (extension chips, ExtensionTagsViewModel) or for mixed selections (check list,+// MixedExtensionsViewModel). Normal profiles are kept before the mixed ones, so a new mixed profile never takes over+// the catch-all role of the built-in "Mixed files" donut (see ProfileSelector).using System.Collections.ObjectModel;using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;using Filee.App.Controls;using Filee.App.Services;-using Filee.Core.Formats;using Filee.Core.Localization;using Filee.Core.Presets;using Filee.Core.Profiles;@@ -22,10 +24,14 @@ public sealed partial class ProfileItemViewModel(ToolbarProfile profile, ILocalipublic string Count => $"{Profile.PresetIds.Count}";+ /// <summary>A donut for mixed selections (marked in the list).</summary>+ public bool IsMixed => Profile.IsFallback;+public void Refresh(ILocalizer l){Name = l.DisplayName(Profile);OnPropertyChanged(nameof(Count));+ OnPropertyChanged(nameof(IsMixed));}}@@ -38,6 +44,7 @@ public sealed partial class ToolbarPageViewModel : ObservableObjectprivate readonly ILocalizer _loc;private readonly WindowService _windows;private bool _loading;+ private bool _repositioning;public ToolbarPageViewModel(UserDataStore store, ILocalizer loc, WindowService windows){@@ -64,9 +71,21 @@ public sealed partial class ToolbarPageViewModel : ObservableObject[ObservableProperty] private string _centerTitle = "";[ObservableProperty] private string _centerSubtitle = "";[ObservableProperty] private string _profileName = "";- [ObservableProperty] private string _extensions = "";- [ObservableProperty] private bool _isFallback;[ObservableProperty] private string? _message;++ /// <summary>The selected profile is for mixed selections (toggle in the profile card).</summary>+ [ObservableProperty] private bool _isMixed;++ /// <summary>False for the last mixed-selection profile: Filee always needs one.</summary>+ [ObservableProperty] private bool _canChangeMixed;++ [ObservableProperty] private bool _canDelete;++ /// <summary>Extension chips of a normal profile (null for a mixed one).</summary>+ [ObservableProperty] private ExtensionTagsViewModel? _extensionTags;++ /// <summary>Check list of a mixed-selection profile (null for a normal one).</summary>+ [ObservableProperty] private MixedExtensionsViewModel? _mixedExtensions;[ObservableProperty] private double _outerRadius;[ObservableProperty] private double _holeRatio;[ObservableProperty] private double _sliceOpacity;@@ -75,12 +94,14 @@ public sealed partial class ToolbarPageViewModel : ObservableObjectpartial void OnSelectedProfileChanged(ProfileItemViewModel? value){+ // The list box briefly drops its selection while the selected profile is moved (see Reposition).+ if (_repositioning)+ return;_loading = true;ProfileName = value is null ? "" : _loc.DisplayName(value.Profile);- Extensions = value is null ? "" : string.Join(", ", value.Profile.Extensions);- IsFallback = value?.Profile.IsFallback == true;_loading = false;Message = null;+ RebuildProfileEditor();Rebuild();}@@ -94,16 +115,56 @@ public sealed partial class ToolbarPageViewModel : ObservableObject_store.SaveLibrary();}- partial void OnExtensionsChanged(string value)+ partial void OnIsMixedChanged(bool value){- if (_loading || Profile is null || Profile.IsFallback)+ if (_loading || SelectedProfile is not { } item || item.Profile.IsFallback == value)return;- Profile.Extensions = value- .Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)- .Select(e => e.TrimStart('.').ToLowerInvariant())- .Distinct()- .ToList();+ if (!value && !CanChangeMixed)+ {+ RebuildProfileEditor(); // the last mixed profile stays mixed+ return;+ }+ // The extensions are kept either way: chips become checks and back, so switching is harmless.+ item.Profile.IsFallback = value;+ Reposition(item);_store.SaveLibrary();+ item.Refresh(_loc);+ RebuildProfileEditor();+ }++ /// <summary>Normal profiles first, then the mixed ones; a profile that switches kind moves to the border.</summary>+ private void Reposition(ProfileItemViewModel item)+ {+ var profile = item.Profile;+ _store.Profiles.Remove(profile);+ var index = profile.IsFallback ? -1 : _store.Profiles.FindIndex(p => p.IsFallback);+ index = index < 0 ? _store.Profiles.Count : index;+ _store.Profiles.Insert(index, profile);++ _repositioning = true;+ try+ {+ Profiles.Move(Profiles.IndexOf(item), index);+ SelectedProfile = item;+ }+ finally+ {+ _repositioning = false;+ }+ }++ /// <summary>Shows the chips or the check list for the selected profile.</summary>+ private void RebuildProfileEditor()+ {+ var profile = Profile;+ var mixedCount = _store.Profiles.Count(p => p.IsFallback);+ _loading = true;+ IsMixed = profile?.IsFallback == true;+ _loading = false;+ CanChangeMixed = profile is not null && !(profile.IsFallback && mixedCount <= 1);+ CanDelete = CanChangeMixed;+ ExtensionTags = profile is { IsFallback: false } ? new ExtensionTagsViewModel(profile, _store.Profiles, _loc, _store.SaveLibrary) : null;+ MixedExtensions = profile is { IsFallback: true } ? new MixedExtensionsViewModel(profile, _store.Profiles, _loc, _store.SaveLibrary) : null;}partial void OnOuterRadiusChanged(double value) => SaveAppearance();@@ -192,17 +253,20 @@ public sealed partial class ToolbarPageViewModel : ObservableObjectprivate void AddProfile(){var profile = new ToolbarProfile { Name = _loc["toolbar.profile_new"], PresetIds = ["to-pdf", "to-png"] };- _store.Profiles.Insert(Math.Max(0, _store.Profiles.Count - 1), profile); // keep the fallback last+ // Before the mixed-selection profiles (normal ones come first; see Reposition).+ var index = _store.Profiles.FindIndex(p => p.IsFallback);+ index = index < 0 ? _store.Profiles.Count : index;+ _store.Profiles.Insert(index, profile);_store.SaveLibrary();var item = new ProfileItemViewModel(profile, _loc);- Profiles.Insert(Math.Max(0, Profiles.Count - 1), item);+ Profiles.Insert(index, item);SelectedProfile = item;}[RelayCommand]private async Task DeleteProfile(){- if (Profile is null || Profile.IsFallback || _windows.Main is null)+ if (Profile is null || !CanDelete || _windows.Main is null)return;if (!await _windows.ConfirmAsync(_windows.Main, _loc["toolbar.delete_profile"] + "?", destructive: true))return;@@ -246,5 +310,5 @@ public sealed partial class ToolbarPageViewModel : ObservableObject}private string? Caption(Preset p) =>- p.TargetFormat == BuiltInData.SameAsSource ? _loc["donut.same_format"] : FormatRegistry.FindById(p.TargetFormat)?.DisplayName;+ p.TargetFormat == BuiltInData.SameAsSource ? _loc["donut.same_format"] : FormatLabels.NameOf(_loc, p.TargetFormat);}diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.csindex 6ffca97f..7a816b81 100644--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs@@ -10,8 +10,17 @@ using Filee.Core.Presets;namespace Filee.App.ViewModels;+/// <summary>What item templates show of a <see cref="Choice{T}"/> (XAML can't name a generic type).</summary>+public interface IChoice+{+ string Label { get; }++ /// <summary>Secondary text shown right-aligned, e.g. the category of a format.</summary>+ string? Detail { get; }+}+/// <summary>A value with a localized label for combo boxes.</summary>-public sealed record Choice<T>(T Value, string Label)+public sealed record Choice<T>(T Value, string Label, string? Detail = null) : IChoice{public override string ToString() => Label;}@@ -19,6 +28,13 @@ public sealed record Choice<T>(T Value, string Label)public sealed partial class PresetEditorViewModel : ObservableObject{private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif"];++ /// <summary>Audio targets without a bitrate or quality to choose.</summary>+ private static readonly HashSet<string> LosslessAudioTargets = ["wav", "flac", "aiff"];++ private static readonly int[] MaxHeightSteps = [0, 2160, 1440, 1080, 720, 480];+ private static readonly int[] BitrateSteps = [0, 96, 128, 192, 256, 320];+private readonly Preset _original;private readonly Preset _edit;private readonly ILocalizer _loc;@@ -29,18 +45,27 @@ public sealed partial class PresetEditorViewModel : ObservableObject_edit = preset.Clone();_loc = loc;+ // ~150 formats in registry order, which groups them by category; the category is shown next to each name+ // and typing the first letters of a name jumps to it.Targets =[new Choice<string>(BuiltInData.SameAsSource, loc["presets.same_as_source"]),.. FormatRegistry.Known.Where(f => f.Writable)- .Select(f => new Choice<string>(f.Id, f.DisplayName)),+ .Select(f => new Choice<string>(+ f.Id,+ f.Id == FormatRegistry.Folder ? loc["presets.target_folder"] : f.DisplayName,+ FormatLabels.Category(loc, f.Category))),];ResizeModes = Enum.GetValues<ResizeMode>().Select(v => new Choice<ResizeMode>(v, loc[$"presets.resize.{v}"])).ToList();PageSizes = Enum.GetValues<PdfPageSize>().Select(v => new Choice<PdfPageSize>(v, loc[$"presets.page_size.{v}"])).ToList();Locations = Enum.GetValues<OutputLocation>().Select(v => new Choice<OutputLocation>(v, loc[$"presets.location.{v}"])).ToList();Conflicts = Enum.GetValues<ConflictPolicy>().Select(v => new Choice<ConflictPolicy>(v, loc[$"presets.conflict.{v}"])).ToList();TiffCompressions = Enum.GetValues<TiffCompression>().Select(v => new Choice<TiffCompression>(v, v.ToString().ToUpperInvariant())).ToList();+ MediaQualities = Enum.GetValues<MediaQuality>().Select(v => new Choice<MediaQuality>(v, loc[$"presets.media_quality.{v}"])).ToList();+ MaxHeights = Steps(MaxHeightSteps, _edit.Media.MaxHeight, h => h == 0 ? loc["presets.max_height.original"] : $"{h}p");+ AudioBitrates = Steps(BitrateSteps, _edit.Media.AudioBitrateKbps, k => k == 0 ? loc["presets.audio_bitrate.auto"] : $"{k} kbps");+ ArchiveLevels = Enum.GetValues<ArchiveLevel>().Select(v => new Choice<ArchiveLevel>(v, loc[$"presets.archive_level.{v}"])).ToList();_name = string.IsNullOrWhiteSpace(_edit.Name) ? loc.DisplayName(_edit) : _edit.Name;_target = Targets.FirstOrDefault(t => t.Value == _edit.TargetFormat) ?? Targets[1];@@ -49,6 +74,12 @@ public sealed partial class PresetEditorViewModel : ObservableObject_location = Locations.First(l => l.Value == _edit.Output.Location);_conflict = Conflicts.First(c => c.Value == _edit.Output.Conflict);_tiffCompression = TiffCompressions.First(t => t.Value == _edit.Image.TiffCompression);+ _mediaQuality = MediaQualities.First(q => q.Value == _edit.Media.Quality);+ _maxHeight = MaxHeights.First(h => h.Value == _edit.Media.MaxHeight);+ _audioBitrate = AudioBitrates.First(b => b.Value == _edit.Media.AudioBitrateKbps);+ _removeAudio = _edit.Media.RemoveAudio;+ _archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);+ _combineIntoOne = _edit.Archive.CombineIntoOne;_quality = _edit.Image.Quality;_resizePercent = _edit.Image.ResizePercent;_longEdge = _edit.Image.LongEdge;@@ -78,13 +109,19 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic IReadOnlyList<Choice<OutputLocation>> Locations { get; }public IReadOnlyList<Choice<ConflictPolicy>> Conflicts { get; }public IReadOnlyList<Choice<TiffCompression>> TiffCompressions { get; }+ public IReadOnlyList<Choice<MediaQuality>> MediaQualities { get; }+ public IReadOnlyList<Choice<int>> MaxHeights { get; }+ public IReadOnlyList<Choice<int>> AudioBitrates { get; }+ public IReadOnlyList<Choice<ArchiveLevel>> ArchiveLevels { get; }[ObservableProperty, NotifyPropertyChangedFor(nameof(NameError), nameof(IsValid))]private string _name;[ObservableProperty][NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowWebp), nameof(ShowIco),- nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit))]+ nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit),+ nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),+ nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote))]private Choice<string> _target;[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge))]@@ -117,18 +154,39 @@ public sealed partial class PresetEditorViewModel : ObservableObject[ObservableProperty] private string _subfolderName;[ObservableProperty] private string _customFolder;[ObservableProperty] private string _pattern;+ [ObservableProperty] private Choice<MediaQuality> _mediaQuality;+ [ObservableProperty] private Choice<int> _maxHeight;+ [ObservableProperty] private Choice<int> _audioBitrate;+ [ObservableProperty] private bool _removeAudio;+ [ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;+ [ObservableProperty] private bool _combineIntoOne;private string TargetId => Target.Value;- private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || FormatRegistry.FindById(TargetId)?.Category == FormatCategory.Image;+ private FormatCategory? TargetCategory => FormatRegistry.FindById(TargetId)?.Category;+ private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || TargetCategory == FormatCategory.Image;+ private bool TargetIsVideo => TargetCategory == FormatCategory.Video;+ private bool TargetIsAudio => TargetCategory == FormatCategory.Audio;+ private bool TargetIsLossyMedia => TargetIsVideo || (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId));public bool ShowImage => TargetIsImage;public bool ShowQuality => TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId);public bool ShowTiff => TargetId is "tiff" or BuiltInData.SameAsSource;public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;public bool ShowIco => TargetId == "ico";+ /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive and font targets.</summary>+ public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font);public bool ShowPdfBuild => TargetId == "pdf";public bool ShowPdfSplit => TargetId == "pdf";public bool ShowDocument => TargetId == "pdf";+ public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio;+ public bool ShowMediaQuality => TargetIsLossyMedia;+ public bool ShowMaxHeight => TargetIsVideo;+ public bool ShowAudioBitrate => TargetIsLossyMedia;+ public bool ShowRemoveAudio => TargetIsVideo;+ public bool ShowArchive => TargetCategory == FormatCategory.Archive;+ public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder;+ /// <summary>"Extract" has nothing to set; a line says what it does instead.</summary>+ public bool ShowExtractNote => TargetId == FormatRegistry.Folder;public bool ShowPercent => Resize.Value == ResizeMode.Percent;public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;public bool ShowMargin => PageSize.Value != PdfPageSize.FitImage;@@ -177,6 +235,14 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpdf.SplitPages = SplitPages;_original.Document.PdfA = PdfA;+ var media = _original.Media;+ media.Quality = MediaQuality.Value;+ media.MaxHeight = MaxHeight.Value;+ media.AudioBitrateKbps = AudioBitrate.Value;+ media.RemoveAudio = RemoveAudio;+ _original.Archive.Level = ArchiveLevel.Value;+ _original.Archive.CombineIntoOne = CombineIntoOne;+var output = _original.Output;output.Location = Location.Value;output.SubfolderName = string.IsNullOrWhiteSpace(SubfolderName) ? "converted" : SubfolderName.Trim();@@ -185,4 +251,8 @@ public sealed partial class PresetEditorViewModel : ObservableObjectoutput.Conflict = Conflict.Value;return true;}++ /// <summary>Fixed choices plus the preset's own value if it isn't one of them (e.g. edited by hand).</summary>+ private static List<Choice<int>> Steps(int[] steps, int current, Func<int, string> label) =>+ [.. steps.Append(current).Distinct().Select(v => new Choice<int>(v, label(v)))];}diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml b/src/Filee.App/Views/Pages/ToolbarPage.axamlindex 5d02d7d8..51ec06c1 100644--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml@@ -3,6 +3,8 @@1. Pick a profile on the left. 2. Arrange its presets on the live donut:chip → donut = add · slice → palette = remove · slice → slice = reorder · right-click / ✎ = edit.Drag & drop is implemented in ToolbarPage.axaml.cs.+ The profile card edits a normal profile's extensions as chips (TagEditor) or, for a mixed-selection profile, which+ extensions a mix may contain (check list grouped by the normal profiles).--><UserControl xmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"@@ -21,6 +23,78 @@<Setter Property="Padding" Value="12,6" /><Setter Property="BoxShadow" Value="0 6 18 0 #33000000" /></Style>++ <!-- Remarks under the extension editors -->+ <Style Selector="PathIcon.note">+ <Setter Property="Width" Value="13" />+ <Setter Property="Height" Value="13" />+ <Setter Property="Margin" Value="0,1,6,0" />+ <Setter Property="VerticalAlignment" Value="Top" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ </Style>+ <Style Selector="PathIcon.note.warning">+ <Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />+ </Style>+ <Style Selector="TextBlock.caption.warning">+ <Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />+ </Style>++ <!-- Mixed-selection check list: group rows with a chevron, extension toggle chips -->+ <Style Selector="Border.ext-groups">+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />+ <Setter Property="Padding" Value="4,4,10,4" />+ </Style>+ <Style Selector="ToggleButton.expander">+ <Setter Property="Padding" Value="6" />+ <Setter Property="MinWidth" Value="0" />+ <Setter Property="MinHeight" Value="0" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="ToggleButton.expander /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ </Style>+ <Style Selector="ToggleButton.expander:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>+ <Style Selector="ToggleButton.expander PathIcon">+ <Setter Property="Width" Value="14" />+ <Setter Property="Height" Value="14" />+ <Setter Property="RenderTransform" Value="none" />+ </Style>+ <Style Selector="ToggleButton.expander:checked PathIcon">+ <Setter Property="RenderTransform" Value="rotate(90deg)" />+ </Style>+ <Style Selector="ToggleButton.extchip">+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Padding" Value="10,3" />+ <Setter Property="Margin" Value="2" />+ <Setter Property="MinHeight" Value="0" />+ <Setter Property="FontSize" Value="12.5" />+ <Setter Property="BorderThickness" Value="1" />+ </Style>+ <Style Selector="ToggleButton.extchip /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ <Setter Property="BorderBrush" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ </Style>+ <Style Selector="ToggleButton.extchip:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>+ <Style Selector="ToggleButton.extchip:checked /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />+ </Style>+ <Style Selector="ToggleButton.extchip:checked:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentStrongBrush}" />+ </Style></UserControl.Styles><Grid x:Name="Root" RowDefinitions="Auto,*">@@ -39,6 +113,9 @@<Border DockPanel.Dock="Right" Classes="badge"><TextBlock Classes="caption" Text="{Binding Count}" /></Border>+ <PathIcon DockPanel.Dock="Right" Width="13" Height="13" Margin="0,0,8,0" Data="{StaticResource Icon.Shapes}"+ Foreground="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding IsMixed}"+ ToolTip.Tip="{DynamicResource toolbar.mixed_badge}" /><TextBlock Text="{Binding Name}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" /></DockPanel></DataTemplate>@@ -66,20 +143,103 @@</Border><TextBlock Classes="caption danger" Text="{Binding Message}" HorizontalAlignment="Center" />- <Border Classes="card">- <StackPanel Spacing="10">- <Grid ColumnDefinitions="*,12,*">- <StackPanel>- <TextBlock Classes="label" Text="{DynamicResource toolbar.name}" />- <TextBox Text="{Binding ProfileName}" />- </StackPanel>- <StackPanel Grid.Column="2">- <TextBlock Classes="label" Text="{DynamicResource toolbar.extensions}" />- <TextBox Text="{Binding Extensions}" PlaceholderText="{DynamicResource toolbar.extensions_hint}" IsEnabled="{Binding !IsFallback}" />- </StackPanel>- </Grid>- <TextBlock Classes="caption" Text="{DynamicResource toolbar.fallback_note}" IsVisible="{Binding IsFallback}" TextWrapping="Wrap" />- <Button HorizontalAlignment="Right" Content="{DynamicResource toolbar.delete_profile}" Command="{Binding DeleteProfileCommand}" IsVisible="{Binding !IsFallback}" />+ <Border x:Name="ProfileCard" Classes="card">+ <StackPanel Spacing="12">+ <StackPanel>+ <TextBlock Classes="label" Text="{DynamicResource toolbar.name}" />+ <TextBox Text="{Binding ProfileName}" />+ </StackPanel>++ <!-- The label wraps (a ToggleSwitch header doesn't), so it sits next to a bare switch. -->+ <StackPanel Spacing="2">+ <DockPanel>+ <ToggleSwitch x:Name="MixedToggle" DockPanel.Dock="Right" OnContent="{x:Null}" OffContent="{x:Null}" MinWidth="0"+ Margin="12,0,0,0" VerticalAlignment="Center"+ IsChecked="{Binding IsMixed}" IsEnabled="{Binding CanChangeMixed}"+ AutomationProperties.Name="{DynamicResource toolbar.mixed_toggle}" />+ <TextBlock Text="{DynamicResource toolbar.mixed_toggle}" TextWrapping="Wrap" VerticalAlignment="Center" />+ </DockPanel>+ <TextBlock Classes="caption" Text="{DynamicResource toolbar.mixed_locked}" TextWrapping="Wrap"+ IsVisible="{Binding !CanChangeMixed}" />+ </StackPanel>++ <!-- Normal profile: extension chips -->+ <ContentControl Content="{Binding ExtensionTags}" IsVisible="{Binding ExtensionTags, Converter={x:Static ObjectConverters.IsNotNull}}">+ <ContentControl.ContentTemplate>+ <DataTemplate x:DataType="vm:ExtensionTagsViewModel">+ <StackPanel Spacing="6">+ <TextBlock Classes="label" Text="{DynamicResource toolbar.extensions}" />+ <c:TagEditor x:Name="ExtensionEditor"+ Tags="{Binding Tags}" Suggestions="{Binding Suggestions}" Text="{Binding Text}"+ AddCommand="{Binding AddCommand}" RemoveCommand="{Binding RemoveCommand}"+ PlaceholderText="{DynamicResource toolbar.extensions_hint}" />+ <TextBlock Classes="caption danger" Text="{Binding InputError}" TextWrapping="Wrap"+ IsVisible="{Binding InputError, Converter={x:Static ObjectConverters.IsNotNull}}" />+ <ItemsControl ItemsSource="{Binding Notes}">+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:ExtensionNote">+ <DockPanel Margin="0,2">+ <PathIcon Classes="note" Classes.warning="{Binding IsWarning}" Data="{StaticResource Icon.Alert}" />+ <TextBlock Classes="caption" Classes.warning="{Binding IsWarning}" Text="{Binding Text}" TextWrapping="Wrap" />+ </DockPanel>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ </StackPanel>+ </DataTemplate>+ </ContentControl.ContentTemplate>+ </ContentControl>++ <!-- Mixed-selection profile: which extensions a mix may contain -->+ <ContentControl Content="{Binding MixedExtensions}" IsVisible="{Binding MixedExtensions, Converter={x:Static ObjectConverters.IsNotNull}}">+ <ContentControl.ContentTemplate>+ <DataTemplate x:DataType="vm:MixedExtensionsViewModel">+ <StackPanel Spacing="6">+ <TextBlock Classes="label" Text="{DynamicResource toolbar.mixed_title}" TextWrapping="Wrap" />+ <Border Classes="ext-groups">+ <ItemsControl ItemsSource="{Binding Groups}">+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:ExtensionGroupViewModel">+ <StackPanel>+ <DockPanel>+ <ToggleButton DockPanel.Dock="Left" Classes="expander" IsChecked="{Binding IsExpanded}"+ ToolTip.Tip="{DynamicResource toolbar.mixed_expand}"+ AutomationProperties.Name="{Binding Name}">+ <PathIcon Data="{StaticResource Icon.ChevronRight}" />+ </ToggleButton>+ <TextBlock DockPanel.Dock="Right" Classes="caption" Text="{Binding Count}" VerticalAlignment="Center" />+ <CheckBox Content="{Binding Name}" IsChecked="{Binding State, Mode=OneWay}"+ Command="{Binding ToggleAllCommand}" Margin="2,0,8,0" MinHeight="30" />+ </DockPanel>+ <ItemsControl ItemsSource="{Binding Extensions}" IsVisible="{Binding IsExpanded}" Margin="32,0,0,8">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <WrapPanel />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:ExtensionToggleViewModel">+ <ToggleButton Classes="extchip" Content="{Binding Text}" IsChecked="{Binding IsChecked}"+ ToolTip.Tip="{Binding ToolTip}" />+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ </StackPanel>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ </Border>+ <DockPanel Margin="0,2">+ <PathIcon Classes="note" Classes.warning="{Binding HintIsWarning}" Data="{StaticResource Icon.Info}" />+ <TextBlock Classes="caption" Classes.warning="{Binding HintIsWarning}" Text="{Binding Hint}" TextWrapping="Wrap" />+ </DockPanel>+ </StackPanel>+ </DataTemplate>+ </ContentControl.ContentTemplate>+ </ContentControl>++ <Button HorizontalAlignment="Right" Content="{DynamicResource toolbar.delete_profile}" Command="{Binding DeleteProfileCommand}"+ IsVisible="{Binding CanDelete}" /></StackPanel></Border>diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axamlindex 700fcdfd..535df2bd 100644--- a/src/Filee.App/Views/PresetEditorView.axaml+++ b/src/Filee.App/Views/PresetEditorView.axaml@@ -1,9 +1,18 @@-<!-- Preset editor form. Used on the Presets page and inside PresetEditorWindow (donut right-click / ✎). -->+<!--+ Preset editor form. Used on the Presets page and inside PresetEditorWindow (donut right-click / ✎).+ Only the option groups that apply to the chosen target are shown (image, video & audio, archive, PDF).+--><UserControl 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.PresetEditorView"x:DataType="vm:PresetEditorViewModel">+ <UserControl.Styles>+ <!-- Target list: the category sits right-aligned next to each format name. -->+ <Style Selector="ComboBox.targets ComboBoxItem">+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />+ </Style>+ </UserControl.Styles><StackPanel Spacing="14"><!-- Name + target --><Grid ColumnDefinitions="*,12,*">@@ -14,7 +23,17 @@</StackPanel><StackPanel Grid.Column="2"><TextBlock Classes="label" Text="{DynamicResource presets.target}" />- <ComboBox ItemsSource="{Binding Targets}" SelectedItem="{Binding Target}" HorizontalAlignment="Stretch" MaxDropDownHeight="360" />+ <ComboBox x:Name="TargetBox" Classes="targets" ItemsSource="{Binding Targets}" SelectedItem="{Binding Target}"+ HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" MaxDropDownHeight="420">+ <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></StackPanel></Grid>@@ -69,8 +88,48 @@</StackPanel></Border>+ <!-- Video & audio options -->+ <Border x:Name="MediaCard" Classes="card" IsVisible="{Binding ShowMedia}" Padding="14">+ <StackPanel Spacing="10">+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.media}" />+ <Grid ColumnDefinitions="*,12,*">+ <StackPanel IsVisible="{Binding ShowMediaQuality}">+ <TextBlock Classes="label" Text="{DynamicResource presets.media_quality}" />+ <ComboBox ItemsSource="{Binding MediaQualities}" SelectedItem="{Binding MediaQuality}" HorizontalAlignment="Stretch" />+ </StackPanel>+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowMaxHeight}">+ <TextBlock Classes="label" Text="{DynamicResource presets.max_height}" />+ <ComboBox ItemsSource="{Binding MaxHeights}" SelectedItem="{Binding MaxHeight}" HorizontalAlignment="Stretch" />+ </StackPanel>+ </Grid>+ <Grid ColumnDefinitions="*,12,*">+ <StackPanel IsVisible="{Binding ShowAudioBitrate}">+ <TextBlock Classes="label" Text="{DynamicResource presets.audio_bitrate}" />+ <ComboBox ItemsSource="{Binding AudioBitrates}" SelectedItem="{Binding AudioBitrate}" HorizontalAlignment="Stretch" />+ </StackPanel>+ <CheckBox Grid.Column="2" VerticalAlignment="Bottom" Content="{DynamicResource presets.remove_audio}"+ IsChecked="{Binding RemoveAudio}" IsVisible="{Binding ShowRemoveAudio}" />+ </Grid>+ </StackPanel>+ </Border>++ <!-- Archive options -->+ <Border x:Name="ArchiveCard" Classes="card" IsVisible="{Binding ShowArchive}" Padding="14">+ <StackPanel Spacing="10">+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.archive}" />+ <Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowArchiveOptions}">+ <StackPanel>+ <TextBlock Classes="label" Text="{DynamicResource presets.archive_level}" />+ <ComboBox ItemsSource="{Binding ArchiveLevels}" SelectedItem="{Binding ArchiveLevel}" HorizontalAlignment="Stretch" />+ </StackPanel>+ </Grid>+ <CheckBox Content="{DynamicResource presets.combine}" IsChecked="{Binding CombineIntoOne}" IsVisible="{Binding ShowArchiveOptions}" />+ <TextBlock Classes="caption" Text="{DynamicResource presets.extract_note}" TextWrapping="Wrap" IsVisible="{Binding ShowExtractNote}" />+ </StackPanel>+ </Border>+<!-- PDF options (render settings also apply when a PDF is converted to images) -->- <Border Classes="card" Padding="14">+ <Border Classes="card" Padding="14" IsVisible="{Binding ShowPdf}"><StackPanel Spacing="10"><TextBlock Classes="h2" Text="{DynamicResource presets.group.pdf}" /><CheckBox Content="{DynamicResource presets.merge}" IsChecked="{Binding Merge}" IsVisible="{Binding ShowPdfBuild}" />diff --git a/tests/Filee.App.Tests/ExtensionEditingTests.cs b/tests/Filee.App.Tests/ExtensionEditingTests.csnew file mode 100644index 00000000..850275d1--- /dev/null+++ b/tests/Filee.App.Tests/ExtensionEditingTests.cs@@ -0,0 +1,303 @@+// Logic behind the donut editor's extension chips and the mixed-selection check list (no UI needed).++using Filee.App.Controls;+using Filee.App.ViewModels.Pages;+using Filee.Core.Localization;+using Filee.Core.Profiles;++namespace Filee.App.Tests;++/// <summary>Returns keys (and "key|arg|arg" for formats) so tests can check which message was chosen.</summary>+internal sealed class KeyLocalizer : ILocalizer+{+ public string Language => "en";+ public string this[string key] => key;+ public string Format(string key, params object[] args) => string.Join("|", [key, .. args.Select(a => a.ToString())]);+ public event EventHandler? LanguageChanged { add { } remove { } }+}++public class ExtensionInputTests+{+ [Theory]+ [InlineData("jpg", "jpg")]+ [InlineData(" .JPG ", "jpg")]+ [InlineData("*.png", "png")]+ [InlineData("**..webp", "webp")]+ [InlineData("*.TAR.GZ", "tar.gz")]+ [InlineData("tar.xz", "tar.xz")]+ [InlineData("dvr-ms", "dvr-ms")]+ [InlineData("xyz", "xyz")]+ [InlineData("jpg.", "jpg")]+ public void Normalizes_extensions(string input, string expected) => Assert.Equal(expected, ExtensionInput.Normalize(input));++ [Theory]+ [InlineData("")]+ [InlineData(" ")]+ [InlineData("*.")]+ [InlineData("a b")]+ [InlineData("a/b")]+ [InlineData(@"C:\x")]+ [InlineData("a..b")]+ [InlineData("photo.jpg")] // two-part extensions only when Filee knows them+ [InlineData("averyveryverylongextension")]+ public void Rejects_what_cannot_be_an_extension(string input) => Assert.Null(ExtensionInput.Normalize(input));++ [Fact]+ public void Suggestions_start_with_the_typed_extension()+ {+ var suggestions = ExtensionInput.Suggest("jp", [], _ => null, new KeyLocalizer());++ Assert.Equal(".jpg", suggestions[0].Text);+ Assert.All(suggestions.Take(3), s => Assert.StartsWith("jp", s.Value));+ Assert.Contains("JPG", suggestions[0].Detail);+ Assert.Contains("format.category.Image", suggestions[0].Detail);+ }++ [Fact]+ public void An_exact_match_comes_first() =>+ Assert.Equal("tar", ExtensionInput.Suggest(".tar", [], _ => null, new KeyLocalizer())[0].Value);++ [Fact]+ public void Suggestions_leave_out_existing_extensions_and_name_the_owner()+ {+ var suggestions = ExtensionInput.Suggest("jp", ["jpg"], e => e == "jpeg" ? "Images" : null, new KeyLocalizer());++ Assert.DoesNotContain(suggestions, s => s.Value == "jpg");+ Assert.Equal("toolbar.ext_in_profile|Images", suggestions.Single(s => s.Value == "jpeg").Note);+ }++ [Fact]+ public void Format_names_and_categories_are_searched_too()+ {+ var loc = new KeyLocalizer();+ Assert.Contains(ExtensionInput.Suggest("JPEG XL", [], _ => null, loc), s => s.Value == "jxl");+ Assert.Contains(ExtensionInput.Suggest("markdown", [], _ => null, loc), s => s.Value == "md");++ var video = ExtensionInput.Suggest("video", [], _ => null, loc, max: 50);+ Assert.Contains(video, s => s.Value == "mp4");+ Assert.Contains(video, s => s.Value == "mkv");+ }++ [Fact]+ public void Nothing_typed_nothing_suggested() => Assert.Empty(ExtensionInput.Suggest(" ", [], _ => null, new KeyLocalizer()));++ [Fact]+ public void Suggestions_are_limited() => Assert.Equal(8, ExtensionInput.Suggest("m", [], _ => null, new KeyLocalizer()).Count);+}++public class ExtensionTagsViewModelTests+{+ private readonly ToolbarProfile _images = new() { Id = "images", Name = "Images", Extensions = ["jpg", "png"] };+ private readonly ToolbarProfile _mine = new() { Id = "mine", Name = "Mine", Extensions = ["webp"] };+ private readonly ToolbarProfile _later = new() { Id = "later", Name = "Later", Extensions = ["gif"] };+ private readonly ToolbarProfile _mixed = new() { Id = "mixed", Name = "Mixed", IsFallback = true, Extensions = ["bmp"] };+ private int _saves;++ private ExtensionTagsViewModel Create() => new(_mine, [_images, _mine, _later, _mixed], new KeyLocalizer(), () => _saves++);++ [Fact]+ public void Adds_normalized_extensions_and_saves()+ {+ var vm = Create();+ vm.AddCommand.Execute(" *.AVIF ");++ Assert.Equal(["webp", "avif"], _mine.Extensions);+ Assert.Equal(1, _saves);+ Assert.Equal([".webp", ".avif"], vm.Tags.Select(t => t.Text));+ Assert.All(vm.Tags, t => Assert.Equal(TagChipKind.Normal, t.Kind));+ Assert.Null(vm.InputError);+ }++ [Fact]+ public void Refuses_duplicates_and_invalid_text()+ {+ var vm = Create();+ vm.AddCommand.Execute(".WEBP");+ Assert.Equal("toolbar.ext_duplicate|.webp", vm.InputError);++ vm.AddCommand.Execute("a/b");+ Assert.Equal("toolbar.ext_invalid|a/b", vm.InputError);++ Assert.Equal(["webp"], _mine.Extensions);+ Assert.Equal(0, _saves);++ vm.Text = "g"; // typing again dismisses the message+ Assert.Null(vm.InputError);+ }++ [Fact]+ public void Warns_when_an_earlier_profile_opens_those_files()+ {+ var vm = Create();+ vm.AddCommand.Execute("jpg");+ vm.AddCommand.Execute("png");++ Assert.Equal(TagChipKind.Warning, vm.Tags.Single(t => t.Value == "jpg").Kind);+ Assert.Equal("toolbar.ext_also_in|Images", vm.Tags.Single(t => t.Value == "jpg").ToolTip);+ var note = Assert.Single(vm.Notes, n => n.IsWarning);+ Assert.Equal("toolbar.ext_claimed_first|.jpg, .png|Images", note.Text);+ }++ [Fact]+ public void Tells_when_this_profile_takes_files_from_a_later_one()+ {+ var vm = Create();+ vm.AddCommand.Execute("gif");+ Assert.Equal("toolbar.ext_claimed_later|.gif|Later", Assert.Single(vm.Notes).Text);+ }++ [Fact]+ public void Extensions_checked_on_mixed_profiles_are_not_claims()+ {+ var vm = Create();+ vm.AddCommand.Execute("bmp");++ Assert.Equal(TagChipKind.Normal, vm.Tags.Single(t => t.Value == "bmp").Kind);+ Assert.Empty(vm.Notes);+ }++ [Fact]+ public void Unknown_extensions_are_kept_but_marked()+ {+ var vm = Create();+ vm.AddCommand.Execute("xyz");++ Assert.Contains("xyz", _mine.Extensions);+ Assert.Equal(TagChipKind.Muted, vm.Tags.Single(t => t.Value == "xyz").Kind);+ Assert.Equal("toolbar.ext_unknown|.xyz", Assert.Single(vm.Notes).Text);+ }++ [Fact]+ public void Removes_extensions()+ {+ var vm = Create();+ vm.RemoveCommand.Execute(vm.Tags[0]);++ Assert.Empty(_mine.Extensions);+ Assert.Empty(vm.Tags);+ Assert.Equal(1, _saves);+ Assert.Equal("toolbar.ext_none", Assert.Single(vm.Notes).Text);+ }++ [Fact]+ public void Suggestions_follow_the_text_and_skip_what_is_there()+ {+ var vm = Create();+ vm.Text = "web";++ Assert.DoesNotContain(vm.Suggestions, s => s.Value == "webp");+ Assert.Contains(vm.Suggestions, s => s.Value == "webm");+ vm.Text = "jp";+ Assert.Equal("toolbar.ext_in_profile|Images", vm.Suggestions.Single(s => s.Value == "jpg").Note);+ }+}++public class MixedExtensionsViewModelTests+{+ private readonly ToolbarProfile _images = new() { Id = "images", Name = "Images", Extensions = ["jpg", "png"] };+ private readonly ToolbarProfile _pdf = new() { Id = "pdf", Name = "PDF", Extensions = ["pdf"] };+ private readonly ToolbarProfile _photos = new() { Id = "photos", Name = "Photos", Extensions = ["jpg", "heic"] };+ private readonly ToolbarProfile _mixed = new() { Id = "mixed", Name = "Mixed", IsFallback = true };+ private readonly ToolbarProfile _scans = new() { Id = "scans", Name = "Scans", IsFallback = true };+ private int _saves;++ private List<ToolbarProfile> All => [_images, _pdf, _photos, _mixed, _scans];++ private MixedExtensionsViewModel Create(ToolbarProfile profile, List<ToolbarProfile>? all = null) =>+ new(profile, all ?? All, new KeyLocalizer(), () => _saves++);++ [Fact]+ public void Groups_follow_the_normal_profiles_and_start_collapsed()+ {+ var vm = Create(_scans);++ Assert.Equal(["Images", "PDF", "Photos"], vm.Groups.Select(g => g.Name));+ Assert.All(vm.Groups, g => Assert.False(g.IsExpanded));+ Assert.All(vm.Groups, g => Assert.Equal(false, g.State));+ Assert.Equal("0 / 2", vm.Groups[0].Count);+ }++ [Fact]+ public void The_group_box_checks_all_then_none()+ {+ var vm = Create(_scans);+ var images = vm.Groups[0];++ images.ToggleAllCommand.Execute(null);+ Assert.Equal(["jpg", "png"], _scans.Extensions);+ Assert.Equal(true, images.State);+ Assert.Equal("2 / 2", images.Count);++ images.ToggleAllCommand.Execute(null);+ Assert.Empty(_scans.Extensions);+ Assert.Equal(false, images.State);+ Assert.Equal(2, _saves);+ }++ [Fact]+ public void Single_extensions_make_a_group_partly_checked_and_stay_in_step_across_groups()+ {+ var vm = Create(_scans);+ var images = vm.Groups[0];+ var photos = vm.Groups[2];++ images.Extensions.Single(e => e.Extension == "jpg").IsChecked = true;++ Assert.Equal(["jpg"], _scans.Extensions);+ Assert.Null(images.State);+ Assert.True(photos.Extensions.Single(e => e.Extension == "jpg").IsChecked); // same extension in "Photos"+ Assert.Equal("1 / 2", photos.Count);++ // A partly checked group box checks the rest.+ images.ToggleAllCommand.Execute(null);+ Assert.Equal(["jpg", "png"], _scans.Extensions);+ }++ [Fact]+ public void Checked_extensions_no_profile_has_get_their_own_group()+ {+ _scans.Extensions = ["jpg", "xmp"];+ var vm = Create(_scans);++ var other = vm.Groups[^1];+ Assert.Equal("toolbar.mixed_other_group", other.Name);+ Assert.Equal([".xmp"], other.Extensions.Select(e => e.Text));+ Assert.Equal(true, other.State);+ Assert.Equal("toolbar.ext_unknown_tip", other.Extensions[0].ToolTip);+ }++ [Fact]+ public void Hint_explains_the_catch_all()+ {+ Assert.Equal("toolbar.mixed_catch_all", Create(_mixed).Hint);++ var scans = Create(_scans);+ Assert.Equal("toolbar.mixed_shadowed|Mixed", scans.Hint);+ Assert.True(scans.HintIsWarning);++ scans.Groups[1].ToggleAllCommand.Execute(null);+ Assert.Equal("toolbar.mixed_others|Mixed", scans.Hint);+ Assert.False(scans.HintIsWarning);+ }++ [Fact]+ public void Hint_warns_when_an_earlier_mixed_profile_covers_every_check()+ {+ _mixed.Extensions = ["jpg", "png", "pdf"];+ _scans.Extensions = ["jpg", "pdf"];+ var vm = Create(_scans);++ Assert.Equal("toolbar.mixed_covered|Mixed", vm.Hint);+ Assert.True(vm.HintIsWarning);+ }++ [Fact]+ public void Hint_says_so_when_no_catch_all_is_left()+ {+ List<ToolbarProfile> all = [_images, _pdf, _mixed];+ var vm = Create(_mixed, all);+ vm.Groups[0].ToggleAllCommand.Execute(null);++ Assert.Equal("toolbar.mixed_others_self", vm.Hint);+ }+}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex 6810f317..964df582 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -2,12 +2,19 @@// in bin/.../screenshots for visual review.using Avalonia.Controls;+using Avalonia.Controls.Primitives;using Avalonia.Headless;using Avalonia.Headless.XUnit;+using Avalonia.Input;using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.App.Controls;using Filee.App.Services;using Filee.App.ViewModels;+using Filee.App.ViewModels.Pages;using Filee.App.Views;+using Filee.Core.Localization;+using Filee.Core.Profiles;using Filee.Core.Settings;namespace Filee.App.Tests;@@ -155,6 +162,210 @@ public class RenderTests}}+ /// <summary>+ /// The extension chips of a profile that shares extensions with "Images" (warning chips), has one Filee doesn't+ /// know (muted chip) and shows suggestions for what is being typed (dark: a refused duplicate instead).+ /// </summary>+ [AvaloniaTheory]+ [InlineData("en", false)]+ [InlineData("ko", false)]+ [InlineData("zh-CN", false)]+ [InlineData("en", true)]+ [InlineData("ko", true)]+ public void Toolbar_extension_editor_renders(string language, bool dark)+ {+ var photos = new ToolbarProfile+ {+ Id = "render-photos",+ Name = language == "ko" ? "사진" : "Photos",+ Extensions = ["jpg", "png", "heic", "dng", "webp", "xyz"],+ PresetIds = ["to-jpg", "to-webp", "half-size", "to-pdf"],+ };+ WithProfiles(language, dark, 1240, profiles => profiles.Insert(profiles.FindIndex(p => p.IsFallback), photos), (window, vm) =>+ {+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile == photos);+ Pump();+ var editor = window.GetVisualDescendants().OfType<TagEditor>().Single();+ editor.FocusInput();+ Pump();+ if (dark)+ {+ window.KeyTextInput("PNG");+ window.KeyPress(Key.Enter, RawInputModifiers.None, PhysicalKey.None, null);+ Assert.NotNull(vm.ExtensionTags!.InputError);+ }+ else+ {+ window.KeyTextInput("we");+ Pump();+ Assert.True(editor.IsSuggestionListOpen);+ }+ Pump();++ Assert.Equal(6, vm.ExtensionTags!.Tags.Count);+ Assert.Equal(2, vm.ExtensionTags.Notes.Count); // shared with "Images" + unknown+ Save(window, $"toolbar-extensions-{language}{(dark ? "-dark" : "")}.png");+ });+ }++ /// <summary>A second mixed-selection donut limited to images and PDF, two groups expanded.</summary>+ [AvaloniaTheory]+ [InlineData("en", false, "render-scans")]+ [InlineData("ko", false, "render-scans")]+ [InlineData("zh-CN", false, "render-scans")]+ [InlineData("ko", true, "render-scans")]+ [InlineData("en", false, "mixed")]+ [InlineData("en", true, "mixed")]+ public void Toolbar_mixed_selection_editor_renders(string language, bool dark, string profileId)+ {+ var scans = new ToolbarProfile+ {+ Id = "render-scans",+ Name = language == "ko" ? "스캔 모음" : "Scans",+ IsFallback = true,+ Extensions = ["jpg", "png", "tiff", "pdf"],+ PresetIds = ["to-pdf", "merge-pdf", "zip-all"],+ };+ WithProfiles(language, dark, 1600, profiles => profiles.Add(scans), (window, vm) =>+ {+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == profileId);+ Pump();+ var mixed = vm.MixedExtensions!;+ if (profileId != "mixed")+ mixed.Groups[0].IsExpanded = true; // Images: partly checked, many chips+ mixed.Groups[1].IsExpanded = true; // PDF: all checked (Scans)+ Pump();++ Assert.True(vm.IsMixed);+ Assert.Null(vm.ExtensionTags);+ Assert.Equal(profileId == "mixed" ? false : null, mixed.Groups[0].State);+ Assert.True(vm.CanDelete); // two mixed profiles: either may go+ Save(window, $"toolbar-mixed-{profileId.Replace("render-", "")}-{language}{(dark ? "-dark" : "")}.png");+ });+ }++ /// <summary>The preset popup with the video/audio and archive sections, and the target list.</summary>+ [AvaloniaTheory]+ [InlineData("en", false)]+ [InlineData("ko", false)]+ [InlineData("zh-CN", false)]+ [InlineData("ko", true)]+ public void Preset_editor_shows_media_and_archive_options(string language, bool dark)+ {+ TestServices.EnsureInitialized(language);+ var theme = AppHost.Get<ThemeService>();+ if (dark)+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);+ try+ {+ var store = AppHost.Get<UserDataStore>();+ var loc = AppHost.Get<ILocalizer>();+ var suffix = $"{language}{(dark ? "-dark" : "")}";++ var media = new PresetEditorViewModel(store.FindPreset("mp4-720")!, loc);+ Assert.True(media.ShowMedia && media.ShowMaxHeight && media.ShowRemoveAudio);+ Assert.False(media.ShowPdf || media.ShowImage || media.ShowArchive);+ Assert.Equal(720, media.MaxHeight.Value);+ var window = new PresetEditorWindow { DataContext = media, Height = 900 };+ window.Show();+ Pump();+ Save(window, $"preset-media-{suffix}.png");++ // The target list: categories next to the names. (Headless popups live in the window's overlay layer,+ // so the open list is part of the window's frame.)+ var box = window.GetVisualDescendants().OfType<ComboBox>().First(c => c.Name == "TargetBox");+ box.IsDropDownOpen = true;+ Pump();+ Assert.True(box.GetVisualDescendants().OfType<Popup>().Single().IsOpen);+ Save(window, $"preset-targets-{suffix}.png");+ box.IsDropDownOpen = false;+ window.Close();++ var archive = new PresetEditorViewModel(store.FindPreset("zip-all")!, loc);+ Assert.True(archive.ShowArchive && archive.ShowArchiveOptions && archive.CombineIntoOne);+ Assert.False(archive.ShowMedia || archive.ShowPdf);+ window = new PresetEditorWindow { DataContext = archive, Height = 760 };+ window.Show();+ Pump();+ Save(window, $"preset-archive-{suffix}.png");+ window.Close();++ // Audio targets have no picture options; lossless ones nothing to set at all; "Extract" only explains.+ archive.Target = archive.Targets.Single(t => t.Value == "mp3");+ Assert.True(archive.ShowMedia && archive.ShowAudioBitrate && !archive.ShowMaxHeight && !archive.ShowRemoveAudio);+ archive.Target = archive.Targets.Single(t => t.Value == "flac");+ Assert.False(archive.ShowMedia);+ archive.Target = archive.Targets.Single(t => t.Value == Filee.Core.Formats.FormatRegistry.Folder);+ Assert.True(archive.ShowArchive && archive.ShowExtractNote && !archive.ShowArchiveOptions);+ }+ finally+ {+ if (dark)+ theme.Apply(new ThemeSettings(), language);+ }+ }++ [AvaloniaFact]+ public void Preset_editor_saves_media_and_archive_options()+ {+ TestServices.EnsureInitialized("en");+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "mp4", Name = "Clip" };+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());+ Assert.Equal("*", vm.Targets[0].Value); // "Same as source" stays first+ Assert.All(vm.Targets.Skip(1), t => Assert.True(Filee.Core.Formats.FormatRegistry.Get(t.Value).Writable));+ Assert.Equal("Video", vm.Target.Detail);++ vm.MediaQuality = vm.MediaQualities.Single(q => q.Value == Filee.Core.Presets.MediaQuality.Small);+ vm.MaxHeight = vm.MaxHeights.Single(h => h.Value == 1080);+ vm.AudioBitrate = vm.AudioBitrates.Single(b => b.Value == 192);+ vm.RemoveAudio = true;+ vm.ArchiveLevel = vm.ArchiveLevels.Single(l => l.Value == Filee.Core.Presets.ArchiveLevel.Maximum);+ vm.CombineIntoOne = true;+ Assert.True(vm.Apply());++ Assert.Equal(Filee.Core.Presets.MediaQuality.Small, preset.Media.Quality);+ Assert.Equal(1080, preset.Media.MaxHeight);+ Assert.Equal(192, preset.Media.AudioBitrateKbps);+ Assert.True(preset.Media.RemoveAudio);+ Assert.Equal(Filee.Core.Presets.ArchiveLevel.Maximum, preset.Archive.Level);+ Assert.True(preset.Archive.CombineIntoOne);++ // A value set outside the editor is offered instead of being lost.+ preset.Media.MaxHeight = 600;+ Assert.Equal("600p", new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).MaxHeight.Label);+ }++ /// <summary>Shows the toolbar page (tall, so the profile card is visible) with temporarily changed profiles.</summary>+ private static void WithProfiles(string language, bool dark, double height, Action<List<ToolbarProfile>> change, Action<Window, ToolbarPageViewModel> act)+ {+ TestServices.EnsureInitialized(language);+ var store = AppHost.Get<UserDataStore>();+ var theme = AppHost.Get<ThemeService>();+ var snapshot = store.Profiles.Select(p => p.Clone()).ToList();+ Window? window = null;+ try+ {+ change(store.Profiles);+ if (dark)+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<ILocalizer>(), AppHost.Get<UpdateService>());+ vm.Navigate("toolbar");+ window = new MainWindow { DataContext = vm, Width = 1080, Height = height };+ window.Show();+ Pump();+ act(window, (ToolbarPageViewModel)vm.CurrentPage);+ }+ finally+ {+ window?.Close();+ if (dark)+ theme.Apply(new ThemeSettings(), language);+ store.Profiles.Clear();+ store.Profiles.AddRange(snapshot);+ store.SaveLibrary();+ }+ }+private static void Pump(){// Let layout, bindings and a few animation frames run.@@ -165,7 +376,7 @@ public class RenderTests}}- private static void Save(Window window, string name)+ private static void Save(TopLevel window, string name){var frame = window.CaptureRenderedFrame();Assert.NotNull(frame);diff --git a/tests/Filee.App.Tests/ToolbarEditorTests.cs b/tests/Filee.App.Tests/ToolbarEditorTests.csnew file mode 100644index 00000000..75893645--- /dev/null+++ b/tests/Filee.App.Tests/ToolbarEditorTests.cs@@ -0,0 +1,247 @@+// Keyboard behaviour of the chip input (TagEditor) and the profile editing of the donut toolbar page,+// driven through a headless window.++using Avalonia;+using Avalonia.Controls;+using Avalonia.Data;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.App.Controls;+using Filee.App.Services;+using Filee.App.ViewModels.Pages;+using Filee.Core.Profiles;+using Filee.Core.Settings;++namespace Filee.App.Tests;++public class TagEditorTests+{+ private readonly ToolbarProfile _profile = new() { Id = "mine", Name = "Mine", Extensions = ["png"] };++ private (Window Window, TagEditor Editor, ExtensionTagsViewModel Vm) Show()+ {+ TestServices.EnsureInitialized("en");+ var vm = new ExtensionTagsViewModel(_profile, [_profile], new KeyLocalizer(), () => { });+ var editor = new TagEditor { AddCommand = vm.AddCommand, RemoveCommand = vm.RemoveCommand, DataContext = vm };+ editor.Bind(TagEditor.TagsProperty, new ReflectionBinding(nameof(vm.Tags)));+ editor.Bind(TagEditor.SuggestionsProperty, new ReflectionBinding(nameof(vm.Suggestions)));+ editor.Bind(TagEditor.TextProperty, new ReflectionBinding(nameof(vm.Text)) { Mode = BindingMode.TwoWay });+ var window = new Window { Width = 500, Height = 400, Content = new StackPanel { Children = { editor, new TextBox() } } };+ window.Show();+ Pump();+ editor.FocusInput();+ Pump();+ return (window, editor, vm);+ }++ private static TextBox Input(TagEditor editor) => editor.GetVisualDescendants().OfType<TextBox>().First();++ [AvaloniaFact]+ public void Enter_turns_the_text_into_a_chip()+ {+ var (window, editor, vm) = Show();+ window.KeyTextInput(".JPG");+ Press(window, Key.Enter);++ Assert.Equal(["png", "jpg"], _profile.Extensions);+ Assert.Equal("", Input(editor).Text);+ Assert.Equal("", vm.Text);+ window.Close();+ }++ [AvaloniaFact]+ public void Separators_and_pasted_lists_add_several_chips()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("gif,");+ Assert.Equal(["png", "gif"], _profile.Extensions);++ window.KeyTextInput("webp tif");+ Assert.Equal(["png", "gif", "webp"], _profile.Extensions);+ Assert.Equal("tif", Input(editor).Text); // unfinished: stays in the box++ // A pasted list with line breaks and wildcards.+ Input(editor).Text = "";+ window.KeyTextInput("*.bmp;\r\n*.TGA\n");+ Assert.Equal(["png", "gif", "webp", "bmp", "tga"], _profile.Extensions);+ window.Close();+ }++ [AvaloniaFact]+ public void Tab_adds_the_text_but_still_moves_on_from_an_empty_box()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("avif");+ Press(window, Key.Tab);+ Assert.Equal(["png", "avif"], _profile.Extensions);+ Assert.True(Input(editor).IsFocused);++ Press(window, Key.Tab);+ Assert.False(Input(editor).IsFocused);+ window.Close();+ }++ [AvaloniaFact]+ public void Backspace_in_the_empty_box_removes_the_last_chip()+ {+ var (window, _, vm) = Show();+ window.KeyTextInput("gif");+ Press(window, Key.Enter);+ Press(window, Key.Back);++ Assert.Equal(["png"], _profile.Extensions);+ Assert.Equal([".png"], vm.Tags.Select(t => t.Text));+ window.Close();+ }++ [AvaloniaFact]+ public void Arrow_keys_pick_a_suggestion()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("jp");+ Pump();+ Assert.True(editor.IsSuggestionListOpen);++ Press(window, Key.Down);+ Press(window, Key.Down);+ Press(window, Key.Enter);++ Assert.Equal(["png", "jpeg"], _profile.Extensions);+ Assert.Equal("", Input(editor).Text);+ Assert.False(editor.IsSuggestionListOpen);+ window.Close();+ }++ [AvaloniaFact]+ public void Escape_closes_the_suggestions_then_clears_the_text()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("jp");+ Pump();+ Press(window, Key.Escape);+ Assert.False(editor.IsSuggestionListOpen);+ Assert.Equal("jp", Input(editor).Text);++ Press(window, Key.Escape);+ Assert.Equal("", Input(editor).Text);+ Assert.Equal(["png"], _profile.Extensions);+ window.Close();+ }++ [AvaloniaFact]+ public void Chips_can_be_reached_and_removed_with_the_keyboard()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("gif,webp,");+ Press(window, Key.Left); // into the last chip (.webp)+ Press(window, Key.Left); // .gif+ Press(window, Key.Delete);+ Pump();++ Assert.Equal(["png", "webp"], _profile.Extensions);+ Assert.False(Input(editor).IsFocused); // focus stays among the chips+ Press(window, Key.Escape);+ Assert.True(Input(editor).IsFocused);+ window.Close();+ }++ [AvaloniaFact]+ public void Leaving_the_box_keeps_what_was_typed()+ {+ var (window, editor, _) = Show();+ window.KeyTextInput("heic");+ ((TextBox)((StackPanel)window.Content!).Children[1]).Focus();+ Pump();++ Assert.Equal(["png", "heic"], _profile.Extensions);+ Assert.Equal("", Input(editor).Text);+ window.Close();+ }++ private static void Press(Window window, Key key)+ {+ window.KeyPress(key, RawInputModifiers.None, PhysicalKey.None, null);+ window.KeyRelease(key, RawInputModifiers.None, PhysicalKey.None, null);+ Dispatcher.UIThread.RunJobs();+ }++ private static void Pump()+ {+ for (var i = 0; i < 5; i++)+ {+ Dispatcher.UIThread.RunJobs();+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();+ }+ }+}++public class ToolbarPageTests+{+ [AvaloniaFact]+ public void Profiles_switch_between_extension_chips_and_the_mixed_check_list()+ {+ TestServices.EnsureInitialized("en");+ var store = AppHost.Get<UserDataStore>();+ var snapshot = store.Profiles.Select(p => p.Clone()).ToList();+ try+ {+ var vm = new ToolbarPageViewModel(store, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<WindowService>());++ // A new profile goes before the mixed ones and starts as a normal profile.+ vm.AddProfileCommand.Execute(null);+ var item = vm.SelectedProfile!;+ var mixedIndex = store.Profiles.FindIndex(p => p.IsFallback);+ Assert.Equal(mixedIndex - 1, store.Profiles.IndexOf(item.Profile));+ Assert.NotNull(vm.ExtensionTags);+ Assert.Null(vm.MixedExtensions);+ vm.ExtensionTags!.AddCommand.Execute("jpg");++ // Made mixed: it moves behind the built-in "Mixed files" (which stays the catch-all) and keeps its+ // extensions as checks.+ vm.IsMixed = true;+ Assert.Same(item, vm.SelectedProfile);+ Assert.True(item.Profile.IsFallback);+ Assert.True(item.IsMixed);+ Assert.Same(item.Profile, store.Profiles[^1]);+ Assert.Equal(store.Profiles.Select(p => p.Id), vm.Profiles.Select(p => p.Profile.Id));+ Assert.Null(vm.ExtensionTags);+ Assert.NotNull(vm.MixedExtensions);+ Assert.True(vm.MixedExtensions!.Groups.Single(g => g.Name == "Images").State is null);+ Assert.Equal("mixed", ProfileSelector.CatchAll(store.Profiles)!.Id);+ Assert.True(vm.CanDelete);++ // And back.+ vm.IsMixed = false;+ Assert.False(item.Profile.IsFallback);+ Assert.Equal(store.Profiles.FindIndex(p => p.IsFallback) - 1, store.Profiles.IndexOf(item.Profile));+ Assert.Equal(["jpg"], item.Profile.Extensions);+ }+ finally+ {+ store.Profiles.Clear();+ store.Profiles.AddRange(snapshot);+ store.SaveLibrary();+ }+ }++ [AvaloniaFact]+ public void The_last_mixed_profile_stays_mixed()+ {+ TestServices.EnsureInitialized("en");+ var store = AppHost.Get<UserDataStore>();+ var vm = new ToolbarPageViewModel(store, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<WindowService>());+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "mixed");++ Assert.True(vm.IsMixed);+ Assert.False(vm.CanChangeMixed);+ Assert.False(vm.CanDelete);+ vm.IsMixed = false;++ Assert.True(store.Profiles.Single(p => p.Id == "mixed").IsFallback);+ Assert.True(vm.IsMixed);+ Assert.NotNull(vm.MixedExtensions);+ }+}