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.

Convert the file a Windows shortcut points to (#159)

KnifeLemon75831ff2dda5
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index 3456df0a..4bf2622d 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -90,9 +90,10 @@ public sealed class RadialController(
}, EmptyDragLimit);
}
- /// <summary>Opens the donut for known files (click mode).</summary>
+ /// <summary>Opens the donut for known files (click mode). Shortcuts among them stand for the files they point to.</summary>
public void ShowForFiles(int x, int y, IReadOnlyList<string> files)
{
+ files = platform.ResolveShortcuts(files);
if (files.Count == 0)
return;
ReleaseProgressToToast();
diff --git a/src/Filee.App/Views/Pages/HomePage.axaml.cs b/src/Filee.App/Views/Pages/HomePage.axaml.cs
index 6ef86397..50faaec2 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;
@@ -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 = RadialWindow.LocalFiles(e);
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..0cb748e2 100644
--- a/src/Filee.App/Views/RadialWindow.axaml.cs
+++ b/src/Filee.App/Views/RadialWindow.axaml.cs
@@ -6,6 +6,7 @@ using Avalonia.Input;
using Avalonia.Platform.Storage;
using Filee.App.Controls;
using Filee.App.Services;
+using Filee.Core.Platform;
namespace Filee.App.Views;
@@ -118,11 +119,15 @@ public partial class RadialWindow : Window
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>()
+ /// <summary>
+ /// Local file paths in the drag data (folders and virtual items are ignored). A shortcut counts as the file it
+ /// points to; one to a folder is ignored like the folder.
+ /// </summary>
+ internal static IReadOnlyList<string> LocalFiles(DragEventArgs e) =>
+ AppHost.Get<IPlatformServices>().ResolveShortcuts((e.DataTransfer.TryGetFiles() ?? [])
+ .Select(item => item.TryGetLocalPath())
+ .OfType<string>()
+ .ToList())
.Where(File.Exists)
.ToList();
}
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
index 5a1b0d9f..c88db21f 100644
--- a/src/Filee.Core/Platform/IPlatformServices.cs
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -28,6 +28,29 @@ public interface IPlatformServices
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.CurrentCultureIgnoreCase)];
}
+ /// <summary>
+ /// The existing file or folder the shortcut at <paramref name="path"/> points to (a .lnk on Windows); null for
+ /// anything else, a broken shortcut, or a platform whose shortcuts Filee doesn't follow (macOS aliases and Linux
+ /// .desktop links aren't followed yet).
+ /// </summary>
+ string? ShortcutTarget(string path) => null;
+
+ /// <summary>
+ /// <paramref name="paths"/> with every shortcut replaced by what it points to, for files that come into Filee
+ /// (drops, the file manager's menu and selection). A broken shortcut stays, so it is reported as unsupported.
+ /// </summary>
+ IReadOnlyList<string> ResolveShortcuts(IReadOnlyList<string> paths) => ResolveShortcuts(paths, ShortcutTarget);
+
+ /// <summary>
+ /// Replaces each path by <paramref name="target"/>'s answer, if any, keeping the order. A shortcut and its target
+ /// brought in together, or two shortcuts to one file, give that file once.
+ /// </summary>
+ static IReadOnlyList<string> ResolveShortcuts(IReadOnlyList<string> paths, Func<string, string?> target)
+ {
+ var resolved = paths.Select(p => target(p) ?? p).ToList();
+ return resolved.SequenceEqual(paths) ? paths : [.. resolved.Distinct(FileSystemPaths.Comparer)];
+ }
+
/// <summary>Files currently selected in the foreground file manager window (empty if none).</summary>
IReadOnlyList<string> GetFileManagerSelection();
diff --git a/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj b/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj
index b57db909..cf5805e7 100644
--- a/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj
+++ b/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj
@@ -1,6 +1,6 @@
<!--
Filee.Platform.Windows: Windows implementation of IPlatformServices
- (Explorer detection & selection, context menu, auto-start, system metrics).
+ (Explorer detection & selection, context menu, auto-start, system metrics, .lnk shortcut targets).
Targets plain net10.0 so the cross-platform app can reference it; every entry point is guarded
with [SupportedOSPlatform("windows")] and only used when OperatingSystem.IsWindows() is true.
-->
@@ -12,5 +12,6 @@
<ItemGroup>
<ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />
+ <InternalsVisibleTo Include="Filee.Platform.Tests" />
</ItemGroup>
</Project>
diff --git a/src/Filee.Platform.Windows/ShellLinks.cs b/src/Filee.Platform.Windows/ShellLinks.cs
new file mode 100644
index 00000000..715a5e01
--- /dev/null
+++ b/src/Filee.Platform.Windows/ShellLinks.cs
@@ -0,0 +1,206 @@
+// Windows shortcuts (.lnk): the file or folder one points to, so a dropped shortcut converts its target (issue #159).
+//
+// The shell's own ShellLink object reads the link, the way Explorer does. Should it be unavailable or fail, the target
+// is read from the file itself ([MS-SHLLINK] LinkInfo: the local base path, or the share name, and the path suffix).
+// Neither searches for a target that has moved (IShellLink.Resolve would, and can show UI or take seconds).
+
+using System.Buffers.Binary;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.ComTypes;
+using System.Runtime.Versioning;
+using System.Text;
+
+namespace Filee.Platform.Windows;
+
+[SupportedOSPlatform("windows")]
+internal static class ShellLinks
+{
+ private const int MaxPath = 32768;
+ private static readonly Guid CLSID_ShellLink = new("00021401-0000-0000-C000-000000000046");
+
+ /// <summary>True for a path ending in ".lnk".</summary>
+ public static bool IsShortcut(string path) => path.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase);
+
+ /// <summary>
+ /// The existing file or folder the shortcut at <paramref name="path"/> points to; null when it isn't a shortcut,
+ /// points to something that isn't a file (Control Panel, an installer-advertised app) or to nothing any more.
+ /// </summary>
+ public static string? TargetOf(string path)
+ {
+ if (!IsShortcut(path) || !File.Exists(path))
+ return null;
+ var target = ReadWithShell(path) ?? ReadFromFile(path);
+ try
+ {
+ return target is not null && (File.Exists(target) || Directory.Exists(target)) ? Path.GetFullPath(target) : null;
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>Writes a shortcut to <paramref name="target"/> (the tests make their shortcuts with it).</summary>
+ internal static void Create(string path, string target)
+ {
+ var link = NewShellLink();
+ try
+ {
+ ((IShellLinkW)link).SetPath(target);
+ ((IPersistFile)link).Save(path, true);
+ }
+ finally
+ {
+ Marshal.FinalReleaseComObject(link);
+ }
+ }
+
+ /// <summary>The target as the shell reads it; null when it has no file system path or the shell failed.</summary>
+ internal static string? ReadWithShell(string path)
+ {
+ object? link = null;
+ try
+ {
+ link = NewShellLink();
+ ((IPersistFile)link).Load(path, 0); // STGM_READ
+ var buffer = new StringBuilder(MaxPath);
+ ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, 0, 0);
+ return buffer.Length > 0 ? buffer.ToString() : null;
+ }
+ catch (Exception ex) when (ex is COMException or InvalidCastException or ArgumentException or UnauthorizedAccessException
+ or IOException or NotSupportedException)
+ {
+ return null;
+ }
+ finally
+ {
+ if (link is not null)
+ Marshal.FinalReleaseComObject(link);
+ }
+ }
+
+ /// <summary>The target as the .lnk file stores it in its LinkInfo; null when unreadable or not stored.</summary>
+ internal static string? ReadFromFile(string path)
+ {
+ try
+ {
+ var info = new FileInfo(path);
+ // A shortcut is a few KB; anything far bigger isn't one.
+ return info.Length is > 0 and < 1 << 20 ? ParseTarget(File.ReadAllBytes(path)) : null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>[MS-SHLLINK]: the path in LinkInfo (local base path or share name, then the common path suffix).</summary>
+ internal static string? ParseTarget(ReadOnlySpan<byte> data)
+ {
+ const int HeaderSize = 0x4C;
+ const uint HasLinkTargetIdList = 0x1, HasLinkInfo = 0x2, ForceNoLinkInfo = 0x100;
+ const uint VolumeIdAndLocalBasePath = 0x1, CommonNetworkRelativeLinkAndPathSuffix = 0x2;
+
+ if (data.Length < HeaderSize || BinaryPrimitives.ReadUInt32LittleEndian(data) != HeaderSize
+ || new Guid(data.Slice(4, 16)) != CLSID_ShellLink)
+ return null;
+ var flags = BinaryPrimitives.ReadUInt32LittleEndian(data[20..]);
+ if ((flags & HasLinkInfo) == 0 || (flags & ForceNoLinkInfo) != 0)
+ return null;
+
+ var offset = HeaderSize;
+ if ((flags & HasLinkTargetIdList) != 0)
+ {
+ if (offset + 2 > data.Length)
+ return null;
+ offset += 2 + BinaryPrimitives.ReadUInt16LittleEndian(data[offset..]);
+ }
+ if (offset + 0x1C > data.Length)
+ return null;
+ var size = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(data[offset..]), (uint)(data.Length - offset));
+ var linkInfo = data.Slice(offset, size);
+ if (linkInfo.Length < 0x1C)
+ return null;
+
+ var headerLength = Field(linkInfo, 4);
+ var linkInfoFlags = Field(linkInfo, 8);
+ var unicode = headerLength >= 0x24;
+ // Unicode copies follow a longer header; Windows writes them when the path doesn't fit the ANSI code page.
+ var suffix = (unicode ? Unicode(linkInfo, Field(linkInfo, 0x20)) : null) ?? Ansi(linkInfo, Field(linkInfo, 0x18));
+
+ if ((linkInfoFlags & VolumeIdAndLocalBasePath) != 0)
+ {
+ var basePath = (unicode ? Unicode(linkInfo, Field(linkInfo, 0x1C)) : null) ?? Ansi(linkInfo, Field(linkInfo, 0x10));
+ return string.IsNullOrEmpty(basePath) ? null : basePath + suffix;
+ }
+ if ((linkInfoFlags & CommonNetworkRelativeLinkAndPathSuffix) != 0)
+ {
+ var at = (int)Field(linkInfo, 0x14);
+ if (at <= 0 || at + 0x14 > linkInfo.Length)
+ return null;
+ var network = linkInfo[at..];
+ var netNameOffset = BinaryPrimitives.ReadUInt32LittleEndian(network[8..]);
+ var netName = netNameOffset > 0x14 && network.Length >= 0x1C
+ ? Unicode(network, BinaryPrimitives.ReadUInt32LittleEndian(network[0x14..]))
+ : Ansi(network, netNameOffset);
+ return string.IsNullOrEmpty(netName) ? null
+ : string.IsNullOrEmpty(suffix) ? netName : netName.TrimEnd('\\') + "\\" + suffix;
+ }
+ return null;
+ }
+
+ /// <summary>A little-endian 32-bit field; 0 past the end.</summary>
+ private static uint Field(ReadOnlySpan<byte> data, int at) =>
+ at + 4 <= data.Length ? BinaryPrimitives.ReadUInt32LittleEndian(data[at..]) : 0;
+
+ /// <summary>A NUL-terminated string in the system's ANSI code page, as Windows writes it.</summary>
+ private static unsafe string? Ansi(ReadOnlySpan<byte> data, uint offset)
+ {
+ if (offset == 0 || offset >= data.Length)
+ return null;
+ var text = data[(int)offset..];
+ var end = text.IndexOf((byte)0);
+ if (end < 0)
+ return null;
+ fixed (byte* start = text)
+ return Marshal.PtrToStringAnsi((nint)start, end); // CP_ACP on Windows
+ }
+
+ /// <summary>A NUL-terminated UTF-16 string.</summary>
+ private static string? Unicode(ReadOnlySpan<byte> data, uint offset)
+ {
+ if (offset == 0 || offset >= data.Length)
+ return null;
+ var text = MemoryMarshal.Cast<byte, char>(data[(int)offset..][..((data.Length - (int)offset) & ~1)]);
+ var end = text.IndexOf('\0');
+ return end < 0 ? null : new string(text[..end]);
+ }
+
+ private static object NewShellLink() =>
+ Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_ShellLink, throwOnError: true)!)!;
+
+ // Only the methods Filee calls are typed; the slots between them keep the vtable order and are never called.
+
+ [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellLinkW
+ {
+ void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder file, int size, nint findData, uint flags);
+ void GetIDList();
+ void SetIDList();
+ void GetDescription();
+ void SetDescription();
+ void GetWorkingDirectory();
+ void SetWorkingDirectory();
+ void GetArguments();
+ void SetArguments();
+ void GetHotkey();
+ void SetHotkey();
+ void GetShowCmd();
+ void SetShowCmd();
+ void GetIconLocation();
+ void SetIconLocation();
+ void SetRelativePath();
+ void Resolve();
+ void SetPath([MarshalAs(UnmanagedType.LPWStr)] string file);
+ }
+}
diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
index 11d461b8..34337327 100644
--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs
+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
@@ -68,6 +68,8 @@ public sealed class WindowsPlatformServices : IPlatformServices
return root == 0 ? null : ProcessNameOf(root);
}
+ public string? ShortcutTarget(string path) => ShellLinks.TargetOf(path);
+
/// <summary>
/// Reads the selection of the foreground Explorer window through the Shell automation object.
/// Must be called on an STA thread (the Avalonia UI thread is STA).
diff --git a/tests/Filee.Core.Tests/ShortcutResolutionTests.cs b/tests/Filee.Core.Tests/ShortcutResolutionTests.cs
new file mode 100644
index 00000000..4f9b26af
--- /dev/null
+++ b/tests/Filee.Core.Tests/ShortcutResolutionTests.cs
@@ -0,0 +1,42 @@
+using Filee.Core.Platform;
+
+namespace Filee.Core.Tests;
+
+public class ShortcutResolutionTests
+{
+ private static readonly string Folder = Path.Combine(Path.GetTempPath(), "filee-shortcuts");
+ private static readonly string Report = Path.Combine(Folder, "report.docx");
+ private static readonly string Photo = Path.Combine(Folder, "photo.jpg");
+ private static readonly string ToReport = Path.Combine(Folder, "report.lnk");
+ private static readonly string AlsoToReport = Path.Combine(Folder, "report (2).lnk");
+ private static readonly string Broken = Path.Combine(Folder, "broken.lnk");
+
+ private static string? Target(string path) =>
+ path == ToReport || path == AlsoToReport ? Report : null;
+
+ [Fact]
+ public void Shortcuts_become_their_targets_in_place()
+ {
+ var files = IPlatformServices.ResolveShortcuts([Photo, ToReport, Broken], Target);
+
+ Assert.Equal([Photo, Report, Broken], files);
+ }
+
+ [Fact]
+ public void A_shortcut_dropped_with_its_target_gives_the_file_once()
+ {
+ Assert.Equal([Report, Photo], IPlatformServices.ResolveShortcuts([ToReport, Photo, Report], Target));
+ Assert.Equal([Report], IPlatformServices.ResolveShortcuts([ToReport, AlsoToReport], Target));
+ }
+
+ [Fact]
+ public void Without_shortcuts_the_list_is_left_as_it_is()
+ {
+ IReadOnlyList<string> files = [Photo, Report];
+ IPlatformServices elsewhere = new NullPlatformServices();
+
+ Assert.Same(files, IPlatformServices.ResolveShortcuts(files, Target));
+ // Where Filee doesn't follow shortcuts, one stays a file of its own.
+ Assert.Equal([ToReport], elsewhere.ResolveShortcuts([ToReport]));
+ }
+}
diff --git a/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj b/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj
index f6ccad1d..a3d0e81a 100644
--- a/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj
+++ b/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj
@@ -7,6 +7,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Filee.Platform.Linux\Filee.Platform.Linux.csproj" />
<ProjectReference Include="..\..\src\Filee.Platform.MacOS\Filee.Platform.MacOS.csproj" />
+ <ProjectReference Include="..\..\src\Filee.Platform.Windows\Filee.Platform.Windows.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
diff --git a/tests/Filee.Platform.Tests/WindowsShortcutTests.cs b/tests/Filee.Platform.Tests/WindowsShortcutTests.cs
new file mode 100644
index 00000000..b2844be5
--- /dev/null
+++ b/tests/Filee.Platform.Tests/WindowsShortcutTests.cs
@@ -0,0 +1,89 @@
+using Filee.Platform.Windows;
+
+namespace Filee.Platform.Tests;
+
+/// <summary>Shortcuts (.lnk) dropped on Filee convert the file they point to (#159).</summary>
+public sealed class WindowsShortcutTests : IDisposable
+{
+ private readonly string _folder = Directory.CreateTempSubdirectory("filee-lnk-").FullName;
+
+ public void Dispose()
+ {
+ try { Directory.Delete(_folder, true); } catch (IOException) { }
+ }
+
+ private string Write(string name)
+ {
+ var path = Path.Combine(_folder, name);
+ File.WriteAllText(path, "x");
+ return path;
+ }
+
+ [System.Runtime.Versioning.SupportedOSPlatform("windows")]
+ private string Link(string name, string target)
+ {
+ var path = Path.Combine(_folder, name);
+ ShellLinks.Create(path, target);
+ return path;
+ }
+
+ [Fact]
+ public void A_shortcut_resolves_to_its_file_or_folder_and_a_broken_one_to_nothing()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.Skip("Windows shortcuts need the Windows shell.");
+ return;
+ }
+ var report = Write("보고서 report.docx");
+ var folder = Directory.CreateDirectory(Path.Combine(_folder, "photos")).FullName;
+ var gone = Write("gone.pdf");
+ var toReport = Link("report.docx - Shortcut.lnk", report);
+ var toFolder = Link("photos.lnk", folder);
+ var broken = Link("gone.lnk", gone);
+ File.Delete(gone);
+ var platform = new WindowsPlatformServices();
+
+ Assert.Equal(report, platform.ShortcutTarget(toReport), StringComparer.OrdinalIgnoreCase);
+ Assert.Equal(folder, platform.ShortcutTarget(toFolder), StringComparer.OrdinalIgnoreCase);
+ Assert.Null(platform.ShortcutTarget(broken));
+ Assert.Null(platform.ShortcutTarget(report));
+ Assert.Null(platform.ShortcutTarget(Path.Combine(_folder, "missing.lnk")));
+ }
+
+ [Fact]
+ public void The_file_format_fallback_reads_the_same_target_as_the_shell()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.Skip("Windows shortcuts need the Windows shell.");
+ return;
+ }
+ var report = Write("보고서 report.docx");
+ var link = Link("report.lnk", report);
+
+ Assert.Equal(report, ShellLinks.ReadFromFile(link), StringComparer.OrdinalIgnoreCase);
+ Assert.Null(ShellLinks.ReadFromFile(report));
+ Assert.Null(ShellLinks.ParseTarget(new byte[10]));
+ }
+
+ [Fact]
+ public void A_shortcut_dropped_with_its_target_gives_the_file_once_and_a_broken_one_stays()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.Skip("Windows shortcuts need the Windows shell.");
+ return;
+ }
+ var report = Write("report.docx");
+ var photo = Write("photo.jpg");
+ var toReport = Link("report.lnk", report);
+ var broken = Path.Combine(_folder, "broken.lnk");
+ File.WriteAllText(broken, "not a shortcut");
+ Core.Platform.IPlatformServices platform = new WindowsPlatformServices();
+
+ var files = platform.ResolveShortcuts([toReport, photo, report, broken]);
+
+ Assert.Equal([report, photo, broken], files, StringComparer.OrdinalIgnoreCase);
+ }
+}