diff --git a/CLAUDE.md b/CLAUDE.md
index 64068fd..cf24af4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -78,20 +78,21 @@ 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`.
-4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop. Hands link creation to `LinkCreator`.
+3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, the batch list (hidden for a single link), and a footer with the About and Add another buttons, an inline error line and the Create link button. Styles live in `Window.Resources`.
+4. **MainWindow.xaml.cs**: Mode switching, file pickers, drag and drop, and the batch list. The cards edit `LinkBatch.Selected`. 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).
-7. **LinkCreator.cs**: The link workflow: replace-existing prompts, and moving an existing file or folder to the target (rename on the same drive, copy with progress across drives, rollback on failure).
-8. **LinkRunner.cs**: `ILinkRunner`, which `LinkCreator` uses to create links. `LinkRunner` runs mklink unelevated, except symbolic links that need admin, which go through the elevated helper. `PrepareAsync()` starts the helper (one UAC prompt) before anything on disk changes.
-9. **LinkCommand.cs**: `LinkKind`, `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used unelevated and by the elevated helper. Success comes from the exit code plus `LinkCheck.IsCreated()` on disk, never from mklink's text (it is in the language of Windows). A failure carries a `LinkError` code from `LinkCheck.Diagnose()`, which travels over the helper's pipe as a number.
+7. **LinkCreator.cs**: The link workflow, for one link (`CreateAsync`) or a batch (`CreateBatchAsync`): replace-existing prompts, and moving an existing file or folder to the target (rename on the same drive, copy with progress across drives, rollback on failure). Each link is planned first (`LinkPlan`: questions asked, nothing on disk changed), then carried out, giving a `LinkOutcome`.
+8. **LinkBatch.cs**: `LinkRow` (one link: location, name, target, its own name auto-fill and errors) and `LinkBatch` (the rows, the selected one, the shortcuts for adding rows, and batch validation including duplicate link paths).
+9. **LinkRunner.cs**: `ILinkRunner`, which `LinkCreator` uses to create links. `LinkRunner` runs mklink unelevated, except symbolic links that need admin, which go through the elevated helper. `PrepareAsync()` starts the helper (one UAC prompt) before anything on disk changes.
+10. **LinkCommand.cs**: `LinkKind`, `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used unelevated and by the elevated helper. Success comes from the exit code plus `LinkCheck.IsCreated()` on disk, never from mklink's text (it is in the language of Windows). A failure carries a `LinkError` code from `LinkCheck.Diagnose()`, which travels over the helper's pipe as a number.
- **LinkCheck.cs**: checks on disk that a link exists and leads to its target, and works out why mklink failed (link path taken, hard link across drives, junction to a network folder, no symbolic link privilege, folder access denied).
- **LinkResultMessage.cs**: turns a request and its `LinkResult` into the localized dialog title and text. `Reason()` gives one failure line, for reuse in a list of results. Long paths are shortened in the middle (`CompactPath`).
-10. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe. `RunHelper()` is the helper's side.
-11. **LinkMover.cs**: File system helpers for moving: copy that keeps attributes and recreates nested links, delete that never follows links.
-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`.
+11. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe. `RunHelper()` is the helper's side.
+12. **LinkMover.cs**: File system helpers for moving: copy that keeps attributes and recreates nested links, delete that never follows links.
+13. **InputValidator.cs**: Field checks behind the inline errors, and `ColorContrast` for text on the accent color.
+14. **Dialogs.cs**: `IDialogService` / `IProgressDialog`, and `MetroDialogService`, which shows them in the window.
+15. **UiHelpers.cs**: Path name extraction, picker start folders, byte formatting, app version, `LinkNameAutoFill`.
### Link Creation Flow
@@ -101,6 +102,16 @@ The window is view glue. Logic lives in plain classes that the tests drive with
4. `RefreshSymlinkAccessNow()` probes again whether a symbolic link needs administrator rights.
5. `LinkCreator.CreateAsync()` handles an existing item at the link path (replace it, or move it to the target), then runs mklink and shows the result through `LinkResultMessage`. `ILinkRunner.PrepareAsync()` is called before the first change on disk.
+### Several links at once (batch)
+
+- **Add another** (footer) adds a row and turns the form into a list. With one row the window looks and behaves exactly like a single link. Removing rows back down to one returns to that view.
+- The cards edit the selected row; the list shows every row on one line (`folder\name -> folder\target`, the names never cut off) with a remove button. Click a row to edit it, Delete removes it.
+- Shortcuts: a new row starts in the last row's link location, and its target picker opens next to the nearest target above it. Picking several targets (multi-select) or dropping several items on the target card fills the selected row and adds a row for each other one. Picking or dropping a link location also moves the rows that shared the old one (or had none).
+- One mode and link type (the pills) for the whole batch. In batch mode, switching mode keeps every target; ones that don't fit are flagged on Create.
+- Create validates every row (`LinkBatch.Validate`: `InputValidator` plus duplicate link paths), marks bad rows in the list and selects the first one. The footer shows the selected row's error, or a pointer to the marked rows.
+- `LinkCreator.CreateBatchAsync()` asks every replace/move question first (each prefixed with its link path), then calls `PrepareAsync()` once (at most one UAC prompt), then creates each link, continuing past failures. One summary dialog lists what was created and what wasn't, and why (declined questions count as skipped). Links in the batch's main folder are listed by name, others by full path. Each failure line is `LinkResultMessage.Reason()`.
+- After a batch with failures, the created rows are removed so only the rest are left to fix. When all were created, the list stays.
+
### Administrator rights
- Junctions and hard links never need admin. Symbolic links need admin unless Windows Developer Mode is on.
@@ -134,7 +145,8 @@ Symlinker/
│ ├── MainWindow.xaml.cs # Window glue
│ ├── MainWindow.Inputs.cs # Inline errors, admin notice
│ ├── Elevation.cs # LaunchOptions, symlink probe, UAC shield
-│ ├── LinkCreator.cs # Link workflow
+│ ├── LinkCreator.cs # Link workflow (single and batch)
+│ ├── LinkBatch.cs # Batch rows, shortcuts, validation
│ ├── LinkRunner.cs # Unelevated or elevated mklink
│ ├── LinkCommand.cs # Runs mklink
│ ├── LinkCheck.cs # Verifies links on disk, diagnoses failures
@@ -185,4 +197,4 @@ Before tagging, update `ReleaseNotes` in `listings.json` for every language and
- Every UI string lives in `Properties/Resources.resx` and must also be added to all 8 translations (de, es, fr, hi, it, ja, pt, zh).
- `Resources.Designer.cs` is not regenerated by `dotnet build`. When adding a string, add its typed property by hand in the same generated style.
-- The window is a fixed 560x280, so check long translations (German, Italian, French) for overflow in pills, buttons and dialogs.
+- The window is 560x280 for a single link. In batch mode it grows by 30 px per row up to 5 rows, then the list scrolls (back to 280 when one row is left). Check long translations (German, Italian, French) for overflow in pills, buttons, the footer and dialogs.
diff --git a/README.md b/README.md
index 9185ae0..2504b6e 100644
--- a/README.md
+++ b/README.md
@@ -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
+- Create several links in one step: **Add another** turns the form into a list, and picking or dropping several targets at once adds a link for each
- 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
diff --git a/Symlinker.Tests/LinkBatchTests.cs b/Symlinker.Tests/LinkBatchTests.cs
new file mode 100644
index 0000000..1bf404c
--- /dev/null
+++ b/Symlinker.Tests/LinkBatchTests.cs
@@ -0,0 +1,397 @@
+namespace Symlinker.Tests
+{
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Linq;
+
+ using Res = Symlinker.Properties.Resources;
+
+ /// The list of links behind batch mode, and each row's display and auto-filled name.
+ public sealed class LinkBatchTests : IDisposable
+ {
+ private readonly TempDir temp = new();
+ private readonly LinkBatch batch = new();
+
+ public void Dispose() => temp.Dispose();
+
+ private static LinkRow Row(string location, string name, string target)
+ {
+ var row = new LinkRow { LinkLocation = location, LinkName = name };
+ row.SetTarget(target);
+ return row;
+ }
+
+ // ---- LinkRow ----
+
+ [Fact]
+ public void Row_StartsEmpty()
+ {
+ var row = new LinkRow();
+
+ Assert.Equal((string.Empty, string.Empty, string.Empty), (row.LinkLocation, row.LinkName, row.Target));
+ Assert.Equal((string.Empty, string.Empty, string.Empty, string.Empty), (row.LinkPath, row.LinkFolder, row.TargetFolder, row.TargetName));
+ Assert.False(row.HasError);
+ Assert.Null(row.ErrorText);
+ Assert.Empty(row.Errors);
+ }
+
+ [Fact]
+ public void Row_TreatsNullAsEmpty()
+ {
+ var row = new LinkRow { LinkLocation = null, LinkName = null };
+ row.SetTarget(null);
+
+ Assert.Equal((string.Empty, string.Empty, string.Empty), (row.LinkLocation, row.LinkName, row.Target));
+ }
+
+ [Theory]
+ [InlineData(@"C:\links", "name", @"C:\links\", @"C:\links\name")]
+ [InlineData(@" C:\links\ ", " name ", @"C:\links\", @"C:\links\name")]
+ [InlineData(@"D:\", "name", @"D:\", @"D:\name")]
+ [InlineData("", "name", "", "name")]
+ public void Row_ShowsTheLinkPath(string location, string name, string folder, string path)
+ {
+ var row = new LinkRow { LinkLocation = location, LinkName = name };
+
+ Assert.Equal((folder, path), (row.LinkFolder, row.LinkPath));
+ }
+
+ [Theory]
+ [InlineData(@"C:\data\Photos", @"C:\data\", "Photos")]
+ [InlineData(@"C:\data\Photos\", @"C:\data\", "Photos")]
+ [InlineData(@"D:\", "", "D:")]
+ [InlineData("Photos", "", "Photos")]
+ public void Row_SplitsTheTarget(string target, string folder, string name)
+ {
+ var row = Row(string.Empty, string.Empty, target);
+
+ Assert.Equal((folder, name), (row.TargetFolder, row.TargetName));
+ }
+
+ [Fact]
+ public void Row_FillsInTheNameFromTheTarget_UntilTheUserTypesOne()
+ {
+ var row = new LinkRow();
+
+ row.SetTarget(@"C:\data\Photos");
+ Assert.Equal("Photos", row.LinkName);
+
+ row.SetTarget(@"C:\data\Music");
+ Assert.Equal("Music", row.LinkName);
+
+ row.LinkName = "Tunes";
+ row.SetTarget(@"C:\data\Videos");
+ Assert.Equal("Tunes", row.LinkName);
+ Assert.Equal(@"C:\data\Videos", row.Target);
+ }
+
+ [Fact]
+ public void Row_AutoFill_IsPerRow()
+ {
+ var first = new LinkRow();
+ var second = new LinkRow();
+
+ first.SetTarget(@"C:\data\Photos");
+ second.SetTarget(@"C:\data\Photos");
+ first.LinkName = "Typed";
+ second.SetTarget(@"C:\data\Music");
+
+ Assert.Equal(("Typed", "Music"), (first.LinkName, second.LinkName));
+ }
+
+ [Fact]
+ public void Row_RaisesChanges_OnlyWhenAValueChanges()
+ {
+ var row = new LinkRow();
+ var raised = new List();
+ row.PropertyChanged += (s, e) => raised.Add(e.PropertyName);
+
+ row.LinkLocation = @"C:\links";
+ row.LinkLocation = @"C:\links";
+ row.LinkName = "name";
+ row.SetTarget(@"C:\data\target");
+
+ // Location, name, then target (whose auto-filled name is skipped: the user's name stays)
+ Assert.Equal(3, raised.Count);
+ Assert.All(raised, name => Assert.Equal(string.Empty, name));
+ }
+
+ [Fact]
+ public void Row_Errors_AreSetAndClearedPerField()
+ {
+ var row = new LinkRow();
+ var raised = 0;
+ row.PropertyChanged += (s, e) => raised++;
+
+ row.SetErrors(new[] { (InputField.LinkName, "name"), (InputField.Target, "target") });
+ Assert.True(row.HasError);
+ Assert.Equal("name", row.ErrorText);
+
+ row.ClearError(InputField.LinkLocation);
+ Assert.Equal(2, row.Errors.Count);
+
+ row.ClearError(InputField.LinkName);
+ Assert.Equal("target", row.ErrorText);
+
+ Assert.Equal(2, raised);
+ }
+
+ [Fact]
+ public void Row_ToInput_CarriesTheModeAndKind()
+ {
+ var row = Row(@"C:\links", "name", @"C:\data\target");
+
+ Assert.Equal(new LinkInput(@"C:\links", "name", @"C:\data\target", false, LinkKind.Hard), row.ToInput(false, LinkKind.Hard));
+ }
+
+ // ---- Adding and removing rows ----
+
+ [Fact]
+ public void Batch_StartsWithOneSelectedRow()
+ {
+ Assert.Same(batch.Selected, Assert.Single(batch.Rows));
+ Assert.False(batch.IsBatch);
+ }
+
+ [Fact]
+ public void Add_StartsInTheLastRowsLinkLocation_AndSelectsIt()
+ {
+ batch.Selected.LinkLocation = @"C:\first";
+ batch.Rows.Add(new LinkRow { LinkLocation = @"C:\last" });
+
+ var row = batch.Add();
+
+ Assert.Same(row, batch.Rows[^1]);
+ Assert.Same(row, batch.Selected);
+ Assert.Equal(@"C:\last", row.LinkLocation);
+ Assert.Equal((string.Empty, string.Empty), (row.LinkName, row.Target));
+ Assert.True(batch.IsBatch);
+ }
+
+ [Fact]
+ public void Remove_KeepsTheLastRow()
+ {
+ var only = batch.Selected;
+
+ batch.Remove(only);
+
+ Assert.Same(only, Assert.Single(batch.Rows));
+ }
+
+ [Fact]
+ public void Remove_IgnoresARowNotInTheList()
+ {
+ batch.Add();
+
+ batch.Remove(new LinkRow());
+
+ Assert.Equal(2, batch.Rows.Count);
+ }
+
+ [Fact]
+ public void Remove_MovesTheSelectionToTheNextRow_OrThePreviousAtTheEnd()
+ {
+ var first = batch.Selected;
+ var second = batch.Add();
+ var third = batch.Add();
+
+ batch.Selected = second;
+ batch.Remove(second);
+ Assert.Same(third, batch.Selected);
+
+ batch.Remove(third);
+ Assert.Same(first, batch.Selected);
+ Assert.False(batch.IsBatch);
+ }
+
+ [Fact]
+ public void Remove_KeepsTheSelection_WhenAnotherRowGoes()
+ {
+ var first = batch.Selected;
+ var second = batch.Add();
+
+ batch.Remove(first);
+
+ Assert.Same(second, batch.Selected);
+ Assert.Same(second, Assert.Single(batch.Rows));
+ }
+
+ // ---- Several targets at once ----
+
+ [Fact]
+ public void AddTargets_DoesNothing_WithNoTargets()
+ {
+ batch.AddTargets(Array.Empty());
+
+ Assert.Single(batch.Rows);
+ Assert.Equal(string.Empty, batch.Selected.Target);
+ }
+
+ [Fact]
+ public void AddTargets_FillsTheSelectedRow_ThenAddsARowForEachOther()
+ {
+ var first = batch.Selected;
+ first.LinkLocation = @"C:\FolderB";
+ var last = batch.Add();
+ batch.Selected = first;
+
+ batch.AddTargets(new[] { @"C:\FolderA\One", @"C:\FolderA\Two", @"C:\FolderA\Three" });
+
+ Assert.Equal(
+ new[] { (@"C:\FolderB", "One", @"C:\FolderA\One"), (@"C:\FolderB", "Two", @"C:\FolderA\Two"), (@"C:\FolderB", "Three", @"C:\FolderA\Three"), (@"C:\FolderB", string.Empty, string.Empty) },
+ batch.Rows.Select(row => (row.LinkLocation, row.LinkName, row.Target)));
+ Assert.Same(first, batch.Selected);
+ Assert.Same(last, batch.Rows[^1]);
+ }
+
+ // ---- Link location ----
+
+ [Fact]
+ public void SetLocation_MovesTheRowsThatSharedIt_AndTheEmptyOnes()
+ {
+ var first = batch.Selected;
+ first.LinkLocation = @"C:\old";
+ var sameFolder = batch.Add();
+ var empty = batch.Add();
+ empty.LinkLocation = " ";
+ var other = batch.Add();
+ other.LinkLocation = @"C:\other";
+ batch.Selected = first;
+
+ batch.SetLocation(@"C:\new");
+
+ Assert.Equal(new[] { @"C:\new", @"C:\new", @"C:\new", @"C:\other" }, batch.Rows.Select(row => row.LinkLocation));
+ }
+
+ // ---- Where the target picker opens ----
+
+ [Fact]
+ public void TargetHint_IsTheRowsOwnTarget_ElseTheNearestOneAbove_ElseNull()
+ {
+ var first = batch.Selected;
+ Assert.Null(batch.TargetHint(first));
+
+ first.SetTarget(@"C:\data\one");
+ var second = batch.Add();
+ second.SetTarget(@"C:\data\two");
+ var third = batch.Add();
+ third.SetTarget(" ");
+
+ Assert.Equal(@"C:\data\two", batch.TargetHint(third));
+ Assert.Equal(@"C:\data\one", batch.TargetHint(first));
+ }
+
+ // ---- Validation ----
+
+ [Fact]
+ public void Validate_PassesGoodRows()
+ {
+ var location = temp.Dir("links");
+ batch.Selected.LinkLocation = location;
+ batch.Selected.SetTarget(temp.Dir("one"));
+ batch.Add().SetTarget(temp.Dir("two"));
+
+ Assert.True(batch.Validate(isFolder: true));
+ Assert.All(batch.Rows, row => Assert.False(row.HasError));
+ }
+
+ [Fact]
+ public void Validate_MarksEachBadRow()
+ {
+ var location = temp.Dir("links");
+ var file = temp.File("file.txt");
+ batch.Selected.LinkLocation = location;
+ batch.Selected.SetTarget(temp.Dir("good"));
+ var mismatch = batch.Add();
+ mismatch.SetTarget(file);
+ var missing = batch.Add();
+
+ Assert.False(batch.Validate(isFolder: true));
+
+ Assert.False(batch.Rows[0].HasError);
+ Assert.Equal(Res.ErrorTargetIsFile, mismatch.ErrorText);
+ Assert.Equal(Res.ErrorLinkNameMissing, missing.ErrorText);
+ }
+
+ [Fact]
+ public void Validate_MarksTheSecondRowCreatingTheSameLink()
+ {
+ var location = temp.Dir("links");
+ var target = temp.Dir("target");
+ batch.Selected.LinkLocation = location;
+ batch.Selected.SetTarget(target);
+ var duplicate = batch.Add();
+ duplicate.LinkLocation = location + "\\";
+ duplicate.SetTarget(temp.Dir("other", "TARGET"));
+ var otherFolder = batch.Add();
+ otherFolder.LinkLocation = temp.Dir("elsewhere");
+ otherFolder.SetTarget(target);
+
+ Assert.False(batch.Validate(isFolder: true));
+
+ Assert.False(batch.Rows[0].HasError);
+ Assert.Equal((InputField.LinkName, Res.ErrorDuplicateLinkPath), Assert.Single(duplicate.Errors));
+ Assert.False(otherFolder.HasError);
+ }
+
+ [Fact]
+ public void Validate_SkipsTheDuplicateCheck_ForRowsWithABadNameOrLocation()
+ {
+ var location = temp.Dir("links");
+ batch.Selected.LinkLocation = location;
+ batch.Selected.SetTarget(temp.Dir("target"));
+ var badName = batch.Add();
+ badName.LinkName = "bad|name";
+ badName.SetTarget(temp.Dir("target2"));
+
+ Assert.False(batch.Validate(isFolder: true));
+
+ Assert.Equal((InputField.LinkName, Res.ErrorLinkNameInvalid), Assert.Single(badName.Errors));
+ }
+
+ [Fact]
+ public void ClearErrors_ClearsEveryRow()
+ {
+ batch.Add();
+ batch.Validate(isFolder: true);
+
+ batch.ClearErrors();
+
+ Assert.All(batch.Rows, row => Assert.False(row.HasError));
+ }
+
+ // ---- After creating ----
+
+ [Fact]
+ public void RemoveCreated_KeepsEverything_WhenAllWereCreated()
+ {
+ batch.Add();
+ var rows = batch.Rows.ToList();
+ var created = new LinkOutcome(LinkStatus.Created, "t", "m");
+
+ batch.RemoveCreated(rows, new[] { created, created });
+
+ Assert.Equal(rows, batch.Rows);
+ }
+
+ [Fact]
+ public void RemoveCreated_LeavesOnlyTheLinksStillToDo()
+ {
+ var first = batch.Selected;
+ var second = batch.Add();
+ var third = batch.Add();
+ var rows = batch.Rows.ToList();
+
+ batch.RemoveCreated(rows, new[]
+ {
+ new LinkOutcome(LinkStatus.Created, "t", "m"),
+ new LinkOutcome(LinkStatus.Failed, "t", "m"),
+ new LinkOutcome(LinkStatus.Skipped, "t", "m"),
+ });
+
+ Assert.Equal(new[] { second, third }, batch.Rows);
+ Assert.DoesNotContain(first, batch.Rows);
+ }
+ }
+}
diff --git a/Symlinker.Tests/LinkCreatorBatchTests.cs b/Symlinker.Tests/LinkCreatorBatchTests.cs
new file mode 100644
index 0000000..b7489bf
--- /dev/null
+++ b/Symlinker.Tests/LinkCreatorBatchTests.cs
@@ -0,0 +1,256 @@
+namespace Symlinker.Tests
+{
+ using System;
+ using System.Globalization;
+ using System.IO;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+ using System.Threading.Tasks;
+
+ using Res = Symlinker.Properties.Resources;
+
+ ///
+ /// Creating several links in one step: every question first, administrator rights once,
+ /// failures don't stop the rest, and one summary at the end.
+ ///
+ public sealed class LinkCreatorBatchTests : IDisposable
+ {
+ private readonly TempDir temp = new();
+ private readonly FakeDialogs dialogs = new();
+ private readonly FakeLinkRunner runner = new();
+ private readonly LinkCreator creator;
+
+ public LinkCreatorBatchTests()
+ {
+ creator = new LinkCreator(dialogs, runner);
+ }
+
+ public void Dispose() => temp.Dispose();
+
+ private string Links => temp.PathOf("links");
+
+ private static string Format(string format, params object[] args) =>
+ string.Format(CultureInfo.CurrentUICulture, format, args);
+
+ private LinkInput Input(string name, string target, string location = null, bool isFolder = true, LinkKind kind = LinkKind.Symbolic) =>
+ new(location ?? Links, name, target, isFolder, kind);
+
+ private static string Summary(int created, int total, string[] createdLines, string[] failedLines)
+ {
+ var text = Format(Res.BatchSummaryCount, created, total);
+ if (createdLines.Length != 0)
+ text += "\n\n" + Res.BatchSummaryCreated + "\n" + string.Join("\n", createdLines);
+ if (failedLines.Length != 0)
+ text += "\n\n" + Res.BatchSummaryNotCreated + "\n" + string.Join("\n", failedLines);
+ return text;
+ }
+
+ [Fact]
+ public async Task Batch_WithNothingToDo_DoesNothing()
+ {
+ var outcomes = await creator.CreateBatchAsync(Array.Empty());
+
+ Assert.Empty(outcomes);
+ Assert.Empty(dialogs.Messages);
+ Assert.Empty(runner.Prepared);
+ }
+
+ [Fact]
+ public async Task Batch_CreatesEveryLink_AsksForAdminRightsOnce_AndShowsOneSummary()
+ {
+ temp.Dir("links");
+ var targets = new[] { temp.Dir("A", "One"), temp.Dir("A", "Two"), temp.Dir("A", "Three") };
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("One", targets[0]), Input("Two", targets[1]), Input(" Three ", targets[2]) });
+
+ Assert.All(outcomes, outcome => Assert.Equal(LinkStatus.Created, outcome.Status));
+ Assert.Equal(
+ new[] { (Path.Combine(Links, "One"), targets[0]), (Path.Combine(Links, "Two"), targets[1]), (Path.Combine(Links, "Three"), targets[2]) },
+ runner.Calls.Select(call => (call.Link, call.Target)));
+ Assert.Same(runner.Calls[0], Assert.Single(runner.Prepared));
+ Assert.Empty(dialogs.Questions);
+
+ var summary = Assert.Single(dialogs.Messages);
+ Assert.Equal((Res.MessageBoxSuccessTitle, Summary(3, 3, new[] { "One", "Two", "Three" }, Array.Empty())), summary);
+ }
+
+ [Fact]
+ public async Task Batch_KeepsGoingPastAFailure_AndSaysWhy()
+ {
+ temp.Dir("links");
+ var one = temp.Dir("One");
+ var two = temp.Dir("Two");
+ var three = temp.Dir("Three");
+ runner.Handler = request => request.Target == two ? LinkResult.Failed("Access is denied.\r\n Try again.") : FakeLinkRunner.Created;
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("One", one), Input("Two", two), Input("Three", three) });
+
+ Assert.Equal(new[] { LinkStatus.Created, LinkStatus.Failed, LinkStatus.Created }, outcomes.Select(outcome => outcome.Status));
+ Assert.Equal(3, runner.Calls.Count);
+ Assert.Equal(
+ (Res.BatchSummaryPartialTitle, Summary(2, 3, new[] { "One", "Three" }, new[] { "Two: Access is denied. Try again." })),
+ Assert.Single(dialogs.Messages));
+ }
+
+ [Fact]
+ public async Task Batch_AsksEveryQuestion_BeforeAnythingOnDiskChanges()
+ {
+ temp.Dir("links");
+ var existingLink = temp.File(@"links\Replace\old.txt");
+ temp.File(@"links\Move\data.txt", "data");
+ var replaceTarget = temp.Dir("ReplaceTarget");
+ temp.File(@"ReplaceTarget\inside.txt");
+ var moveTarget = temp.PathOf("MoveTarget");
+ var plain = temp.Dir("Plain");
+
+ var questionsWhenPrepared = -1;
+ var replacedWhenPrepared = true;
+ runner.OnPrepare = () =>
+ {
+ questionsWhenPrepared = dialogs.Questions.Count;
+ replacedWhenPrepared = !File.Exists(existingLink);
+ };
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("Replace", replaceTarget), Input("Move", moveTarget), Input("Plain", plain) });
+
+ Assert.Equal(2, questionsWhenPrepared);
+ Assert.False(replacedWhenPrepared);
+ Assert.Single(runner.Prepared);
+
+ // In a batch, each question starts with the link it is about
+ Assert.Equal(
+ new[]
+ {
+ (Res.DialogFolderExistsDialog, Path.Combine(Links, "Replace") + "\n\n" + Res.DialogFolderExists),
+ (Res.DialogMoveTitle, Path.Combine(Links, "Move") + "\n\n" + Format(Res.DialogMoveFolder, "Move", moveTarget)),
+ },
+ dialogs.Questions.Select(question => (question.Title, question.Message)));
+
+ Assert.All(outcomes, outcome => Assert.Equal(LinkStatus.Created, outcome.Status));
+ Assert.False(Directory.Exists(Path.Combine(Links, "Replace")));
+ Assert.Equal("data", File.ReadAllText(Path.Combine(moveTarget, "data.txt")));
+ Assert.Equal(3, runner.Calls.Count);
+ }
+
+ [Fact]
+ public async Task Batch_SkipsTheLinksTheUserSaidNoTo()
+ {
+ temp.Dir("links");
+ var existing = temp.File(@"links\Replace\old.txt");
+ var target = temp.Dir("Target");
+ temp.File(@"Target\inside.txt");
+ var plain = temp.Dir("Plain");
+ dialogs.Answer = false;
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("Replace", target), Input("Plain", plain) });
+
+ Assert.Equal(new[] { LinkStatus.Skipped, LinkStatus.Created }, outcomes.Select(outcome => outcome.Status));
+ Assert.True(File.Exists(existing));
+ Assert.Equal(plain, Assert.Single(runner.Calls).Target);
+ Assert.Equal(
+ (Res.BatchSummaryPartialTitle, Summary(1, 2, new[] { "Plain" }, new[] { "Replace: " + Res.LinkCreationAborted })),
+ Assert.Single(dialogs.Messages));
+ }
+
+ [Fact]
+ public async Task Batch_StopsQuietly_WhenAdminRightsAreDeclined()
+ {
+ temp.Dir("links");
+ var existing = temp.File(@"links\Replace\old.txt");
+ var target = temp.Dir("Target");
+ temp.File(@"Target\inside.txt");
+ runner.PrepareResult = false;
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("Replace", target), Input("Other", temp.Dir("Other")) });
+
+ Assert.Null(outcomes);
+ Assert.True(File.Exists(existing));
+ Assert.Empty(runner.Calls);
+ Assert.Empty(dialogs.Messages);
+ }
+
+ [Fact]
+ public async Task Batch_DoesNotAskForAdminRights_WhenNoLinkIsLeftToCreate()
+ {
+ temp.Dir("links");
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("One", temp.PathOf("missing")), Input("Two", " ") });
+
+ Assert.All(outcomes, outcome => Assert.Equal(LinkStatus.Failed, outcome.Status));
+ Assert.Empty(runner.Prepared);
+ Assert.Equal(
+ (Res.BatchSummaryPartialTitle, Summary(0, 2, Array.Empty(), new[] { "One: " + Res.FilesOrFolderNotExists, "Two: " + Res.FillBlanks })),
+ Assert.Single(dialogs.Messages));
+ }
+
+ [Fact]
+ public async Task Batch_ReportsAnUnexpectedError_ForThatLinkOnly()
+ {
+ temp.Dir("links");
+ var good = temp.Dir("Good");
+
+ var outcomes = await creator.CreateBatchAsync(new[] { Input("Bad\0Name", good), Input("Good", good) });
+
+ Assert.Equal(new[] { LinkStatus.Failed, LinkStatus.Created }, outcomes.Select(outcome => outcome.Status));
+ Assert.StartsWith(Res.MessageBoxExceptionOcurred + "\n", outcomes[0].Message);
+ Assert.Single(runner.Calls);
+ }
+
+ [Fact]
+ public async Task Batch_ListsLinksOutsideTheMainFolder_ByTheirFullPath()
+ {
+ temp.Dir("links");
+ var elsewhere = temp.Dir("elsewhere");
+ var target = temp.Dir("Target");
+
+ await creator.CreateBatchAsync(new[] { Input("One", target), Input("Two", target, location: elsewhere), Input("Three", target, location: Links + "\\") });
+
+ Assert.Equal(Summary(3, 3, new[] { "One", Path.Combine(elsewhere, "Two"), "Three" }, Array.Empty()), dialogs.Last.Message);
+ }
+
+ [Fact]
+ public async Task Batch_MentionsALeftoverCopy_EvenThoughTheLinkWorks()
+ {
+ temp.File(@"links\name\data.txt");
+ var target = temp.PathOf("target");
+ var staging = temp.PathOf("links", "name.symlinker-move");
+ creator.IsSameVolume = (_, _) => false;
+ creator.ProgressInterval = TimeSpan.Zero;
+ FileStream lockedFile = null;
+
+ // Something holds a file open in the old copy, so it can't be removed
+ runner.Handler = request =>
+ {
+ if (request.Target == target)
+ lockedFile = new FileStream(Path.Combine(staging, "data.txt"), FileMode.Open, FileAccess.Read, FileShare.None);
+ return FakeLinkRunner.Created;
+ };
+
+ try
+ {
+ await creator.CreateBatchAsync(new[] { Input("name", target), Input("other", temp.Dir("other")) });
+ }
+ finally
+ {
+ lockedFile?.Dispose();
+ }
+
+ var leftover = Regex.Replace(Format(Res.MoveCleanupFailed, staging), @"\s*\n\s*", " ");
+ Assert.Equal(
+ (Res.MessageBoxSuccessTitle, Summary(2, 2, new[] { "name: " + leftover, "other" }, Array.Empty())),
+ dialogs.Last);
+ }
+
+ [Fact]
+ public async Task Single_ReportsAnUnexpectedErrorWhilePlanning()
+ {
+ temp.Dir("links");
+
+ await creator.CreateAsync(Input("Bad\0Name", temp.Dir("Target")));
+
+ Assert.Equal(Res.MessageBoxErrorTitle, dialogs.Last.Title);
+ Assert.StartsWith(Res.MessageBoxExceptionOcurred + "\n", dialogs.Last.Message);
+ Assert.Empty(runner.Prepared);
+ }
+ }
+}
diff --git a/Symlinker/LinkBatch.cs b/Symlinker/LinkBatch.cs
new file mode 100644
index 0000000..a53a422
--- /dev/null
+++ b/Symlinker/LinkBatch.cs
@@ -0,0 +1,252 @@
+namespace Symlinker
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.ComponentModel;
+ using System.IO;
+ using System.Linq;
+
+ using Res = Symlinker.Properties.Resources;
+
+ /// One link in the list: the folder it goes in, its name and what it points to.
+ internal sealed class LinkRow : INotifyPropertyChanged
+ {
+ // Each row keeps its own auto-filled name, so typing a name in one row never affects another
+ private readonly LinkNameAutoFill autoFill = new();
+ private readonly List<(InputField Field, string Message)> errors = new();
+
+ private string linkLocation = string.Empty;
+ private string linkName = string.Empty;
+ private string target = string.Empty;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+
+ public string LinkLocation
+ {
+ get => linkLocation;
+ set => Set(ref linkLocation, value ?? string.Empty);
+ }
+
+ public string LinkName
+ {
+ get => linkName;
+ set => Set(ref linkName, value ?? string.Empty);
+ }
+
+ public string Target
+ {
+ get => target;
+ private set => Set(ref target, value);
+ }
+
+ /// Where the link will be created, as shown in the list.
+ public string LinkPath => LinkFolder + linkName.Trim();
+
+ /// The link location with a trailing separator, shown dimmed before the name. Empty when not set.
+ public string LinkFolder => FolderPart(linkLocation, withName: false);
+
+ /// The folder that holds the target, with a trailing separator, shown dimmed before the target's name.
+ public string TargetFolder => FolderPart(target, withName: true);
+
+ /// The target's own name, the part of the target that matters most in the list.
+ public string TargetName => UiHelpers.GetName(target.Trim());
+
+ /// What is wrong with this row, in screen order. Empty when nothing is.
+ public IReadOnlyList<(InputField Field, string Message)> Errors => errors;
+
+ public bool HasError => errors.Count != 0;
+
+ /// The first problem, shown as the row's tooltip.
+ public string ErrorText => HasError ? errors[0].Message : null;
+
+ /// Sets the target and fills in the link name from it, unless the user typed their own.
+ public void SetTarget(string path)
+ {
+ path ??= string.Empty;
+ Target = path;
+ var name = autoFill.Update(LinkName, UiHelpers.GetName(path));
+ if (name != null)
+ LinkName = name;
+ }
+
+ public void SetErrors(IEnumerable<(InputField Field, string Message)> problems)
+ {
+ errors.Clear();
+ errors.AddRange(problems);
+ OnErrorsChanged();
+ }
+
+ /// Editing a field clears its error.
+ public void ClearError(InputField field)
+ {
+ if (errors.RemoveAll(error => error.Field == field) != 0)
+ OnErrorsChanged();
+ }
+
+ public LinkInput ToInput(bool isFolder, LinkKind kind) => new(LinkLocation, LinkName, Target, isFolder, kind);
+
+ ///
+ /// The folder part of a path, ending in a separator. With , the
+ /// path's own name is left out (a target); otherwise the whole path is the folder (a location).
+ ///
+ private static string FolderPart(string path, bool withName)
+ {
+ var trimmed = path.Trim().TrimEnd('\\', '/');
+ if (withName)
+ trimmed = trimmed[..^UiHelpers.GetName(trimmed).Length].TrimEnd('\\', '/');
+
+ return trimmed.Length == 0 ? string.Empty : trimmed + "\\";
+ }
+
+ private void OnErrorsChanged() => Raise();
+
+ private void Set(ref string field, string value)
+ {
+ if (field == value)
+ return;
+
+ field = value;
+ Raise();
+ }
+
+ // Every display property derives from the three fields and the errors, so refresh them all
+ private void Raise() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));
+ }
+
+ ///
+ /// The links to create in one step. There is always at least one row; with a single row the
+ /// window looks the same as before batches existed. The cards edit .
+ ///
+ internal sealed class LinkBatch
+ {
+ public LinkBatch()
+ {
+ Selected = new LinkRow();
+ Rows.Add(Selected);
+ }
+
+ public ObservableCollection Rows { get; } = new();
+
+ /// The row the cards show and edit.
+ public LinkRow Selected { get; set; }
+
+ /// Whether there is more than one link, so the window shows the list.
+ public bool IsBatch => Rows.Count > 1;
+
+ /// Adds an empty row in the last row's link location and selects it.
+ public LinkRow Add()
+ {
+ var row = new LinkRow { LinkLocation = Rows[^1].LinkLocation };
+ Rows.Add(row);
+ Selected = row;
+ return row;
+ }
+
+ /// Removes a row, keeping at least one. A removed selection moves to its neighbor.
+ public void Remove(LinkRow row)
+ {
+ var index = Rows.IndexOf(row);
+ if (index < 0 || Rows.Count == 1)
+ return;
+
+ Rows.RemoveAt(index);
+ if (Selected == row)
+ Selected = Rows[Math.Min(index, Rows.Count - 1)];
+ }
+
+ ///
+ /// Uses several picked or dropped targets at once: the first one goes in the selected row,
+ /// and each of the others gets a new row after it in the same link location.
+ ///
+ public void AddTargets(IReadOnlyList targets)
+ {
+ if (targets.Count == 0)
+ return;
+
+ var current = Selected;
+ current.SetTarget(targets[0]);
+
+ var index = Rows.IndexOf(current);
+ foreach (var path in targets.Skip(1))
+ {
+ var row = new LinkRow { LinkLocation = current.LinkLocation };
+ row.SetTarget(path);
+ Rows.Insert(++index, row);
+ }
+ }
+
+ ///
+ /// Sets a picked or dropped link location on the selected row, and on every other row that
+ /// was in the same place (or had none yet), so rows added together stay together.
+ ///
+ public void SetLocation(string location)
+ {
+ var old = Selected.LinkLocation;
+ foreach (var row in Rows)
+ {
+ if (row.LinkLocation == old || row.LinkLocation.Trim().Length == 0)
+ row.LinkLocation = location;
+ }
+ }
+
+ ///
+ /// A path to open the target picker next to: the row's own target, or else the nearest
+ /// target above it, so consecutive rows don't need re-navigating. Null when there is none.
+ ///
+ public string TargetHint(LinkRow row)
+ {
+ for (var index = Rows.IndexOf(row); index >= 0; index--)
+ {
+ if (Rows[index].Target.Trim().Length != 0)
+ return Rows[index].Target;
+ }
+
+ return null;
+ }
+
+ ///
+ /// Checks every row and records its problems, including two rows that would create the same
+ /// link. Returns true when all rows are fine.
+ ///
+ public bool Validate(bool isFolder)
+ {
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var row in Rows)
+ {
+ var problems = InputValidator.Validate(row.LinkName, row.LinkLocation, row.Target, isFolder);
+ if (!problems.Any(p => p.Field != InputField.Target) && !seen.Add(FullLinkPath(row)))
+ problems.Insert(0, (InputField.LinkName, Res.ErrorDuplicateLinkPath));
+
+ row.SetErrors(problems);
+ }
+
+ return Rows.All(row => !row.HasError);
+ }
+
+ public void ClearErrors()
+ {
+ foreach (var row in Rows)
+ row.SetErrors(Array.Empty<(InputField, string)>());
+ }
+
+ ///
+ /// After a batch where some links weren't created, drops the ones that were, so only the
+ /// rows left to fix stay in the list. When every link was created, the list stays as it is.
+ ///
+ public void RemoveCreated(IReadOnlyList rows, IReadOnlyList outcomes)
+ {
+ if (outcomes.All(outcome => outcome.Status == LinkStatus.Created))
+ return;
+
+ for (var index = 0; index < rows.Count; index++)
+ {
+ if (outcomes[index].Status == LinkStatus.Created)
+ Remove(rows[index]);
+ }
+ }
+
+ // Name and location passed validation, so this path is well formed and the location exists
+ private static string FullLinkPath(LinkRow row) => Path.GetFullPath(Path.Combine(row.LinkLocation.Trim(), row.LinkName.Trim()));
+ }
+}
diff --git a/Symlinker/LinkCreator.cs b/Symlinker/LinkCreator.cs
index d755146..34ff1f9 100644
--- a/Symlinker/LinkCreator.cs
+++ b/Symlinker/LinkCreator.cs
@@ -1,10 +1,13 @@
namespace Symlinker
{
using System;
+ using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
+ using System.Text;
+ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
@@ -13,6 +16,45 @@ namespace Symlinker
/// What the user entered in the window.
internal sealed record LinkInput(string LinkLocation, string LinkName, string Destination, bool IsFolder, LinkKind Kind);
+ /// What became of one link.
+ internal enum LinkStatus
+ {
+ Created,
+ Failed,
+
+ /// The user said no (to replacing or moving, or canceled a move).
+ Skipped,
+ }
+
+ ///
+ /// How creating one link went, with the dialog that reports it. marks a
+ /// created link whose message the batch summary should still show (e.g. a leftover copy to delete).
+ ///
+ internal sealed record LinkOutcome(LinkStatus Status, string Title, string Message, bool Notable = false)
+ {
+ public static LinkOutcome Error(string message) => new(LinkStatus.Failed, Res.MessageBoxErrorTitle, message);
+
+ public static LinkOutcome Aborted() => new(LinkStatus.Skipped, Res.LinkCreationAbortedWarning, Res.LinkCreationAborted);
+ }
+
+ /// What creating one link involves, worked out (and agreed to) before anything on disk changes.
+ internal sealed class LinkPlan
+ {
+ /// The link to create. Null when is already decided.
+ public LinkRequest Request { get; init; }
+
+ /// An existing entry at the link path to delete first, with .
+ public string Existing { get; init; }
+
+ public Action Delete { get; init; }
+
+ /// A real file or folder at the link path to move to the target first.
+ public FileSystemInfo MoveSource { get; init; }
+
+ /// Set when the link won't be created (bad input or the user said no), or once it was tried.
+ public LinkOutcome Outcome { get; set; }
+ }
+
///
/// Creates links from what the user entered: validates it, asks before replacing anything,
/// and offers to move an existing file or folder to the target and leave a link behind.
@@ -44,77 +86,173 @@ public LinkCreator(IDialogService dialogs, ILinkRunner runner)
internal string AppDataFolder { get; set; } =
Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
+ /// Creates one link, asking before replacing or moving anything, and shows how it went.
public async Task CreateAsync(LinkInput request)
{
try
{
- request = request with
+ var plan = await PlanAsync(request, inBatch: false);
+ if (plan.Outcome == null)
{
- LinkLocation = request.LinkLocation.Trim(),
- LinkName = request.LinkName.Trim(),
- Destination = request.Destination.Trim(),
- };
-
- var linkLocation = request.LinkLocation;
- var linkName = request.LinkName;
- var destination = request.Destination;
+ // Ask for administrator rights before anything on disk changes; a declined prompt quietly stops here
+ if (!await runner.PrepareAsync(plan.Request))
+ return;
- if (string.IsNullOrWhiteSpace(linkLocation) || string.IsNullOrWhiteSpace(linkName) || string.IsNullOrWhiteSpace(destination))
- {
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FillBlanks);
- return;
+ plan.Outcome = await ExecuteAsync(plan);
}
- if (linkName.Contains('"') || linkLocation.Contains('"') || destination.Contains('"'))
- {
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.InvalidQuoteInPath);
- return;
- }
+ await dialogs.ShowMessageAsync(plan.Outcome.Title, plan.Outcome.Message);
+ }
+ catch (Exception exception)
+ {
+ await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, ExceptionMessage(exception));
+ }
+ }
- // Full path: the administrator helper runs in a different working folder
- var linkPath = Path.GetFullPath(Path.Combine(linkLocation, linkName));
+ ///
+ /// Creates several links in one step. Every question (replace, or move to the target) is asked
+ /// first, then administrator rights once, before anything on disk changes. A link that fails
+ /// doesn't stop the others, and one summary at the end lists what happened.
+ /// Returns the outcome of each input, or null when the UAC prompt was declined (nothing changed).
+ ///
+ public async Task> CreateBatchAsync(IReadOnlyList inputs)
+ {
+ if (inputs.Count == 0)
+ return Array.Empty();
- // A real file or folder already sits where the link goes and the target is free:
- // offer to move it to the target and leave a link behind (#33)
- if (Directory.Exists(linkLocation) && Path.IsPathFullyQualified(destination))
+ var plans = new List();
+ foreach (var input in inputs)
+ {
+ try
{
- FileSystemInfo existing = request.IsFolder ? new DirectoryInfo(linkPath) : new FileInfo(linkPath);
- if (existing.Exists && !LinkMover.IsLink(existing) && IsFreeMoveTarget(destination, request.IsFolder))
- {
- await OfferMoveAsync(request, existing, linkPath, Path.GetFullPath(destination));
- return;
- }
+ plans.Add(await PlanAsync(input, inBatch: true));
}
-
- if (request.IsFolder && Directory.Exists(linkLocation) && Directory.Exists(destination))
+ catch (Exception exception)
{
- await ReplaceOrCreateAsync(
- request,
- linkPath,
- Directory.GetDirectories(linkLocation),
- Res.DialogFolderExistsDialog,
- Res.DialogFolderExists,
- path => Directory.Delete(path, true));
+ plans.Add(new LinkPlan { Outcome = LinkOutcome.Error(ExceptionMessage(exception)) });
}
- else if (!request.IsFolder && Directory.Exists(linkLocation) && File.Exists(destination))
+ }
+
+ // One kind of link for the whole batch, so one check settles administrator rights for all of them
+ var pending = plans.Where(plan => plan.Outcome == null).ToList();
+ if (pending.Count != 0 && !await runner.PrepareAsync(pending[0].Request))
+ return null;
+
+ foreach (var plan in pending)
+ plan.Outcome = await ExecuteAsync(plan);
+
+ var outcomes = plans.Select(plan => plan.Outcome).ToList();
+ await dialogs.ShowMessageAsync(
+ outcomes.All(outcome => outcome.Status == LinkStatus.Created) ? Res.MessageBoxSuccessTitle : Res.BatchSummaryPartialTitle,
+ Summarize(inputs, outcomes));
+ return outcomes;
+ }
+
+ /// The batch summary: how many links were created, then which ones and which not (and why).
+ private static string Summarize(IReadOnlyList inputs, IReadOnlyList outcomes)
+ {
+ // Links in the folder most of the batch goes in are listed by name, which is much shorter;
+ // the others by their full path
+ static string Folder(LinkInput input) => input.LinkLocation.Trim().TrimEnd('\\', '/');
+ var mainFolder = inputs.GroupBy(Folder, StringComparer.OrdinalIgnoreCase).OrderByDescending(group => group.Count()).First().Key;
+
+ string Line(LinkInput input, LinkOutcome outcome, bool withReason)
+ {
+ var path = string.Equals(Folder(input), mainFolder, StringComparison.OrdinalIgnoreCase)
+ ? input.LinkName.Trim()
+ : Path.Combine(input.LinkLocation.Trim(), input.LinkName.Trim());
+ return withReason ? path + ": " + Regex.Replace(outcome.Message.Trim(), @"\s*\n\s*", " ") : path;
+ }
+
+ var created = outcomes.Count(outcome => outcome.Status == LinkStatus.Created);
+ var text = new StringBuilder(string.Format(CultureInfo.CurrentUICulture, Res.BatchSummaryCount, created, outcomes.Count));
+
+ if (created != 0)
+ {
+ text.Append("\n\n").Append(Res.BatchSummaryCreated);
+ for (var index = 0; index < outcomes.Count; index++)
{
- await ReplaceOrCreateAsync(
- request,
- linkPath,
- Directory.GetFiles(linkLocation),
- Res.DialogDeleteFileWarning,
- Res.DialogDeleteFile,
- File.Delete);
+ if (outcomes[index].Status == LinkStatus.Created)
+ text.Append('\n').Append(Line(inputs[index], outcomes[index], outcomes[index].Notable));
}
- else
+ }
+
+ if (created != outcomes.Count)
+ {
+ text.Append("\n\n").Append(Res.BatchSummaryNotCreated);
+ for (var index = 0; index < outcomes.Count; index++)
{
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FilesOrFolderNotExists);
+ if (outcomes[index].Status != LinkStatus.Created)
+ text.Append('\n').Append(Line(inputs[index], outcomes[index], true));
}
}
- catch (Exception exception)
+
+ return text.ToString();
+ }
+
+ private static string ExceptionMessage(Exception exception) => Res.MessageBoxExceptionOcurred + "\n" + exception.Message;
+
+ ///
+ /// Works out what creating the link involves and asks the user any question it needs, without
+ /// changing anything on disk. The plan already has an when the
+ /// link won't be created (bad input, or the user said no).
+ ///
+ private async Task PlanAsync(LinkInput request, bool inBatch)
+ {
+ request = request with
+ {
+ LinkLocation = request.LinkLocation.Trim(),
+ LinkName = request.LinkName.Trim(),
+ Destination = request.Destination.Trim(),
+ };
+
+ var linkLocation = request.LinkLocation;
+ var linkName = request.LinkName;
+ var destination = request.Destination;
+
+ if (string.IsNullOrWhiteSpace(linkLocation) || string.IsNullOrWhiteSpace(linkName) || string.IsNullOrWhiteSpace(destination))
+ return new LinkPlan { Outcome = LinkOutcome.Error(Res.FillBlanks) };
+
+ if (linkName.Contains('"') || linkLocation.Contains('"') || destination.Contains('"'))
+ return new LinkPlan { Outcome = LinkOutcome.Error(Res.InvalidQuoteInPath) };
+
+ // Full path: the administrator helper runs in a different working folder
+ var linkPath = Path.GetFullPath(Path.Combine(linkLocation, linkName));
+
+ // A real file or folder already sits where the link goes and the target is free:
+ // offer to move it to the target and leave a link behind (#33)
+ if (Directory.Exists(linkLocation) && Path.IsPathFullyQualified(destination))
{
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message);
+ FileSystemInfo existing = request.IsFolder ? new DirectoryInfo(linkPath) : new FileInfo(linkPath);
+ if (existing.Exists && !LinkMover.IsLink(existing) && IsFreeMoveTarget(destination, request.IsFolder))
+ return await PlanMoveAsync(request, existing, linkPath, Path.GetFullPath(destination), inBatch);
}
+
+ if (request.IsFolder && Directory.Exists(linkLocation) && Directory.Exists(destination))
+ {
+ return await PlanReplaceAsync(
+ request,
+ linkPath,
+ Directory.GetDirectories(linkLocation),
+ Res.DialogFolderExistsDialog,
+ Res.DialogFolderExists,
+ path => Directory.Delete(path, true),
+ inBatch);
+ }
+
+ if (!request.IsFolder && Directory.Exists(linkLocation) && File.Exists(destination))
+ {
+ return await PlanReplaceAsync(
+ request,
+ linkPath,
+ Directory.GetFiles(linkLocation),
+ Res.DialogDeleteFileWarning,
+ Res.DialogDeleteFile,
+ File.Delete,
+ inBatch);
+ }
+
+ return new LinkPlan { Outcome = LinkOutcome.Error(Res.FilesOrFolderNotExists) };
}
///
@@ -132,28 +270,24 @@ private static bool IsFreeMoveTarget(string destination, bool isFolder)
return isFolder && !Directory.EnumerateFileSystemEntries(destination).Any();
}
+ /// In a batch, a question starts with the link it is about, since several may be asked in a row.
+ private static string Question(string message, string linkPath, bool inBatch) => inBatch ? linkPath + "\n\n" + message : message;
+
///
- /// Creates the link, first asking to delete an entry with the same name from .
+ /// Plans the link, first asking to delete an entry with the same name from .
///
- private async Task ReplaceOrCreateAsync(LinkInput request, string linkPath, string[] siblings, string title, string question, Action delete)
+ private async Task PlanReplaceAsync(LinkInput request, string linkPath, string[] siblings, string title, string question, Action delete, bool inBatch)
{
var existing = siblings.FirstOrDefault(e => Path.GetFileName(e).Equals(request.LinkName, StringComparison.OrdinalIgnoreCase));
- if (existing != null && !await dialogs.ConfirmAsync(title, question))
- {
- await dialogs.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted);
- return;
- }
-
- // Ask for administrator rights before deleting anything; a declined prompt quietly stops here
- var linkRequest = ToLinkRequest(request, linkPath, request.Destination);
- if (!await runner.PrepareAsync(linkRequest))
- return;
-
- if (existing != null)
- delete(existing);
+ if (existing != null && !await dialogs.ConfirmAsync(title, Question(question, linkPath, inBatch)))
+ return new LinkPlan { Outcome = LinkOutcome.Aborted() };
- var result = LinkResultMessage.For(linkRequest, await runner.RunAsync(linkRequest));
- await dialogs.ShowMessageAsync(result.Title, result.Message);
+ return new LinkPlan
+ {
+ Request = ToLinkRequest(request, linkPath, request.Destination),
+ Existing = existing,
+ Delete = delete,
+ };
}
private static LinkRequest ToLinkRequest(LinkInput input, string linkPath, string target) => new()
@@ -164,16 +298,13 @@ private async Task ReplaceOrCreateAsync(LinkInput request, string linkPath, stri
Directory = input.IsFolder,
};
- private async Task OfferMoveAsync(LinkInput request, FileSystemInfo existing, string linkPath, string target)
+ private async Task PlanMoveAsync(LinkInput request, FileSystemInfo existing, string linkPath, string target, bool inBatch)
{
// In the Store package, Windows keeps files this process creates under AppData in a
// private per-package copy: other apps can't see them and uninstalling deletes them.
// Links are fine (mklink runs in cmd.exe), but moved files would end up hidden there.
if (IsPackaged() && LinkMover.IsSameOrInside(target, AppDataFolder))
- {
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MoveIntoAppDataUnsupported);
- return;
- }
+ return new LinkPlan { Outcome = LinkOutcome.Error(Res.MoveIntoAppDataUnsupported) };
var message = string.Format(
CultureInfo.CurrentUICulture,
@@ -181,26 +312,40 @@ private async Task OfferMoveAsync(LinkInput request, FileSystemInfo existing, st
existing.Name,
target);
- if (!await dialogs.ConfirmAsync(Res.DialogMoveTitle, message, Res.ButtonMoveAndLink, Res.ButtonCancel))
- {
- await dialogs.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted);
- return;
- }
+ if (!await dialogs.ConfirmAsync(Res.DialogMoveTitle, Question(message, linkPath, inBatch), Res.ButtonMoveAndLink, Res.ButtonCancel))
+ return new LinkPlan { Outcome = LinkOutcome.Aborted() };
- // Ask for administrator rights before moving anything, so a declined prompt
- // never leaves files moved without a link
- var linkRequest = ToLinkRequest(request, linkPath, target);
- if (!await runner.PrepareAsync(linkRequest))
- return;
+ return new LinkPlan { Request = ToLinkRequest(request, linkPath, target), MoveSource = existing };
+ }
- IsMoving = true;
+ /// Carries out a plan: moves and links, or replaces and links, or just links. Never throws.
+ private async Task ExecuteAsync(LinkPlan plan)
+ {
try
{
- await MoveAndLinkAsync(request.IsFolder, existing, linkRequest);
+ if (plan.MoveSource != null)
+ {
+ IsMoving = true;
+ try
+ {
+ return await MoveAndLinkAsync(plan.Request.Directory, plan.MoveSource, plan.Request);
+ }
+ finally
+ {
+ IsMoving = false;
+ }
+ }
+
+ if (plan.Existing != null)
+ plan.Delete(plan.Existing);
+
+ var result = await runner.RunAsync(plan.Request);
+ var message = LinkResultMessage.For(plan.Request, result);
+ return new LinkOutcome(result.Success ? LinkStatus.Created : LinkStatus.Failed, message.Title, message.Message);
}
- finally
+ catch (Exception exception)
{
- IsMoving = false;
+ return LinkOutcome.Error(ExceptionMessage(exception));
}
}
@@ -208,7 +353,7 @@ private async Task OfferMoveAsync(LinkInput request, FileSystemInfo existing, st
/// Moves to the link's target and creates the link where it was.
/// Any failure before the link exists puts everything back the way it was.
///
- private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRequest linkRequest)
+ private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRequest linkRequest)
{
var target = linkRequest.Target;
var originalPath = source.FullName;
@@ -216,10 +361,7 @@ private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRe
// The target is free (missing or an empty folder), so the source can't be inside it;
// only the other way around needs checking
if (LinkMover.IsSameOrInside(target, originalPath))
- {
- await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MoveTargetInsideSource);
- return;
- }
+ return LinkOutcome.Error(Res.MoveTargetInsideSource);
var targetWasEmptyFolder = Directory.Exists(target);
@@ -255,18 +397,16 @@ private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRe
var copyError = await CopyWithProgressAsync(staged, target);
if (copyError != null)
{
- var title = copyError == Res.MoveCanceled ? Res.LinkCreationAbortedWarning : Res.MessageBoxErrorTitle;
- await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, copyError, title);
- return;
+ var outcome = copyError == Res.MoveCanceled
+ ? new LinkOutcome(LinkStatus.Skipped, Res.LinkCreationAbortedWarning, copyError)
+ : LinkOutcome.Error(copyError);
+ return RollBackMove(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, outcome);
}
}
var linked = await runner.RunAsync(linkRequest);
if (!linked.Success)
- {
- await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, LinkResultMessage.Reason(linkRequest, linked)));
- return;
- }
+ return RollBackMove(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, MoveFailed(LinkResultMessage.Reason(linkRequest, linked)));
if (currentPath != target)
{
@@ -276,27 +416,33 @@ private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRe
}
catch (Exception)
{
- await dialogs.ShowMessageAsync(
+ // The link works; the user only needs to know about the leftover copy
+ return new LinkOutcome(
+ LinkStatus.Created,
Res.MessageBoxSuccessTitle,
- string.Format(CultureInfo.CurrentUICulture, Res.MoveCleanupFailed, currentPath));
- return;
+ string.Format(CultureInfo.CurrentUICulture, Res.MoveCleanupFailed, currentPath),
+ Notable: true);
}
}
var moved = LinkResultMessage.ForMove(linkRequest, source.Name);
- await dialogs.ShowMessageAsync(moved.Title, moved.Message);
+ return new LinkOutcome(LinkStatus.Created, moved.Title, moved.Message);
}
catch (Exception exception)
{
- await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, exception.Message));
+ return RollBackMove(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, MoveFailed(exception.Message));
}
}
- /// Puts the original back where it was and removes any partial copy, then explains what happened.
- private async Task RollBackMoveAsync(string originalPath, string currentPath, string target, bool copiedToTarget, bool targetWasEmptyFolder, string message, string title = null)
- {
- title ??= Res.MessageBoxErrorTitle;
+ private static LinkOutcome MoveFailed(string reason) =>
+ LinkOutcome.Error(string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, reason));
+ ///
+ /// Puts the original back where it was and removes any partial copy. Returns
+ /// , or where the files are now if they couldn't be put back.
+ ///
+ private static LinkOutcome RollBackMove(string originalPath, string currentPath, string target, bool copiedToTarget, bool targetWasEmptyFolder, LinkOutcome outcome)
+ {
try
{
// Only remove the target when it is our own copy, never the only copy of the files
@@ -309,15 +455,14 @@ private async Task RollBackMoveAsync(string originalPath, string currentPath, st
if (targetWasEmptyFolder)
Directory.CreateDirectory(target);
+
+ return outcome;
}
catch (Exception)
{
// Tell the user where their files are now; this is the original path if they never left it
- message = string.Format(CultureInfo.CurrentUICulture, Res.MoveRollbackFailed, currentPath);
- title = Res.MessageBoxErrorTitle;
+ return LinkOutcome.Error(string.Format(CultureInfo.CurrentUICulture, Res.MoveRollbackFailed, currentPath));
}
-
- await dialogs.ShowMessageAsync(title, message);
}
///
diff --git a/Symlinker/MainWindow.Inputs.cs b/Symlinker/MainWindow.Inputs.cs
index f2cfbfd..1753a84 100644
--- a/Symlinker/MainWindow.Inputs.cs
+++ b/Symlinker/MainWindow.Inputs.cs
@@ -42,9 +42,6 @@ public partial class MainWindow
private static readonly Color ErrorColorLight = Color.FromRgb(0xC4, 0x2B, 0x1C);
private static readonly Color ErrorColorDark = Color.FromRgb(0xFF, 0x99, 0xA4);
- // Fields with a problem, in the order they appear on screen, with the message for each
- private readonly List> inputErrors = new();
-
private LaunchOptions launchOptions;
// Whether creating a symbolic link needs administrator rights (no admin, no Developer Mode)
@@ -121,7 +118,7 @@ private void UpdateAdminNotice()
adminNoticeShield.Visibility = adminNoticeShield.Source != null ? Visibility.Visible : Visibility.Collapsed;
// Field errors take the same spot and matter more
- adminPanel.Visibility = wouldPrompt && inputErrors.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
+ adminPanel.Visibility = wouldPrompt && FooterError == null ? Visibility.Visible : Visibility.Collapsed;
}
private void OnThemeChanged(object sender, ThemeChangedEventArgs e) => UpdateThemeBrushes();
@@ -186,63 +183,87 @@ private void RefreshSymlinkAccessNow()
UpdateAdminNotice();
}
- /// Checks every field, marks the bad ones and shows what's wrong. Returns true when all are fine.
+ ///
+ /// Checks every link, marks the bad fields and shows what's wrong. In a batch, the first row
+ /// with a problem is selected so its fields show in the cards. Returns true when all are fine.
+ ///
private bool ValidateInputs()
{
- inputErrors.Clear();
-
- var boxes = new Dictionary
+ var valid = batch.Validate(isFolder);
+ if (!valid)
{
- [InputField.LinkName] = linkNameTextBox,
- [InputField.LinkLocation] = linkLocationTextBox,
- [InputField.Target] = destinationLocationTextBox,
- };
-
- foreach (var (field, message) in InputValidator.Validate(linkNameTextBox.Text, linkLocationTextBox.Text, destinationLocationTextBox.Text, isFolder))
- AddInputError(boxes[field], message);
+ var row = batch.Rows.First(r => r.HasError);
+ if (row != batch.Selected)
+ {
+ batch.Selected = row;
+ UpdateBatchView();
+ LoadRow(row);
+ }
+
+ BoxFor(row.Errors[0].Field).Focus();
+ }
ShowInputErrors();
- if (inputErrors.Count != 0)
- inputErrors[0].Key.Focus();
-
- return inputErrors.Count == 0;
+ return valid;
}
- private void AddInputError(TextBox box, string message) => inputErrors.Add(new KeyValuePair(box, message));
+ private TextBox BoxFor(InputField field) => field switch
+ {
+ InputField.LinkName => linkNameTextBox,
+ InputField.LinkLocation => linkLocationTextBox,
+ _ => destinationLocationTextBox,
+ };
private void ClearInputErrors()
{
- inputErrors.Clear();
+ batch.ClearErrors();
ShowInputErrors();
}
private void InputTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
- // Editing a field clears its error
- var removed = inputErrors.RemoveAll(error => error.Key == sender);
- if (removed != 0)
- ShowInputErrors();
+ // Editing a field clears its error; filling the cards from a row doesn't
+ if (loadingRow || !batch.Selected.HasError)
+ return;
+
+ var field = sender == linkNameTextBox ? InputField.LinkName
+ : sender == linkLocationTextBox ? InputField.LinkLocation
+ : InputField.Target;
+ batch.Selected.ClearError(field);
+ ShowInputErrors();
}
+ ///
+ /// The message for the footer: the selected link's first problem, or (in a batch) a pointer to
+ /// the rows marked in the list. Null when nothing is wrong.
+ ///
+ private string FooterError =>
+ batch.Selected.ErrorText ?? (batch.IsBatch && batch.Rows.Any(row => row.HasError) ? Res.ErrorBatchRows : null);
+
private void ShowInputErrors()
{
+ var errors = batch.Selected.Errors;
foreach (var box in new[] { linkNameTextBox, linkLocationTextBox, destinationLocationTextBox })
{
- var message = inputErrors.Where(error => error.Key == box).Select(error => error.Value).FirstOrDefault();
+ var message = errors.Where(error => BoxFor(error.Field) == box).Select(error => error.Message).FirstOrDefault();
InputError.SetHasError(box, message != null);
AutomationProperties.SetHelpText(box, message ?? string.Empty);
}
UpdateAdminNotice();
- if (inputErrors.Count == 0)
+ var footer = FooterError;
+ if (footer == null)
{
errorPanel.Visibility = Visibility.Collapsed;
errorText.Text = string.Empty;
return;
}
- errorText.Text = inputErrors[0].Value;
+ if (errorText.Text == footer && errorPanel.Visibility == Visibility.Visible)
+ return;
+
+ errorText.Text = footer;
errorPanel.Visibility = Visibility.Visible;
// Let screen readers announce the new message
diff --git a/Symlinker/MainWindow.xaml b/Symlinker/MainWindow.xaml
index 1379c9c..fbd9e74 100644
--- a/Symlinker/MainWindow.xaml
+++ b/Symlinker/MainWindow.xaml
@@ -38,6 +38,8 @@
10
+
+
@@ -237,6 +239,106 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+