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.

Read file paths other macOS file managers send, keep the donut up after a later launch

KnifeLemona52c3a6dd361
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 843fcc0f..c4dac75b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -86,6 +86,14 @@ Bump `AppSettings.CurrentSchemaVersion` and add a step to `SettingsMigrations` w
Everything OS-specific goes through `IPlatformServices` (`Filee.Core/Platform`). Windows lives in
`Filee.Platform.Windows`; macOS will get its own project. Global input uses SharpHook on both.
+On macOS, files reach Filee from file managers other than Finder too (issue #160). The "Convert with Filee" service
+(`MacOSServicesProvider`) and the donut's drags (`DraggedFiles`) read file URLs first, then the older
+`NSFilenamesPboardType` array of paths (`PasteboardPaths`); the service also takes plain-text lines that are absolute
+paths. The donut registers those types with AppKit next to Avalonia's own, so such a drag reaches it, and a drag or
+service request without readable files is logged with the types it offered. File promises (`NSFilePromiseProvider`)
+can't be received through Avalonia. A click-mode donut opened for a later launch or the service forgives one loss of
+focus within a second of opening (`ActivationGrace`): Filee becoming the active app can take focus away from it.
+
## Explorer integration
Settings → General → "Show “Convert with Filee” in the Explorer context menu" (`AppSettings.ContextMenuEnabled`) is
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.cs
index ba48ba9c..e7c8ef68 100644
--- a/src/Filee.App/App.axaml.cs
+++ b/src/Filee.App/App.axaml.cs
@@ -47,12 +47,15 @@ public partial class App : Application
private void Start(IClassicDesktopStyleApplicationLifetime desktop)
{
+ var log = AppHost.Get<ILogger<App>>();
// macOS: "Convert with Filee" in Finder's right-click menu. Registered first, so a service picked while
- // Filee wasn't running is delivered as soon as it starts.
+ // Filee wasn't running is delivered as soon as it starts. A request without files Filee can find (another
+ // file manager put its selection on the pasteboard in a form Filee doesn't read) is logged with what it held.
if (OperatingSystem.IsMacOS())
- Filee.Platform.MacOS.MacOSServicesProvider.Register(files =>
- Dispatcher.UIThread.Post(() => HandleCommandLine(CommandLine.Parse(["--convert", .. files]))));
- var log = AppHost.Get<ILogger<App>>();
+ Filee.Platform.MacOS.MacOSServicesProvider.Register(
+ files => Dispatcher.UIThread.Post(() => HandleCommandLine(CommandLine.Parse(["--convert", .. files]))),
+ types => log.LogWarning("Convert with Filee was picked, but the request named no existing file; it held: {Types}",
+ types.Count == 0 ? "nothing" : string.Join(", ", types)));
// Exceptions in UI event handlers end Filee; write them down first (they are not marked handled).
Dispatcher.UIThread.UnhandledException += (_, e) =>
log.LogCritical(e.Exception, "Unhandled exception on the UI thread");
@@ -303,7 +306,7 @@ public partial class App : Application
var (x, y) = AppHost.Get<TriggerService>().LastCursor;
if (x == 0 && y == 0 && AppHost.Get<WindowService>().Main is { } main)
(x, y) = (main.Position.X + 200, main.Position.Y + 200);
- AppHost.Get<RadialController>().ShowForFiles(x, y, files);
+ AppHost.Get<RadialController>().ShowForFiles(x, y, files, forAnotherProcess: true);
}
}
diff --git a/src/Filee.App/Services/ActivationGrace.cs b/src/Filee.App/Services/ActivationGrace.cs
new file mode 100644
index 00000000..f8253582
--- /dev/null
+++ b/src/Filee.App/Services/ActivationGrace.cs
@@ -0,0 +1,34 @@
+// macOS: a click-mode donut opened for another process (a later launch handing over files, the Services menu) can
+// lose focus right after it opens, before the user did anything: Filee becomes the active app while the donut shows,
+// and AppKit may make another of its windows key on the way (issue #160: `open -n -a Filee.app --args --convert`
+// logged the files but no donut stayed up). The click-mode donut closes when it loses focus, so it closed at once.
+// The first focus loss within a moment of opening is forgiven instead.
+
+namespace Filee.App.Services;
+
+internal sealed class ActivationGrace(TimeSpan length, Func<DateTime> now)
+{
+ /// <summary>Long enough for an activation to settle; short enough that a quick click elsewhere still closes.</summary>
+ public static readonly TimeSpan Default = TimeSpan.FromSeconds(1);
+
+ private DateTime? _openedAt;
+
+ public ActivationGrace() : this(Default, () => DateTime.UtcNow) { }
+
+ /// <summary>The donut just opened for another process: forgive the next focus loss within the grace.</summary>
+ public void Start() => _openedAt = now();
+
+ /// <summary>The donut opened for something else, or closed: focus losses close it again.</summary>
+ public void Cancel() => _openedAt = null;
+
+ /// <summary>
+ /// The donut lost focus: true when that is forgiven (once, and only within the grace after <see cref="Start"/>).
+ /// </summary>
+ public bool Forgives()
+ {
+ if (_openedAt is not { } openedAt)
+ return false;
+ _openedAt = null;
+ return now() - openedAt <= length;
+ }
+}
diff --git a/src/Filee.App/Services/DraggedFiles.cs b/src/Filee.App/Services/DraggedFiles.cs
new file mode 100644
index 00000000..0a9b47c3
--- /dev/null
+++ b/src/Filee.App/Services/DraggedFiles.cs
@@ -0,0 +1,45 @@
+// The local files in a drag. Avalonia reads file URLs (what Explorer, Finder and Linux file managers offer); on macOS
+// some other file managers offer the older NSFilenamesPboardType array of paths instead (QSpace Pro, issue #160),
+// which Avalonia passes through as a platform format of its own.
+
+using Avalonia.Input;
+using Avalonia.Platform.Storage;
+using Filee.Core.Platform;
+using Filee.Platform.MacOS;
+
+namespace Filee.App.Services;
+
+internal static class DraggedFiles
+{
+ /// <summary>Whether the drag offers files in a form Filee reads (they may still turn out to be folders).</summary>
+ public static bool Offered(IDataTransfer data) =>
+ data.Contains(DataFormat.File) || data.Items.Any(item => item.Formats.Any(IsFilenames));
+
+ /// <summary>Local file paths in the drag (folders and virtual items are ignored).</summary>
+ public static IReadOnlyList<string> Local(IDataTransfer data) => Local(data, File.Exists);
+
+ internal static IReadOnlyList<string> Local(IDataTransfer data, Func<string, bool> fileExists)
+ {
+ var files = (data.TryGetFiles() ?? [])
+ .Select(item => item.TryGetLocalPath())
+ .OfType<string>()
+ .Where(fileExists)
+ .ToList();
+ return files.Count > 0 ? files : Filenames(data).Where(fileExists).Distinct(FileSystemPaths.Comparer).ToList();
+ }
+
+ /// <summary>The formats a drag offers, for the log when Filee finds no files in it.</summary>
+ public static string Describe(IDataTransfer data) =>
+ data.Formats.Count == 0 ? "nothing" : string.Join(", ", data.Formats.Select(format => format.Identifier).Distinct());
+
+ private static IEnumerable<string> Filenames(IDataTransfer data) =>
+ data.Items.SelectMany(item => item.Formats.Where(IsFilenames).SelectMany(format => item.TryGetRaw(format) switch
+ {
+ byte[] bytes => PasteboardPaths.FromPropertyList(bytes),
+ string text => PasteboardPaths.FromPropertyList(text),
+ _ => [],
+ }));
+
+ private static bool IsFilenames(DataFormat format) =>
+ format.Kind == DataFormatKind.Platform && PasteboardPaths.IsFilenamesType(format.Identifier);
+}
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index 3456df0a..1344eb2e 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -48,6 +48,8 @@ public sealed class RadialController(
private IDisposable? _handOffTimer;
private int _dragGeneration;
private bool _dragReachedDonut;
+ private bool _fileDragsAccepted;
+ private readonly ActivationGrace _grace = new();
/// <summary>A gesture over something that isn't a file drag (a rubber-band selection) is common: a line now and then.</summary>
private static readonly LogThrottle Throttle = new(TimeSpan.FromMinutes(1));
@@ -72,6 +74,7 @@ public sealed class RadialController(
public void ShowForDrag(int x, int y)
{
ReleaseProgressToToast();
+ _grace.Cancel();
var window = EnsureWindow();
// A ring from an earlier conversion (finished or handed to the toast) must not keep this gesture's window up.
window.DonutControl.LeaveProgressMode();
@@ -90,12 +93,19 @@ public sealed class RadialController(
}, EmptyDragLimit);
}
- /// <summary>Opens the donut for known files (click mode).</summary>
- public void ShowForFiles(int x, int y, IReadOnlyList<string> files)
+ /// <summary>
+ /// Opens the donut for known files (click mode). <paramref name="forAnotherProcess"/>: the files came from a later
+ /// launch or the Services menu, so on macOS the donut may lose focus once while Filee becomes the active app.
+ /// </summary>
+ public void ShowForFiles(int x, int y, IReadOnlyList<string> files, bool forAnotherProcess = false)
{
if (files.Count == 0)
return;
ReleaseProgressToToast();
+ if (forAnotherProcess && OperatingSystem.IsMacOS())
+ _grace.Start();
+ else
+ _grace.Cancel();
var window = EnsureWindow();
_dropped = false;
_converted = false;
@@ -149,6 +159,7 @@ public sealed class RadialController(
_window.DonutControl.LeaveProgressMode();
}
_visible = false;
+ _grace.Cancel();
var window = _window;
// A group about to open (its dwell timer running) must not open on a closing donut.
window.DonutControl.CollapseGroup();
@@ -187,6 +198,13 @@ public sealed class RadialController(
var donut = window.DonutControl;
window.DragEntered += () => _dragReachedDonut = true;
+ // Tells "the drag reached the donut but brought no files" apart, with what it brought (file promises, say).
+ window.DragWithoutFiles += formats =>
+ {
+ if (Throttle.TryEnter("drag-without-files", out var held))
+ log.LogInformation("A drag without files Filee reads entered the donut; it offered: {Formats}{Held}",
+ formats, LogThrottle.HeldText(held));
+ };
window.FilesEntered += files =>
{
if (viewModel.IsClickMode || SameFiles(files, viewModel.Files))
@@ -210,8 +228,19 @@ public sealed class RadialController(
window.EscapePressed += () => Close();
window.Deactivated += (_, _) =>
{
- if (viewModel.IsClickMode && !_editing)
- Close();
+ if (!viewModel.IsClickMode || _editing)
+ return;
+ if (_grace.Forgives())
+ {
+ log.LogInformation("The donut lost focus as it opened for another app's request; it stays open");
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (_visible && viewModel.IsClickMode && !window.IsActive)
+ window.Activate();
+ });
+ return;
+ }
+ Close();
};
donut.ActiveIndexChanged += (_, index) => viewModel.ShowHint(index, donut.ActiveSubIndex, donut.IsCenterHot);
@@ -381,7 +410,14 @@ public sealed class RadialController(
// below normal windows while it keeps the mark (after the Photos app opened, for one). Then Explorer stays on
// top of the donut and the drop never reaches it, so put it back on top every time.
if (window.TryGetPlatformHandle()?.Handle is { } handle)
+ {
platform.RaiseTopmost(handle);
+ if (!_fileDragsAccepted && OperatingSystem.IsMacOS() && platform is Filee.Platform.MacOS.MacOSPlatformServices mac)
+ {
+ mac.AcceptFileDrags(handle);
+ _fileDragsAccepted = true;
+ }
+ }
_visible = true;
if (activate)
window.Activate();
diff --git a/src/Filee.App/Views/Pages/HomePage.axaml.cs b/src/Filee.App/Views/Pages/HomePage.axaml.cs
index 6ef86397..2d233609 100644
--- a/src/Filee.App/Views/Pages/HomePage.axaml.cs
+++ b/src/Filee.App/Views/Pages/HomePage.axaml.cs
@@ -3,7 +3,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
-using Avalonia.Platform.Storage;
using Filee.App.Services;
using Microsoft.Extensions.Logging;
@@ -23,13 +22,13 @@ public partial class HomePage : UserControl
DragDrop.AddDragEnterHandler(DropZone, (_, e) =>
{
DropZone.Classes.Add("over");
- var files = e.DataTransfer.Contains(DataFormat.File);
+ var files = DraggedFiles.Offered(e.DataTransfer);
e.DragEffects = files ? DragDropEffects.Copy : DragDropEffects.None;
if (Interlocked.Exchange(ref _dragEnterLogged, 1) == 0)
AppHost.Get<ILogger<HomePage>>().LogInformation("First drag over the drop zone (files: {Files})", files);
});
DragDrop.AddDragOverHandler(DropZone, (_, e) =>
- e.DragEffects = e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None);
+ e.DragEffects = DraggedFiles.Offered(e.DataTransfer) ? DragDropEffects.Copy : DragDropEffects.None);
DragDrop.AddDragLeaveHandler(DropZone, (_, _) => DropZone.Classes.Remove("over"));
DragDrop.AddDropHandler(DropZone, OnDrop);
}
@@ -37,11 +36,7 @@ public partial class HomePage : UserControl
private void OnDrop(object? sender, DragEventArgs e)
{
DropZone.Classes.Remove("over");
- var files = (e.DataTransfer.TryGetFiles() ?? [])
- .Select(f => f.TryGetLocalPath())
- .OfType<string>()
- .Where(File.Exists)
- .ToList();
+ var files = DraggedFiles.Local(e.DataTransfer);
if (files.Count == 0)
return;
diff --git a/src/Filee.App/Views/RadialWindow.axaml.cs b/src/Filee.App/Views/RadialWindow.axaml.cs
index 0cfaab79..45da984c 100644
--- a/src/Filee.App/Views/RadialWindow.axaml.cs
+++ b/src/Filee.App/Views/RadialWindow.axaml.cs
@@ -3,7 +3,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
-using Avalonia.Platform.Storage;
using Filee.App.Controls;
using Filee.App.Services;
@@ -30,6 +29,9 @@ public partial class RadialWindow : Window
/// <summary>Files entered the window during a drag.</summary>
public event Action<IReadOnlyList<string>>? FilesEntered;
+ /// <summary>A drag without files Filee reads entered the window: the formats it offered (for the log).</summary>
+ public event Action<string>? DragWithoutFiles;
+
/// <summary>A drop landed on the donut: (hit, files).</summary>
public event Action<DonutHit, IReadOnlyList<string>>? Dropped;
@@ -42,15 +44,18 @@ public partial class RadialWindow : Window
public event Action<int, DonutHit, double>? DragSummary;
private int _dragOverEvents;
+ private bool _dragOffersFiles;
private DonutHit _lastDragHit;
private Point? _lastDragAt;
private void OnDragEnter(object? sender, DragEventArgs e)
{
DragEntered?.Invoke();
- var files = LocalFiles(e);
+ var files = DraggedFiles.Local(e.DataTransfer);
+ _dragOffersFiles = DraggedFiles.Offered(e.DataTransfer);
if (files.Count == 0)
{
+ DragWithoutFiles?.Invoke(DraggedFiles.Describe(e.DataTransfer));
e.DragEffects = DragDropEffects.None;
return;
}
@@ -67,11 +72,10 @@ public partial class RadialWindow : Window
_dragOverEvents++;
_lastDragHit = hit;
_lastDragAt = at;
- var files = e.DataTransfer.Contains(DataFormat.File);
Donut.SetExternalHit(hit, at);
// Always COPY. Reporting MOVE would make Explorer delete the source files after the drop.
- e.DragEffects = files && Donut.Converts(hit) ? DragDropEffects.Copy : DragDropEffects.None;
+ e.DragEffects = _dragOffersFiles && Donut.Converts(hit) ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
@@ -89,7 +93,7 @@ public partial class RadialWindow : Window
Donut.CollapseGroup();
Donut.SetExternalHighlight(-1);
e.DragEffects = Donut.Converts(hit) ? DragDropEffects.Copy : DragDropEffects.None;
- Dropped?.Invoke(hit, LocalFiles(e));
+ Dropped?.Invoke(hit, DraggedFiles.Local(e.DataTransfer));
e.Handled = true;
}
@@ -117,12 +121,4 @@ public partial class RadialWindow : Window
if (change.Property == IsVisibleProperty && !change.GetNewValue<bool>())
Donut.CollapseGroup();
}
-
- /// <summary>Local file paths in the drag data (folders and virtual items are ignored).</summary>
- private static IReadOnlyList<string> LocalFiles(DragEventArgs e) =>
- (e.DataTransfer.TryGetFiles() ?? [])
- .Select(item => item.TryGetLocalPath())
- .OfType<string>()
- .Where(File.Exists)
- .ToList();
}
diff --git a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
index 894ea02f..f0565d7b 100644
--- a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
+++ b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
@@ -110,6 +110,16 @@ public sealed class MacOSPlatformServices : IPlatformServices
NativeMethods.RaiseTopmost(windowHandle);
}
+ /// <summary>
+ /// Lets drags that offer file paths or file promises in older forms reach the window (the donut), not just ones
+ /// offering file URLs: other file managers than Finder write those (issue #160).
+ /// </summary>
+ public void AcceptFileDrags(nint windowHandle)
+ {
+ if (windowHandle != 0)
+ NativeMethods.AddDraggedTypes(windowHandle, PasteboardPaths.DragTypes);
+ }
+
internal static IReadOnlyList<string> ParseSelection(string json) =>
JsonSerializer.Deserialize<string[]>(json) ?? [];
diff --git a/src/Filee.Platform.MacOS/MacOSServicesProvider.cs b/src/Filee.Platform.MacOS/MacOSServicesProvider.cs
index aacba77e..495a1073 100644
--- a/src/Filee.Platform.MacOS/MacOSServicesProvider.cs
+++ b/src/Filee.Platform.MacOS/MacOSServicesProvider.cs
@@ -24,16 +24,19 @@ public static class MacOSServicesProvider
// Kept alive for as long as Objective-C may call it.
private static readonly ServiceMethod Method = ConvertFiles;
private static Action<IReadOnlyList<string>>? _handler;
+ private static Action<IReadOnlyList<string>>? _nothingUsable;
private static nint _provider;
/// <summary>
/// Answers the service from now on; <paramref name="handler"/> gets the files (on the main thread). Call it on the
- /// main thread early at start: a service picked while Filee wasn't running is delivered once this is set.
+ /// main thread early at start: a service picked while Filee wasn't running is delivered once this is set. When the
+ /// pasteboard names no existing file, <paramref name="nothingUsable"/> gets the types it offered instead.
/// </summary>
[SupportedOSPlatform("macos")]
- public static void Register(Action<IReadOnlyList<string>> handler)
+ public static void Register(Action<IReadOnlyList<string>> handler, Action<IReadOnlyList<string>>? nothingUsable = null)
{
_handler = handler;
+ _nothingUsable = nothingUsable;
if (_provider != 0)
return;
NativeLibrary.Load(AppKit);
@@ -57,6 +60,8 @@ public static class MacOSServicesProvider
var files = FilesOn(pasteboard);
if (files.Count > 0)
_handler?.Invoke(files);
+ else
+ _nothingUsable?.Invoke(Strings(Send(pasteboard, sel_registerName("types"))));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -64,8 +69,20 @@ public static class MacOSServicesProvider
}
}
- /// <summary>The file paths on a pasteboard (Finder puts file URLs there).</summary>
- private static List<string> FilesOn(nint pasteboard)
+ /// <summary>
+ /// The existing files and folders on a pasteboard. Finder puts file URLs there; other file managers (QSpace Pro,
+ /// issue #160) may put the older NSFilenamesPboardType array of paths, or only text: the first of these that names any.
+ /// </summary>
+ private static IReadOnlyList<string> FilesOn(nint pasteboard) => PasteboardPaths.FirstExisting(
+ [
+ () => FileUrls(pasteboard),
+ () => Strings(Send(pasteboard, sel_registerName("propertyListForType:"), NSString(PasteboardPaths.FilenamesType))),
+ () => ItemStrings(pasteboard, PasteboardPaths.FileUrlType).Select(PasteboardPaths.FromFileUrl).OfType<string>(),
+ () => ItemStrings(pasteboard, PasteboardPaths.TextType).SelectMany(PasteboardPaths.FromText),
+ ], PasteboardPaths.Exists);
+
+ /// <summary>File URLs read as NSURL objects (AppKit resolves file reference URLs).</summary>
+ private static List<string> FileUrls(nint pasteboard)
{
var files = new List<string>();
var classes = Send(objc_getClass("NSArray"), sel_registerName("arrayWithObject:"), objc_getClass("NSURL"));
@@ -85,6 +102,58 @@ public static class MacOSServicesProvider
return files;
}
+ /// <summary>The value of <paramref name="type"/> as text on each pasteboard item that has it.</summary>
+ private static List<string> ItemStrings(nint pasteboard, string type)
+ {
+ var values = new List<string>();
+ var items = Send(pasteboard, sel_registerName("pasteboardItems"));
+ if (items == 0)
+ return values;
+ var name = NSString(type);
+ var count = Send(items, sel_registerName("count"));
+ for (nint index = 0; index < count; index++)
+ {
+ var item = Send(items, sel_registerName("objectAtIndex:"), index);
+ if (Utf8(Send(item, sel_registerName("stringForType:"), name)) is { Length: > 0 } value)
+ values.Add(value);
+ }
+ return values;
+ }
+
+ /// <summary>The strings in an NSArray (anything else in it is skipped); none for nil or any other object.</summary>
+ private static List<string> Strings(nint array)
+ {
+ var values = new List<string>();
+ if (array == 0 || !SendBool(array, sel_registerName("isKindOfClass:"), objc_getClass("NSArray")))
+ return values;
+ var stringClass = objc_getClass("NSString");
+ var count = Send(array, sel_registerName("count"));
+ for (nint index = 0; index < count; index++)
+ {
+ var value = Send(array, sel_registerName("objectAtIndex:"), index);
+ if (SendBool(value, sel_registerName("isKindOfClass:"), stringClass) && Utf8(value) is { } text)
+ values.Add(text);
+ }
+ return values;
+ }
+
+ /// <summary>An autoreleased NSString (the service method runs inside AppKit's autorelease pool).</summary>
+ private static nint NSString(string value)
+ {
+ var utf8 = Marshal.StringToCoTaskMemUTF8(value);
+ try
+ {
+ return Send(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), utf8);
+ }
+ finally
+ {
+ Marshal.FreeCoTaskMem(utf8);
+ }
+ }
+
+ private static string? Utf8(nint text) =>
+ text == 0 ? null : Marshal.PtrToStringUTF8(Send(text, sel_registerName("UTF8String")));
+
[DllImport(ObjC)]
private static extern nint objc_getClass([MarshalAs(UnmanagedType.LPUTF8Str)] string name);
@@ -117,6 +186,10 @@ public static class MacOSServicesProvider
[return: MarshalAs(UnmanagedType.I1)]
private static extern bool SendBool(nint receiver, nint selector);
+ [DllImport(ObjC, EntryPoint = "objc_msgSend")]
+ [return: MarshalAs(UnmanagedType.I1)]
+ private static extern bool SendBool(nint receiver, nint selector, nint argument);
+
[DllImport(AppKit)]
private static extern void NSUpdateDynamicServices();
}
diff --git a/src/Filee.Platform.MacOS/NativeMethods.cs b/src/Filee.Platform.MacOS/NativeMethods.cs
index 79ce6885..6d423711 100644
--- a/src/Filee.Platform.MacOS/NativeMethods.cs
+++ b/src/Filee.Platform.MacOS/NativeMethods.cs
@@ -132,6 +132,41 @@ internal static class NativeMethods
SendVoid(window, sel_registerName("orderFrontRegardless"));
}
+ /// <summary>
+ /// Adds <paramref name="types"/> to the drag types of every view in <paramref name="window"/> that already takes
+ /// drags (Avalonia's view, registered for public.data only). AppKit sends a drag to a view only when it offers one
+ /// of the view's types, and some apps' file drags may not conform to public.data.
+ /// </summary>
+ internal static void AddDraggedTypes(nint window, IReadOnlyList<string> types)
+ {
+ using var pool = new AutoreleasePool();
+ AddDraggedTypesTo(Send(window, sel_registerName("contentView")), types);
+ }
+
+ private static void AddDraggedTypesTo(nint view, IReadOnlyList<string> types)
+ {
+ if (view == 0)
+ return;
+ var registered = Send(view, sel_registerName("registeredDraggedTypes"));
+ if (registered != 0 && Send(registered, sel_registerName("count")) > 0)
+ {
+ // The whole list: AppKit doesn't document whether registering adds to the view's types or replaces them.
+ var all = Send(objc_getClass("NSMutableArray"), sel_registerName("arrayWithArray:"), registered);
+ foreach (var type in types)
+ {
+ var name = CFStringCreateWithCString(0, type, 0x08000100);
+ if (!SendBool(all, sel_registerName("containsObject:"), name))
+ SendVoid(all, sel_registerName("addObject:"), name);
+ CFRelease(name);
+ }
+ SendVoid(view, sel_registerName("registerForDraggedTypes:"), all);
+ }
+ var subviews = Send(view, sel_registerName("subviews"));
+ var count = subviews == 0 ? 0 : Send(subviews, sel_registerName("count"));
+ for (nint index = 0; index < count; index++)
+ AddDraggedTypesTo(Send(subviews, sel_registerName("objectAtIndex:"), index), types);
+ }
+
private readonly struct AutoreleasePool : IDisposable
{
private readonly nint _pool = Send(Send(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")), sel_registerName("init"));
@@ -218,13 +253,23 @@ internal static class NativeMethods
[DllImport(ObjC, EntryPoint = "objc_msgSend")]
private static extern nint Send(nint receiver, nint selector);
+ [DllImport(ObjC, EntryPoint = "objc_msgSend")]
+ private static extern nint Send(nint receiver, nint selector, nint argument);
+
[DllImport(ObjC, EntryPoint = "objc_msgSend")]
[return: MarshalAs(UnmanagedType.I1)]
private static extern bool SendBool(nint receiver, nint selector);
+ [DllImport(ObjC, EntryPoint = "objc_msgSend")]
+ [return: MarshalAs(UnmanagedType.I1)]
+ private static extern bool SendBool(nint receiver, nint selector, nint argument);
+
[DllImport(ObjC, EntryPoint = "objc_msgSend")]
private static extern void SendVoid(nint receiver, nint selector);
+ [DllImport(ObjC, EntryPoint = "objc_msgSend")]
+ private static extern void SendVoid(nint receiver, nint selector, nint argument);
+
[DllImport(ObjC, EntryPoint = "objc_msgSend")]
private static extern void SendInteger(nint receiver, nint selector, nint value);
}
diff --git a/src/Filee.Platform.MacOS/PasteboardPaths.cs b/src/Filee.Platform.MacOS/PasteboardPaths.cs
new file mode 100644
index 00000000..f745c55d
--- /dev/null
+++ b/src/Filee.Platform.MacOS/PasteboardPaths.cs
@@ -0,0 +1,110 @@
+// File paths in the forms other Mac apps put them on a pasteboard. Finder writes one file URL per item
+// (public.file-url); other file managers (QSpace Pro, issue #160) write the older NSFilenamesPboardType, a property
+// list array of paths, and some only plain text. Pure parsing here, so it can be tested anywhere; the pasteboard
+// itself is read by MacOSServicesProvider (the Services menu) and RadialWindow (drags, through Avalonia).
+
+using System.Text;
+using System.Xml;
+using System.Xml.Linq;
+using Filee.Core.Platform;
+
+namespace Filee.Platform.MacOS;
+
+public static class PasteboardPaths
+{
+ /// <summary>The pasteboard type of an array of paths, as older apps write it.</summary>
+ public const string FilenamesType = "NSFilenamesPboardType";
+
+ /// <summary>
+ /// The same type as a pasteboard item lists it: AppKit gives types that aren't UTIs a dynamic UTI.
+ /// </summary>
+ public const string FilenamesUti = "dyn.ah62d4rv4gu8y6y4grf0gn5xbrzw1gydcr7u1e3cytf2gn";
+
+ public const string FileUrlType = "public.file-url";
+
+ public const string TextType = "public.utf8-plain-text";
+
+ /// <summary>
+ /// Types the donut registers for on top of Avalonia's own, so a drag offering only these still reaches it (and its
+ /// types get logged when Filee can't read them). The last three are file promises, which Filee can't receive.
+ /// </summary>
+ public static IReadOnlyList<string> DragTypes { get; } =
+ [
+ FileUrlType, FilenamesType,
+ "com.apple.NSFilePromiseItemMetaData", "com.apple.pasteboard.promised-file-url", "Apple files promise pasteboard type",
+ ];
+
+ /// <summary>Whether <paramref name="type"/> names NSFilenamesPboardType, by its name or its dynamic UTI.</summary>
+ public static bool IsFilenamesType(string type) => type is FilenamesType or FilenamesUti;
+
+ /// <summary>
+ /// The paths in an NSFilenamesPboardType property list as a pasteboard item's data: AppKit writes property lists to
+ /// the pasteboard as XML.
+ /// </summary>
+ public static IReadOnlyList<string> FromPropertyList(byte[]? data) =>
+ data is null || data.Length == 0 ? [] : FromPropertyList(Encoding.UTF8.GetString(data));
+
+ /// <summary>The paths in an NSFilenamesPboardType property list written as XML.</summary>
+ public static IReadOnlyList<string> FromPropertyList(string? xml)
+ {
+ if (string.IsNullOrWhiteSpace(xml))
+ return [];
+ try
+ {
+ // The plist DOCTYPE names Apple's DTD: never fetched (DtdProcessing.Ignore).
+ using var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = null });
+ var root = XDocument.Load(reader).Root;
+ var array = root?.Name.LocalName == "plist" ? root.Element("array") : root?.Name.LocalName == "array" ? root : null;
+ return array?.Elements("string").Select(e => e.Value).Where(IsAbsolute).ToList() ?? [];
+ }
+ catch (XmlException)
+ {
+ return [];
+ }
+ }
+
+ /// <summary>The path of a file URL ("file:///Users/a/b%20c.png"), or null for anything else.</summary>
+ public static string? FromFileUrl(string? url)
+ {
+ // The scheme is checked first: on Unix, .NET reads a bare "/path" as an absolute file URI as well.
+ url = url?.Trim();
+ if (url is null || !url.StartsWith("file:", StringComparison.OrdinalIgnoreCase)
+ || !Uri.TryCreate(url, UriKind.Absolute, out var uri) || !uri.IsFile || uri.Host is not ("" or "localhost"))
+ return null;
+ var path = Uri.UnescapeDataString(uri.AbsolutePath);
+ // A file reference URL (/.file/id=…) names no path; AppKit resolves those itself.
+ return IsAbsolute(path) && !path.StartsWith("/.file/id=", StringComparison.Ordinal) ? path : null;
+ }
+
+ /// <summary>Lines of plain text that are absolute paths or file URLs; anything else in the text is skipped.</summary>
+ public static IReadOnlyList<string> FromText(string? text)
+ {
+ if (string.IsNullOrEmpty(text))
+ return [];
+ return text.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(line => line.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? FromFileUrl(line) : line)
+ .OfType<string>()
+ .Where(IsAbsolute)
+ .ToList();
+ }
+
+ /// <summary>
+ /// The paths of the first source, in order of preference, that names any path that <paramref name="exists"/>:
+ /// only those, without repeats. Later sources aren't read once one has given paths.
+ /// </summary>
+ public static IReadOnlyList<string> FirstExisting(IEnumerable<Func<IEnumerable<string>>> sources, Func<string, bool> exists)
+ {
+ foreach (var source in sources)
+ {
+ var paths = source().Where(exists).Distinct(FileSystemPaths.Comparer).ToList();
+ if (paths.Count > 0)
+ return paths;
+ }
+ return [];
+ }
+
+ /// <summary>A file or folder at <paramref name="path"/>.</summary>
+ public static bool Exists(string path) => File.Exists(path) || Directory.Exists(path);
+
+ private static bool IsAbsolute(string path) => path.StartsWith('/') && path.Length > 1;
+}
diff --git a/tests/Filee.App.Tests/OtherFileManagerTests.cs b/tests/Filee.App.Tests/OtherFileManagerTests.cs
new file mode 100644
index 00000000..ba70d407
--- /dev/null
+++ b/tests/Filee.App.Tests/OtherFileManagerTests.cs
@@ -0,0 +1,76 @@
+// macOS file managers other than Finder (issue #160): drags offering NSFilenamesPboardType instead of file URLs, and
+// a click-mode donut opened for another process that loses focus once as Filee becomes the active app.
+
+using System.Text;
+using Avalonia.Input;
+using Filee.App.Services;
+using Filee.Platform.MacOS;
+
+namespace Filee.App.Tests;
+
+public class OtherFileManagerTests
+{
+ private const string Plist = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0"><array><string>/Users/a/1.png</string><string>/Users/a/folder</string><string>/Users/a/1.png</string></array></plist>
+ """;
+
+ private static readonly HashSet<string> Files = ["/Users/a/1.png", "/Users/a/2.png"];
+
+ private static DataTransfer Drag(string type, byte[] value)
+ {
+ var data = new DataTransfer();
+ data.Add(DataTransferItem.Create(DataFormat.CreateBytesPlatformFormat(type), value));
+ return data;
+ }
+
+ [Theory]
+ [InlineData(PasteboardPaths.FilenamesType)]
+ [InlineData(PasteboardPaths.FilenamesUti)]
+ public void A_drag_offering_an_array_of_paths_brings_its_files(string type)
+ {
+ using var data = Drag(type, Encoding.UTF8.GetBytes(Plist));
+
+ Assert.True(DraggedFiles.Offered(data));
+ Assert.Equal(["/Users/a/1.png"], DraggedFiles.Local(data, Files.Contains));
+ }
+
+ [Fact]
+ public void A_drag_of_text_or_file_promises_brings_no_files_and_says_what_it_offered()
+ {
+ using var text = new DataTransfer();
+ text.Add(DataTransferItem.CreateText("/Users/a/1.png"));
+ using var promise = Drag("com.apple.NSFilePromiseItemMetaData", [1, 2, 3]);
+
+ Assert.False(DraggedFiles.Offered(text));
+ Assert.Empty(DraggedFiles.Local(text, Files.Contains));
+ Assert.False(DraggedFiles.Offered(promise));
+ Assert.Empty(DraggedFiles.Local(promise, Files.Contains));
+ Assert.Equal("com.apple.NSFilePromiseItemMetaData", DraggedFiles.Describe(promise));
+ using var empty = new DataTransfer();
+ Assert.Equal("nothing", DraggedFiles.Describe(empty));
+ }
+
+ [Fact]
+ public void The_first_focus_loss_soon_after_opening_for_another_process_is_forgiven_once()
+ {
+ var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+ var grace = new ActivationGrace(TimeSpan.FromSeconds(1), () => now);
+
+ Assert.False(grace.Forgives()); // never started: a focus loss closes as before
+
+ grace.Start();
+ now += TimeSpan.FromMilliseconds(300);
+ Assert.True(grace.Forgives());
+ Assert.False(grace.Forgives()); // only once
+
+ grace.Start();
+ now += TimeSpan.FromSeconds(2);
+ Assert.False(grace.Forgives()); // too late: the user clicked elsewhere
+
+ grace.Start();
+ grace.Cancel();
+ Assert.False(grace.Forgives());
+ }
+}
diff --git a/tests/Filee.Platform.Tests/PasteboardPathsTests.cs b/tests/Filee.Platform.Tests/PasteboardPathsTests.cs
new file mode 100644
index 00000000..fcf3db2a
--- /dev/null
+++ b/tests/Filee.Platform.Tests/PasteboardPathsTests.cs
@@ -0,0 +1,100 @@
+// Paths in the forms Mac apps other than Finder put them on a pasteboard (issue #160: QSpace Pro).
+
+using System.Text;
+using Filee.Platform.MacOS;
+
+namespace Filee.Platform.Tests;
+
+public sealed class PasteboardPathsTests
+{
+ private const string Filenames = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <array>
+ <string>/Users/a/사진 1.png</string>
+ <string>/Users/a/R&amp;D/notes.txt</string>
+ <string>relative.txt</string>
+ <string></string>
+ </array>
+ </plist>
+ """;
+
+ [Fact]
+ public void FilenamesPropertyListGivesItsAbsolutePaths()
+ {
+ string[] expected = ["/Users/a/사진 1.png", "/Users/a/R&D/notes.txt"];
+ Assert.Equal(expected, PasteboardPaths.FromPropertyList(Filenames));
+ Assert.Equal(expected, PasteboardPaths.FromPropertyList(Encoding.UTF8.GetBytes(Filenames)));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("<plist version=\"1.0\"><dict><key>a</key><string>/tmp/x</string></dict></plist>")]
+ [InlineData("<plist><array><string>/tmp/x</string>")]
+ [InlineData("/tmp/x")]
+ public void AnythingButAnArrayOfPathsGivesNone(string? text) =>
+ Assert.Empty(PasteboardPaths.FromPropertyList(text));
+
+ [Fact]
+ public void EmptyDataGivesNone()
+ {
+ Assert.Empty(PasteboardPaths.FromPropertyList((byte[]?)null));
+ Assert.Empty(PasteboardPaths.FromPropertyList([]));
+ }
+
+ [Theory]
+ [InlineData("file:///Users/a/b%20c.png", "/Users/a/b c.png")]
+ [InlineData("file://localhost/tmp/x.png", "/tmp/x.png")]
+ [InlineData("file:///Users/a/%EC%82%AC%EC%A7%84.png", "/Users/a/사진.png")]
+ [InlineData(" file:///tmp/x.png\n", "/tmp/x.png")]
+ [InlineData("file:///.file/id=6571367.2773272/", null)]
+ [InlineData("file://server/share/x.png", null)]
+ [InlineData("https://example.com/x.png", null)]
+ [InlineData("/tmp/x.png", null)]
+ [InlineData("", null)]
+ [InlineData(null, null)]
+ public void FileUrlGivesItsPath(string? url, string? expected) =>
+ Assert.Equal(expected, PasteboardPaths.FromFileUrl(url));
+
+ [Fact]
+ public void TextGivesTheLinesThatArePathsOrFileUrls()
+ {
+ const string text = "/tmp/a.png\nsome words\r\nfile:///tmp/b%20c.png\r\n\r\n /tmp/d.jpg \nC:\\x.png\n/";
+ Assert.Equal(["/tmp/a.png", "/tmp/b c.png", "/tmp/d.jpg"], PasteboardPaths.FromText(text));
+ Assert.Empty(PasteboardPaths.FromText(null));
+ Assert.Empty(PasteboardPaths.FromText("a.png"));
+ }
+
+ [Fact]
+ public void TheFirstSourceNamingAnExistingPathWinsWithoutRepeats()
+ {
+ var existing = new HashSet<string> { "/tmp/a.png", "/tmp/b.png", "/tmp/c.png" };
+ var readLast = false;
+ var paths = PasteboardPaths.FirstExisting(
+ [
+ () => ["/tmp/missing.png"],
+ () => ["/tmp/b.png", "/tmp/gone.png", "/tmp/a.png", "/tmp/b.png"],
+ () =>
+ {
+ readLast = true;
+ return ["/tmp/c.png"];
+ },
+ ], existing.Contains);
+
+ Assert.Equal(["/tmp/b.png", "/tmp/a.png"], paths);
+ Assert.False(readLast);
+ Assert.Empty(PasteboardPaths.FirstExisting([() => ["/tmp/missing.png"], () => []], existing.Contains));
+ }
+
+ [Fact]
+ public void FilenamesTypeIsKnownByItsNameAndItsDynamicUti()
+ {
+ Assert.True(PasteboardPaths.IsFilenamesType("NSFilenamesPboardType"));
+ Assert.True(PasteboardPaths.IsFilenamesType(PasteboardPaths.FilenamesUti));
+ Assert.False(PasteboardPaths.IsFilenamesType("public.file-url"));
+ Assert.Contains(PasteboardPaths.FilenamesType, PasteboardPaths.DragTypes);
+ Assert.Contains(PasteboardPaths.FileUrlType, PasteboardPaths.DragTypes);
+ }
+}