Skip to content

Commit b77a73b

Browse files
BornToBeRootclaude
andcommitted
Fix: Run command third review findings
- Run command "settings" with a filtered application list no longer crashes (the search is cleared first). - The dialog has a title bar with a close button. - The DNS server argument is validated (configured name or IP address / host with a domain); a mistyped type like "aaa" is reported. - A request is only passed to the application if it is shown. - After running a suggestion with the mouse, the focus isn't taken back by the closing dialog. - History: entries of hidden applications are not shown; commands are stored case-insensitively (ListHelper.Modify with a comparer). - Text after a quoted profile name is an unknown argument. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4de3fdb commit b77a73b

10 files changed

Lines changed: 123 additions & 20 deletions

File tree

‎Source/NETworkManager.Models/RunCommand/RunCommandParser.cs‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,35 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
8585
// Profile: the rest of the input after "@" is the name.
8686
if (words[1].StartsWith('@'))
8787
{
88-
// Quotes around the name or the whole target (e.g. @"My Server" or "@My Server") are removed.
89-
var profileName = input[(input.IndexOf('@') + 1)..].Trim().Trim('"').Trim();
88+
var rest = input[(input.IndexOf('@') + 1)..].Trim();
89+
string profileName;
90+
string textAfterName = null;
91+
92+
// Name in quotes (e.g. @"My Server"): text after the closing quote is not part of the name.
93+
var closingQuote = rest.StartsWith('"') ? rest.IndexOf('"', 1) : -1;
94+
95+
if (closingQuote > 0)
96+
{
97+
profileName = rest[1..closingQuote].Trim();
98+
99+
var remainder = rest[(closingQuote + 1)..].Trim();
100+
101+
if (remainder.Length > 0)
102+
textAfterName = remainder;
103+
}
104+
else
105+
{
106+
// Quotes around the whole target (e.g. "@My Server") or an open quote while typing are removed.
107+
profileName = rest.Trim('"').Trim();
108+
}
90109

91110
var error = !command.SupportsProfile
92111
? RunCommandParseError.NoProfiles
93112
: profileName.Length == 0
94113
? RunCommandParseError.MissingProfileName
95-
: RunCommandParseError.None;
114+
: textAfterName != null
115+
? RunCommandParseError.UnknownArgument
116+
: RunCommandParseError.None;
96117

97118
return new RunCommandParseResult
98119
{
@@ -103,7 +124,12 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
103124
CurrentWord = "@" + profileName,
104125
InputBeforeCurrentWord = commandPrefix,
105126
Error = error,
106-
ErrorValue = error == RunCommandParseError.NoProfiles ? command.Command : null
127+
ErrorValue = error switch
128+
{
129+
RunCommandParseError.NoProfiles => command.Command,
130+
RunCommandParseError.UnknownArgument => textAfterName,
131+
_ => null
132+
}
107133
};
108134
}
109135

‎Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,16 @@ public void QuotedProfileName(string input)
168168
Assert.Equal("Web Server 01", result.ProfileName);
169169
}
170170

171+
[Fact]
172+
public void TextAfterAQuotedProfileName()
173+
{
174+
var result = Parse("rdp @\"Web Server\" x");
175+
176+
Assert.Equal("Web Server", result.ProfileName);
177+
Assert.Equal(RunCommandParseError.UnknownArgument, result.Error);
178+
Assert.Equal("x", result.ErrorValue);
179+
}
180+
171181
[Fact]
172182
public void ListThatIsBeingTyped()
173183
{

‎Source/NETworkManager.Tests/Utilities/ListHelperTests.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,16 @@ public void IgnoresDefaultValue()
107107
Assert.Equal([22], list);
108108
}
109109

110+
[Fact]
111+
public void UsesTheComparerAndKeepsTheLatestSpelling()
112+
{
113+
ObservableCollection<string> list = ["a", "ping 10.0.0.1"];
114+
115+
ListHelper.Modify(list, "Ping 10.0.0.1", 5, StringComparer.OrdinalIgnoreCase);
116+
117+
Assert.Equal(["Ping 10.0.0.1", "a"], list);
118+
}
119+
110120
[Fact]
111121
public void ThrowsIfTheLengthIsNotPositive()
112122
{

‎Source/NETworkManager.Utilities/ListHelper.cs‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,48 @@ public static class ListHelper
1919
/// <param name="list">List to modify (e.g. a history of the settings).</param>
2020
/// <param name="entry">Entry to add to the list.</param>
2121
/// <param name="length">Maximum length of the list. Oldest entries will be removed if the list exceeds this length.</param>
22+
/// <param name="comparer">Comparer for existing entries (e.g. case-insensitive). If null, the default comparer is used.</param>
2223
/// <typeparam name="T">Type of the list entries. Currently <see cref="string"/> or <see cref="int"/>.</typeparam>
23-
public static void Modify<T>(ObservableCollection<T> list, T entry, int length)
24+
public static void Modify<T>(ObservableCollection<T> list, T entry, int length,
25+
IEqualityComparer<T> comparer = null)
2426
{
27+
comparer ??= EqualityComparer<T>.Default;
28+
2529
if (length <= 0)
2630
throw new ArgumentOutOfRangeException(nameof(length), "Length must be greater than zero.");
2731

2832
if (EqualityComparer<T>.Default.Equals(entry, default) || entry is string text && string.IsNullOrEmpty(text))
2933
return;
3034

31-
var index = list.IndexOf(entry);
35+
var index = -1;
36+
37+
for (var i = 0; i < list.Count; i++)
38+
{
39+
if (!comparer.Equals(list[i], entry))
40+
continue;
41+
42+
index = i;
43+
break;
44+
}
3245

33-
if (index > 0)
34-
list.Move(index, 0);
35-
else if (index < 0)
46+
if (index < 0)
47+
{
3648
list.Insert(0, entry);
49+
}
50+
else
51+
{
52+
if (index > 0)
53+
list.Move(index, 0);
54+
55+
// Keep the latest spelling (e.g. with a case-insensitive comparer)
56+
if (!EqualityComparer<T>.Default.Equals(list[0], entry))
57+
list[0] = entry;
58+
}
3759

3860
// Remove duplicates (e.g. from older settings files)
3961
for (var i = list.Count - 1; i > 0; i--)
4062
{
41-
if (EqualityComparer<T>.Default.Equals(list[i], entry))
63+
if (comparer.Equals(list[i], entry))
4264
list.RemoveAt(i);
4365
}
4466

‎Source/NETworkManager/MainWindow.xaml.cs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,8 +1065,9 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro
10651065
if (string.IsNullOrEmpty(request.Target) && request.Profile == null)
10661066
return;
10671067

1068-
// Create a new tab / perform the action in the application
1069-
if (ContentControlApplication.Content is IApplicationRequestHandler handler)
1068+
// Create a new tab / perform the action in the application (only if it is shown)
1069+
if (SelectedApplication?.Name == request.Application &&
1070+
ContentControlApplication.Content is IApplicationRequestHandler handler)
10701071
handler.Open(request);
10711072
else
10721073
Log.Warn($"Application {request.Application} cannot handle a request with a target or profile.");
@@ -1158,6 +1159,9 @@ private void NavigationManager_SettingsRequested(object sender, EventArgs e)
11581159
if (SettingsViewIsOpen)
11591160
return;
11601161

1162+
// Clear the search, otherwise no application may be selected (the settings page depends on it)
1163+
ApplicationSearch = string.Empty;
1164+
11611165
OpenSettings();
11621166
}
11631167

‎Source/NETworkManager/RunCommandManager.cs‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using System.Collections.Generic;
1313
using System.Globalization;
1414
using System.Linq;
15+
using System.Net;
1516
using System.Windows.Controls;
1617

1718
namespace NETworkManager;
@@ -200,7 +201,9 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT
200201
_ => null
201202
};
202203

203-
error = Validate(argumentValidator, result.Argument);
204+
error = result.Command.Argument == RunCommandArgument.DNSServer
205+
? ValidateDNSServer(result.Argument)
206+
: Validate(argumentValidator, result.Argument);
204207

205208
if (error != null)
206209
return error;
@@ -218,6 +221,26 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT
218221
return null;
219222
}
220223

224+
/// <summary>
225+
/// Validates the DNS server argument: the name of a configured DNS server, or custom DNS server(s) in the format
226+
/// of the DNS lookup (IP address or host with a domain, optional port). A single word that is neither (e.g. a
227+
/// mistyped type like "aaa") is an unknown argument instead of a DNS server.
228+
/// </summary>
229+
private static string ValidateDNSServer(string dnsServer)
230+
{
231+
if (GetDNSServers().Any(x => string.Equals(x, dnsServer, StringComparison.OrdinalIgnoreCase)))
232+
return null;
233+
234+
foreach (var server in dnsServer.Split(';'))
235+
{
236+
if (!ServerConnectionInfo.TryParse(server, out var serverInfo, 53, TransportProtocol.Udp) ||
237+
!IPAddress.TryParse(serverInfo.Server, out _) && !serverInfo.Server.Contains('.'))
238+
return string.Format(Strings.UnknownArgumentX, server);
239+
}
240+
241+
return null;
242+
}
243+
221244
private static string Validate(ValidationRule validator, string value)
222245
{
223246
if (validator == null)

‎Source/NETworkManager/ViewModels/RunCommandViewModel.cs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,12 @@ public RunCommandViewModel(Action<RunCommandViewModel> runHandler, Action<RunCom
5757
_commands = RunCommandManager.GetCommands();
5858
_runHandler = runHandler;
5959

60-
_history = [.. SettingsManager.Current.RunCommand_History.Select(x => (x, RunCommandParser.Parse(x, _commands).Command))];
60+
// Entries of commands that are not available anymore (e.g. a hidden application) are not shown.
61+
_history =
62+
[
63+
.. SettingsManager.Current.RunCommand_History.Select(x => (x, RunCommandParser.Parse(x, _commands).Command))
64+
.Where(x => x.Command != null)
65+
];
6166

6267
CancelCommand = new RelayCommand(_ => cancelHandler(this));
6368

@@ -212,8 +217,9 @@ public void Run()
212217
Request = request;
213218
IsSettings = result.Command.Type == RunCommandType.Setting;
214219

220+
// Commands are case-insensitive, so "Ping 10.0.0.1" and "ping 10.0.0.1" are the same entry.
215221
ListHelper.Modify(SettingsManager.Current.RunCommand_History, text.Trim(),
216-
SettingsManager.Current.General_HistoryListEntries);
222+
SettingsManager.Current.General_HistoryListEntries, StringComparer.OrdinalIgnoreCase);
217223

218224
_runHandler(this);
219225
}

‎Source/NETworkManager/Views/RunCommandChildWindow.xaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
1313
xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
1414
Style="{StaticResource DefaultChildWindow}"
15-
ShowTitleBar="False"
16-
ShowCloseButton="False"
15+
Title="{x:Static localization:Strings.RunCommand}"
16+
CloseButtonCommand="{Binding CancelCommand}"
1717
AllowMove="False"
1818
ChildWindowWidth="650"
1919
VerticalContentAlignment="Top"

‎Source/NETworkManager/Views/RunCommandChildWindow.xaml.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ private void ListBoxSuggestions_OnPreviewMouseLeftButtonUp(object sender, MouseB
6161
ViewModel.SelectedSuggestion = (RunCommandSuggestion)item.DataContext;
6262
ViewModel.Run();
6363

64-
TextBoxInput.Focus();
64+
// The dialog stays open if the input is not valid (otherwise the opened application or dialog gets the focus).
65+
if (IsOpen)
66+
TextBoxInput.Focus();
6567
}
6668

6769
private void ListBoxSuggestions_OnSelectionChanged(object sender, SelectionChangedEventArgs e)

‎Website/docs/run-command.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ All features that accept a target also accept a profile (`@profile`). The other
5050
:::note
5151

5252
- **Remote Desktop, PowerShell, PuTTY, TigerVNC and Web Console** open the connect dialog with the host, so the connection settings can be adjusted before connecting. A profile connects directly with its settings.
53-
- **DNS lookup:** The type is the DNS record type (`a`, `aaaa`, `any`, `caa`, `cname`, `dnskey`, `mx`, `ns`, `ptr`, `soa`, `srv`, `txt`). Without a type, IP addresses are looked up with `ptr` and other hosts with the type selected in the feature. The DNS server is the name of a configured DNS server (case-insensitive, e.g. `cloudflare`) or a custom DNS server (e.g. `1.1.1.1`).
53+
- **DNS lookup:** The type is the DNS record type (`a`, `aaaa`, `any`, `caa`, `cname`, `dnskey`, `mx`, `ns`, `ptr`, `soa`, `srv`, `txt`). Without a type, IP addresses are looked up with `ptr` and other hosts with the type selected in the feature. The DNS server is the name of a configured DNS server (case-insensitive, e.g. `cloudflare`) or custom DNS server(s): an IP address or a host with a domain, with an optional port, separated by `;` (e.g. `1.1.1.1`, `dns.google:53`).
5454
- **RDAP:** The type is `domain`, `nameserver`, `tld`, `ip`, `asn` or `entity`. Without a type, it is detected from the query (see [RDAP](./application/rdap.md#example-inputs)).
5555
- **Wake on LAN:** The magic packet is sent to the broadcast address (or the one last used in the feature). If there is no valid broadcast address yet, the MAC address is only filled in. A profile sends the magic packet with its settings.
5656

@@ -75,6 +75,6 @@ While typing, suggestions are shown below the input:
7575
| `Up`, `Down` | Select a suggestion |
7676
| `Tab` | Insert the selected suggestion into the input |
7777
| `Enter` | Run the selected suggestion |
78-
| `Esc` | Close the dialog |
78+
| `Esc` | Close the dialog (or the close button) |
7979

8080
Run commands are saved in a history (the number of entries is set in [Settings > General](./settings/general.md)).

0 commit comments

Comments
 (0)