diff --git a/src/Titano.Core.Windows/Shell/AppPaths.cs b/src/Titano.Core.Windows/Shell/AppPaths.cs new file mode 100644 index 00000000..e2cfd70e --- /dev/null +++ b/src/Titano.Core.Windows/Shell/AppPaths.cs @@ -0,0 +1,64 @@ +namespace Titano.Core.Windows.Shell; + +/// +/// Where the desktop programs keep their data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the +/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is +/// reported by and refused by . +/// +public sealed class AppPaths +{ + public const string ProductFolderName = "Titano"; + public const string DatabaseFileName = "titano.db"; + + private AppPaths(string dataRoot, bool isPortable, string? syncedFolder) + { + DataRoot = dataRoot; + IsPortable = isPortable; + SyncedFolder = syncedFolder; + } + + public bool IsPortable { get; } + + public string DataRoot { get; } + + public string DatabasePath => Path.Combine(DataRoot, DatabaseFileName); + + public string LogsDirectory => Path.Combine(DataRoot, "logs"); + + public string CacheDirectory => Path.Combine(DataRoot, "cache"); + + public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails"); + + /// The OneDrive sync root containing , or null when the location is safe. + public string? SyncedFolder { get; } + + public bool IsInSyncedFolder => SyncedFolder is not null; + + /// Paths for this process: the executable's folder decides portable mode. + public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData); + + /// Paths for an executable in , checked against the user's OneDrive roots. + public static AppPaths Resolve(string applicationDirectory, string localAppData) => + Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots()); + + internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList syncRoots) + { + var portable = PortableMode.IsEnabled(applicationDirectory); + var root = Path.GetFullPath(portable + ? Path.Combine(applicationDirectory, PortableMode.DataFolderName) + : Path.Combine(localAppData, ProductFolderName)); + return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots)); + } + + /// Creates the data, logs, cache and thumbnails folders. + /// The data root lies inside a OneDrive-synced folder. + public void CreateDirectories() + { + if (SyncedFolder is not null) + throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation."); + Directory.CreateDirectory(DataRoot); + Directory.CreateDirectory(LogsDirectory); + Directory.CreateDirectory(CacheDirectory); + Directory.CreateDirectory(ThumbnailsDirectory); + } +} diff --git a/src/Titano.Core.Windows/Shell/KnownFolders.cs b/src/Titano.Core.Windows/Shell/KnownFolders.cs new file mode 100644 index 00000000..928addbd --- /dev/null +++ b/src/Titano.Core.Windows/Shell/KnownFolders.cs @@ -0,0 +1,38 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Shell; + +/// Known folder paths through SHGetKnownFolderPath (honours folder redirection). +public static partial class KnownFolders +{ + /// FOLDERID_LocalAppData. + public static readonly Guid LocalAppDataId = new("f1b32785-6fba-4fcf-9d55-7b8e7f157091"); + + /// FOLDERID_Pictures. + public static readonly Guid PicturesId = new("33e28130-4e1e-4676-835a-98395c3bc3bb"); + + /// %LOCALAPPDATA% (never synced by OneDrive). + public static string LocalAppData => GetPath(LocalAppDataId); + + /// The user's Pictures folder (may be redirected into OneDrive). + public static string Pictures => GetPath(PicturesId); + + /// The folder does not exist or is not available to this user. + public static string GetPath(Guid folderId) + { + var hr = SHGetKnownFolderPath(folderId, 0, 0, out var buffer); + try + { + Marshal.ThrowExceptionForHR(hr); + return Marshal.PtrToStringUni(buffer) ?? string.Empty; + } + finally + { + // The buffer must be freed whether or not the call succeeded. + Marshal.FreeCoTaskMem(buffer); + } + } + + [LibraryImport("shell32.dll")] + private static partial int SHGetKnownFolderPath(in Guid folderId, uint flags, nint token, out nint path); +} diff --git a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs new file mode 100644 index 00000000..b37a5a67 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs @@ -0,0 +1,48 @@ +using Microsoft.Win32; + +namespace Titano.Core.Windows.Shell; + +/// Folders synchronised by OneDrive for the current user (personal and work/school accounts). +public static class OneDriveFolders +{ + private const string AccountsKey = @"Software\Microsoft\OneDrive\Accounts"; + private static readonly string[] EnvironmentVariables = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]; + + /// + /// Sync roots from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder, + /// as full paths without a trailing separator, distinct (case-insensitive). + /// + public static IReadOnlyList SyncRoots() + { + var roots = new List(); + foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable)); + using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey); + if (accounts is not null) + { + foreach (var name in accounts.GetSubKeyNames()) + { + using var account = accounts.OpenSubKey(name); + Add(roots, account?.GetValue("UserFolder") as string); + } + } + return roots; + } + + /// The sync root that contains , or null. Both are expected to be full paths. + public static string? Containing(string path, IEnumerable syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root)); + + /// True when equals or lies below it (whole path segments, case-insensitive). + internal static bool IsUnder(string path, string root) + { + var trimmedRoot = root.TrimEnd('\\', '/'); + if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false; + return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/'; + } + + private static void Add(List roots, string? candidate) + { + if (string.IsNullOrWhiteSpace(candidate) || !Path.IsPathFullyQualified(candidate)) return; + var full = Path.GetFullPath(candidate).TrimEnd('\\', '/'); + if (!roots.Contains(full, StringComparer.OrdinalIgnoreCase)) roots.Add(full); + } +} diff --git a/src/Titano.Core.Windows/Shell/PortableMode.cs b/src/Titano.Core.Windows/Shell/PortableMode.cs new file mode 100644 index 00000000..2c438a37 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/PortableMode.cs @@ -0,0 +1,10 @@ +namespace Titano.Core.Windows.Shell; + +/// Portable mode (BRIEF §6.2): a portable.txt next to the executable keeps all data under .\data\. +public static class PortableMode +{ + public const string MarkerFileName = "portable.txt"; + public const string DataFolderName = "data"; + + public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName)); +} diff --git a/src/Titano.Core.Windows/Shell/ShellLauncher.cs b/src/Titano.Core.Windows/Shell/ShellLauncher.cs new file mode 100644 index 00000000..ecf9ed72 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/ShellLauncher.cs @@ -0,0 +1,132 @@ +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Shell; + +/// +/// The only shell verbs Titano may invoke (BRIEF §8.6): open for web and Microsoft Store links and +/// explore/select for revealing files. Callable from any thread: the work runs on an STA as shell +/// extensions require (inline on a UI thread, otherwise on a short-lived STA thread). +/// +public static partial class ShellLauncher +{ + private static readonly string[] AllowedSchemes = ["http", "https", "ms-windows-store"]; + + private const uint SEE_MASK_NOASYNC = 0x100; + private const uint SEE_MASK_FLAG_NO_UI = 0x400; + private const int SW_SHOWNORMAL = 1; + + /// True for absolute http, https and ms-windows-store URLs, the only links handed to the shell. + public static bool IsAllowedUrl(string url) => + Uri.TryCreate(url, UriKind.Absolute, out var uri) + && AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase); + + /// Opens the URL with ShellExecuteEx("open"); false when the shell could not open it. + /// The URL is not an absolute http, https or ms-windows-store URL. + public static bool OpenUrl(string url) + { + if (!IsAllowedUrl(url)) throw new ArgumentException("Only http, https and ms-windows-store URLs may be opened.", nameof(url)); + var canonical = new Uri(url, UriKind.Absolute).AbsoluteUri; + return RunOnSta(() => Execute("open", canonical)); + } + + /// + /// Shows a file selected in its Explorer folder (SHOpenFolderAndSelectItems) or opens a folder ("explore"). + /// False when the path does not exist or the shell failed. + /// + public static bool RevealInExplorer(string path) + { + var full = Path.GetFullPath(path); + if (Directory.Exists(full)) return RunOnSta(() => Execute("explore", full)); + return File.Exists(full) && RunOnSta(() => SelectInFolder(full)); + } + + private static unsafe bool Execute(string verb, string file) + { + fixed (char* verbPointer = verb) + fixed (char* filePointer = file) + { + var info = new ShellExecuteInfo + { + Size = (uint)sizeof(ShellExecuteInfo), + Mask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI, + Verb = (nint)verbPointer, + File = (nint)filePointer, + Show = SW_SHOWNORMAL, + }; + return ShellExecuteExW(ref info); + } + } + + private static bool SelectInFolder(string file) + { + if (SHParseDisplayName(file, 0, out var itemList, 0, out _) < 0) return false; + try + { + // With no child items the absolute ID list names the item to select; Explorer opens its parent. + return SHOpenFolderAndSelectItems(itemList, 0, 0, 0) >= 0; + } + finally + { + Marshal.FreeCoTaskMem(itemList); + } + } + + private static bool RunOnSta(Func action) + { + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) return action(); + var result = false; + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + result = action(); + } + catch (Exception ex) + { + failure = ExceptionDispatchInfo.Capture(ex); + } + }) + { + IsBackground = true, + Name = "Titano shell", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + failure?.Throw(); + return result; + } + + /// SHELLEXECUTEINFOW (112 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct ShellExecuteInfo + { + public uint Size; + public uint Mask; + public nint Window; + public nint Verb; + public nint File; + public nint Parameters; + public nint Directory; + public int Show; + public nint InstanceApp; + public nint ItemIdList; + public nint Class; + public nint ClassKey; + public uint HotKey; + public nint IconOrMonitor; + public nint Process; + } + + [LibraryImport("shell32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool ShellExecuteExW(ref ShellExecuteInfo info); + + [LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int SHParseDisplayName(string name, nint bindContext, out nint itemIdList, uint attributesIn, out uint attributesOut); + + [LibraryImport("shell32.dll")] + private static partial int SHOpenFolderAndSelectItems(nint folder, uint count, nint items, uint flags); +} diff --git a/src/Titano.Core.Windows/Shell/TaskbarProgress.cs b/src/Titano.Core.Windows/Shell/TaskbarProgress.cs new file mode 100644 index 00000000..d60d59e2 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/TaskbarProgress.cs @@ -0,0 +1,84 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Shell; + +/// TBPFLAG: the taskbar button progress style. +public enum TaskbarProgressState +{ + None = 0x0, + Indeterminate = 0x1, + Normal = 0x2, + Error = 0x4, + Paused = 0x8, +} + +/// +/// Taskbar button progress through ITaskbarList3. The taskbar object is apartment-threaded: create, use and dispose +/// an instance on the UI thread that owns the window. Every call returns false (never throws) when the taskbar is +/// unavailable, the window handle is null or stale, or the shell rejects the call. +/// +public sealed class TaskbarProgress : IDisposable +{ + private static readonly Guid TaskbarListClsid = new("56fdf344-fd6d-11d0-958a-006097c9a090"); + private ITaskbarList3? _taskbar; + + public TaskbarProgress() + { + if (Win32Com.TryCreateInstance(TaskbarListClsid, typeof(ITaskbarList3).GUID, out var instance) >= 0 + && instance is ITaskbarList3 taskbar + && taskbar.HrInit() >= 0) + { + _taskbar = taskbar; + return; + } + Win32Com.Release(instance); + } + + /// False when no taskbar is available (e.g. a session without Explorer). + public bool IsAvailable => _taskbar is not null; + + public bool SetState(nint window, TaskbarProgressState state) => + _taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressState(window, state) >= 0; + + /// Sets the bar to / (switches to if no progress was shown). + public bool SetValue(nint window, ulong completed, ulong total) => + total > 0 && _taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressValue(window, Math.Min(completed, total), total) >= 0; + + public void Dispose() + { + Win32Com.Release(_taskbar); + _taskbar = null; + } +} + +/// ITaskbarList3 (ITaskbarList → ITaskbarList2 → ITaskbarList3), declared up to SetProgressState. +[ComImport] +[Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface ITaskbarList3 +{ + [PreserveSig] + int HrInit(); + + [PreserveSig] + int AddTab(nint window); + + [PreserveSig] + int DeleteTab(nint window); + + [PreserveSig] + int ActivateTab(nint window); + + [PreserveSig] + int SetActiveAlt(nint window); + + [PreserveSig] + int MarkFullscreenWindow(nint window, int fullscreen); + + [PreserveSig] + int SetProgressValue(nint window, ulong completed, ulong total); + + [PreserveSig] + int SetProgressState(nint window, TaskbarProgressState state); +} diff --git a/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs new file mode 100644 index 00000000..3be36314 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs @@ -0,0 +1,75 @@ +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Shell; + +public sealed class AppPathsTests(TestContext context) +{ + [Test] + public void PortableMarkerKeepsDataNextToTheExecutable() + { + var app = context.CreateTempDirectory("app"); + var local = context.CreateTempDirectory("local"); + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + + var paths = AppPaths.Resolve(app, local, []); + Assert.True(paths.IsPortable); + Assert.Equal(Path.Combine(app, "data"), paths.DataRoot); + Assert.Equal(Path.Combine(app, "data", "titano.db"), paths.DatabasePath); + Assert.False(paths.IsInSyncedFolder); + + paths.CreateDirectories(); + Assert.True(Directory.Exists(paths.LogsDirectory)); + Assert.True(Directory.Exists(paths.CacheDirectory)); + Assert.True(Directory.Exists(paths.ThumbnailsDirectory)); + } + + [Test] + public void InstalledModeUsesLocalAppData() + { + var app = context.CreateTempDirectory("app"); + var local = context.CreateTempDirectory("local"); + + var paths = AppPaths.Resolve(app, local, []); + Assert.False(paths.IsPortable); + Assert.Equal(Path.Combine(local, "Titano"), paths.DataRoot); + Assert.Equal(Path.Combine(local, "Titano", "titano.db"), paths.DatabasePath); + } + + [Test] + public void DataInsideOneDriveIsReportedAndRefused() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + + var paths = AppPaths.Resolve(app, context.CreateTempDirectory("local"), [oneDrive]); + Assert.True(paths.IsInSyncedFolder); + Assert.Equal(oneDrive, paths.SyncedFolder); + Assert.Throws(paths.CreateDirectories); + Assert.False(Directory.Exists(paths.DataRoot)); + } + + [Test] + public void SyncRootMatchingIsSegmentWise() + { + var root = Path.Combine(context.CreateTempDirectory(), "OneDrive"); + Assert.True(OneDriveFolders.IsUnder(root, root)); + Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar)); + Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root)); + Assert.False(OneDriveFolders.IsUnder(root + "Backup", root)); + Assert.Null(OneDriveFolders.Containing(root + "Backup", [root])); + } + + [Test] + [WindowsOnly] + public void ResolveChecksTheRealOneDriveRoots() + { + var app = context.CreateTempDirectory("app"); + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var paths = AppPaths.Resolve(app, KnownFolders.LocalAppData); + Assert.True(paths.IsPortable); + Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, OneDriveFolders.SyncRoots()), paths.SyncedFolder); + Assert.True(OneDriveFolders.SyncRoots().All(Path.IsPathFullyQualified)); + } +} diff --git a/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs b/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs new file mode 100644 index 00000000..e55a8539 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs @@ -0,0 +1,57 @@ +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Shell; + +public sealed class ShellTests(TestContext context) +{ + private static readonly nint StaleWindow = 0x0BAD_F00D; + + [Theory] + [Case("https://apps.microsoft.com/detail/9nctdw2w1bh8")] + [Case("http://nas.local:8443/admin")] + [Case("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8")] + public void WebAndStoreUrlsAreAllowed(string url) => Assert.True(ShellLauncher.IsAllowedUrl(url)); + + [Theory] + [Case("file:///C:/Windows/System32/cmd.exe")] + [Case(@"C:\Windows\System32\cmd.exe")] + [Case(@"\\server\share\run.bat")] + [Case("javascript:alert(1)")] + [Case("mailto:someone@example.com")] + [Case("relative/page.html")] + [Case("")] + public void OtherTargetsAreRejected(string url) => Assert.False(ShellLauncher.IsAllowedUrl(url)); + + [Test] + public void OpenUrlRefusesRejectedTargetsBeforeTouchingTheShell() => + Assert.Throws(() => ShellLauncher.OpenUrl("file:///C:/Windows/System32/cmd.exe")); + + [Test] + public void RevealOfAMissingPathReturnsFalse() => + Assert.False(ShellLauncher.RevealInExplorer(Path.Combine(context.CreateTempDirectory(), "missing.jpg"))); + + [Test] + [WindowsOnly] + public void KnownFoldersMatchTheSystem() + { + Assert.Equal( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToUpperInvariant(), + KnownFolders.LocalAppData.ToUpperInvariant()); + Assert.True(Path.IsPathFullyQualified(KnownFolders.Pictures), KnownFolders.Pictures); + } + + [Test] + [WindowsOnly] + public void TaskbarCallsWithoutAValidWindowReturnFalse() + { + using var taskbar = new TaskbarProgress(); + Assert.False(taskbar.SetState(0, TaskbarProgressState.Normal)); + Assert.False(taskbar.SetValue(0, 1, 2)); + Assert.False(taskbar.SetState(StaleWindow, TaskbarProgressState.Indeterminate)); + Assert.False(taskbar.SetValue(StaleWindow, 1, 2)); + taskbar.Dispose(); + Assert.False(taskbar.IsAvailable); + Assert.False(taskbar.SetValue(StaleWindow, 1, 2)); + } +}