feat(windows): add shell launcher, taskbar progress and app paths

ShellLauncher opens only http(s) and ms-windows-store URLs and reveals files
(SHOpenFolderAndSelectItems) or folders ("explore") on an STA. TaskbarProgress
wraps ITaskbarList3 and returns false for null or stale windows. KnownFolders
reads LocalAppData/Pictures via SHGetKnownFolderPath. AppPaths resolves the
data root (%LOCALAPPDATA%\Titano or .\data in portable mode) and refuses to
create it inside a OneDrive sync root (environment variables and
HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:46:10 +00:00
1 parent 0e6c15cb13
commit 2b37f486e2
8 files changed
+508

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
namespace Titano.Core.Windows.Shell;
/// <summary>
/// Where the desktop programs keep their data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is
/// reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
/// </summary>
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");
/// <summary>The OneDrive sync root containing <see cref="DataRoot"/>, or null when the location is safe.</summary>
public string? SyncedFolder { get; }
public bool IsInSyncedFolder => SyncedFolder is not null;
/// <summary>Paths for this process: the executable's folder decides portable mode.</summary>
public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData);
/// <summary>Paths for an executable in <paramref name="applicationDirectory"/>, checked against the user's OneDrive roots.</summary>
public static AppPaths Resolve(string applicationDirectory, string localAppData) =>
Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots());
internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList<string> 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));
}
/// <summary>Creates the data, logs, cache and thumbnails folders.</summary>
/// <exception cref="InvalidOperationException">The data root lies inside a OneDrive-synced folder.</exception>
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);
}
}
@@ -0,0 +1,38 @@
using System.Runtime.InteropServices;
namespace Titano.Core.Windows.Shell;
/// <summary>Known folder paths through SHGetKnownFolderPath (honours folder redirection).</summary>
public static partial class KnownFolders
{
/// <summary>FOLDERID_LocalAppData.</summary>
public static readonly Guid LocalAppDataId = new("f1b32785-6fba-4fcf-9d55-7b8e7f157091");
/// <summary>FOLDERID_Pictures.</summary>
public static readonly Guid PicturesId = new("33e28130-4e1e-4676-835a-98395c3bc3bb");
/// <summary>%LOCALAPPDATA% (never synced by OneDrive).</summary>
public static string LocalAppData => GetPath(LocalAppDataId);
/// <summary>The user's Pictures folder (may be redirected into OneDrive).</summary>
public static string Pictures => GetPath(PicturesId);
/// <exception cref="COMException">The folder does not exist or is not available to this user.</exception>
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);
}
@@ -0,0 +1,48 @@
using Microsoft.Win32;
namespace Titano.Core.Windows.Shell;
/// <summary>Folders synchronised by OneDrive for the current user (personal and work/school accounts).</summary>
public static class OneDriveFolders
{
private const string AccountsKey = @"Software\Microsoft\OneDrive\Accounts";
private static readonly string[] EnvironmentVariables = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"];
/// <summary>
/// Sync roots from the OneDrive environment variables and <c>HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder</c>,
/// as full paths without a trailing separator, distinct (case-insensitive).
/// </summary>
public static IReadOnlyList<string> SyncRoots()
{
var roots = new List<string>();
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;
}
/// <summary>The sync root that contains <paramref name="path"/>, or null. Both are expected to be full paths.</summary>
public static string? Containing(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
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<string> 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);
}
}
@@ -0,0 +1,10 @@
namespace Titano.Core.Windows.Shell;
/// <summary>Portable mode (BRIEF §6.2): a <c>portable.txt</c> next to the executable keeps all data under <c>.\data\</c>.</summary>
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));
}
@@ -0,0 +1,132 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
namespace Titano.Core.Windows.Shell;
/// <summary>
/// The only shell verbs Titano may invoke (BRIEF §8.6): <c>open</c> for web and Microsoft Store links and
/// <c>explore</c>/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).
/// </summary>
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;
/// <summary>True for absolute http, https and ms-windows-store URLs, the only links handed to the shell.</summary>
public static bool IsAllowedUrl(string url) =>
Uri.TryCreate(url, UriKind.Absolute, out var uri)
&& AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase);
/// <summary>Opens the URL with ShellExecuteEx("open"); false when the shell could not open it.</summary>
/// <exception cref="ArgumentException">The URL is not an absolute http, https or ms-windows-store URL.</exception>
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));
}
/// <summary>
/// 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.
/// </summary>
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<bool> 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;
}
/// <summary>SHELLEXECUTEINFOW (112 bytes on x64).</summary>
[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);
}
@@ -0,0 +1,84 @@
using System.Runtime.InteropServices;
using Titano.Core.Windows.Interop;
namespace Titano.Core.Windows.Shell;
/// <summary>TBPFLAG: the taskbar button progress style.</summary>
public enum TaskbarProgressState
{
None = 0x0,
Indeterminate = 0x1,
Normal = 0x2,
Error = 0x4,
Paused = 0x8,
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>False when no taskbar is available (e.g. a session without Explorer).</summary>
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;
/// <summary>Sets the bar to <paramref name="completed"/>/<paramref name="total"/> (switches to <see cref="TaskbarProgressState.Normal"/> if no progress was shown).</summary>
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;
}
}
/// <summary>ITaskbarList3 (ITaskbarList → ITaskbarList2 → ITaskbarList3), declared up to SetProgressState.</summary>
[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);
}
@@ -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<string?>(oneDrive, paths.SyncedFolder);
Assert.Throws<InvalidOperationException>(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));
}
}
@@ -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<ArgumentException>(() => 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));
}
}