Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ The window is view glue. Logic lives in plain classes that the tests drive with

1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate. With `--link-helper` it runs the hidden elevated helper instead (see "Administrator rights").
2. **App.xaml / App.xaml.cs**: Loads MahApps.Metro styles and syncs the theme (light/dark and accent color) with Windows.
3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, and a footer with the About button, an inline error line and the Create link button. Styles live in `Window.Resources`.
3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, and a footer with the About and settings buttons, an inline error line and the Create link button. Styles live in `Window.Resources`.
4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop. Hands link creation to `LinkCreator`.
5. **MainWindow.Inputs.cs**: Inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, and the up-front admin notice.
6. **Elevation.cs**: `LaunchOptions` (command-line parsing) and `Elevation` (admin check, symbolic link privilege probe, the UAC shield icon).
Expand All @@ -92,6 +92,7 @@ The window is view glue. Logic lives in plain classes that the tests drive with
12. **InputValidator.cs**: Field checks behind the inline errors, and `ColorContrast` for text on the accent color.
13. **Dialogs.cs**: `IDialogService` / `IProgressDialog`, and `MetroDialogService`, which shows them in the window.
14. **UiHelpers.cs**: Path name extraction, picker start folders, byte formatting, app version, `LinkNameAutoFill`.
15. **ExplorerMenu.cs**: The optional Explorer right-click entries (see "Explorer menu" below).

### Link Creation Flow

Expand All @@ -111,6 +112,15 @@ The window is view glue. Logic lives in plain classes that the tests drive with
- Both ends check the other's process ID on the pipe (`GetNamedPipeClientProcessId` / `GetNamedPipeServerProcessId`), and `LinkCommand` rejects paths with quotes or line breaks, so the helper only ever runs a single mklink.
- Command-line options (`--mode`, `--type`, `--location`, `--name`, `--target`) still prefill the form. The old `--engage` flag is still accepted and ignored.

### Explorer menu

- The settings button (cog, next to About) has one checkable item that adds or removes the Explorer right-click entries. Off by default.
- `ExplorerMenu` writes classic shell verbs under `HKCU\Software\Classes` (no admin): "Create link to this" on files (`*\shell`) and folders (`Directory\shell`), starting Symlinker with `--mode file|folder --target "%1"`, and "Create link here" on folders and a folder's background (`Directory\Background\shell`), with `--location "%1"` or `"%V"`. Verb keys are `Symlinker.LinkTo` and `Symlinker.LinkHere`, with `MultiSelectModel=Single` and the exe's icon.
- The path is the last argument on purpose: Explorer passes a drive root as `"C:\"`, which Windows splits into `C:"`. `LaunchOptions.Parse` turns a trailing quote on `--location`/`--target` back into a backslash.
- On every start, `ExplorerMenu.Refresh()` rewrites the entries when they are on but point at another exe (ClickOnce installs each update in a new folder) or use other menu text (the Windows language changed).
- Hidden in the Store build (`Elevation.IsPackaged()`): registry writes of a packaged app are virtualized, so Explorer would never see them. A Store version would need a `desktop4:FileExplorerContextMenus` entry backed by an `IExplorerCommand` COM handler.
- Tests point `ExplorerMenu` at a throwaway `HKCU\Software\SymlinkerTests\<guid>` key instead of `Software\Classes`.

### Important Patterns

- **Command building**: mklink flags are `/D` (directory symlink), `/H` (hard link), `/J` (junction); paths are wrapped in quotes.
Expand Down Expand Up @@ -144,6 +154,7 @@ Symlinker/
│ ├── InputValidator.cs # Field checks, accent contrast
│ ├── Dialogs.cs # Dialog abstraction + MahApps implementation
│ ├── UiHelpers.cs # Small UI helpers
│ ├── ExplorerMenu.cs # Explorer right-click entries
│ ├── Program.cs # Entry point
│ ├── Properties/
│ │ ├── Resources.resx # English strings
Expand Down Expand Up @@ -179,6 +190,7 @@ Before tagging, update `ReleaseNotes` in `listings.json` for every language and

- **Drag and drop**: Works because the window always runs unelevated. It does not work if the user starts Symlinker as administrator themselves, because Windows blocks drops from a lower-privilege Explorer.
- **Store version, moving into AppData**: the Microsoft Store version can't move existing files into a target under `AppData` (see "Publishing (Microsoft Store / MSIX)"). Linking there without moving works.
- **Explorer menu**: on Windows 11 the entries are under "Show more options" (classic verbs). Not available in the Store version. Uninstalling the ClickOnce or portable version leaves the entries behind, pointing at a missing exe; turn them off first.
- **Platform**: Windows 10/11 only.

## Localization
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ scoop install extras/symlinker
- Create **symbolic links**, **hard links**, and **directory junctions** with a few clicks
- Supports both file and folder link types
- Drag and drop paths directly into the application
- Optional Explorer right-click entries ("Create link to this" and "Create link here") that open Symlinker with the form filled in. Turn them on from the settings button next to About. On Windows 11 they are under "Show more options". Not available in the Microsoft Store version
- Automatic UAC elevation (administrator privileges required for symlink creation)
- Automatic updates through the Microsoft Store or ClickOnce
- Light and dark mode support — syncs with your Windows theme and accent color
Expand Down
26 changes: 26 additions & 0 deletions Symlinker.Tests/ElevationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,32 @@ public void Parse_IgnoresUnknownAndIncompleteArguments()
Assert.Null(options.Mode);
}

[Theory]
[InlineData(@"Symlinker.exe --location ""C:\""", @"C:\")]
[InlineData(@"Symlinker.exe --location ""D:\My Links""", @"D:\My Links")]
public void Parse_ReadsTheLocationAsExplorerPassesIt(string commandLine, string expected)
{
// Explorer passes a drive root as "C:\", which Windows splits into C:"
Assert.Equal(expected, LaunchOptions.Parse(CommandLine.Split(commandLine)[1..]).LinkLocation);
}

[Fact]
public void Parse_RestoresTheBackslashOfATarget()
{
var options = LaunchOptions.Parse(CommandLine.Split(@"Symlinker.exe --mode folder --target ""E:\""")[1..]);

Assert.Equal(@"E:\", options.Target);
Assert.Equal("folder", options.Mode);
}

[Fact]
public void Parse_KeepsPathsWithSpaces()
{
var options = LaunchOptions.Parse(CommandLine.Split(@"Symlinker.exe --mode file --target ""D:\My Data\a b.txt""")[1..]);

Assert.Equal(@"D:\My Data\a b.txt", options.Target);
}

[Theory]
[InlineData("folder", true)]
[InlineData("FOLDER", true)]
Expand Down
239 changes: 239 additions & 0 deletions Symlinker.Tests/ExplorerMenuTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
namespace Symlinker.Tests
{
using System;
using System.Linq;

using Microsoft.Win32;

/// <summary>
/// Registers the Explorer entries under a throwaway HKCU\Software\SymlinkerTests\... key
/// instead of HKCU\Software\Classes, so Explorer never sees them.
/// </summary>
public sealed class ExplorerMenuTests : IDisposable
{
private const string ExePath = @"C:\Program Files\Symlinker\Symlinker.exe";
private const string TestsKey = @"Software\SymlinkerTests";

private readonly string classesPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");

public void Dispose()
{
Registry.CurrentUser.DeleteSubKeyTree(classesPath, throwOnMissingSubKey: false);

// Remove the parent too once the last test is done with it
try
{
Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
}
catch (InvalidOperationException)
{
// Another test still has its key in there
}
}

[Fact]
public void IsOff_ByDefault()
{
var menu = Menu();

Assert.False(menu.IsEnabled);
Assert.False(menu.IsCurrent);
}

[Fact]
public void Enable_WritesEveryEntry()
{
var menu = Menu();

menu.Enable();

Assert.True(menu.IsEnabled);
Assert.True(menu.IsCurrent);

using var file = Open(@"*\shell\Symlinker.LinkTo");
Assert.Equal("Link to", file.GetValue("MUIVerb"));
Assert.Equal($"\"{ExePath}\",0", file.GetValue("Icon"));
Assert.Equal("Single", file.GetValue("MultiSelectModel"));
Assert.Equal($"\"{ExePath}\" --mode file --target \"%1\"", Command(@"*\shell\Symlinker.LinkTo"));

using var folder = Open(@"Directory\shell\Symlinker.LinkTo");
Assert.Equal("Link to", folder.GetValue("MUIVerb"));
Assert.Equal($"\"{ExePath}\" --mode folder --target \"%1\"", Command(@"Directory\shell\Symlinker.LinkTo"));

using var here = Open(@"Directory\shell\Symlinker.LinkHere");
Assert.Equal("Link here", here.GetValue("MUIVerb"));
Assert.Equal($"\"{ExePath}\" --location \"%1\"", Command(@"Directory\shell\Symlinker.LinkHere"));

using var background = Open(@"Directory\Background\shell\Symlinker.LinkHere");
Assert.Equal("Link here", background.GetValue("MUIVerb"));
Assert.Equal($"\"{ExePath}\" --location \"%V\"", Command(@"Directory\Background\shell\Symlinker.LinkHere"));
}

[Fact]
public void Commands_ReachTheWindowAsLaunchOptions()
{
// What Windows passes to Main for each command, with Explorer's placeholders filled in
var entries = Menu().Entries;
var toFile = Arguments(entries[0].Command.Replace("%1", @"D:\My Data\notes.txt"));
var toFolder = Arguments(entries[1].Command.Replace("%1", @"D:\My Data"));
var hereOnRoot = Arguments(entries[3].Command.Replace("%V", @"C:\"));

Assert.Equal(false, LaunchOptions.Parse(toFile).IsFolderMode);
Assert.Equal(@"D:\My Data\notes.txt", LaunchOptions.Parse(toFile).Target);
Assert.Equal(true, LaunchOptions.Parse(toFolder).IsFolderMode);
Assert.Equal(@"D:\My Data", LaunchOptions.Parse(toFolder).Target);
Assert.Equal(@"C:\", LaunchOptions.Parse(hereOnRoot).LinkLocation);
}

[Fact]
public void Disable_RemovesEveryEntry_AndLeavesOtherVerbs()
{
using (var other = Registry.CurrentUser.CreateSubKey(classesPath + @"\Directory\shell\SomethingElse"))
other.SetValue("MUIVerb", "Other app");

var menu = Menu();
menu.Enable();
menu.Disable();

Assert.False(menu.IsEnabled);
Assert.Null(Open(@"*\shell\Symlinker.LinkTo"));
Assert.Null(Open(@"Directory\Background\shell\Symlinker.LinkHere"));
Assert.NotNull(Open(@"Directory\shell\SomethingElse"));
}

[Fact]
public void Disable_WhenAlreadyOff_DoesNothing()
{
Menu().Disable();

Assert.False(Menu().IsEnabled);
}

[Fact]
public void TrySetEnabled_TurnsTheEntriesOnAndOff()
{
var menu = Menu();

Assert.Null(menu.TrySetEnabled(true));
Assert.True(menu.IsEnabled);

Assert.Null(menu.TrySetEnabled(false));
Assert.False(menu.IsEnabled);
}

[Fact]
public void TrySetEnabled_ReportsRegistryErrors()
{
Registry.CurrentUser.CreateSubKey(classesPath).Dispose();
using var readOnly = Registry.CurrentUser.OpenSubKey(classesPath, writable: false);
var menu = new ExplorerMenu(readOnly, @"Classes", ExePath, "Link to", "Link here");

Assert.False(string.IsNullOrEmpty(menu.TrySetEnabled(true)));
}

[Fact]
public void Refresh_WhenOff_LeavesItOff()
{
var menu = Menu();

Assert.False(menu.Refresh());
Assert.False(menu.IsEnabled);
}

[Fact]
public void Refresh_WhenCurrent_DoesNothing()
{
var menu = Menu();
menu.Enable();

Assert.False(menu.Refresh());
}

[Fact]
public void Refresh_AfterAnUpdate_PointsTheEntriesAtTheNewExe()
{
Menu(@"C:\Users\me\AppData\Local\Apps\2.0\old\Symlinker.exe").Enable();
var current = Menu();

Assert.True(current.IsEnabled);
Assert.False(current.IsCurrent);
Assert.True(current.Refresh());
Assert.True(current.IsCurrent);
Assert.StartsWith($"\"{ExePath}\"", Command(@"*\shell\Symlinker.LinkTo"));
}

[Fact]
public void Refresh_AfterALanguageChange_RewritesTheText()
{
Menu().Enable();
var german = new ExplorerMenu(Registry.CurrentUser, classesPath, ExePath, "Link hierauf erstellen", "Link hier erstellen");

Assert.True(german.Refresh());
using var key = Open(@"Directory\shell\Symlinker.LinkHere");
Assert.Equal("Link hier erstellen", key.GetValue("MUIVerb"));
}

[Fact]
public void Refresh_RestoresAMissingEntry()
{
var menu = Menu();
menu.Enable();
Registry.CurrentUser.DeleteSubKeyTree(classesPath + @"\*\shell\Symlinker.LinkTo");

Assert.True(menu.IsEnabled);
Assert.True(menu.Refresh());
Assert.NotNull(Open(@"*\shell\Symlinker.LinkTo"));
}

[Fact]
public void Refresh_TreatsAnEntryWithoutCommandAsStale()
{
var menu = Menu();
menu.Enable();
Registry.CurrentUser.DeleteSubKeyTree(classesPath + @"\*\shell\Symlinker.LinkTo\command");

Assert.False(menu.IsCurrent);
Assert.True(menu.Refresh());
Assert.True(menu.IsCurrent);
}

[Fact]
public void Refresh_SwallowsRegistryErrors()
{
Menu(@"D:\old\Symlinker.exe").Enable();
using var readOnly = Registry.CurrentUser.OpenSubKey(TestsKey, writable: false);
var menu = new ExplorerMenu(readOnly, classesPath[(TestsKey.Length + 1)..], ExePath, "Link to", "Link here");

Assert.True(menu.IsEnabled);
Assert.False(menu.Refresh());
}

[Fact]
public void ForCurrentUser_UsesTheUserClassesKeyAndTheAppStrings()
{
var menu = ExplorerMenu.ForCurrentUser(ExePath);

Assert.Equal(Properties.Resources.ExplorerMenuLinkTo, menu.Entries[0].Label);
Assert.Equal(Properties.Resources.ExplorerMenuLinkHere, menu.Entries[3].Label);

// Only reads the real registry; whatever is there, the answer is a plain bool
Assert.IsType<bool>(menu.IsEnabled);
Assert.Equal(@"Software\Classes", ExplorerMenu.UserClassesPath);
}

private ExplorerMenu Menu(string exePath = ExePath) =>
new(Registry.CurrentUser, classesPath, exePath, "Link to", "Link here");

private RegistryKey Open(string keyPath) => Registry.CurrentUser.OpenSubKey(classesPath + "\\" + keyPath);

private string Command(string keyPath)
{
using var key = Open(keyPath + @"\command");
return (string)key.GetValue(string.Empty);
}

/// <summary>Splits a command line the way Windows does for Main, dropping the exe.</summary>
private static string[] Arguments(string commandLine) =>
CommandLine.Split(commandLine).Skip(1).ToArray();
}
}
26 changes: 26 additions & 0 deletions Symlinker.Tests/TestSupport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,30 @@ public Task<LinkResult> CreateLinkAsync(LinkRequest request)

public void Dispose() => Disposed = true;
}

/// <summary>Splits a command line into arguments the way Windows does (CommandLineToArgvW).</summary>
internal static class CommandLine
{
public static string[] Split(string commandLine)
{
var argv = CommandLineToArgvW(commandLine, out var count);
try
{
var args = new string[count];
for (var i = 0; i < count; i++)
args[i] = System.Runtime.InteropServices.Marshal.PtrToStringUni(System.Runtime.InteropServices.Marshal.ReadIntPtr(argv, i * IntPtr.Size));
return args;
}
finally
{
LocalFree(argv);
}
}

[System.Runtime.InteropServices.DllImport("shell32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern IntPtr CommandLineToArgvW(string commandLine, out int count);

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr memory);
}
}
12 changes: 10 additions & 2 deletions Symlinker/Elevation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ public static LaunchOptions Parse(string[] args)
{
case ModeArg: options.Mode = value; break;
case TypeArg: options.LinkType = value; break;
case LocationArg: options.LinkLocation = value; break;
case LocationArg: options.LinkLocation = FixQuotedPath(value); break;
case NameArg: options.LinkName = value; break;
case TargetArg: options.Target = value; break;
case TargetArg: options.Target = FixQuotedPath(value); break;
default: continue;
}

Expand All @@ -62,6 +62,14 @@ public static LaunchOptions Parse(string[] args)

return options;
}

/// <summary>
/// Windows reads a backslash right before a closing quote as an escaped quote, so a drive
/// root passed as "C:\" (Explorer does this for %V) arrives as C:" instead. Paths can't
/// contain quotes, so a trailing quote can only be that lost backslash.
/// </summary>
private static string FixQuotedPath(string value) =>
value.EndsWith('"') ? value[..^1] + "\\" : value;
}

/// <summary>
Expand Down
Loading
Loading