Skip to content

Commit 4de3fdb

Browse files
BornToBeRootclaude
andcommitted
Fix: Run command second review findings, IP Geolocation and Wake on LAN
- Enter runs what was typed: no preselected suggestion for an empty input or an unknown command with arguments (e.g. "pin 10.0.0.1"); completing a command keeps the arguments. - "@": a profile is only preselected if exactly one matches, so duplicate names show the error and the profiles to select. - Parser: a list that is being typed ("10.0.0.1; ") stays the target, ";" in quotes is kept, quotes around "@name" are removed. - Web Console requests require the WebView2 runtime. - The run command "settings" keeps the open settings page. - History and profiles are loaded once per dialog. - New commands: ipgeolocation (geo) and wakeonlan (wol <MAC> [broadcast]). - Application list: removed a redundant scroll on startup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fe9631f commit 4de3fdb

14 files changed

Lines changed: 194 additions & 32 deletions

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@ public enum RunCommandArgument
77
{
88
None,
99
Ports,
10-
DNSServer
10+
DNSServer,
11+
Broadcast
1112
}

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ namespace NETworkManager.Models.RunCommand;
1111
public static partial class RunCommandParser
1212
{
1313
/// <summary>
14-
/// A list separator with whitespace around it ("10.0.0.1; 10.0.0.2").
14+
/// A list separator with whitespace around it ("10.0.0.1; 10.0.0.2"), or a value in quotes, which is kept as it is.
1515
/// </summary>
16-
[GeneratedRegex(@"\s*;\s*")]
17-
private static partial Regex ListSeparatorRegex();
16+
[GeneratedRegex("\"[^\"]*(?:\"|$)|\\s*;\\s*")]
17+
private static partial Regex ListSeparatorOrQuoteRegex();
1818

1919
/// <summary>
2020
/// A word: a value in quotes (can contain spaces, the closing quote can be missing while typing) or a value
@@ -40,12 +40,16 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
4040
{
4141
input = (input ?? string.Empty).TrimStart();
4242

43+
// Whitespace around ";" is removed (outside of quotes), so a list that is being typed ("10.0.0.1; ") is still
44+
// the same word.
45+
var normalized = ListSeparatorOrQuoteRegex().Replace(input, x => x.Value.StartsWith('"') ? x.Value : ";");
46+
4347
// Words as typed (with quotes, to rebuild the input) and their values (without quotes)
44-
var tokens = WordRegex().Matches(ListSeparatorRegex().Replace(input, ";")).Select(x => x.Value).ToArray();
48+
var tokens = WordRegex().Matches(normalized).Select(x => x.Value).ToArray();
4549
var words = tokens.Select(Unquote).ToArray();
4650

4751
// Whitespace in an open quote (e.g. "Google ) is part of the word that is being typed.
48-
var endsWithWhitespace = input.Length > 0 && char.IsWhiteSpace(input[^1]) &&
52+
var endsWithWhitespace = normalized.Length > 0 && char.IsWhiteSpace(normalized[^1]) &&
4953
!(tokens.Length > 0 && IsOpenQuote(tokens[^1]));
5054

5155
if (words.Length == 0)
@@ -81,7 +85,8 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
8185
// Profile: the rest of the input after "@" is the name.
8286
if (words[1].StartsWith('@'))
8387
{
84-
var profileName = Unquote(input[(input.IndexOf('@') + 1)..].Trim());
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();
8590

8691
var error = !command.SupportsProfile
8792
? RunCommandParseError.NoProfiles

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

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,14 +158,35 @@ public void CompletionKeepsQuotes()
158158
Assert.Equal("dns borntoberoot.net \"Google Public DNS\" ", result.InputBeforeCurrentWord);
159159
}
160160

161-
[Fact]
162-
public void QuotedProfileName()
161+
[Theory]
162+
[InlineData("rdp @\"Web Server 01\"")]
163+
[InlineData("rdp \"@Web Server 01\"")]
164+
public void QuotedProfileName(string input)
163165
{
164-
var result = Parse("rdp @\"Web Server 01\"");
166+
var result = Parse(input);
165167

166168
Assert.Equal("Web Server 01", result.ProfileName);
167169
}
168170

171+
[Fact]
172+
public void ListThatIsBeingTyped()
173+
{
174+
// "; " is the separator of a list that is still being typed, not the end of the target.
175+
var result = Parse("ping 10.0.0.1; ");
176+
177+
Assert.Equal(RunCommandPosition.Target, result.Position);
178+
Assert.Equal("10.0.0.1;", result.Target);
179+
Assert.Equal("ping ", result.InputBeforeCurrentWord);
180+
}
181+
182+
[Fact]
183+
public void SemicolonInQuotesIsKept()
184+
{
185+
var result = Parse("dns borntoberoot.net \"DNS ; Server\"");
186+
187+
Assert.Equal("DNS ; Server", result.Argument);
188+
}
189+
169190
[Fact]
170191
public void HostsAndType()
171192
{

‎Source/NETworkManager/ApplicationRequest.cs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,17 @@ public sealed record PortScannerRequest() : ApplicationRequest(ApplicationName.P
5151
public string Ports { get; init; }
5252
}
5353

54+
/// <summary>
55+
/// Request to open Wake on LAN.
56+
/// </summary>
57+
public sealed record WakeOnLANRequest() : ApplicationRequest(ApplicationName.WakeOnLAN)
58+
{
59+
/// <summary>
60+
/// Broadcast address. If null, the broadcast address of the application is used.
61+
/// </summary>
62+
public string Broadcast { get; init; }
63+
}
64+
5465
/// <summary>
5566
/// Request to open RDAP.
5667
/// </summary>

‎Source/NETworkManager/MainWindow.xaml.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -644,10 +644,6 @@ private void LoadApplicationList()
644644
SelectedApplication = applicationList.FirstOrDefault(x => x.IsDefault) ??
645645
applicationList.FirstOrDefault(x => x.IsVisible);
646646

647-
// Scroll into view
648-
if (SelectedApplication != null)
649-
ListViewApplication.ScrollIntoView(SelectedApplication);
650-
651647
// Expand application view
652648
ApplicationViewIsExpanded = SettingsManager.Current.ExpandApplicationView;
653649
}
@@ -1027,7 +1023,7 @@ private void ClearSearchOnApplicationListMinimize()
10271023

10281024
ApplicationSearch = string.Empty;
10291025

1030-
// Scroll into view
1026+
// Scroll into view. The selection doesn't change here, so ListViewApplication_OnSelectionChanged doesn't scroll.
10311027
ListViewApplication.ScrollIntoView(SelectedApplication);
10321028
}
10331029

@@ -1158,6 +1154,10 @@ private void OpenSettings()
11581154

11591155
private void NavigationManager_SettingsRequested(object sender, EventArgs e)
11601156
{
1157+
// The settings are already open (e.g. run command "settings"), keep the current page.
1158+
if (SettingsViewIsOpen)
1159+
return;
1160+
11611161
OpenSettings();
11621162
}
11631163

‎Source/NETworkManager/RunCommandManager.cs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT
181181
ApplicationName.RemoteDesktop => new RemoteDesktopHostnameAndPortValidator(),
182182
ApplicationName.WebConsole => new HttpAndHttpsUriValidator(),
183183
ApplicationName.Whois => new DomainValidator(),
184+
ApplicationName.IPGeolocation => new IPAddressOrHostnameValidator(),
185+
ApplicationName.WakeOnLAN => new MACAddressValidator(),
184186
_ => null
185187
};
186188

@@ -189,8 +191,20 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT
189191
if (error != null)
190192
return error;
191193

192-
if (result.Command.Argument == RunCommandArgument.Ports && result.Argument != null)
193-
return Validate(new PortRangeValidator(), result.Argument);
194+
if (result.Argument != null)
195+
{
196+
ValidationRule argumentValidator = result.Command.Argument switch
197+
{
198+
RunCommandArgument.Ports => new PortRangeValidator(),
199+
RunCommandArgument.Broadcast => new IPv4AddressValidator(),
200+
_ => null
201+
};
202+
203+
error = Validate(argumentValidator, result.Argument);
204+
205+
if (error != null)
206+
return error;
207+
}
194208

195209
// RDAP: the query must match the type (e.g. "1.10" as ASN)
196210
if (result.Command.Application == ApplicationName.RDAP)
@@ -231,6 +245,7 @@ private static ApplicationRequest CreateRequest(RunCommandParseResult result)
231245
QueryType = result.Type != null ? Enum.Parse<QueryType>(result.Type, true) : null
232246
},
233247
ApplicationName.PortScanner => new PortScannerRequest { Target = result.Target, Ports = result.Argument },
248+
ApplicationName.WakeOnLAN => new WakeOnLANRequest { Target = result.Target, Broadcast = result.Argument },
234249
ApplicationName.RDAP => new RDAPRequest { Target = result.Target, QueryType = GetRDAPQueryType(result.Type) },
235250
_ => new ApplicationRequest(result.Command.Application) { Target = result.Target }
236251
};
@@ -272,6 +287,9 @@ [.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]),
272287
ApplicationName.RDAP => Create(name, [], $"{Required(Strings.Query)} {Optional(Strings.Type)}", true,
273288
types: [.. RDAPTypes.Keys]),
274289
ApplicationName.Whois => Create(name, [], Required(Strings.Domain), true),
290+
ApplicationName.IPGeolocation => Create(name, ["geo"], Required(Strings.Host), true),
291+
ApplicationName.WakeOnLAN => Create(name, ["wol"],
292+
$"{Required(Strings.MACAddress)} {Optional(Strings.Broadcast)}", true, RunCommandArgument.Broadcast),
275293
_ => Create(name, [], string.Empty, false)
276294
}).ToList();
277295

‎Source/NETworkManager/ViewModels/IPGeolocationHostViewModel.cs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ private bool QueryProfile_CanExecute(object obj)
123123
/// </summary>
124124
private void QueryProfileAction()
125125
{
126-
AddTab(SelectedProfile.IPGeolocation_Host);
126+
AddTab(SelectedProfile);
127127
}
128128

129129
/// <summary>
@@ -147,7 +147,7 @@ private static void CloseItemAction(ItemActionCallbackArgs<TabablzControl> args)
147147
/// Adds a new tab for the specified domain.
148148
/// </summary>
149149
/// <param name="domain">The domain to query.</param>
150-
private void AddTab(string domain = null)
150+
public void AddTab(string domain = null)
151151
{
152152
var tabId = Guid.NewGuid();
153153

@@ -157,5 +157,14 @@ private void AddTab(string domain = null)
157157
SelectedTabIndex = TabItems.Count - 1;
158158
}
159159

160+
/// <summary>
161+
/// Adds a new tab for the host of the specified profile.
162+
/// </summary>
163+
/// <param name="profile">The profile to query.</param>
164+
public void AddTab(ProfileInfo profile)
165+
{
166+
AddTab(profile.IPGeolocation_Host);
167+
}
168+
160169
#endregion
161170
}

‎Source/NETworkManager/ViewModels/RunCommandViewModel.cs‎

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ public class RunCommandViewModel : ViewModelBase
3535
private readonly IReadOnlyList<RunCommandDefinition> _commands;
3636
private readonly Action<RunCommandViewModel> _runHandler;
3737

38+
/// <summary>
39+
/// Recent commands with their command (parsed once, the history doesn't change while the dialog is open).
40+
/// </summary>
41+
private readonly List<(string Text, RunCommandDefinition Command)> _history;
42+
43+
/// <summary>
44+
/// Profiles per command (loaded once per command while the dialog is open).
45+
/// </summary>
46+
private readonly Dictionary<RunCommandDefinition, List<ProfileInfo>> _profiles = [];
47+
3848
private RunCommandParseResult _result;
3949

4050
/// <summary>
@@ -47,6 +57,8 @@ public RunCommandViewModel(Action<RunCommandViewModel> runHandler, Action<RunCom
4757
_commands = RunCommandManager.GetCommands();
4858
_runHandler = runHandler;
4959

60+
_history = [.. SettingsManager.Current.RunCommand_History.Select(x => (x, RunCommandParser.Parse(x, _commands).Command))];
61+
5062
CancelCommand = new RelayCommand(_ => cancelHandler(this));
5163

5264
UpdateSuggestions();
@@ -241,9 +253,37 @@ .. GetHistorySuggestions()
241253
foreach (var suggestion in suggestions)
242254
Suggestions.Add(suggestion);
243255

244-
// The input as typed is the first suggestion, so Enter runs what was typed. Profiles, history entries and
245-
// types are selected with Up/Down.
246-
SelectedSuggestion = Suggestions.FirstOrDefault();
256+
SelectedSuggestion = GetPreselectedSuggestion();
257+
}
258+
259+
/// <summary>
260+
/// Gets the suggestion that Enter runs without selecting one, so Enter runs what was typed:
261+
/// - After the command: the input as typed (first suggestion).
262+
/// - While typing the command: the best matching command, but not if the input is empty or an unknown command has
263+
/// arguments (e.g. a typo like "pin 10.0.0.1"), which would drop the input.
264+
/// - While typing a profile ("@"): the profile, only if exactly one matches. Otherwise, the typed name is used,
265+
/// which must be unique (e.g. two profiles with the same name in different groups).
266+
/// </summary>
267+
private RunCommandSuggestion GetPreselectedSuggestion()
268+
{
269+
return _result.Position switch
270+
{
271+
RunCommandPosition.Command when string.IsNullOrWhiteSpace(Input) ||
272+
_result.Command == null && GetInputAfterCommand().Length > 0 => null,
273+
RunCommandPosition.Target when _result.ProfileName != null => Suggestions.Count == 1 ? Suggestions[0] : null,
274+
_ => Suggestions.FirstOrDefault()
275+
};
276+
}
277+
278+
/// <summary>
279+
/// Gets the input after the first word (the command), e.g. "10.0.0.1" for "pin 10.0.0.1".
280+
/// </summary>
281+
private string GetInputAfterCommand()
282+
{
283+
var input = Input.TrimStart();
284+
var index = input.IndexOfAny([' ', '\t']);
285+
286+
return index < 0 ? string.Empty : input[index..].Trim();
247287
}
248288

249289
/// <summary>
@@ -273,6 +313,9 @@ private IEnumerable<RunCommandSuggestion> GetCommandSuggestions()
273313
if (string.IsNullOrEmpty(text))
274314
suggestions.AddRange(GetHistorySuggestions().Take(MaxHistorySuggestions));
275315

316+
// Completing the command keeps the arguments (e.g. "pin 10.0.0.1" → "ping 10.0.0.1").
317+
var arguments = GetInputAfterCommand();
318+
276319
var commands = new List<(int Rank, RunCommandSuggestion Suggestion)>();
277320

278321
foreach (var command in _commands)
@@ -298,7 +341,7 @@ private IEnumerable<RunCommandSuggestion> GetCommandSuggestions()
298341
Title = translatedName,
299342
Description = string.Join(", ", names),
300343
Info = command.Syntax,
301-
CompletionText = (name ?? command.Command) + " "
344+
CompletionText = (name ?? command.Command) + " " + arguments
302345
}));
303346
}
304347

@@ -331,7 +374,13 @@ private IEnumerable<RunCommandSuggestion> GetProfileSuggestions()
331374
return null;
332375
}
333376

334-
return RunCommandManager.GetProfiles(_result.Command)
377+
if (!_profiles.TryGetValue(_result.Command, out var profiles))
378+
{
379+
profiles = [.. RunCommandManager.GetProfiles(_result.Command)];
380+
_profiles[_result.Command] = profiles;
381+
}
382+
383+
return profiles
335384
.Select(x => (Profile: x, Target: x.GetTarget(application)))
336385
.Select(x => (x.Profile, x.Target, Rank: GetRank(x.Profile, x.Target, text)))
337386
.Where(x => x.Rank != null)
@@ -399,8 +448,7 @@ private IEnumerable<RunCommandSuggestion> GetHistorySuggestions()
399448
{
400449
var input = Input.Trim();
401450

402-
return SettingsManager.Current.RunCommand_History
403-
.Select(x => (Text: x, RunCommandParser.Parse(x, _commands).Command))
451+
return _history
404452
.Where(x => _result.Command == null && string.IsNullOrEmpty(input) ||
405453
_result.Command != null &&
406454
x.Command == _result.Command &&

‎Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,13 +198,39 @@ private void WakeUpAction()
198198

199199
private void WakeUpProfileAction()
200200
{
201-
_ = WakeUp(NETworkManager.Profiles.Application.WakeOnLAN.CreateInfo(SelectedProfile));
201+
WakeUp(SelectedProfile);
202202
}
203203

204204
#endregion
205205

206206
#region Methods
207207

208+
/// <summary>
209+
/// Sends the magic packet to the computer of the profile.
210+
/// </summary>
211+
/// <param name="profile">Profile to wake up.</param>
212+
public void WakeUp(ProfileInfo profile)
213+
{
214+
_ = WakeUp(NETworkManager.Profiles.Application.WakeOnLAN.CreateInfo(profile));
215+
}
216+
217+
/// <summary>
218+
/// Sets the MAC address (and broadcast address) and sends the magic packet, if the broadcast address is valid
219+
/// (e.g. from a previous wake up). Otherwise, the values are only filled in.
220+
/// </summary>
221+
/// <param name="macAddress">MAC address of the computer.</param>
222+
/// <param name="broadcast">Broadcast address. If null, the current broadcast address is used.</param>
223+
public void WakeUp(string macAddress, string broadcast)
224+
{
225+
MACAddress = macAddress;
226+
227+
if (broadcast != null)
228+
Broadcast = broadcast;
229+
230+
if (Broadcast != null && RegexHelper.IPv4AddressRegex().IsMatch(Broadcast))
231+
WakeUpAction();
232+
}
233+
208234
private async Task WakeUp(WakeOnLANInfo info)
209235
{
210236
IsStatusMessageDisplayed = false;

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
namespace NETworkManager.Views;
44

5-
public partial class IPGeolocationHostView
5+
public partial class IPGeolocationHostView : IApplicationRequestHandler
66
{
77
private readonly IPGeolocationHostViewModel _viewModel = new();
88

@@ -12,6 +12,14 @@ public IPGeolocationHostView()
1212
DataContext = _viewModel;
1313
}
1414

15+
public void Open(ApplicationRequest request)
16+
{
17+
if (request.Profile != null)
18+
_viewModel.AddTab(request.Profile);
19+
else
20+
_viewModel.AddTab(request.Target);
21+
}
22+
1523
public void OnViewHide()
1624
{
1725
_viewModel.OnViewHide();

0 commit comments

Comments
 (0)