From dd8abf875667e1740e2defae21d3163ba54b05a0 Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 09:19:47 -0800 Subject: [PATCH 1/6] Store excluded directories relative to the local path. - Add is disabled until a valid local path is set, and the picked directory must be a subdirectory of it. - Exclusions are saved relative to the local path and resolved to full paths when the sync starts. - On every settings load, exclusions are validated; old full paths are converted and the file resaved. Invalid entries show a warning and the app does not continue. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSyncUI/AppSettings.cs | 151 ++++++++++++++++++++++++++++++++++++- SFTPSyncUI/SFTPSyncUI.cs | 10 ++- SFTPSyncUI/SettingsForm.cs | 87 +++++++++++++++------ docs/sftpsyncui.html | 2 +- 4 files changed, 221 insertions(+), 29 deletions(-) diff --git a/SFTPSyncUI/AppSettings.cs b/SFTPSyncUI/AppSettings.cs index 326ab8a..4ec5293 100644 --- a/SFTPSyncUI/AppSettings.cs +++ b/SFTPSyncUI/AppSettings.cs @@ -55,6 +55,25 @@ public class AppSettings { var setingsChanged = false; + // Exclusions are stored relative to the local path. Validate them on every load (a user may have + // hand-edited the file) and convert full paths from older settings files. This uses the configured + // local path before it is checked for existence below, as the conversion is purely textual. + var normalizedExclusions = NormalizeExcludedDirectories(settings.LocalPath, settings.ExcludedDirectories); + if (normalizedExclusions.Errors.Count > 0) + { + throw new InvalidSettingsException( + "The excluded directories in the settings file are not valid:\n\n" + + string.Join("\n", normalizedExclusions.Errors.Select(e => " - " + e)) + + "\n\nExcluded directories must be subdirectories of the Local Path, stored as paths relative to it." + + $"\n\nPlease correct the settings file and start the application again:\n{SettingsFile}"); + } + + if (!normalizedExclusions.Directories.SequenceEqual(settings.ExcludedDirectories, StringComparer.Ordinal)) + { + settings.excludedDirectories = normalizedExclusions.Directories; + setingsChanged = true; + } + if (!string.IsNullOrWhiteSpace(settings.LocalPath) && !Directory.Exists(settings.LocalPath)) { @@ -62,8 +81,12 @@ public class AppSettings setingsChanged = true; } - if (settings.ExcludedDirectories.RemoveAll(dir => !Directory.Exists(dir)) > 0) + // Remove excluded directories that no longer exist (only possible to check with a valid local path) + if (!string.IsNullOrWhiteSpace(settings.LocalPath) + && settings.excludedDirectories.RemoveAll(dir => !Directory.Exists(Path.Combine(settings.LocalPath, dir))) > 0) + { setingsChanged = true; + } if (settings.AccessVerified && (string.IsNullOrWhiteSpace(settings.RemoteHost) || @@ -84,6 +107,121 @@ public class AppSettings return settings ?? null; } + // Path.GetInvalidPathChars() only reports '|' and control characters on modern .NET, so list the rest explicitly + private static bool HasInvalidPathCharacters(string path) => + path.IndexOfAny(['<', '>', '"', '|', '?', '*']) >= 0 + || path.Any(char.IsControl) + || (!Path.IsPathRooted(path) && path.Contains(':')); + + /// + /// Try to express a directory as a path relative to the local path. The directory may be a full path or already + /// relative to the local path. Fails if it is not a strict subdirectory of the local path. + /// + public static bool TryGetRelativeSubdirectory(string localPath, string directory, out string relativePath) + { + relativePath = String.Empty; + + if (string.IsNullOrWhiteSpace(localPath) || string.IsNullOrWhiteSpace(directory) + || HasInvalidPathCharacters(directory)) + { + return false; + } + + try + { + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(localPath)); + + // A relative path must not use ".." to escape (or wander around in) the local path + if (!Path.IsPathRooted(directory) + && directory.Split('\\', '/').Any(segment => segment == "..")) + { + return false; + } + + var full = Path.TrimEndingDirectorySeparator( + Path.GetFullPath(Path.IsPathRooted(directory) ? directory : Path.Combine(root, directory))); + + var relative = Path.GetRelativePath(root, full); + + // Same directory, outside the local path, or on a different drive + if (relative == "." + || Path.IsPathRooted(relative) + || relative == ".." + || relative.StartsWith(".." + Path.DirectorySeparatorChar)) + { + return false; + } + + relativePath = relative; + return true; + } + catch (Exception) + { + // Invalid characters or otherwise malformed path + return false; + } + } + + /// + /// Validate a list of excluded directories against the local path, and convert any full paths to relative ones. + /// Relative paths are kept when there is no local path (they are checked structurally only), but a full path + /// cannot be converted without one. + /// + private static (List Directories, List Errors) NormalizeExcludedDirectories(string localPath, List directories) + { + var result = new List(); + var errors = new List(); + + foreach (var directory in directories) + { + if (string.IsNullOrWhiteSpace(directory)) + { + errors.Add("(blank entry)"); + continue; + } + + if (string.IsNullOrWhiteSpace(localPath)) + { + // Nothing to compare with. A full path can't be made relative; a relative one must at least be well formed. + bool wellFormedRelative = !Path.IsPathRooted(directory) + && !HasInvalidPathCharacters(directory) + && !directory.Split('\\', '/').Any(segment => segment == ".."); + + if (wellFormedRelative) + result.Add(directory); + else + errors.Add($"{directory} (no Local Path is set)"); + + continue; + } + + if (TryGetRelativeSubdirectory(localPath, directory, out var relative)) + { + if (!result.Contains(relative, StringComparer.OrdinalIgnoreCase)) + result.Add(relative); + } + else + { + errors.Add($"{directory} (not a subdirectory of {localPath})"); + } + } + + return (result, errors); + } + + /// + /// The excluded directories as full paths (the local path combined with each relative path). + /// + public List GetExcludedDirectoryFullPaths() + { + if (string.IsNullOrWhiteSpace(LocalPath)) + return new List(); + + return ExcludedDirectories + .Select(relative => Path.GetFullPath(Path.Combine(LocalPath, relative))) + .ToList(); + } + public bool SaveToFile() { bool saved = false; @@ -325,7 +463,7 @@ public string RemotePath } } - //Excluded directories + //Excluded directories, stored as paths relative to LocalPath private List excludedDirectories = new List(); @@ -345,4 +483,11 @@ public List ExcludedDirectories } } } -} \ No newline at end of file + /// + /// The settings file contains values that make it unsafe to continue (for example invalid excluded directories). + /// + public class InvalidSettingsException : ApplicationException + { + public InvalidSettingsException(string message) : base(message) { } + } +} diff --git a/SFTPSyncUI/SFTPSyncUI.cs b/SFTPSyncUI/SFTPSyncUI.cs index 146aa7c..5508414 100644 --- a/SFTPSyncUI/SFTPSyncUI.cs +++ b/SFTPSyncUI/SFTPSyncUI.cs @@ -76,6 +76,12 @@ static void Main() { settings = AppSettings.LoadFromFile(); } + catch (InvalidSettingsException ex) + { + MessageBox.Show(ex.Message, Application.ProductName + " - Invalid Settings", MessageBoxButtons.OK, MessageBoxIcon.Warning); + Application.Exit(); + return; + } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -290,7 +296,7 @@ public static async void StartSync(Action loggerAction) settings.RemotePath, pattern, director, - settings.ExcludedDirectories, + settings.GetExcludedDirectoryFullPaths(), initialSyncTask, settings.DeleteEnabled, workerIndex == 0); @@ -338,7 +344,7 @@ public static async void StartSync(Action loggerAction) settings.LocalPath, settings.RemotePath, patterns, - settings.ExcludedDirectories, + settings.GetExcludedDirectoryFullPaths(), patterns.Length); } catch (Exception ex) diff --git a/SFTPSyncUI/SettingsForm.cs b/SFTPSyncUI/SettingsForm.cs index 6efb3cd..31e8dc7 100644 --- a/SFTPSyncUI/SettingsForm.cs +++ b/SFTPSyncUI/SettingsForm.cs @@ -34,6 +34,7 @@ public SettingsForm(AppSettings settings, bool syncRunning) textBoxLocalPath.Text = _settings.LocalPath; textBoxSearchSpec.Text = _settings.LocalSearchPattern; listBox.Items.AddRange(_settings.ExcludedDirectories.ToArray()); + UpdateExclusionControls(); //Remote system settings textBoxRemoteHost.Text = _settings.RemoteHost; @@ -92,6 +93,8 @@ private void textBoxLocalPath_TextChanged(object sender, EventArgs e) { _settings?.LocalPath = textBoxLocalPath.Text; } + + UpdateExclusionControls(); } private void buttonLocalPath_Click(object sender, EventArgs e) @@ -159,37 +162,75 @@ public static bool isValidSearchSpec(string input) /// private void btnAdd_Click(object sender, EventArgs e) { - //Create a directory picker dialog - var directoryPicker = new FolderBrowserDialog + //Exclusions are stored relative to the local path, so we need a valid one + var localPath = textBoxLocalPath.Text; + if (!IsLocalPathValid()) + { + UpdateExclusionControls(); + return; + } + + //Create a directory picker dialog, starting in the local path + using var directoryPicker = new FolderBrowserDialog { - Description = "Select a directory to exclude" + Description = "Select a directory to exclude", + InitialDirectory = localPath, + SelectedPath = localPath }; //Show it and check if the user picked a directory - if (directoryPicker.ShowDialog() == DialogResult.OK) + if (directoryPicker.ShowDialog() != DialogResult.OK) + return; + + //The directory must be below the local path. Store it relative to the local path. + if (!AppSettings.TryGetRelativeSubdirectory(localPath, directoryPicker.SelectedPath, out var newItem)) { - //Get the selected directory and add it to the list - string newItem = directoryPicker.SelectedPath; - listBox.Items.Add(newItem); - - //Sort the list items alphabetically - var items = listBox.Items.Cast().OrderBy(item => item).ToList(); - listBox.Items.Clear(); - foreach (var item in items) - { - listBox.Items.Add(item); - } + MessageBox.Show( + $"The excluded directory must be a subdirectory of the Local Path:{Environment.NewLine}{Environment.NewLine}{localPath}", + "Invalid Excluded Directory", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + return; + } - // Select the newly added item in the list - int index = listBox.Items.IndexOf(newItem); - if (index >= 0) - { - listBox.SelectedIndex = index; - } + //Already excluded? + var existing = listBox.Items.Cast() + .FirstOrDefault(item => string.Equals(item, newItem, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + listBox.SelectedItem = existing; + return; + } + + //Add it and sort the list items alphabetically + listBox.Items.Add(newItem); + var items = listBox.Items.Cast().OrderBy(item => item).ToList(); + listBox.Items.Clear(); + foreach (var item in items) + { + listBox.Items.Add(item); + } - //And save the new excluded directories to the settings - _settings?.ExcludedDirectories = listBox.Items.Cast().ToList(); + // Select the newly added item in the list + int index = listBox.Items.IndexOf(newItem); + if (index >= 0) + { + listBox.SelectedIndex = index; } + + //And save the new excluded directories to the settings + _settings?.ExcludedDirectories = listBox.Items.Cast().ToList(); + } + + private bool IsLocalPathValid() => + !String.IsNullOrWhiteSpace(textBoxLocalPath.Text) && Directory.Exists(textBoxLocalPath.Text); + + /// + /// Directories can only be excluded once a valid local path has been specified + /// + private void UpdateExclusionControls() + { + btnAdd.Enabled = IsLocalPathValid(); } /// diff --git a/docs/sftpsyncui.html b/docs/sftpsyncui.html index 27e8c3c..d256757 100644 --- a/docs/sftpsyncui.html +++ b/docs/sftpsyncui.html @@ -149,7 +149,7 @@

Search spec

 

Exclusions

 

-

You can use the Add and Remove buttons to manage the list of directories to be excluded from the sync process, regardless of whether those directories contain any files that match the Search Spec file extensions. You should only add directories that are below the main Local Path directory.

+

You can use the Add and Remove buttons to manage the list of directories to be excluded from the sync process, regardless of whether those directories contain any files that match the Search Spec file extensions. The Add button is available only once a valid Local Path has been specified, and only directories below the Local Path can be added. Excluded directories are saved relative to the Local Path.

 


From c5a2b6632661e1a232750a8ccc3c30128a1220d4 Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 09:22:56 -0800 Subject: [PATCH 2/6] Check excluded directories when the local path changes. The new local path is committed when the field loses focus, after the Browse picker, or on close. If any exclusions do not exist under it, the user can remove them or reject the new path. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSyncUI/SettingsForm.cs | 126 +++++++++++++++++++++++++++++++------ 1 file changed, 108 insertions(+), 18 deletions(-) diff --git a/SFTPSyncUI/SettingsForm.cs b/SFTPSyncUI/SettingsForm.cs index 31e8dc7..2715036 100644 --- a/SFTPSyncUI/SettingsForm.cs +++ b/SFTPSyncUI/SettingsForm.cs @@ -13,6 +13,8 @@ public partial class SettingsForm : Form private bool initialUiLoad = false; private bool _syncRunning = false; private bool _invalidRemotePathOnLoad = false; + private string _committedLocalPath = String.Empty; + private bool _committingLocalPath = false; private const string InvalidRemotePathMessage = "The remote path must be specified in Linux format (for example /dga1303/1tallent/win), " + @@ -34,8 +36,13 @@ public SettingsForm(AppSettings settings, bool syncRunning) textBoxLocalPath.Text = _settings.LocalPath; textBoxSearchSpec.Text = _settings.LocalSearchPattern; listBox.Items.AddRange(_settings.ExcludedDirectories.ToArray()); + _committedLocalPath = _settings.LocalPath; UpdateExclusionControls(); + //Check the local path (against the excluded directories) when leaving the field and when closing the form + textBoxLocalPath.Validating += (s, e) => CommitLocalPath(); + FormClosing += (s, e) => CommitLocalPath(); + //Remote system settings textBoxRemoteHost.Text = _settings.RemoteHost; textBoxRemoteUser.Text = _settings.RemoteUsername; @@ -87,32 +94,112 @@ private void SettingsForm_Shown(object sender, EventArgs e) private void textBoxLocalPath_TextChanged(object sender, EventArgs e) { - if (!initialUiLoad - && (String.IsNullOrWhiteSpace(textBoxLocalPath.Text) - || Directory.Exists(textBoxLocalPath.Text))) + //The new path is not saved here. It is committed (and checked against the excluded + //directories) when the user leaves the field, picks a directory, or closes the form, + //so that we don't react to partially typed paths. + UpdateExclusionControls(); + } + + /// + /// Save the local path from the text box, first checking that the excluded directories still exist under it. + /// If any do not, the user can either remove those exclusions or reject the new local path (the text box + /// is then put back to the previous path). + /// + /// False if the user rejected the new local path, otherwise true + private bool CommitLocalPath() + { + if (_settings == null || initialUiLoad || _committingLocalPath) + return true; + + _committingLocalPath = true; + try { - _settings?.LocalPath = textBoxLocalPath.Text; - } + var newPath = textBoxLocalPath.Text; + var blank = String.IsNullOrWhiteSpace(newPath); - UpdateExclusionControls(); + //A path that doesn't exist is not saved (as before), and the Add button stays disabled + if (!blank && !Directory.Exists(newPath)) + return true; + + if (string.Equals(newPath, _committedLocalPath, StringComparison.OrdinalIgnoreCase)) + return true; + + if (!blank) + { + var missing = listBox.Items.Cast() + .Where(relative => !Directory.Exists(Path.Combine(newPath, relative))) + .ToList(); + + if (missing.Count > 0) + { + var shown = string.Join(Environment.NewLine, missing.Take(10).Select(m => " " + m)); + if (missing.Count > 10) + shown += Environment.NewLine + $" ...and {missing.Count - 10} more"; + + var removeButton = new TaskDialogButton("Remove these exclusions"); + var chooseButton = new TaskDialogButton("Choose a different Local Path"); + + var page = new TaskDialogPage + { + Caption = "Excluded Directories", + Heading = "Some excluded directories do not exist under the new Local Path", + Text = $"The new Local Path is:{Environment.NewLine} {newPath}{Environment.NewLine}{Environment.NewLine}" + + $"These excluded directories are not subdirectories of it:{Environment.NewLine}{shown}", + Icon = TaskDialogIcon.Warning, + AllowCancel = true, + DefaultButton = chooseButton, + Buttons = { removeButton, chooseButton } + }; + + if (TaskDialog.ShowDialog(this, page) != removeButton) + { + //Reject the new local path + textBoxLocalPath.Text = _committedLocalPath; + return false; + } + + foreach (var item in missing) + listBox.Items.Remove(item); + + _settings.ExcludedDirectories = listBox.Items.Cast().ToList(); + } + } + + _settings.LocalPath = newPath; + _committedLocalPath = newPath; + return true; + } + finally + { + _committingLocalPath = false; + } } private void buttonLocalPath_Click(object sender, EventArgs e) { - using var folderDialog = new FolderBrowserDialog + //Keep asking until the user picks a local path that is acceptable, or cancels + while (true) { - Description = "Local path", - UseDescriptionForTitle = true, - ShowNewFolderButton = true, - InitialDirectory = !String.IsNullOrWhiteSpace(textBoxLocalPath.Text) && Directory.Exists(textBoxLocalPath.Text) - ? textBoxLocalPath.Text - : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) - }; + using var folderDialog = new FolderBrowserDialog + { + Description = "Local path", + UseDescriptionForTitle = true, + ShowNewFolderButton = true, + InitialDirectory = !String.IsNullOrWhiteSpace(textBoxLocalPath.Text) && Directory.Exists(textBoxLocalPath.Text) + ? textBoxLocalPath.Text + : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + }; + + if (folderDialog.ShowDialog() != DialogResult.OK + || string.IsNullOrWhiteSpace(folderDialog.SelectedPath)) + { + return; + } - if (folderDialog.ShowDialog() == DialogResult.OK - && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath)) - { textBoxLocalPath.Text = folderDialog.SelectedPath; + + if (CommitLocalPath()) + return; } } @@ -162,7 +249,10 @@ public static bool isValidSearchSpec(string input) /// private void btnAdd_Click(object sender, EventArgs e) { - //Exclusions are stored relative to the local path, so we need a valid one + //Exclusions are stored relative to the local path, so we need a valid, committed one + if (!CommitLocalPath()) + return; + var localPath = textBoxLocalPath.Text; if (!IsLocalPathValid()) { From 675d9f6b4646b48fc4e23dd88a49f8160360408a Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 09:24:40 -0800 Subject: [PATCH 3/6] Repair unescaped backslashes in hand-edited Windows paths when loading settings. The raw JSON text for LocalPath and ExcludedDirectories is fixed before parsing, and the file is resaved with correct escaping. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSyncUI/AppSettings.cs | 138 +++++++++++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 1 deletion(-) diff --git a/SFTPSyncUI/AppSettings.cs b/SFTPSyncUI/AppSettings.cs index 4ec5293..ba0627f 100644 --- a/SFTPSyncUI/AppSettings.cs +++ b/SFTPSyncUI/AppSettings.cs @@ -1,4 +1,5 @@  +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -16,6 +17,7 @@ public class AppSettings // Do we have a user settings file? bool justCreated = false; + bool pathsRepaired = false; if (!File.Exists(SettingsFile)) { @@ -35,6 +37,10 @@ public class AppSettings try { string jsonString = File.ReadAllText(SettingsFile); + + // Fix single backslashes in hand-edited Windows paths before the JSON is parsed + jsonString = RepairPathBackslashes(jsonString, out pathsRepaired); + settings = JsonSerializer.Deserialize(jsonString); if (settings != null) { @@ -53,7 +59,7 @@ public class AppSettings // Verify settings if (settings != null) { - var setingsChanged = false; + var setingsChanged = pathsRepaired; // Exclusions are stored relative to the local path. Validate them on every load (a user may have // hand-edited the file) and convert full paths from older settings files. This uses the configured @@ -107,6 +113,136 @@ public class AppSettings return settings ?? null; } + /// + /// Fix unescaped backslashes in the Windows path values (LocalPath and ExcludedDirectories) of the raw JSON text. + /// A path pasted into the file by hand has single backslashes (C:\dev\proj), which JSON requires to be doubled. + /// This must run before deserializing: sequences such as \d make the JSON invalid, and others (\t \n \r \b \f) + /// are valid escapes that would silently turn into control characters. Those are never valid in a path, so + /// they are treated as a backslash followed by a letter. + /// + internal static string RepairPathBackslashes(string json, out bool changed) + { + var sb = new StringBuilder(json.Length + 16); + string? currentKey = null; + bool inExcludedArray = false; + char previous = '\0'; // the previous significant character outside of strings ('"' after a string) + int i = 0; + + while (i < json.Length) + { + char c = json[i]; + + if (c == '"') + { + bool isValue = previous == ':' || (inExcludedArray && (previous == '[' || previous == ',')); + bool isPath = isValue && (inExcludedArray || currentKey == "LocalPath"); + + int start = i; + int j = i + 1; + + if (isPath) + { + sb.Append('"'); + while (j < json.Length) + { + char ch = json[j]; + + if (ch == '"') + break; + + if (ch != '\\') + { + sb.Append(ch); + j++; + continue; + } + + char next = j + 1 < json.Length ? json[j + 1] : '\0'; + + if (next == '\\' || next == '/') + { + // Already escaped + sb.Append(ch).Append(next); + j += 2; + } + else if (next == 'u' && j + 5 < json.Length && json.Substring(j + 2, 4).All(Uri.IsHexDigit)) + { + // Unicode escape + sb.Append(json, j, 6); + j += 6; + } + else if (next == '"' && IsEndOfValue(json, j + 2)) + { + // A path ending in a backslash: the quote closes the string + sb.Append(@"\\"); + j++; + } + else if (next == '"') + { + // Genuinely escaped quote; leave it alone + sb.Append(ch).Append(next); + j += 2; + } + else + { + // A lone backslash (including \b \f \n \r \t, which can't be in a path) + sb.Append(@"\\"); + j++; + } + } + + if (j < json.Length) + sb.Append('"'); + } + else + { + while (j < json.Length && json[j] != '"') + { + if (json[j] == '\\') + j++; + j++; + } + + sb.Append(json, start, Math.Min(j + 1, json.Length) - start); + + // A string that is not a value is a key + if (!isValue) + currentKey = json.Substring(start + 1, Math.Min(j, json.Length) - start - 1); + } + + i = j + 1; + previous = '"'; + continue; + } + + sb.Append(c); + i++; + + if (char.IsWhiteSpace(c)) + continue; + + previous = c; + + if (c == '[' && currentKey == "ExcludedDirectories") + inExcludedArray = true; + else if (c == ']') + inExcludedArray = false; + } + + var result = sb.ToString(); + changed = !string.Equals(result, json, StringComparison.Ordinal); + return result; + } + + // True if only whitespace follows before a ',' ']' '}' or the end of the text + private static bool IsEndOfValue(string json, int index) + { + while (index < json.Length && char.IsWhiteSpace(json[index])) + index++; + + return index >= json.Length || json[index] == ',' || json[index] == ']' || json[index] == '}'; + } + // Path.GetInvalidPathChars() only reports '|' and control characters on modern .NET, so list the rest explicitly private static bool HasInvalidPathCharacters(string path) => path.IndexOfAny(['<', '>', '"', '|', '?', '*']) >= 0 From bbdc203ebd258131f6b3a87420a145f80449c1a2 Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 10:00:17 -0800 Subject: [PATCH 4/6] Log list: allow a single row or adjacent range to be selected, with a Copy context menu. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSyncUI/MainForm.Designer.cs | 2 +- SFTPSyncUI/MainForm.cs | 105 +++++++++++++++++++++++++++++++- 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/SFTPSyncUI/MainForm.Designer.cs b/SFTPSyncUI/MainForm.Designer.cs index 270854c..6337702 100644 --- a/SFTPSyncUI/MainForm.Designer.cs +++ b/SFTPSyncUI/MainForm.Designer.cs @@ -60,7 +60,7 @@ private void InitializeComponent() listBoxMessages.Margin = new Padding(10, 11, 10, 11); listBoxMessages.Name = "listBoxMessages"; listBoxMessages.ScrollAlwaysVisible = true; - listBoxMessages.SelectionMode = SelectionMode.MultiSimple; + listBoxMessages.SelectionMode = SelectionMode.MultiExtended; listBoxMessages.Size = new Size(1184, 705); listBoxMessages.TabIndex = 14; listBoxMessages.DrawItem += ListBoxMessages_DrawItem; diff --git a/SFTPSyncUI/MainForm.cs b/SFTPSyncUI/MainForm.cs index 9fd30c7..b6f093d 100644 --- a/SFTPSyncUI/MainForm.cs +++ b/SFTPSyncUI/MainForm.cs @@ -76,6 +76,103 @@ public MainForm(AppSettings settings) WindowState = _settings.StartInTray ? FormWindowState.Minimized : FormWindowState.Normal; ShowInTaskbar = WindowState != FormWindowState.Minimized; + //Log list: a selection is one row or a range of adjacent rows, and can be copied + SetupLogListSelection(); + } + + // ----- LOG LIST SELECTION AND COPY ----- + + private bool _adjustingLogSelection = false; + + private void SetupLogListSelection() + { + var logContextMenu = new ContextMenuStrip(); + var copyItem = new ToolStripMenuItem("&Copy") + { + ShortcutKeyDisplayString = "Ctrl+C" + }; + copyItem.Click += (s, e) => CopySelectedLogRows(); + logContextMenu.Items.Add(copyItem); + + //Only offer the menu when there is something selected + logContextMenu.Opening += (s, e) => e.Cancel = listBoxMessages.SelectedItems.Count == 0; + listBoxMessages.ContextMenuStrip = logContextMenu; + + listBoxMessages.SelectedIndexChanged += (s, e) => EnsureContiguousLogSelection(); + + //Right-clicking a row that is not selected selects just that row, like most list controls + listBoxMessages.MouseDown += (s, e) => + { + if (e.Button != MouseButtons.Right) + return; + + int index = listBoxMessages.IndexFromPoint(e.Location); + if (index >= 0 && !listBoxMessages.GetSelected(index)) + { + listBoxMessages.ClearSelected(); + listBoxMessages.SetSelected(index, true); + } + }; + + listBoxMessages.KeyDown += (s, e) => + { + if (e.Control && e.KeyCode == Keys.C) + { + CopySelectedLogRows(); + e.Handled = true; + e.SuppressKeyPress = true; + } + }; + } + + /// + /// Extended selection allows Ctrl+click to build a scattered selection. Only a single row or a range of + /// adjacent rows is allowed, so fill any gap between the first and last selected rows. + /// + private void EnsureContiguousLogSelection() + { + if (_adjustingLogSelection || listBoxMessages.SelectedIndices.Count < 2) + return; + + int first = listBoxMessages.SelectedIndices[0]; + int last = listBoxMessages.SelectedIndices[listBoxMessages.SelectedIndices.Count - 1]; + + if (last - first + 1 == listBoxMessages.SelectedIndices.Count) + return; + + _adjustingLogSelection = true; + try + { + listBoxMessages.BeginUpdate(); + for (int i = first; i <= last; i++) + listBoxMessages.SetSelected(i, true); + } + finally + { + listBoxMessages.EndUpdate(); + _adjustingLogSelection = false; + } + } + + /// + /// Copy the selected log rows to the clipboard, one per line, in the order they appear in the list + /// + private void CopySelectedLogRows() + { + if (listBoxMessages.SelectedItems.Count == 0) + return; + + var text = string.Join(Environment.NewLine, listBoxMessages.SelectedItems.Cast().Select(item => item.ToString())); + + try + { + Clipboard.SetText(text); + } + catch (Exception ex) + { + //The clipboard can be locked by another application + MessageBox.Show($"Failed to copy to the clipboard: {ex.Message}", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); + } } private void mnuFileExit_Click(object sender, EventArgs e) { @@ -157,10 +254,14 @@ private void AppendLog(string message) private void AddMessage(string message) { + // If the user is looking at a selection, keep the view where it is (the new row pushes everything + // down by one), otherwise keep the newest message at the top + int topIndex = listBoxMessages.TopIndex; + bool keepView = listBoxMessages.SelectedItems.Count > 0 && topIndex > 0; + listBoxMessages.Items.Insert(0, message); - // Keep newest at top - listBoxMessages.TopIndex = 0; + listBoxMessages.TopIndex = keepView ? topIndex + 1 : 0; // Optional: trim excess from UI if _log did a dequeue if (listBoxMessages.Items.Count > 1000) From f0b59956933b10babecdff9bce023c8d78a59c84 Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 10:03:43 -0800 Subject: [PATCH 5/6] Bump version to 1.12. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSync/SFTPSync.csproj | 6 +++--- SFTPSyncLib/SFTPSyncLib.csproj | 6 +++--- SFTPSyncSetup/Product.wxs | 2 +- SFTPSyncSetup/SFTPSyncSetup.wixproj | 2 +- SFTPSyncStop/SFTPSyncStop.csproj | 6 +++--- SFTPSyncUI/SFTPSyncUI.csproj | 6 +++--- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/SFTPSync/SFTPSync.csproj b/SFTPSync/SFTPSync.csproj index 3001cc3..6b6df8f 100644 --- a/SFTPSync/SFTPSync.csproj +++ b/SFTPSync/SFTPSync.csproj @@ -6,9 +6,9 @@ enable enable AnyCPU;x64 - 1.11 - 1.11 - 1.11 + 1.12 + 1.12 + 1.12 diff --git a/SFTPSyncLib/SFTPSyncLib.csproj b/SFTPSyncLib/SFTPSyncLib.csproj index c4f8fa1..17fa5d0 100644 --- a/SFTPSyncLib/SFTPSyncLib.csproj +++ b/SFTPSyncLib/SFTPSyncLib.csproj @@ -5,9 +5,9 @@ enable x64;AnyCPU enable - 1.11 - 1.11 - 1.11 + 1.12 + 1.12 + 1.12 diff --git a/SFTPSyncSetup/Product.wxs b/SFTPSyncSetup/Product.wxs index 4ed1746..a151d6f 100644 --- a/SFTPSyncSetup/Product.wxs +++ b/SFTPSyncSetup/Product.wxs @@ -5,7 +5,7 @@ Id="*" Name="SFTPSync" Language="1033" - Version="1.11" + Version="1.12" Manufacturer="Synergex International Corporation" UpgradeCode="6000f870-b811-4e22-b80b-5b8956317d09"> diff --git a/SFTPSyncSetup/SFTPSyncSetup.wixproj b/SFTPSyncSetup/SFTPSyncSetup.wixproj index 5fd897c..bd26796 100644 --- a/SFTPSyncSetup/SFTPSyncSetup.wixproj +++ b/SFTPSyncSetup/SFTPSyncSetup.wixproj @@ -6,7 +6,7 @@ 3.10 5074cbcb-641b-4a9c-b3bc-8dd0b78810a6 2.0 - SFTPSync-1.11 + SFTPSync-1.12 Package SFTPSyncSetup diff --git a/SFTPSyncStop/SFTPSyncStop.csproj b/SFTPSyncStop/SFTPSyncStop.csproj index 2e1863a..e8b3162 100644 --- a/SFTPSyncStop/SFTPSyncStop.csproj +++ b/SFTPSyncStop/SFTPSyncStop.csproj @@ -6,9 +6,9 @@ enable enable AnyCPU;x64 - 1.11 - 1.11 - 1.11 + 1.12 + 1.12 + 1.12 diff --git a/SFTPSyncUI/SFTPSyncUI.csproj b/SFTPSyncUI/SFTPSyncUI.csproj index 6f8511b..fc1a216 100644 --- a/SFTPSyncUI/SFTPSyncUI.csproj +++ b/SFTPSyncUI/SFTPSyncUI.csproj @@ -20,10 +20,10 @@ LICENSE.md True Synergex International, Inc. - 1.11 - 1.11 + 1.12 + 1.12 preview - 1.11 + 1.12 From ac718efe9d9b070026dba334cdbaf341dac2bc5c Mon Sep 17 00:00:00 2001 From: Steve Ives Date: Fri, 20 Nov 2026 10:06:05 -0800 Subject: [PATCH 6/6] Stop sync without blocking the UI thread. Closing the SFTP connections is a blocking network call, so do it in parallel on background threads, keep Start disabled until teardown completes, and log any connection that takes more than 2 seconds to close. Co-Authored-By: Claude Sonnet 5.5 --- SFTPSyncUI/MainForm.cs | 16 +++++++++++++--- SFTPSyncUI/SFTPSyncUI.cs | 33 +++++++++++++++++++++------------ 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/SFTPSyncUI/MainForm.cs b/SFTPSyncUI/MainForm.cs index b6f093d..eb8fbb4 100644 --- a/SFTPSyncUI/MainForm.cs +++ b/SFTPSyncUI/MainForm.cs @@ -330,14 +330,24 @@ private void startSync() } } - private void stopSync() + private async void stopSync() { if (syncRunning) { - SFTPSyncUI.StopSync(AppendLog); + // Stopping can take a while if the server is slow to close connections. Keep the UI responsive, + // and don't allow a new sync to start until the old one has been torn down. syncRunning = false; - mnuFileStartSync.Enabled = true; mnuFileStopSync.Enabled = false; + mnuFileStartSync.Enabled = false; + + try + { + await SFTPSyncUI.StopSync(AppendLog); + } + finally + { + mnuFileStartSync.Enabled = true; + } } } diff --git a/SFTPSyncUI/SFTPSyncUI.cs b/SFTPSyncUI/SFTPSyncUI.cs index 5508414..637c92c 100644 --- a/SFTPSyncUI/SFTPSyncUI.cs +++ b/SFTPSyncUI/SFTPSyncUI.cs @@ -419,7 +419,7 @@ await runInitialSyncTask.ContinueWith(t => /// /// /// - public static async void StopSync(Action loggerAction) + public static async Task StopSync(Action loggerAction) { var setStatus = new Action(status => { @@ -444,20 +444,29 @@ public static async void StopSync(Action loggerAction) RemoteSyncWorkers.Clear(); } - foreach (var remoteSync in workerSnapshot) + // Closing an SFTP connection is a blocking network call that can take a long time if the server is slow + // to respond, so tear everything down on background threads (in parallel) to keep the UI responsive. + await Task.Run(() => { - try + Parallel.ForEach(workerSnapshot, remoteSync => { - remoteSync.Dispose(); - } - catch { /* Swallow any exceptions */ } - } + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + try + { + remoteSync.Dispose(); + } + catch { /* Swallow any exceptions */ } - lock (DirectorLock) - { - activeDirector?.Dispose(); - activeDirector = null; - } + if (stopwatch.Elapsed > TimeSpan.FromSeconds(2)) + Logger.LogInfo($"Closing a connection took {stopwatch.Elapsed.TotalSeconds:0.0} seconds"); + }); + + lock (DirectorLock) + { + activeDirector?.Dispose(); + activeDirector = null; + } + }); var task = syncTask; if (task != null)