Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

Tab flips the open donut to its back face

KnifeLemon3936dff3bf40
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 730407ed..62998882 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -57,6 +57,8 @@
"donut.empty": "Drag presets here",
"donut.same_format": "Same format",
"donut.group_caption": "Group of {0}",
+ "donut.flip_to_back": "Tab ↻ back",
+ "donut.flip_to_front": "Tab ↻ front",
"toast.converting": "{0} → {1}",
"toast.done": "Done",
@@ -321,6 +323,9 @@
"toolbar.opacity": "Opacity",
"toolbar.new_preset": "New preset",
"toolbar.new_group": "New group",
+ "toolbar.face_front": "Front",
+ "toolbar.face_back": "Back",
+ "toolbar.face_hint": "Tab flips the open donut over.",
"group.editor_title": "Group",
"group.hint": "A group is one donut slice for several presets: rest on it or move outward and they fan out around it.",
"group.members": "Presets ({0} / {1})",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 033e997a..e1ea4df7 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -53,6 +53,8 @@
"donut.empty": "Arrastra ajustes preestablecidos aquí",
"donut.same_format": "Mismo formato",
"donut.group_caption": "Grupo de {0}",
+ "donut.flip_to_back": "Tab ↻ reverso",
+ "donut.flip_to_front": "Tab ↻ anverso",
"toast.converting": "{0} → {1}",
"toast.done": "Hecho",
"toast.done_errors": "Fallaron {0} de {1}",
@@ -308,6 +310,9 @@
"toolbar.opacity": "Opacidad",
"toolbar.new_preset": "Nuevo ajuste",
"toolbar.new_group": "Nuevo grupo",
+ "toolbar.face_front": "Anverso",
+ "toolbar.face_back": "Reverso",
+ "toolbar.face_hint": "Tab da la vuelta al menú circular abierto.",
"group.editor_title": "Grupo",
"group.hint": "Un grupo es una sola porción del menú circular para varios ajustes preestablecidos: detente en él o muévete hacia fuera y se despliegan a su alrededor.",
"group.members": "Ajustes preestablecidos ({0} / {1})",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 66a74ca9..a51d5d94 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -53,6 +53,8 @@
"donut.empty": "प्रीसेट यहाँ खींचें",
"donut.same_format": "वही फ़ॉर्मैट",
"donut.group_caption": "{0} का समूह",
+ "donut.flip_to_back": "Tab ↻ पीछे",
+ "donut.flip_to_front": "Tab ↻ आगे",
"toast.converting": "{0} → {1}",
"toast.done": "हो गया",
"toast.done_errors": "{1} में से {0} विफल",
@@ -308,6 +310,9 @@
"toolbar.opacity": "अपारदर्शिता",
"toolbar.new_preset": "नया प्रीसेट",
"toolbar.new_group": "नया समूह",
+ "toolbar.face_front": "आगे",
+ "toolbar.face_back": "पीछे",
+ "toolbar.face_hint": "Tab दबाकर खुले डोनट को पलटें।",
"group.editor_title": "समूह",
"group.hint": "समूह कई प्रीसेट के लिए डोनट की एक स्लाइस होता है: उस पर रुकें या बाहर की ओर बढ़ें और प्रीसेट उसके चारों ओर फैल जाएँगे।",
"group.members": "प्रीसेट ({0} / {1})",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 3f5d09bb..6ad3ef78 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -57,6 +57,8 @@
"donut.empty": "프리셋을 끌어다 놓으세요",
"donut.same_format": "같은 형식",
"donut.group_caption": "묶음 · {0}개",
+ "donut.flip_to_back": "Tab ↻ 뒷면",
+ "donut.flip_to_front": "Tab ↻ 앞면",
"toast.converting": "{0} → {1}",
"toast.done": "완료",
@@ -321,6 +323,9 @@
"toolbar.opacity": "불투명도",
"toolbar.new_preset": "새 프리셋",
"toolbar.new_group": "새 묶음",
+ "toolbar.face_front": "앞면",
+ "toolbar.face_back": "뒷면",
+ "toolbar.face_hint": "Tab을 누르면 열린 도넛이 뒤집혀요.",
"group.editor_title": "묶음",
"group.hint": "묶음은 여러 프리셋을 도넛 한 칸에 담아요. 칸 위에 머물거나 바깥으로 움직이면 주변으로 펼쳐져요.",
"group.members": "프리셋 ({0} / {1})",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 655a9180..96a61082 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -57,6 +57,8 @@
"donut.empty": "Przeciągnij tu ustawienia",
"donut.same_format": "Ten sam format",
"donut.group_caption": "Grupa: {0}",
+ "donut.flip_to_back": "Tab ↻ tył",
+ "donut.flip_to_front": "Tab ↻ przód",
"toast.converting": "{0} → {1}",
"toast.done": "Gotowe",
@@ -321,6 +323,9 @@
"toolbar.opacity": "Krycie",
"toolbar.new_preset": "Nowe ustawienie",
"toolbar.new_group": "Nowa grupa",
+ "toolbar.face_front": "Przód",
+ "toolbar.face_back": "Tył",
+ "toolbar.face_hint": "Tab obraca otwarty pierścień.",
"group.editor_title": "Grupa",
"group.hint": "Grupa to jeden wycinek pierścienia dla kilku ustawień: zatrzymaj się na nim lub przesuń na zewnątrz, a rozłożą się wokół.",
"group.members": "Ustawienia ({0} / {1})",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index dcaae0b4..d8d3499a 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -57,6 +57,8 @@
"donut.empty": "把预设拖到这里",
"donut.same_format": "同格式",
"donut.group_caption": "组 · {0} 项",
+ "donut.flip_to_back": "Tab ↻ 背面",
+ "donut.flip_to_front": "Tab ↻ 正面",
"toast.converting": "{0} → {1}",
"toast.done": "完成",
@@ -321,6 +323,9 @@
"toolbar.opacity": "不透明度",
"toolbar.new_preset": "新预设",
"toolbar.new_group": "新建组",
+ "toolbar.face_front": "正面",
+ "toolbar.face_back": "背面",
+ "toolbar.face_hint": "按 Tab 可翻转打开的圆环。",
"group.editor_title": "组",
"group.hint": "组把多个预设放进圆环的一格。停留在上面或向外移动,它们就会在周围展开。",
"group.members": "预设({0} / {1})",
diff --git a/src/Filee.App/Controls/DonutMenu.Flip.cs b/src/Filee.App/Controls/DonutMenu.Flip.cs
new file mode 100644
index 00000000..a9d10128
--- /dev/null
+++ b/src/Filee.App/Controls/DonutMenu.Flip.cs
@@ -0,0 +1,179 @@
+// Flipping the donut to its other face: every profile has a front and a back list of slices, and Tab turns the open
+// donut over. The ring turns about the vertical axis like a coin (its width goes 1 → 0, the faces swap while it is
+// edge-on, 0 → 1); the hub stays where it is and says what Tab does ("Tab ↻ back").
+//
+// Click mode → Tab / Shift+Tab reach the focused window (HandleKey).
+// Drag mode → the window has no keyboard focus during an OS drag: RadialController calls Flip when the global
+// hook sees Tab (TriggerService.FlipKeyPressed).
+//
+// The control only animates: the owner swaps Items when FaceSwapping is raised (RadialWindow → RadialViewModel), so
+// the slices, hit-testing and what a drop converts with always belong to the face that is drawn.
+
+using Avalonia;
+using Avalonia.Media;
+using Filee.App.Services;
+
+namespace Filee.App.Controls;
+
+public sealed partial class DonutMenu
+{
+ /// <summary>There is another face with slices for these files: Tab flips to it.</summary>
+ public static readonly StyledProperty<bool> CanFlipProperty =
+ AvaloniaProperty.Register<DonutMenu, bool>(nameof(CanFlip));
+
+ /// <summary>Small line at the bottom of the hub, e.g. "Tab ↻ back" (null for none).</summary>
+ public static readonly StyledProperty<string?> CenterHintProperty =
+ AvaloniaProperty.Register<DonutMenu, string?>(nameof(CenterHint));
+
+ /// <summary>How long a flip takes, there and back: the faces swap halfway.</summary>
+ internal const double FlipDuration = 0.2;
+
+ private double _flipClock = -1; // seconds into the running flip; -1 none
+ private bool _flipSwapped; // the running flip swapped the faces already
+ private bool _flipQueued; // Tab again during a flip: flip once more after it
+ private bool _swapping; // FaceSwapping is being handled (Items change for the flip, not for new files)
+ private Point? _lastExternalAt; // where a drag from outside was last seen on the donut
+
+ public bool CanFlip { get => GetValue(CanFlipProperty); set => SetValue(CanFlipProperty, value); }
+ public string? CenterHint { get => GetValue(CenterHintProperty); set => SetValue(CenterHintProperty, value); }
+
+ /// <summary>
+ /// The donut is edge-on (at once without animations): the owner shows the other face now by changing
+ /// <see cref="Items"/>, <see cref="CanFlip"/> and <see cref="CenterHint"/>.
+ /// </summary>
+ public event EventHandler? FaceSwapping;
+
+ /// <summary>A flip is running.</summary>
+ internal bool IsFlipping => _flipClock >= 0;
+
+ /// <summary>How wide the ring is drawn now: 1 normally, down to 0 while a flip has it edge-on.</summary>
+ internal double FlipScale => _flipClock < 0 ? 1 : Math.Abs(Math.Cos(Math.PI * Math.Min(_flipClock / FlipDuration, 1)));
+
+ /// <summary>
+ /// Turns the donut over to its other face (Tab), folding an open group's ring away first. Without animations the
+ /// faces swap at once. Returns false when there is nothing to flip to (<see cref="CanFlip"/>), in the editor or
+ /// while the donut shows a conversion's progress.
+ /// </summary>
+ public bool Flip()
+ {
+ if (IsEditMode || _progressMode || _closing)
+ return false;
+ if (IsFlipping)
+ {
+ // Pressed again before the turn ended: once more afterwards (twice cancels that out again).
+ _flipQueued = !_flipQueued;
+ return true;
+ }
+ if (!CanFlip)
+ return false;
+ CollapseGroup();
+ if (!Motion.Enabled)
+ {
+ SwapFaces();
+ return true;
+ }
+ _flipClock = 0;
+ _flipSwapped = false;
+ StartAnimation();
+ return true;
+ }
+
+ /// <summary>
+ /// The second half of a flip for items that were already swapped (the editor's Front / Back switch): the ring
+ /// turns in from edge-on. Nothing without animations.
+ /// </summary>
+ public void PlayFlipIn()
+ {
+ if (!Motion.Enabled)
+ return;
+ _flipClock = FlipDuration / 2;
+ _flipSwapped = true;
+ _flipQueued = false;
+ StartAnimation();
+ }
+
+ /// <summary>Advances a running flip. Returns true while it needs more frames.</summary>
+ private bool StepFlip(double dt)
+ {
+ if (_flipClock < 0)
+ return false;
+ _flipClock += dt;
+ if (!_flipSwapped && _flipClock >= FlipDuration / 2)
+ SwapFaces();
+ if (_flipClock < FlipDuration)
+ return true;
+ EndFlip();
+ return IsFlipping; // a queued flip started
+ }
+
+ /// <summary>Ends a running flip where it ends (the faces swapped): animations off or frames stalled.</summary>
+ private void FinishFlip()
+ {
+ while (IsFlipping)
+ {
+ if (!_flipSwapped)
+ SwapFaces();
+ EndFlip();
+ }
+ }
+
+ private void EndFlip()
+ {
+ _flipClock = -1;
+ if (!_flipQueued)
+ return;
+ _flipQueued = false;
+ Flip();
+ }
+
+ private void CancelFlip()
+ {
+ _flipClock = -1;
+ _flipQueued = false;
+ }
+
+ /// <summary>
+ /// Has the owner show the other face, then lights up what is under the drag or the mouse on it, as if it had just
+ /// moved there: a keyboard selection starts over (the arrows begin at the first slice again).
+ /// </summary>
+ private void SwapFaces()
+ {
+ _flipSwapped = true;
+ var dragAt = _lastExternalAt;
+ var pointer = _keyboardHold ? null : _lastPointer;
+ _swapping = true;
+ try
+ {
+ FaceSwapping?.Invoke(this, EventArgs.Empty);
+ }
+ finally
+ {
+ _swapping = false;
+ }
+
+ if (dragAt is { } at)
+ {
+ SetExternalHit(HitTest(at), at);
+ }
+ else if (pointer is { } p)
+ {
+ _lastPointer = p;
+ var hit = HitTest(p);
+ TrackGroups(hit, p);
+ SetHover(hit.Kind is DonutHitKind.Segment or DonutHitKind.SubSegment ? hit.Index : -1);
+ }
+ ActiveIndexChanged?.Invoke(this, ActiveIndex); // the hub's text follows the new face
+ InvalidateVisual();
+ }
+
+ /// <summary>Squeezes the ring horizontally about <paramref name="center"/> by <see cref="FlipScale"/>.</summary>
+ private Matrix FlipTransform(Point center)
+ {
+ var scale = FlipScale;
+ if (scale >= 1)
+ return Matrix.Identity;
+ // Never quite 0: a singular transform can't be inverted for hit tests and clips.
+ return Matrix.CreateTranslation(-center.X, -center.Y) * Matrix.CreateScale(Math.Max(scale, 0.01), 1) *
+ Matrix.CreateTranslation(center.X, center.Y);
+ }
+}
diff --git a/src/Filee.App/Controls/DonutMenu.Groups.cs b/src/Filee.App/Controls/DonutMenu.Groups.cs
index baec5c09..e272988a 100644
--- a/src/Filee.App/Controls/DonutMenu.Groups.cs
+++ b/src/Filee.App/Controls/DonutMenu.Groups.cs
@@ -4,7 +4,8 @@
// Pointer / drag → resting on a group's slice (ExpandDelay), or moving outward on it, opens its ring; the ring
// stays open on its way out to it (the gap, the neighbours' outer half) and folds on another slice,
// the hole, or going round the outside away from it.
-// Keyboard → arrows / Tab move, Enter opens a group or converts, Esc / Backspace fold a ring first.
+// Keyboard → arrows move, Enter opens a group or converts, Esc / Backspace fold a ring first, Tab flips
+// the donut (DonutMenu.Flip.cs).
// See-through → Windows and macOS let the pointer and drags through fully transparent pixels: a nearly
// transparent backdrop and LeftThroughSeam keep a group from folding when it only seems to leave.
@@ -199,13 +200,20 @@ public sealed partial class DonutMenu
}
/// <summary>
- /// Keyboard (click mode): arrows and Tab move around the donut, Enter converts or opens a group; in a group's ring
- /// the arrows move between its slices, Enter converts and Esc / Backspace go back to the donut.
- /// Returns false for keys left to the window (Esc on the donut closes it).
+ /// Keyboard (click mode): arrows move around the donut, Enter converts or opens a group; in a group's ring the
+ /// arrows move between its slices, Enter converts and Esc / Backspace go back to the donut. Tab and Shift+Tab flip
+ /// the donut to its other face (<see cref="Flip"/>). Returns false for keys left to the window (Esc on the donut
+ /// closes it).
/// </summary>
public bool HandleKey(Key key, KeyModifiers modifiers = KeyModifiers.None)
{
- if (!HandleKeyCore(key, modifiers))
+ if (key == Key.Tab && !IsEditMode && !_progressMode)
+ {
+ // Also when there is nothing to flip to: Tab never takes the focus off the donut.
+ Flip();
+ return true;
+ }
+ if (!HandleKeyCore(key))
return false;
// The keyboard has the donut now: the mouse resting where it was (or nudged a pixel, or Windows re-sending its
// position) doesn't take it back; moving it on purpose does.
@@ -214,7 +222,7 @@ public sealed partial class DonutMenu
return true;
}
- private bool HandleKeyCore(Key key, KeyModifiers modifiers)
+ private bool HandleKeyCore(Key key)
{
if (IsEditMode || _progressMode || Count == 0)
return false;
@@ -222,7 +230,6 @@ public sealed partial class DonutMenu
{
Key.Right or Key.Down => 1,
Key.Left or Key.Up => -1,
- Key.Tab => modifiers.HasFlag(KeyModifiers.Shift) ? -1 : 1,
_ => 0,
};
@@ -294,6 +301,7 @@ public sealed partial class DonutMenu
{
if (lastAt is { } at && LeftThroughSeam(at))
return;
+ _lastExternalAt = null;
CollapseGroup();
SetExternalHighlight(-1);
}
@@ -314,6 +322,8 @@ public sealed partial class DonutMenu
/// </summary>
public void SetExternalHit(DonutHit hit, Point? at = null)
{
+ if (at is not null)
+ _lastExternalAt = at; // a flip lights up what the drag rests on, on the other face
TrackGroups(hit, at);
SetExternalHighlight(hit.Kind is DonutHitKind.Segment or DonutHitKind.SubSegment ? hit.Index : -1,
hit.Kind == DonutHitKind.Center);
diff --git a/src/Filee.App/Controls/DonutMenu.cs b/src/Filee.App/Controls/DonutMenu.cs
index 29ef8627..dea3129b 100644
--- a/src/Filee.App/Controls/DonutMenu.cs
+++ b/src/Filee.App/Controls/DonutMenu.cs
@@ -6,7 +6,7 @@
// Motion.Enabled == false every value jumps straight to its target.
//
// After a drop the donut turns into a progress ring: see DonutMenu.Progress.cs. Group slices, which fan out a ring
-// of presets, and the keyboard: DonutMenu.Groups.cs.
+// of presets, and the keyboard: DonutMenu.Groups.cs. Tab flips the donut to its other face: DonutMenu.Flip.cs.
using System.Globalization;
using Avalonia;
@@ -131,7 +131,8 @@ public sealed partial class DonutMenu : Control
AffectsMeasure<DonutMenu>(OuterRadiusProperty, ReserveSubRingProperty);
AffectsRender<DonutMenu>(HoleRatioProperty, SliceOpacityProperty, CenterTitleProperty, CenterSubtitleProperty,
IsEditModeProperty, SliceBrushProperty, SliceBorderBrushProperty, CenterBrushProperty, AccentBrushProperty,
- OnAccentBrushProperty, ForegroundProperty, SecondaryForegroundProperty, SuccessBrushProperty, CornerRadiusProperty);
+ OnAccentBrushProperty, ForegroundProperty, SecondaryForegroundProperty, SuccessBrushProperty, CornerRadiusProperty,
+ CenterHintProperty);
ItemsProperty.Changed.AddClassHandler<DonutMenu>((d, _) => d.OnItemsChanged());
}
@@ -407,6 +408,10 @@ public sealed partial class DonutMenu : Control
_expanded = _shownExpanded = _subHover = -1;
ClearPending();
_expand = default;
+ // New files (or none): a flip of the old ones is over. A flip's own swap keeps going (SwapFaces).
+ if (!_swapping)
+ CancelFlip();
+ _lastExternalAt = null;
// The window is reused: a keyboard hold from the last time it was open must not swallow the first moves now.
_keyboardHold = _ringFromKeys = false;
_keyAnchor = _lastPointer = null;
@@ -679,6 +684,7 @@ public sealed partial class DonutMenu : Control
if (_expanded < 0)
_shownExpanded = -1;
StepLayout(0, snap: true);
+ FinishFlip();
if (_openClock < double.MaxValue)
{
_openClock = double.MaxValue;
@@ -726,6 +732,7 @@ public sealed partial class DonutMenu : Control
if (_expanded < 0)
_shownExpanded = -1;
StepLayout(dt);
+ FinishFlip(); // animations switched off halfway through a flip
if (_closing)
FinishClose();
active |= StepProgress(dt); // hold timers still run without animation
@@ -744,6 +751,7 @@ public sealed partial class DonutMenu : Control
_shownExpanded = -1;
active |= StepProgress(dt);
active |= StepLayout(dt);
+ active |= StepFlip(dt);
if (_openClock < double.MaxValue)
{
@@ -805,6 +813,29 @@ public sealed partial class DonutMenu : Control
return;
}
+ // A flip turns the ring (and its shadow and a group's ring) about the vertical axis; the hub stays.
+ var flip = FlipTransform(center);
+ using (context.PushTransform(flip))
+ RenderRing(context, center, r1, r2, n, typeface, typefaceRegular);
+
+ var reaching = _expanded >= 0 ? _expanded : _pendingGroup;
+ if (!IsEditMode && reaching >= 0 && reaching < n && Items![reaching].Children is { Count: > 0 } reachable)
+ DrawHitBackdrop(context, center, reaching, reachable.Count);
+ if (!IsEditMode && _shownExpanded >= 0 && _shownExpanded < n && _expand.Value > 0.01)
+ {
+ using (context.PushTransform(flip))
+ DrawSubRing(context, center, typeface, typefaceRegular);
+ }
+
+ DrawCenter(context, center, r1, typeface, typefaceRegular);
+
+ if (IsEditMode && _hoverIndex >= 0 && _hoverIndex < n && _dimmedIndex < 0 && !IsFlipping)
+ DrawEditButton(context, EditButtonCenter(_hoverIndex));
+ }
+
+ /// <summary>The shadow, the slices and the edit mode's drop preview.</summary>
+ private void RenderRing(DrawingContext context, Point center, double r1, double r2, int n, Typeface typeface, Typeface typefaceRegular)
+ {
DrawSoftShadow(context, center, r2);
if (n == 0)
@@ -858,17 +889,6 @@ public sealed partial class DonutMenu : Control
if (IsEditMode && _previewSpan.Value > 0.01)
DrawPreview(context, center, r1, r2, typeface, typefaceRegular);
-
- var reaching = _expanded >= 0 ? _expanded : _pendingGroup;
- if (!IsEditMode && reaching >= 0 && reaching < n && Items![reaching].Children is { Count: > 0 } reachable)
- DrawHitBackdrop(context, center, reaching, reachable.Count);
- if (!IsEditMode && _shownExpanded >= 0 && _shownExpanded < n && _expand.Value > 0.01)
- DrawSubRing(context, center, typeface, typefaceRegular);
-
- DrawCenter(context, center, r1, typeface, typefaceRegular);
-
- if (IsEditMode && _hoverIndex >= 0 && _hoverIndex < n && _dimmedIndex < 0)
- DrawEditButton(context, EditButtonCenter(_hoverIndex));
}
private void DrawSoftShadow(DrawingContext context, Point center, double r2)
@@ -902,11 +922,22 @@ public sealed partial class DonutMenu : Control
var maxWidth = radius * 1.6;
var title = MakeText(CenterTitle ?? "", bold, 14, Foreground, maxWidth, maxLines: 2);
var subtitle = MakeText(CenterSubtitle ?? "", regular, 11.5, cancelHot ? DangerBrush : SecondaryForeground, maxWidth, maxLines: 2);
- var total = title.Height + (string.IsNullOrEmpty(CenterSubtitle) ? 0 : subtitle.Height + 2);
+ // "Tab ↻ back": small, under the rest, a little narrower (the hub is round).
+ var hint = string.IsNullOrEmpty(CenterHint) ? null : MakeText(CenterHint, regular, 10.5, SecondaryForeground, maxWidth * 0.85);
+ var total = title.Height + (string.IsNullOrEmpty(CenterSubtitle) ? 0 : subtitle.Height + 2) + (hint is null ? 0 : hint.Height + 5);
var y = center.Y - total / 2;
DrawCentered(context, title, center.X, y);
+ y += title.Height;
if (!string.IsNullOrEmpty(CenterSubtitle))
- DrawCentered(context, subtitle, center.X, y + title.Height + 2);
+ {
+ DrawCentered(context, subtitle, center.X, y + 2);
+ y += subtitle.Height + 2;
+ }
+ if (hint is not null)
+ {
+ using (context.PushOpacity(0.85))
+ DrawCentered(context, hint, center.X, y + 5);
+ }
}
private void DrawLabel(DrawingContext context, DonutItem item, Point center, double radius, double angle,
@@ -914,7 +945,8 @@ public sealed partial class DonutMenu : Control
{
var foreground = hot ? OnAccentBrush : item.IsEnabled ? Foreground : SecondaryForeground;
var width = Math.Clamp(maxWidth, 30, 120);
- var label = MakeText(item.Label, bold, 13, foreground, width, maxLines: 2);
+ var text = KeepKoreanWords(item.Label);
+ var label = MakeText(text, bold, LabelSize(text, bold, width), foreground, width, maxLines: 2);
var showCaption = !string.IsNullOrEmpty(item.Caption) &&
!string.Equals(item.Caption, item.Label, StringComparison.OrdinalIgnoreCase) &&
label.Height + 14 < maxHeight;
@@ -928,6 +960,57 @@ public sealed partial class DonutMenu : Control
DrawCentered(context, caption, anchor.X, y + label.Height);
}
+ private const double LabelFontSize = 13;
+ private const double MinLabelFontSize = 10;
+ private readonly Dictionary<(string Text, Typeface Typeface, double Width), double> _labelSizes = new();
+
+ /// <summary>
+ /// The size a slice's name is drawn at: 13, or smaller (down to 10) when one of its words is wider than the slice
+ /// (<paramref name="width"/>), which would otherwise break in the middle ("Grayscal|e" on a thin slice). Words in
+ /// Chinese or Japanese are left out: those break between any two characters.
+ /// </summary>
+ internal double LabelSize(string text, Typeface typeface, double width)
+ {
+ var line = Math.Round(width);
+ var key = (text, typeface, line);
+ if (_labelSizes.TryGetValue(key, out var size))
+ return size;
+ if (_labelSizes.Count >= MaxCachedWedges)
+ _labelSizes.Clear();
+ var widest = text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
+ .Where(word => !word.Any(IsHanOrKana))
+ .Select(word => new FormattedText(word, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, LabelFontSize, null).Width)
+ .DefaultIfEmpty(0)
+ .Max();
+ // A pixel to spare: a word exactly as wide as the line still wraps.
+ size = widest < line ? LabelFontSize : Math.Max(MinLabelFontSize, LabelFontSize * (line - 1) / widest);
+ return _labelSizes[key] = size;
+ }
+
+ /// <summary>Chinese characters, kana and the CJK symbols and full-width forms: a line may break between any two.</summary>
+ private static bool IsHanOrKana(char c) =>
+ c is >= '\u2E80' and <= '\u312F' or >= '\u3190' and <= '\u9FFF' or >= '\uF900' and <= '\uFAFF' or >= '\uFF00' and <= '\uFFEF';
+
+ /// <summary>
+ /// Korean is written with spaces between words and wraps there, but the text layout also breaks between any two
+ /// Hangul syllables ("ZIP 하나|로"). A word joiner between them keeps each word on one line.
+ /// </summary>
+ internal static string KeepKoreanWords(string text)
+ {
+ if (!text.Any(IsHangul))
+ return text;
+ var kept = new System.Text.StringBuilder(text.Length * 2);
+ for (var i = 0; i < text.Length; i++)
+ {
+ kept.Append(text[i]);
+ if (i + 1 < text.Length && IsHangul(text[i]) && IsHangul(text[i + 1]))
+ kept.Append('\u2060');
+ }
+ return kept.ToString();
+ }
+
+ private static bool IsHangul(char c) => c is >= '\uAC00' and <= '\uD7A3';
+
private Point EditButtonCenter(int index)
{
var mid = DonutGeometry.MidAngle(index, Count);
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index cc7dcb9c..5ec5b761 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -7,6 +7,8 @@
// Click mode (keyboard shortcut, context menu, drop zone):
// files are known up front → donut appears activated → click a slice to convert, right-click to edit,
// Esc / click outside closes.
+// Tab flips the open donut to its other face (DonutMenu.Flip.cs): in click mode the focused window gets the key, in
+// drag mode (no focus during an OS drag) the global hook reports it while the donut shows files.
// After a drop / click the donut becomes a progress ring at the same spot (DonutMenu.Progress.cs):
// finished quickly → ✓ pops up in the centre, then the ring fades out;
// still running after HandOffAfter, failed, Esc, click elsewhere or a new gesture → the toast takes over.
@@ -15,6 +17,7 @@ using System.ComponentModel;
using Avalonia;
using Avalonia.Threading;
using Filee.App.Controls;
+using Filee.App.Services.Triggers;
using Filee.App.ViewModels;
using Filee.App.Views;
using Filee.Core.Conversion;
@@ -31,6 +34,7 @@ public sealed class RadialController(
WindowService windows,
UserDataStore store,
IPlatformServices platform,
+ TriggerService triggers,
ILogger<RadialController> log)
{
/// <summary>
@@ -84,6 +88,7 @@ public sealed class RadialController(
viewModel.ResetForDrag();
window.DonutControl.AllowContextEdit = false;
PlaceAndShow(window, x, y, activate: false);
+ WatchFlipKey();
var generation = ++_dragGeneration;
DispatcherTimer.RunOnce(() =>
@@ -115,6 +120,7 @@ public sealed class RadialController(
viewModel.FitToThisDonut();
window.DonutControl.AllowContextEdit = true;
PlaceAndShow(window, x, y, activate: true);
+ WatchFlipKey();
window.DonutControl.PlayOpenAnimation();
}
@@ -161,6 +167,7 @@ public sealed class RadialController(
_window.DonutControl.LeaveProgressMode();
}
_visible = false;
+ WatchFlipKey();
_grace.Cancel();
var window = _window;
// A group about to open (its dwell timer running) must not open on a closing donut.
@@ -213,10 +220,12 @@ public sealed class RadialController(
return;
viewModel.Load(files, clickMode: false);
donut.PlayOpenAnimation();
+ WatchFlipKey();
};
window.Dropped += (hit, files) =>
{
_dropped = true;
+ WatchFlipKey();
if (hit.Kind is DonutHitKind.Segment or DonutHitKind.SubSegment)
Convert(hit.Index, hit.Sub, files.Count > 0 ? files : viewModel.Files);
else
@@ -246,6 +255,12 @@ public sealed class RadialController(
};
donut.ActiveIndexChanged += (_, index) => viewModel.ShowHint(index, donut.ActiveSubIndex, donut.IsCenterHot);
+ // Drag mode: Tab seen by the global hook (click mode gets it as a key of the focused window).
+ triggers.FlipKeyPressed += (_, _) =>
+ {
+ if (_visible && !_dropped && !viewModel.IsClickMode && viewModel.HasFiles)
+ donut.Flip();
+ };
donut.SegmentInvoked += (_, index) => Convert(index, -1, viewModel.Files);
donut.SubSegmentInvoked += (_, hit) => Convert(hit.Group, hit.Sub, viewModel.Files);
donut.CenterInvoked += (_, _) => Close();
@@ -351,6 +366,7 @@ public sealed class RadialController(
private void HideWindow()
{
_visible = false;
+ WatchFlipKey();
_window?.DonutControl.CollapseGroup();
_window?.Hide();
}
@@ -366,7 +382,7 @@ public sealed class RadialController(
if (await windows.EditPresetAsync(preset, _window))
{
store.SaveLibrary();
- viewModel.Load(viewModel.Files, viewModel.IsClickMode);
+ viewModel.Load(viewModel.Files, viewModel.IsClickMode, viewModel.IsBackFace);
}
}
finally
@@ -377,6 +393,13 @@ public sealed class RadialController(
_window.Activate();
}
+ /// <summary>
+ /// Has the global hook report Tab only while a drag-mode donut shows files that could flip; Tab is left alone
+ /// otherwise (see <see cref="TriggerService.WatchFlipKey"/>).
+ /// </summary>
+ private void WatchFlipKey() =>
+ triggers.WatchFlipKey = _visible && !_dropped && !viewModel.IsClickMode && viewModel.HasFiles;
+
/// <summary>
/// Top-left corner of a <paramref name="sidePx"/> square window centred on <paramref name="cursor"/>, moved into
/// <paramref name="area"/> when that would cross its edge. With group slices the window holds the ring they fan out
diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.cs
index 6e193cf3..ae2faae4 100644
--- a/src/Filee.App/Services/Triggers/TriggerService.cs
+++ b/src/Filee.App/Services/Triggers/TriggerService.cs
@@ -57,6 +57,33 @@ public sealed class TriggerService : IDisposable
/// <summary>A hold or keyboard gesture: open the donut for the file manager's current selection.</summary>
public event EventHandler<GestureEventArgs>? SelectionGesture;
+ /// <summary>Tab went down while <see cref="WatchFlipKey"/> was on: flip the donut.</summary>
+ public event EventHandler? FlipKeyPressed;
+
+ private volatile bool _watchFlipKey;
+ private bool _flipKeyDown; // hook thread only
+
+ /// <summary>
+ /// On while the drag-mode donut shows files: Tab is reported (<see cref="FlipKeyPressed"/>), once per press, not
+ /// for the repeats of a held key. During an OS drag the donut's window has no keyboard focus, so Tab reaches
+ /// Filee only through the hook. Nothing is swallowed: the hook only listens (Explorer and Finder ignore Tab
+ /// during a drag, so the drag goes on), and with the donut closed Tab isn't even looked at.
+ /// </summary>
+ public bool WatchFlipKey
+ {
+ get => _watchFlipKey;
+ set => _watchFlipKey = value;
+ }
+
+ /// <summary>Tab went down or up (hook thread).</summary>
+ private void OnFlipKey(bool down)
+ {
+ var repeat = down && _flipKeyDown;
+ _flipKeyDown = down;
+ if (down && !repeat && _watchFlipKey)
+ Post(() => FlipKeyPressed?.Invoke(this, EventArgs.Empty));
+ }
+
/// <summary>Last known cursor position (physical pixels).</summary>
public (int X, int Y) LastCursor { get; private set; }
@@ -125,7 +152,17 @@ public sealed class TriggerService : IDisposable
_hook.MouseMoved += (_, e) => OnMove(e);
_hook.MouseDraggedRelative += (_, e) => OnRelativeMove(e);
_hook.MouseMovedRelative += (_, e) => OnRelativeMove(e);
- _hook.KeyPressed += (_, e) => _detector.KeyDown(KeyName(e.Data.KeyCode), Map(e.RawEvent.Mask));
+ _hook.KeyPressed += (_, e) =>
+ {
+ if (e.Data.KeyCode == KeyCode.VcTab)
+ OnFlipKey(down: true);
+ _detector.KeyDown(KeyName(e.Data.KeyCode), Map(e.RawEvent.Mask));
+ };
+ _hook.KeyReleased += (_, e) =>
+ {
+ if (e.Data.KeyCode == KeyCode.VcTab)
+ OnFlipKey(down: false);
+ };
// Own the actual Run thread. SharpHook's RunAsync task completes BEFORE its finally
// clears the native callback, so awaiting that task alone is not a safe restart barrier.
var hook = _hook;
diff --git a/src/Filee.App/ViewModels/GroupEditorViewModel.cs b/src/Filee.App/ViewModels/GroupEditorViewModel.cs
index 6128fa0d..60537cd9 100644
--- a/src/Filee.App/ViewModels/GroupEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/GroupEditorViewModel.cs
@@ -121,12 +121,15 @@ public sealed partial class GroupEditorViewModel : ObservableObject
return true;
}
- /// <summary>Removes the group from the store and from every donut (its presets stay).</summary>
+ /// <summary>Removes the group from the store and from every donut, front and back (its presets stay).</summary>
public void Delete()
{
_store.Presets.Remove(_group);
foreach (var profile in _store.Profiles)
+ {
profile.PresetIds.Remove(_group.Id);
+ profile.BackPresetIds?.Remove(_group.Id);
+ }
Deleted = true;
}
diff --git a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs
index 86d38769..0e511ce8 100644
--- a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs
@@ -1,4 +1,5 @@
-// Donut toolbar editor: 1) choose a profile 2) arrange its presets on a live donut by drag & drop.
+// Donut toolbar editor: 1) choose a profile 2) arrange its presets on a live donut by drag & drop, on the front face
+// or on the back (Tab flips the open donut to it), picked with the Front / Back switch above the donut.
// 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
@@ -100,6 +101,22 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
/// <summary>Extension chips of a normal profile (null for a mixed one).</summary>
[ObservableProperty] private ExtensionTagsViewModel? _extensionTags;
+ /// <summary>The donut shows and edits the back face of the profile (the Front / Back switch).</summary>
+ [ObservableProperty] private bool _editingBack;
+
+ /// <summary>The front face is edited: the other half of the switch.</summary>
+ public bool EditingFront
+ {
+ get => !EditingBack;
+ set => EditingBack = !value;
+ }
+
+ /// <summary>Slices on the front face, for the switch.</summary>
+ public int FrontCount => Profile?.PresetIds.Count ?? 0;
+
+ /// <summary>Slices on the back face, for the switch.</summary>
+ public int BackCount => Profile?.BackPresetIds?.Count ?? 0;
+
/// <summary>Check list of a mixed-selection profile (null for a normal one).</summary>
[ObservableProperty] private MixedExtensionsViewModel? _mixedExtensions;
[ObservableProperty] private double _outerRadius;
@@ -108,6 +125,17 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
private ToolbarProfile? Profile => SelectedProfile?.Profile;
+ /// <summary>The preset ids of the face being edited (null without a profile).</summary>
+ private List<string>? Slices => Profile is not { } profile ? null
+ : EditingBack ? (profile.BackPresetIds ??= []) : profile.PresetIds;
+
+ partial void OnEditingBackChanged(bool value)
+ {
+ OnPropertyChanged(nameof(EditingFront));
+ Message = null;
+ Rebuild();
+ }
+
partial void OnSelectedProfileChanged(ProfileItemViewModel? value)
{
// The list box briefly drops its selection while the selected profile is moved (see Reposition).
@@ -200,48 +228,52 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
// ───────── Editing operations called by the view's drag & drop ─────────
- public int SliceCount => Profile?.PresetIds.Count ?? 0;
+ /// <summary>Slices on the face being edited.</summary>
+ public int SliceCount => Slices?.Count ?? 0;
- /// <summary>Adds a palette preset at <paramref name="index"/> (clamped). Returns false when the donut is full.</summary>
+ /// <summary>
+ /// Adds a palette preset to the face being edited at <paramref name="index"/> (clamped). Returns false when that
+ /// face is full.
+ /// </summary>
public bool Insert(string presetId, int index)
{
- if (Profile is null || Profile.PresetIds.Contains(presetId))
+ if (Slices is not { } slices || slices.Contains(presetId))
return false;
- if (Profile.PresetIds.Count >= ToolbarProfile.MaxSlices)
+ if (slices.Count >= ToolbarProfile.MaxSlices)
{
Message = _loc.Format("toolbar.max_reached", ToolbarProfile.MaxSlices);
return false;
}
- Profile.PresetIds.Insert(Math.Clamp(index, 0, Profile.PresetIds.Count), presetId);
+ slices.Insert(Math.Clamp(index, 0, slices.Count), presetId);
Commit();
return true;
}
public void RemoveAt(int index)
{
- if (Profile is null || index < 0 || index >= Profile.PresetIds.Count)
+ if (Slices is not { } slices || index < 0 || index >= slices.Count)
return;
- Profile.PresetIds.RemoveAt(index);
+ slices.RemoveAt(index);
Commit();
}
/// <summary>Moves a slice onto another slice's position.</summary>
public void Move(int from, int to)
{
- if (Profile is null || from == to || from < 0 || from >= Profile.PresetIds.Count)
+ if (Slices is not { } slices || from == to || from < 0 || from >= slices.Count)
return;
- var id = Profile.PresetIds[from];
- Profile.PresetIds.RemoveAt(from);
- Profile.PresetIds.Insert(Math.Clamp(to, 0, Profile.PresetIds.Count), id);
+ var id = slices[from];
+ slices.RemoveAt(from);
+ slices.Insert(Math.Clamp(to, 0, slices.Count), id);
Commit();
}
/// <summary>Opens the preset popup for the slice at <paramref name="index"/>.</summary>
public async Task EditAsync(int index)
{
- if (Profile is null || index < 0 || index >= Profile.PresetIds.Count)
+ if (Slices is not { } slices || index < 0 || index >= slices.Count)
return;
- var preset = _store.FindPreset(Profile.PresetIds[index]);
+ var preset = _store.FindPreset(slices[index]);
if (preset is not null && await _windows.EditPresetAsync(preset, _windows.Main))
Commit();
}
@@ -282,15 +314,15 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
if (!await _windows.EditPresetAsync(preset, _windows.Main))
return;
_store.Presets.Add(preset);
- if (Profile is not null && Profile.PresetIds.Count < ToolbarProfile.MaxSlices)
- Profile.PresetIds.Add(preset.Id);
+ if (Slices is { Count: < ToolbarProfile.MaxSlices } slices)
+ slices.Add(preset.Id);
Commit();
}
[RelayCommand]
private void AddProfile()
{
- var profile = new ToolbarProfile { Name = _loc["toolbar.profile_new"], PresetIds = ["to-pdf", "to-png"] };
+ var profile = new ToolbarProfile { Name = _loc["toolbar.profile_new"], PresetIds = ["to-pdf", "to-png"], BackPresetIds = [] };
// 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;
@@ -365,11 +397,11 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
Rebuild();
}
- /// <summary>Rebuilds the donut slices and the palette from the model.</summary>
+ /// <summary>Rebuilds the donut slices (of the face being edited) and the palette from the model.</summary>
private void Rebuild()
{
var profile = Profile;
- var used = profile?.PresetIds ?? [];
+ var used = Slices ?? [];
DonutItems = used
.Select(_store.FindPreset)
.OfType<Preset>()
@@ -389,7 +421,11 @@ public sealed partial class ToolbarPageViewModel : ObservableObject
}
CenterTitle = profile is null ? "" : _loc.DisplayName(profile);
- CenterSubtitle = $"{used.Count} / {ToolbarProfile.MaxSlices}";
+ CenterSubtitle = EditingBack
+ ? $"{_loc["toolbar.face_back"]} · {used.Count} / {ToolbarProfile.MaxSlices}"
+ : $"{used.Count} / {ToolbarProfile.MaxSlices}";
+ OnPropertyChanged(nameof(FrontCount));
+ OnPropertyChanged(nameof(BackCount));
}
private string? Caption(Preset p) =>
diff --git a/src/Filee.App/ViewModels/RadialViewModel.cs b/src/Filee.App/ViewModels/RadialViewModel.cs
index 37f25c5b..af3d6117 100644
--- a/src/Filee.App/ViewModels/RadialViewModel.cs
+++ b/src/Filee.App/ViewModels/RadialViewModel.cs
@@ -1,5 +1,7 @@
-// State of the live donut toolbar: which files are being converted and which presets are offered.
+// State of the live donut toolbar: which files are being converted and which presets are offered, on the front and
+// the back face of the donut (Tab flips between them, see DonutMenu.Flip.cs).
+using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using Filee.App.Controls;
using Filee.App.Services;
@@ -20,6 +22,12 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
[ObservableProperty] private double _holeRatio = 0.42;
[ObservableProperty] private double _sliceOpacity = 0.96;
+ /// <summary>The other face has a slice for these files: Tab flips to it.</summary>
+ [ObservableProperty] private bool _canFlip;
+
+ /// <summary>"Tab ↻ back" / "Tab ↻ front" in the hub while <see cref="CanFlip"/>, else null.</summary>
+ [ObservableProperty] private string? _flipHint;
+
/// <summary>
/// The window keeps room for the ring a group fans out. Dragging, the donut is placed before the files (and so
/// the donut) are known: room when any donut has a group. In click mode only when this one does
@@ -49,6 +57,31 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
/// <summary>For each slice, the presets its group fans out (empty for an ordinary preset).</summary>
private IReadOnlyList<IReadOnlyList<Preset>> _subPresets = [];
+ /// <summary>The slices of one face of the donut, for the files on it.</summary>
+ private sealed record Face(IReadOnlyList<Preset> Presets, IReadOnlyList<IReadOnlyList<Preset>> SubPresets, IReadOnlyList<DonutItem> Items)
+ {
+ public static readonly Face Empty = new([], [], []);
+
+ /// <summary>
+ /// A slice converts these files. A face without one isn't flipped to: all of it greyed out would only be a
+ /// dead end, and Tab doing nothing there is what it does on a donut with no back face.
+ /// </summary>
+ public bool IsUsable => Items.Any(item => item.IsEnabled);
+ }
+
+ private Face _front = Face.Empty;
+
+ // The back face: its presets as the profile has them, and its slices for the files once they are checked (null
+ // until then). Checking every preset against the files takes as long as for the front (a moment when engines are
+ // missing), so the back is checked after the front is on screen, not before (see Load).
+ private IReadOnlyList<string> _backIds = [];
+ private IReadOnlyList<FileFormat> _formats = [];
+ private Face? _back;
+ private int _loads;
+
+ /// <summary>The back face is showing (after a flip).</summary>
+ public bool IsBackFace { get; private set; }
+
/// <summary>
/// The preset that slice <paramref name="index"/> converts with, or slice <paramref name="sub"/> of its group's ring;
/// null when there is none or it can't convert these files.
@@ -80,19 +113,22 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
{
IsClickMode = false;
Files = [];
- Presets = [];
- _subPresets = [];
ApplyAppearance();
- ReserveSubRing = store.Profiles.Any(profile => profile.PresetIds.Any(id => store.FindPreset(id)?.IsGroup == true));
- Items = [];
+ ReserveSubRing = store.Profiles.Any(profile => HasGroups(profile.PresetIds.Concat(profile.BackPresetIds ?? [])));
+ _loads++;
+ (_front, _back, _backIds, _formats) = (Face.Empty, Face.Empty, [], []);
+ ShowFace(back: false);
CenterTitle = loc["donut.center_drag"];
CenterSubtitle = null;
DonutOpacity = 0;
HitBackground = "#01000000";
}
- /// <summary>Fills the donut for the given files.</summary>
- public void Load(IReadOnlyList<string> files, bool clickMode)
+ /// <summary>
+ /// Fills the donut for the given files, on its front face, or on the back when <paramref name="backFace"/> and the
+ /// back has a slice for them (the same files again after a preset was edited).
+ /// </summary>
+ public void Load(IReadOnlyList<string> files, bool clickMode, bool backFace = false)
{
IsClickMode = clickMode;
Files = files;
@@ -102,12 +138,76 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
var profile = ProfileSelector.Select(store.Profiles, files);
var formats = ProfileSelector.DetectFormats(files);
- Presets = (profile?.PresetIds ?? [])
+ // Both faces follow the same rule: a slice that can't convert these files is greyed out and says why.
+ _front = BuildFace(profile?.PresetIds ?? [], formats);
+ (_back, _backIds, _formats) = (null, [.. profile?.BackPresetIds ?? []], formats);
+ var load = ++_loads;
+ if (backFace)
+ {
+ ShowFace(BackFace().IsUsable);
+ }
+ else
+ {
+ ShowFace(back: false, checkBack: false);
+ // Right after the donut is drawn: until then Tab has nothing to flip to, nor the hub a hint.
+ if (_backIds.Count > 0)
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (load == _loads && _back is null)
+ ShowFace(IsBackFace);
+ }, DispatcherPriority.Background);
+ }
+
+ CenterTitle = formats.Count == 1
+ ? loc.Format("donut.files_same", files.Count, formats[0].DisplayName)
+ : loc.Format("donut.files_mixed", files.Count);
+ CenterSubtitle = clickMode ? loc["donut.close_hint"] : null;
+ }
+
+ /// <summary>
+ /// Shows the other face (the donut is edge-on in its flip). Returns false, changing nothing, when it has no slice
+ /// for these files (<see cref="CanFlip"/>).
+ /// </summary>
+ public bool ToggleFace()
+ {
+ if (_back is null)
+ ShowFace(IsBackFace); // asked for before it was checked: check it now
+ if (!CanFlip)
+ return false;
+ ShowFace(!IsBackFace);
+ CenterSubtitle = IsClickMode ? loc["donut.close_hint"] : null;
+ return true;
+ }
+
+ /// <summary>Shows a face; <paramref name="checkBack"/> false leaves an unchecked back face (and the flip) for later.</summary>
+ private void ShowFace(bool back, bool checkBack = true)
+ {
+ var face = back ? BackFace() : _front;
+ if (IsBackFace != back || !ReferenceEquals(Items, face.Items))
+ {
+ IsBackFace = back;
+ Presets = face.Presets;
+ _subPresets = face.SubPresets;
+ Items = face.Items;
+ }
+ var other = back ? _front : checkBack ? BackFace() : _back;
+ CanFlip = other?.IsUsable == true;
+ FlipHint = CanFlip ? loc[back ? "donut.flip_to_front" : "donut.flip_to_back"] : null;
+ }
+
+ /// <summary>The back face's slices for the files, checked now if they weren't yet.</summary>
+ private Face BackFace() => _back ??= BuildFace(_backIds, _formats);
+
+ private bool HasGroups(IEnumerable<string> presetIds) => presetIds.Any(id => store.FindPreset(id)?.IsGroup == true);
+
+ private Face BuildFace(IEnumerable<string> presetIds, IReadOnlyList<FileFormat> formats)
+ {
+ var presets = presetIds
.Select(store.FindPreset)
.OfType<Preset>()
.ToList();
- _subPresets = Presets
+ var subPresets = presets
.Select(p => (IReadOnlyList<Preset>)(p.IsGroup ? p.SubPresetIds : [])
.Select(store.FindPreset).OfType<Preset>().Where(c => !c.IsGroup).Take(Preset.MaxSubPresets).ToList())
.ToList();
@@ -129,12 +229,12 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
};
}
- Items = Presets.Select((p, i) =>
+ var items = presets.Select((p, i) =>
{
if (!p.IsGroup)
return ItemOf(p);
// A group: its own name and size, and its presets on the ring it fans out (labels only, they're small).
- var children = _subPresets[i].Select(c => ItemOf(c, caption: false)).ToList();
+ var children = subPresets[i].Select(c => ItemOf(c, caption: false)).ToList();
return new DonutItem
{
Id = p.Id,
@@ -147,11 +247,7 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
Children = children,
};
}).ToList();
-
- CenterTitle = formats.Count == 1
- ? loc.Format("donut.files_same", files.Count, formats[0].DisplayName)
- : loc.Format("donut.files_mixed", files.Count);
- CenterSubtitle = clickMode ? loc["donut.close_hint"] : null;
+ return new Face(presets, subPresets, items);
}
/// <summary>Updates the centre hint for the emphasised slice (and slice <paramref name="sub"/> of its group's ring).</summary>
@@ -174,8 +270,11 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
CenterSubtitle = IsClickMode ? loc["donut.close_hint"] : null;
}
- /// <summary>Click mode, before the window is placed: room for a group's ring only if this donut has a group.</summary>
- public void FitToThisDonut() => ReserveSubRing = Items.Any(item => item.IsGroup);
+ /// <summary>
+ /// Click mode, before the window is placed: room for a group's ring only if this donut has a group, on either face
+ /// (the window must not grow, and the donut move, when it flips).
+ /// </summary>
+ public void FitToThisDonut() => ReserveSubRing = _front.Items.Any(item => item.IsGroup) || HasGroups(_backIds);
private void ApplyAppearance()
{
diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml b/src/Filee.App/Views/Pages/ToolbarPage.axaml
index 62e7ddb4..673a58b9 100644
--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml
+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml
@@ -1,6 +1,6 @@
<!--
Donut toolbar editor.
- 1. Pick a profile on the left. 2. Arrange its presets on the live donut:
+ 1. Pick a profile on the left. 2. Arrange its presets on the live donut, front or back face (the switch above it):
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
@@ -39,6 +39,38 @@
<Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />
</Style>
+ <!-- Front / Back switch above the donut: two segments in a pill, the face being edited filled with the accent -->
+ <Style Selector="Border.faces">
+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="Padding" Value="3" />
+ </Style>
+ <Style Selector="RadioButton.face">
+ <Setter Property="Background" Value="Transparent" />
+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />
+ <Setter Property="FontWeight" Value="SemiBold" />
+ <Setter Property="Cursor" Value="Hand" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border Background="{TemplateBinding Background}" CornerRadius="999" Padding="16,5">
+ <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"
+ Foreground="{TemplateBinding Foreground}" />
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+ <Style Selector="RadioButton.face:pointerover">
+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
+ </Style>
+ <Style Selector="RadioButton.face:checked">
+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />
+ <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />
+ </Style>
+ <Style Selector="RadioButton.face TextBlock.count">
+ <Setter Property="FontWeight" Value="Normal" />
+ <Setter Property="Opacity" Value="0.8" />
+ </Style>
+
<!-- Mixed-selection check list: group rows with a chevron, extension toggle chips -->
<Style Selector="Border.ext-groups">
<Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />
@@ -138,13 +170,34 @@
<StackPanel Grid.Column="2" Spacing="12">
<TextBlock Classes="label" Text="{DynamicResource toolbar.step_arrange}" />
<Border Classes="card" Padding="8">
- <c:DonutMenu x:Name="Donut" IsEditMode="True" HorizontalAlignment="Center"
- Items="{Binding DonutItems}"
- CenterTitle="{Binding CenterTitle}"
- CenterSubtitle="{Binding CenterSubtitle}"
- OuterRadius="{Binding OuterRadius}"
- HoleRatio="{Binding HoleRatio, Converter={x:Static vm:ToolbarConverters.Percent}}"
- SliceOpacity="{Binding SliceOpacity, Converter={x:Static vm:ToolbarConverters.Percent}}" />
+ <StackPanel>
+ <!-- Which face of the donut the slices below are: the front, or the back Tab flips the open donut to. -->
+ <Border x:Name="FaceSwitch" Classes="faces" HorizontalAlignment="Center" Margin="0,6,0,0">
+ <StackPanel Orientation="Horizontal">
+ <RadioButton Classes="face" IsChecked="{Binding EditingFront}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <TextBlock Text="{DynamicResource toolbar.face_front}" />
+ <TextBlock Classes="count" Text="{Binding FrontCount}" />
+ </StackPanel>
+ </RadioButton>
+ <RadioButton Classes="face" IsChecked="{Binding EditingBack}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <TextBlock Text="{DynamicResource toolbar.face_back}" />
+ <TextBlock Classes="count" Text="{Binding BackCount}" />
+ </StackPanel>
+ </RadioButton>
+ </StackPanel>
+ </Border>
+ <TextBlock Classes="caption" HorizontalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap"
+ Margin="12,6,12,0" Text="{DynamicResource toolbar.face_hint}" />
+ <c:DonutMenu x:Name="Donut" IsEditMode="True" HorizontalAlignment="Center"
+ Items="{Binding DonutItems}"
+ CenterTitle="{Binding CenterTitle}"
+ CenterSubtitle="{Binding CenterSubtitle}"
+ OuterRadius="{Binding OuterRadius}"
+ HoleRatio="{Binding HoleRatio, Converter={x:Static vm:ToolbarConverters.Percent}}"
+ SliceOpacity="{Binding SliceOpacity, Converter={x:Static vm:ToolbarConverters.Percent}}" />
+ </StackPanel>
</Border>
<TextBlock Classes="caption danger" Text="{Binding Message}" HorizontalAlignment="Center" />
diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs b/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs
index e303efab..8aecceea 100644
--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs
+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs
@@ -4,8 +4,10 @@
// Targets: a donut slice (insert at / move to that position), the empty ring or the hole (append),
// or the palette box (remove a slice).
// A floating "ghost" chip follows the pointer, and the donut opens a gap where the drop would land, with a
-// translucent slice of the dragged preset in it (DonutMenu.SetDropPreview).
+// translucent slice of the dragged preset in it (DonutMenu.SetDropPreview). The Front / Back switch shows the other
+// face of the profile, and the donut turns in to it as the open donut does on Tab.
+using System.ComponentModel;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
@@ -27,6 +29,7 @@ public partial class ToolbarPage : UserControl
}
private DragState? _drag;
+ private ToolbarPageViewModel? _subscribed;
public ToolbarPage()
{
@@ -51,6 +54,24 @@ public partial class ToolbarPage : UserControl
if (Vm is not null)
await Vm.EditAsync(index);
};
+ DataContextChanged += (_, _) =>
+ {
+ if (_subscribed is not null)
+ _subscribed.PropertyChanged -= OnViewModelChanged;
+ _subscribed = Vm;
+ if (_subscribed is not null)
+ _subscribed.PropertyChanged += OnViewModelChanged;
+ };
+ }
+
+ /// <summary>The switch showed the other face (its slices are in already): the donut turns in to it.</summary>
+ private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName == nameof(ToolbarPageViewModel.EditingBack))
+ {
+ EndDrag();
+ Donut.PlayFlipIn();
+ }
}
private ToolbarPageViewModel? Vm => DataContext as ToolbarPageViewModel;
diff --git a/src/Filee.App/Views/RadialWindow.axaml b/src/Filee.App/Views/RadialWindow.axaml
index 86c09bbb..bf9b770a 100644
--- a/src/Filee.App/Views/RadialWindow.axaml
+++ b/src/Filee.App/Views/RadialWindow.axaml
@@ -27,6 +27,8 @@
OuterRadius="{Binding OuterRadius}"
HoleRatio="{Binding HoleRatio}"
SliceOpacity="{Binding SliceOpacity}"
- ReserveSubRing="{Binding ReserveSubRing}" />
+ ReserveSubRing="{Binding ReserveSubRing}"
+ CanFlip="{Binding CanFlip}"
+ CenterHint="{Binding FlipHint}" />
</Panel>
</Window>
diff --git a/src/Filee.App/Views/RadialWindow.axaml.cs b/src/Filee.App/Views/RadialWindow.axaml.cs
index 64dcdb23..6513ee19 100644
--- a/src/Filee.App/Views/RadialWindow.axaml.cs
+++ b/src/Filee.App/Views/RadialWindow.axaml.cs
@@ -5,6 +5,7 @@ using Avalonia.Controls;
using Avalonia.Input;
using Filee.App.Controls;
using Filee.App.Services;
+using Filee.App.ViewModels;
using Filee.Core.Platform;
namespace Filee.App.Views;
@@ -20,6 +21,8 @@ public partial class RadialWindow : Window
DragDrop.AddDragOverHandler(Root, OnDragOver);
DragDrop.AddDragLeaveHandler(Root, OnDragLeave);
DragDrop.AddDropHandler(Root, OnDrop);
+ // Halfway through a flip (Tab) the donut shows the other face of the profile.
+ Donut.FaceSwapping += (_, _) => (DataContext as RadialViewModel)?.ToggleFace();
}
public DonutMenu DonutControl => Donut;
diff --git a/tests/Filee.App.Tests/DonutFlipTests.cs b/tests/Filee.App.Tests/DonutFlipTests.cs
new file mode 100644
index 00000000..f774141f
--- /dev/null
+++ b/tests/Filee.App.Tests/DonutFlipTests.cs
@@ -0,0 +1,455 @@
+// Tab flips the open donut to the back face of its profile: in click mode as a key of the focused window, in drag
+// mode through the global hook. Arrows still move between slices, an empty or unusable back face doesn't flip, the
+// back face greys out what can't convert the files like the front, and "Reduce animations" swaps the faces at once.
+
+using Avalonia;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Input;
+using Avalonia.Input.Raw;
+using Avalonia.Platform.Storage;
+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.Platform;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+using Microsoft.Extensions.Logging.Abstractions;
+using SharpHook.Data;
+
+namespace Filee.App.Tests;
+
+[Collection("Motion")]
+public class DonutFlipTests
+{
+ private static readonly string[] Photos = [@"C:\photos\a.jpg", @"C:\photos\b.jpg"];
+
+ private static UserDataStore Store => AppHost.Get<UserDataStore>();
+
+ private static ToolbarProfile Images => Store.Profiles.Single(p => p.Id == "images");
+
+ /// <summary>The image donut's back face, as the library has it now.</summary>
+ private static List<string> ImageBack => Images.BackPresetIds!.Where(id => Store.FindPreset(id) is not null).ToList();
+
+ /// <summary>
+ /// Runs <paramref name="test"/> with animations on or off and the image donut's back face as given (null: the
+ /// built-in one); everything is put back afterwards.
+ /// </summary>
+ private static void With(bool animations, List<string>? back, Action test, string language = "en")
+ {
+ TestServices.EnsureInitialized(language);
+ var images = Images;
+ var (front, before) = (images.PresetIds.ToList(), images.BackPresetIds?.ToList());
+ try
+ {
+ if (back is not null)
+ images.BackPresetIds = back;
+ Motion.Configure(!animations, () => false);
+ test();
+ }
+ finally
+ {
+ Motion.Configure(false, () => false);
+ images.PresetIds = front;
+ images.BackPresetIds = before;
+ }
+ }
+
+ /// <summary>The donut for <paramref name="files"/>, opened like the selection shortcut opens it.</summary>
+ private static (RadialViewModel Vm, RadialWindow Window, DonutMenu Donut) OpenClickMode(params string[] files)
+ {
+ var vm = AppHost.Get<RadialViewModel>();
+ vm.Load(files.Length > 0 ? files : Photos, clickMode: true);
+ vm.FitToThisDonut();
+ var window = new RadialWindow { DataContext = vm };
+ HintLikeTheController(vm, window.DonutControl);
+ window.Show();
+ Dispatcher.UIThread.RunJobs();
+ return (vm, window, window.DonutControl);
+ }
+
+ /// <summary>The hub says what the slice under the pointer or the keyboard does, as RadialController has it.</summary>
+ private static void HintLikeTheController(RadialViewModel vm, DonutMenu donut) =>
+ donut.ActiveIndexChanged += (_, index) => vm.ShowHint(index, donut.ActiveSubIndex, donut.IsCenterHot);
+
+ [AvaloniaFact]
+ public void Tab_flips_to_the_back_and_shift_tab_back_to_the_front_in_click_mode() => With(animations: true, back: null, () =>
+ {
+ var loc = AppHost.Get<ILocalizer>();
+ var (vm, window, donut) = OpenClickMode();
+ var front = vm.Items.Select(i => i.Id).ToList();
+ Assert.True(vm.CanFlip);
+ Assert.Equal(loc["donut.flip_to_back"], vm.FlipHint);
+ Assert.Equal(vm.FlipHint, donut.CenterHint);
+
+ Assert.True(donut.HandleKey(Key.Tab));
+ Assert.True(donut.IsFlipping);
+ donut.Advance(DonutMenu.FlipDuration * 0.3);
+ Assert.InRange(donut.FlipScale, 0.01, 0.99); // turning, still the front
+ Assert.False(vm.IsBackFace);
+ Assert.Equal(front, vm.Items.Select(i => i.Id));
+
+ donut.Advance(DonutMenu.FlipDuration * 0.3); // past edge-on: the back
+ Assert.True(vm.IsBackFace);
+ Assert.Equal(ImageBack, vm.Items.Select(i => i.Id));
+ Assert.Equal(loc["donut.flip_to_front"], donut.CenterHint);
+ Assert.Equal(loc["donut.close_hint"], vm.CenterSubtitle);
+ donut.Advance(DonutMenu.FlipDuration);
+ Assert.False(donut.IsFlipping);
+ Assert.Equal(1, donut.FlipScale);
+
+ Assert.True(donut.HandleKey(Key.Tab, KeyModifiers.Shift));
+ donut.Advance(DonutMenu.FlipDuration);
+ Assert.False(vm.IsBackFace);
+ Assert.Equal(front, vm.Items.Select(i => i.Id));
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void The_window_hands_tab_to_the_donut() => With(animations: false, back: null, () =>
+ {
+ var (vm, window, _) = OpenClickMode();
+ window.KeyPress(Key.Tab, RawInputModifiers.None, PhysicalKey.Tab, null);
+ Dispatcher.UIThread.RunJobs();
+ Assert.True(vm.IsBackFace);
+ Assert.True(window.IsVisible);
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void Tab_pressed_again_during_a_flip_flips_once_more_after_it() => With(animations: true, back: null, () =>
+ {
+ var (vm, window, donut) = OpenClickMode();
+ donut.HandleKey(Key.Tab);
+ donut.Advance(0.02);
+ donut.HandleKey(Key.Tab); // before the first turn ended
+ for (var i = 0; i < 40; i++)
+ donut.Advance(1 / 60.0);
+ Assert.False(donut.IsFlipping);
+ Assert.False(vm.IsBackFace); // turned over twice
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void Arrows_still_move_between_slices_and_start_over_on_the_other_face() => With(animations: false, back: null, () =>
+ {
+ var (vm, window, donut) = OpenClickMode();
+ Assert.True(donut.HandleKey(Key.Right));
+ Assert.True(donut.HandleKey(Key.Right));
+ Assert.Equal(1, donut.ActiveIndex);
+ Assert.Contains(vm.Items[1].Label, vm.CenterSubtitle);
+
+ Assert.True(donut.HandleKey(Key.Tab));
+ Assert.True(vm.IsBackFace);
+ Assert.Equal(-1, donut.ActiveIndex); // the selection starts over on the back
+ Assert.Equal(AppHost.Get<ILocalizer>()["donut.close_hint"], vm.CenterSubtitle);
+
+ Assert.True(donut.HandleKey(Key.Left)); // wraps to the last slice of the back
+ Assert.Equal(vm.Items.Count - 1, donut.ActiveIndex);
+ Assert.Equal(ImageBack[^1], vm.Items[donut.ActiveIndex].Id);
+ Assert.Equal(ImageBack[^1], vm.PresetAt(donut.ActiveIndex, -1)!.Id); // what Enter converts with
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void With_animations_off_the_faces_swap_at_once() => With(animations: false, back: null, () =>
+ {
+ var (vm, window, donut) = OpenClickMode();
+ Assert.True(donut.Flip());
+ Assert.False(donut.IsFlipping);
+ Assert.Equal(1, donut.FlipScale);
+ Assert.True(vm.IsBackFace);
+ Assert.False(donut.Advance(0)); // nothing left to animate
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void A_donut_without_a_back_face_does_not_flip() => With(animations: true, back: [], () =>
+ {
+ var (vm, window, donut) = OpenClickMode();
+ Assert.False(vm.CanFlip);
+ Assert.Null(vm.FlipHint);
+ Assert.False(donut.CanFlip);
+
+ Assert.True(donut.HandleKey(Key.Tab)); // still Tab's: it doesn't move the focus off the donut
+ Assert.False(donut.IsFlipping);
+ Assert.False(donut.Flip());
+ Assert.False(vm.IsBackFace);
+ Assert.False(vm.ToggleFace());
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void The_back_face_greys_out_what_cannot_convert_the_files_and_one_with_nothing_left_does_not_flip()
+ {
+ var group = new Preset
+ {
+ Id = "flip-test-sounds",
+ Name = "Sounds",
+ Kind = PresetKind.Group,
+ TargetFormat = Preset.GroupTarget,
+ SubPresetIds = ["to-wav", "to-flac"],
+ };
+ With(animations: false, back: ["to-wav", "flip-test-sounds"], () =>
+ {
+ Store.Presets.Add(group);
+ try
+ {
+ // Pictures can't become sounds: nothing on the back is for them, so there is nothing to flip to.
+ var (vm, window, donut) = OpenClickMode();
+ Assert.False(vm.CanFlip);
+ Assert.Null(vm.FlipHint);
+ Assert.False(donut.Flip());
+ window.Close();
+
+ // One slice for them is enough; the others are greyed out with the reason, as on the front.
+ Images.BackPresetIds = ["to-wav", "flip-test-sounds", "to-gif"];
+ (vm, window, donut) = OpenClickMode();
+ Assert.True(vm.CanFlip);
+ Assert.True(donut.Flip());
+ Assert.Equal(["to-wav", "flip-test-sounds", "to-gif"], vm.Items.Select(i => i.Id));
+ Assert.False(vm.Items[0].IsEnabled);
+ Assert.NotNull(vm.Items[0].DisabledReason);
+ Assert.True(vm.Items[1].IsGroup);
+ Assert.False(vm.Items[1].IsEnabled); // every slice of its ring is greyed out
+ Assert.All(vm.Items[1].Children!, child => Assert.False(child.IsEnabled));
+ Assert.True(vm.Items[2].IsEnabled);
+ Assert.Null(vm.PresetAt(0, -1));
+ Assert.Equal("to-gif", vm.PresetAt(2, -1)!.Id);
+ window.Close();
+ }
+ finally
+ {
+ Store.Presets.Remove(group);
+ }
+ });
+ }
+
+ [AvaloniaFact]
+ public void An_open_group_ring_folds_before_the_donut_turns() => With(animations: true, back: null, () =>
+ {
+ Images.PresetIds = [.. Images.PresetIds, "rotate"];
+ var (vm, window, donut) = OpenClickMode();
+ Assert.True(vm.ReserveSubRing);
+ var group = vm.Items.Count - 1;
+ donut.SetExternalHit(new DonutHit(DonutHitKind.Segment, group));
+ donut.ExpandPendingGroup();
+ Assert.Equal(DonutHitKind.SubSegment, donut.HitTest(donut.SubSliceCenter(group, 1)).Kind);
+
+ donut.HandleKey(Key.Tab);
+ Assert.NotEqual(DonutHitKind.SubSegment, donut.HitTest(donut.SubSliceCenter(group, 1)).Kind);
+ Assert.False(vm.IsBackFace); // the ring folds first, the faces swap halfway through the turn
+ donut.Advance(DonutMenu.FlipDuration);
+ Assert.True(vm.IsBackFace);
+ window.Close();
+ });
+
+ [AvaloniaFact]
+ public void A_drag_resting_on_a_slice_lights_up_the_slice_there_on_the_other_face() => With(animations: false, back: null, () =>
+ {
+ var vm = AppHost.Get<RadialViewModel>();
+ vm.ResetForDrag();
+ var window = new RadialWindow { DataContext = vm };
+ HintLikeTheController(vm, window.DonutControl);
+ window.Show();
+ vm.Load(Photos, clickMode: false);
+ Dispatcher.UIThread.RunJobs();
+ var donut = window.DonutControl;
+ var n = vm.Items.Count;
+ var center = new Point(donut.Bounds.Width / 2, donut.Bounds.Height / 2);
+ var at = DonutGeometry.PointAt(center, vm.OuterRadius * (1 + vm.HoleRatio) / 2, DonutGeometry.MidAngle(2, n));
+ donut.SetExternalHit(donut.HitTest(at), at);
+ Assert.Equal(2, donut.ActiveIndex);
+
+ Assert.True(donut.Flip());
+
+ var back = vm.Items.Count;
+ var expected = DonutGeometry.HitTest(center, at, vm.OuterRadius * vm.HoleRatio, vm.OuterRadius, back, 7).Index;
+ Assert.Equal(expected, donut.ActiveIndex);
+ Assert.Equal(AppHost.Get<ILocalizer>().Format("donut.drop_to", vm.Items[expected].Label), vm.CenterSubtitle);
+ window.Close();
+ });
+
+ /// <summary>
+ /// Drag mode: the donut's window has no keyboard focus during the OS drag, so Tab comes from the global hook (here a
+ /// stand-in for libuiohook): it flips the donut while files are on it, and is left alone once the donut is gone.
+ /// </summary>
+ [AvaloniaFact]
+ public void In_drag_mode_tab_from_the_global_hook_flips_the_donut() => With(animations: false, back: null, () =>
+ {
+ var provider = new TriggerServiceLifecycleTests.DelayedProvider();
+ provider.AllowExit.Set();
+ using var triggers = TriggerServiceLifecycleTests.Create(provider, () => { });
+ triggers.Start();
+ Assert.True(SpinWait.SpinUntil(() => provider.Runs == 1, 2000));
+ var vm = AppHost.Get<RadialViewModel>();
+ var radial = new RadialController(vm, AppHost.Get<ConversionService>(), AppHost.Get<WindowService>(), Store,
+ AppHost.Get<IPlatformServices>(), triggers, NullLogger<RadialController>.Instance);
+ var folder = Directory.CreateTempSubdirectory("filee-flip-");
+ try
+ {
+ var file = Path.Combine(folder.FullName, "photo.jpg");
+ File.WriteAllBytes(file, [0xFF, 0xD8, 0xFF]);
+
+ radial.ShowForDrag(400, 400);
+ var window = radial.Window!;
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab); // before files: nothing to flip, not even watched
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab);
+ Assert.False(TriggerServiceLifecycleTests.Settle(() => triggers.WatchFlipKey));
+
+ var data = new DataTransfer();
+ var item = window.StorageProvider.TryGetFileFromPathAsync(file).GetAwaiter().GetResult();
+ Assert.NotNull(item);
+ data.Add(DataTransferItem.CreateFile(item));
+ var at = new Point(window.Bounds.Width / 2 + 60, window.Bounds.Height / 2);
+ window.DragDrop(at, RawDragEventType.DragEnter, data, DragDropEffects.Copy, RawInputModifiers.Control);
+ Dispatcher.UIThread.RunJobs();
+ Assert.Equal(new[] { file }, vm.Files);
+ Assert.False(vm.IsBackFace);
+ Assert.True(triggers.WatchFlipKey);
+
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab, EventMask.LeftCtrl);
+ Assert.True(TriggerServiceLifecycleTests.Settle(() => vm.IsBackFace));
+ Assert.Equal(ImageBack, vm.Items.Select(i => i.Id));
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab, EventMask.LeftCtrl);
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab, EventMask.LeftCtrl);
+ Assert.False(TriggerServiceLifecycleTests.Settle(() => vm.IsBackFace));
+
+ // The drag moved on: Tab is the user's again.
+ radial.Close(animate: false);
+ Assert.False(triggers.WatchFlipKey);
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab);
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab);
+ Assert.False(TriggerServiceLifecycleTests.Settle(() => vm.IsBackFace));
+ window.Close();
+ }
+ finally
+ {
+ folder.Delete(recursive: true);
+ }
+ });
+
+ /// <summary>The image donut's back face, light and dark, and the ring halfway through its turn.</summary>
+ [AvaloniaTheory]
+ [InlineData("en", false)]
+ [InlineData("ko", false)]
+ [InlineData("ko", true)]
+ [InlineData("zh-CN", false)]
+ public void The_back_face_renders(string language, bool dark) => With(animations: true, back: null, () =>
+ {
+ var theme = AppHost.Get<ThemeService>();
+ try
+ {
+ if (dark)
+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark, CornerRadius = 16 }, language);
+ var (vm, window, donut) = OpenClickMode(@"C:\photos\a.jpg", @"C:\photos\b.jpg", @"C:\photos\c.jpg");
+ var suffix = $"{language}{(dark ? "-dark" : "")}";
+ donut.FinishAnimations();
+ RenderTests.Pump();
+ RenderTests.Save(window, $"donut-front-hint-{suffix}.png");
+
+ // Drawn right here, not by the render loop: that would play the rest of the turn first.
+ donut.HandleKey(Key.Tab);
+ donut.Advance(DonutMenu.FlipDuration * 0.3);
+ Assert.InRange(donut.FlipScale, 0.2, 0.8);
+ var size = new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height);
+ using (var turning = new Avalonia.Media.Imaging.RenderTargetBitmap(size))
+ {
+ turning.Render(window);
+ turning.Save(Path.Combine(TestServices.ScreenshotDirectory, $"donut-flip-midway-{suffix}.png"));
+ }
+
+ donut.FinishAnimations();
+ Assert.True(vm.IsBackFace);
+ donut.SetExternalHighlight(2);
+ RenderTests.Pump();
+ Assert.Equal(1, donut.FlipScale);
+ RenderTests.Save(window, $"donut-back-{suffix}.png");
+ window.Close();
+ }
+ finally
+ {
+ if (dark)
+ theme.Apply(new ThemeSettings(), language);
+ }
+ }, language);
+
+ /// <summary>
+ /// The editor's Front / Back switch: the donut shows and edits the back face, the front stays as it was, and
+ /// "Reset to default" puts the built-in back face back.
+ /// </summary>
+ [AvaloniaTheory]
+ [InlineData("en", false)]
+ [InlineData("ko", false)]
+ [InlineData("ko", true)]
+ [InlineData("zh-CN", false)]
+ public void The_editor_switches_between_the_front_and_the_back(string language, bool dark) => With(animations: false, back: null, () =>
+ {
+ var theme = AppHost.Get<ThemeService>();
+ var snapshot = Store.Profiles.Select(p => p.Clone()).ToList();
+ Avalonia.Controls.Window? window = null;
+ try
+ {
+ if (dark)
+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);
+ var main = new MainWindowViewModel(AppHost.Services, AppHost.Get<ILocalizer>(), AppHost.Get<UpdateService>());
+ main.Navigate("toolbar");
+ window = new MainWindow { DataContext = main, Width = 1080, Height = 1000 };
+ window.Show();
+ var page = (ToolbarPageViewModel)main.CurrentPage!;
+ page.SelectedProfile = page.Profiles.Single(p => p.Profile.Id == "images");
+ RenderTests.Pump();
+ var front = Images.PresetIds.ToList();
+ var switcher = window.GetVisualDescendants().OfType<Avalonia.Controls.Border>().Single(b => b.Name == "FaceSwitch");
+ var faces = switcher.GetVisualDescendants().OfType<Avalonia.Controls.RadioButton>().ToList();
+ Assert.Equal(2, faces.Count);
+ Assert.True(faces[0].IsChecked);
+ Assert.Equal(front, page.DonutItems.Select(i => i.Id));
+
+ // The switch shows the back face, and every edit goes there.
+ faces[1].IsChecked = true;
+ RenderTests.Pump();
+ Assert.True(page.EditingBack);
+ Assert.False(faces[0].IsChecked);
+ Assert.Equal(ImageBack, page.DonutItems.Select(i => i.Id));
+ Assert.Equal(ImageBack.Count, page.BackCount);
+ Assert.DoesNotContain(page.Palette, chip => ImageBack.Contains(chip.PresetId));
+ Assert.Contains(page.Palette, chip => chip.PresetId == "to-png"); // on the front, still free for the back
+ Assert.Contains(AppHost.Get<ILocalizer>()["toolbar.face_back"], page.CenterSubtitle);
+ RenderTests.Save(window, $"toolbar-back-face-{language}{(dark ? "-dark" : "")}.png");
+
+ var back = ImageBack;
+ Assert.True(page.Insert("to-psd", 0));
+ page.Move(0, 2);
+ page.RemoveAt(page.SliceCount - 1);
+ List<string> edited = [.. back[..2], "to-psd", .. back[2..^1]];
+ Assert.Equal(edited, Images.BackPresetIds);
+ Assert.Equal(front, Images.PresetIds); // the front as it was
+ Assert.Equal(edited, page.DonutItems.Select(i => i.Id));
+
+ page.Reset(page.SelectedProfile!);
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "images").BackPresetIds, Images.BackPresetIds);
+ Assert.Equal(Images.BackPresetIds, page.DonutItems.Select(i => i.Id)); // still on the back
+
+ faces[0].IsChecked = true;
+ RenderTests.Pump();
+ Assert.False(page.EditingBack);
+ Assert.Equal(front, page.DonutItems.Select(i => i.Id));
+ }
+ finally
+ {
+ window?.Close();
+ if (dark)
+ theme.Apply(new ThemeSettings(), language);
+ Store.Profiles.Clear();
+ Store.Profiles.AddRange(snapshot);
+ Store.SaveLibrary();
+ }
+ }, language);
+}
diff --git a/tests/Filee.App.Tests/DonutLabelPlacementTests.cs b/tests/Filee.App.Tests/DonutLabelPlacementTests.cs
index 5933004c..27b44c8e 100644
--- a/tests/Filee.App.Tests/DonutLabelPlacementTests.cs
+++ b/tests/Filee.App.Tests/DonutLabelPlacementTests.cs
@@ -84,6 +84,25 @@ public class DonutLabelPlacementTests
return (sx / n, sy / n);
}
+ /// <summary>
+ /// A word wider than its slice ("Grayscale" on a thin one) is drawn smaller rather than broken in the middle, and a
+ /// Korean word stays on one line. Chinese, which breaks between any two characters, keeps its size.
+ /// </summary>
+ [AvaloniaFact]
+ public void A_word_wider_than_its_slice_gets_smaller_instead_of_breaking()
+ {
+ TestServices.EnsureInitialized("en");
+ var donut = new DonutMenu();
+ var typeface = new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold);
+
+ Assert.Equal(13, donut.LabelSize("Half size", typeface, 60));
+ Assert.InRange(donut.LabelSize("Grayscale", typeface, 40), 10, 12.9);
+ Assert.Equal(10, donut.LabelSize("Supercalifragilistic", typeface, 30)); // no smaller than 10
+ Assert.Equal(13, donut.LabelSize("去除背景去除背景", typeface, 40));
+ Assert.Equal("ZIP 하\u2060나\u2060로", DonutMenu.KeepKoreanWords("ZIP 하나로"));
+ Assert.Equal("Merge PDF", DonutMenu.KeepKoreanWords("Merge PDF"));
+ }
+
private static (byte[] Pixels, int Width, int Height) Read(Avalonia.Media.Imaging.WriteableBitmap bitmap)
{
using var buffer = bitmap.Lock();
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 0302a374..325eeae5 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1539,7 +1539,7 @@ public class RenderTests
notice.Close();
}
- private static void Pump()
+ internal static void Pump()
{
// Let layout, bindings and a few animation frames run.
for (var i = 0; i < 40; i++)
@@ -1549,7 +1549,7 @@ public class RenderTests
}
}
- private static void Save(TopLevel window, string name)
+ internal static void Save(TopLevel window, string name)
{
// Disposed at the end, so the frame stays alive while Skia encodes it: a collection in between (the idle memory
// trim runs one on another thread) would otherwise finalize its image under the encoder.
diff --git a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
index 4f6bdad9..212e064f 100644
--- a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
+++ b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
@@ -1,5 +1,6 @@
-// Verifies that retrying gestures waits for the previous native hook to release its shared callback, and that
-// Wayland's relative mouse motion still starts a drag gesture.
+// Verifies that retrying gestures waits for the previous native hook to release its shared callback, that
+// Wayland's relative mouse motion still starts a drag gesture, and that Tab is reported (to flip the drag donut) only
+// while asked for.
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
@@ -132,6 +133,49 @@ public sealed class TriggerServiceLifecycleTests
Assert.Equal((60, 60), service.LastCursor);
}
+ [AvaloniaFact]
+ public void Tab_is_reported_only_while_watched_and_once_per_press()
+ {
+ var provider = new DelayedProvider();
+ provider.AllowExit.Set();
+ using var service = Create(provider, () => { });
+ var flips = 0;
+ service.FlipKeyPressed += (_, _) => flips++;
+ service.Start();
+ Assert.True(SpinWait.SpinUntil(() => provider.Runs == 1, 2000));
+
+ // The donut is closed: Tab is none of Filee's business.
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab);
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab);
+ Assert.Equal(0, Settle(() => flips));
+
+ service.WatchFlipKey = true;
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab, EventMask.LeftCtrl); // the drag's modifier still held
+ Assert.Equal(1, Settle(() => flips));
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab); // the key repeating while held: no second flip
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcA);
+ Assert.Equal(1, Settle(() => flips));
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab);
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab);
+ Assert.Equal(2, Settle(() => flips));
+
+ service.WatchFlipKey = false;
+ provider.PostKey(EventType.KeyReleased, KeyCode.VcTab);
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcTab);
+ Assert.Equal(2, Settle(() => flips));
+ }
+
+ /// <summary>Runs the work the hook posted to the UI thread for a moment, then reads the value.</summary>
+ internal static T Settle<T>(Func<T> read)
+ {
+ for (var i = 0; i < 20; i++)
+ {
+ Thread.Sleep(10);
+ Dispatcher.UIThread.RunJobs();
+ }
+ return read();
+ }
+
private static (DelayedProvider Provider, TriggerService Service, Func<GestureEventArgs?> Started) StartGesture(bool wayland)
{
var provider = new DelayedProvider();
@@ -152,7 +196,7 @@ public sealed class TriggerServiceLifecycleTests
return started()!;
}
- private static TriggerService Create(DelayedProvider provider, Action key, bool wayland = false) =>
+ internal static TriggerService Create(DelayedProvider provider, Action key, bool wayland = false) =>
new(new NullPlatformServicesForHooks { PressCarriesPosition = !wayland }, NullLogger<TriggerService>.Instance, () =>
{
var hook = new EventLoopGlobalHook(provider, useBackgroundThreadForEventLoop: true);
@@ -161,7 +205,7 @@ public sealed class TriggerServiceLifecycleTests
});
// Models libuiohook's process-wide callback and asynchronous native shutdown. No OS input is hooked.
- private sealed class DelayedProvider : IGlobalHookProvider
+ internal sealed class DelayedProvider : IGlobalHookProvider
{
private readonly object _gate = new();
private DispatchProc? _callback;
@@ -208,6 +252,15 @@ public sealed class TriggerServiceLifecycleTests
}
}
+ public void PostKey(EventType type, KeyCode code, EventMask mask = EventMask.None)
+ {
+ lock (_gate)
+ {
+ var e = new UioHookEvent { Type = type, Mask = mask, Keyboard = new KeyboardEventData { KeyCode = code } };
+ _callback?.Invoke(ref e, _data);
+ }
+ }
+
public void PressKey()
{
lock (_gate)
@@ -218,7 +271,7 @@ public sealed class TriggerServiceLifecycleTests
}
}
- private sealed class NullPlatformServicesForHooks : IPlatformServices
+ internal sealed class NullPlatformServicesForHooks : IPlatformServices
{
public bool PressCarriesPosition { get; init; } = true;
public bool IsFileManagerAt(int x, int y) => true;